pass $chain_rules to printrule()
[ferm.git] / src / ferm
blob5cde6cf62839cae91880131b42c28d880d50abe6
1 #!/usr/bin/perl
4 # ferm, a firewall setup program that makes firewall rules easy!
6 # Copyright (C) 2001-2008 Auke Kok, Max Kellermann
8 # Comments, questions, greetings and additions to this program
9 # may be sent to <ferm@foo-projects.org>
13 # This program is free software; you can redistribute it and/or modify
14 # it under the terms of the GNU General Public License as published by
15 # the Free Software Foundation; either version 2 of the License, or
16 # (at your option) any later version.
18 # This program is distributed in the hope that it will be useful,
19 # but WITHOUT ANY WARRANTY; without even the implied warranty of
20 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 # GNU General Public License for more details.
23 # You should have received a copy of the GNU General Public License
24 # along with this program; if not, write to the Free Software
25 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
28 # $Id$
30 BEGIN {
31 eval { require strict; import strict; };
32 $has_strict = not $@;
33 if ($@) {
34 # we need no vars.pm if there is not even strict.pm
35 $INC{'vars.pm'} = 1;
36 *vars::import = sub {};
37 } else {
38 require IO::Handle;
41 eval { require Getopt::Long; import Getopt::Long; };
42 $has_getopt = not $@;
45 use vars qw($has_strict $has_getopt);
47 use vars qw($DATE $VERSION);
49 # subversion keyword magic
50 $DATE = '$Date$' =~ m,(\d{4})-(\d\d)-(\d\d), ? $1.$2.$3 : '';
52 $VERSION = '2.0';
53 $VERSION .= '~svn' . $DATE;
55 ## interface variables
56 # %option = command line and other options
57 use vars qw(%option);
59 ## hooks
60 use vars qw(@pre_hooks @post_hooks);
62 ## parser variables
63 # $script: current script file
64 # @stack = ferm's parser stack containing local variables
65 # $auto_chain = index for the next auto-generated chain
66 use vars qw($script @stack $auto_chain);
68 ## netfilter variables
69 # %domains = state information about all domains ("ip" and "ip6")
70 # - initialized: domain initialization is done
71 # - tools: hash providing the paths of the domain's tools
72 # - previous: save file of the previous ruleset, for rollback
73 # - tables{$name}: ferm state information about tables
74 # - has_builtin: whether built-in chains have been determined in this table
75 # - chains{$chain}: ferm state information about the chains
76 # - builtin: whether this is a built-in chain
77 use vars qw(%domains);
79 ## constants
80 use vars qw(%deprecated_keywords);
82 # keywords from ferm 1.1 which are deprecated, and the new one; these
83 # are automatically replaced, and a warning is printed
84 %deprecated_keywords = ( goto => 'jump',
87 # these hashes provide the Netfilter module definitions
88 use vars qw(%proto_defs %match_defs %target_defs);
91 # This subsubsystem allows you to support (most) new netfilter modules
92 # in ferm. Add a call to one of the "add_XY_def()" functions below.
94 # Ok, now about the cryptic syntax: the function "add_XY_def()"
95 # registers a new module. There are three kinds of modules: protocol
96 # module (e.g. TCP, ICMP), match modules (e.g. state, physdev) and
97 # target modules (e.g. DNAT, MARK).
99 # The first parameter is always the module name which is passed to
100 # iptables with "-p", "-m" or "-j" (depending on which kind of module
101 # this is).
103 # After that, you add an encoded string for each option the module
104 # supports. This is where it becomes tricky.
106 # foo defaults to an option with one argument (which may be a ferm
107 # array)
109 # foo*0 option without any arguments
111 # foo=s one argument which must not be a ferm array ('s' stands for
112 # 'scalar')
114 # u32=m an array which renders into multiple iptables options in one
115 # rule
117 # ctstate=c one argument, if it's an array, pass it to iptables as a
118 # single comma separated value; example:
119 # ctstate (ESTABLISHED RELATED) translates to:
120 # --ctstate ESTABLISHED,RELATED
122 # foo=sac three arguments: scalar, array, comma separated; you may
123 # concatenate more than one letter code after the '='
125 # foo&bar one argument; call the perl function '&bar()' which parses
126 # the argument
128 # !foo negation is allowed and the '!' is written before the keyword
130 # foo! same as above, but '!' is after the keyword and before the
131 # parameters
133 # to:=to-destination makes "to" an alias for "to-destination"; you have
134 # to add a declaration for option "to-destination"
137 # add a module definition
138 sub add_def_x {
139 my $defs = shift;
140 my $domain_family = shift;
141 my $params_default = shift;
142 my $name = shift;
143 die if exists $defs->{$domain_family}{$name};
144 my $def = $defs->{$domain_family}{$name} = {};
145 foreach (@_) {
146 my $keyword = $_;
147 my $k = {};
149 my $params = $params_default;
150 $params = $1 if $keyword =~ s,\*(\d+)$,,;
151 $params = $1 if $keyword =~ s,=([acs]+|m)$,,;
152 if ($keyword =~ s,&(\S+)$,,) {
153 $params = eval "\\&$1";
154 die $@ if $@;
156 $k->{params} = $params if $params;
158 $k->{negation} = $k->{pre_negation} = 1 if $keyword =~ s,^!,,;
159 $k->{negation} = 1 if $keyword =~ s,!$,,;
161 $k->{alias} = [$1, $def->{keywords}{$1} || die] if $keyword =~ s,:=(\S+)$,,;
163 $def->{keywords}{$keyword} = $k;
166 return $def;
169 # add a protocol module definition
170 sub add_proto_def_x(@) {
171 my $domain_family = shift;
172 add_def_x(\%proto_defs, $domain_family, 1, @_);
175 # add a match module definition
176 sub add_match_def_x(@) {
177 my $domain_family = shift;
178 add_def_x(\%match_defs, $domain_family, 1, @_);
181 # add a target module definition
182 sub add_target_def_x(@) {
183 my $domain_family = shift;
184 add_def_x(\%target_defs, $domain_family, 's', @_);
187 sub add_def {
188 my $defs = shift;
189 add_def_x($defs, 'ip', @_);
192 # add a protocol module definition
193 sub add_proto_def(@) {
194 add_def(\%proto_defs, 1, @_);
197 # add a match module definition
198 sub add_match_def(@) {
199 add_def(\%match_defs, 1, @_);
202 # add a target module definition
203 sub add_target_def(@) {
204 add_def(\%target_defs, 's', @_);
207 add_proto_def 'dccp', qw(dccp-types!=c dccp-option!);
208 add_proto_def 'mh', qw(mh-type!);
209 add_proto_def 'icmp', qw(icmp-type!);
210 add_proto_def 'icmpv6', qw(icmpv6-type! icmp-type:=icmpv6-type);
211 add_proto_def 'sctp', qw(chunk-types!=sc);
212 add_proto_def 'tcp', qw(tcp-flags!=cc !syn*0 tcp-option! mss);
213 add_proto_def 'udp', qw();
215 add_match_def '',
216 # --source, --destination
217 qw(source! saddr:=source destination! daddr:=destination),
218 # --in-interface
219 qw(in-interface! interface:=in-interface if:=in-interface),
220 # --out-interface
221 qw(out-interface! outerface:=out-interface of:=out-interface),
222 # --fragment
223 qw(!fragment*0);
224 add_match_def 'account', qw(aaddr=s aname=s ashort*0);
225 add_match_def 'addrtype', qw(src-type dst-type);
226 add_match_def 'ah', qw(ahspi! ahlen! ahres*0);
227 add_match_def 'comment', qw(comment=s);
228 add_match_def 'condition', qw(condition!);
229 add_match_def 'connbytes', qw(!connbytes connbytes-dir connbytes-mode);
230 add_match_def 'connlimit', qw(!connlimit-above connlimit-mask);
231 add_match_def 'connmark', qw(mark);
232 add_match_def 'conntrack', qw(ctstate=c ctproto ctorigsrc! ctorigdst!),
233 qw(ctreplsrc! ctrepldst! ctstatus ctexpire=s);
234 add_match_def 'dscp', qw(dscp dscp-class);
235 add_match_def 'ecn', qw(ecn-tcp-cwr*0 ecn-tcp-ece*0 ecn-ip-ect);
236 add_match_def 'esp', qw(espspi!);
237 add_match_def 'eui64';
238 add_match_def 'fuzzy', qw(lower-limit=s upper-limit=s);
239 add_match_def 'hbh', qw(hbh-len! hbh-opts=c);
240 add_match_def 'helper', qw(helper);
241 add_match_def 'hl', qw(hl-eq! hl-lt=s hl-gt=s);
242 add_match_def 'hashlimit', qw(hashlimit=s hashlimit-burst=s hashlimit-mode=s hashlimit-name=s),
243 qw(hashlimit-htable-size=s hashlimit-htable-max=s),
244 qw(hashlimit-htable-expire=s hashlimit-htable-gcinterval=s);
245 add_match_def 'iprange', qw(!src-range !dst-range);
246 add_match_def 'ipv4options', qw(ssrr*0 lsrr*0 no-srr*0 !rr*0 !ts*0 !ra*0 !any-opt*0);
247 add_match_def 'ipv6header', qw(header!=c soft*0);
248 add_match_def 'length', qw(length!);
249 add_match_def 'limit', qw(limit=s limit-burst=s);
250 add_match_def 'mac', qw(mac-source!);
251 add_match_def 'mark', qw(mark);
252 add_match_def 'multiport', qw(source-ports!&multiport_params),
253 qw(destination-ports!&multiport_params ports!&multiport_params);
254 add_match_def 'nth', qw(every counter start packet);
255 add_match_def 'owner', qw(uid-owner gid-owner pid-owner sid-owner cmd-owner);
256 add_match_def 'physdev', qw(physdev-in! physdev-out!),
257 qw(!physdev-is-in*0 !physdev-is-out*0 !physdev-is-bridged*0);
258 add_match_def 'pkttype', qw(pkt-type),
259 add_match_def 'policy',
260 qw(dir pol strict*0 reqid spi proto mode tunnel-src tunnel-dst next*0);
261 add_match_def 'psd', qw(psd-weight-threshold psd-delay-threshold),
262 qw(psd-lo-ports-weight psd-hi-ports-weight);
263 add_match_def 'quota', qw(quota=s);
264 add_match_def 'random', qw(average);
265 add_match_def 'realm', qw(realm!);
266 add_match_def 'recent', qw(name=s !set*0 !rcheck*0 !update*0 !seconds !hitcount rttl*0 rsource*0 rdest*0);
267 add_match_def 'rt', qw(rt-type! rt-segsleft! rt-len! rt-0-res*0 rt-0-addrs=c rt-0-not-strict*0);
268 add_match_def 'set', qw(set=sc);
269 add_match_def 'state', qw(state=c);
270 add_match_def 'statistic', qw(mode=s probability=s every=s packet=s);
271 add_match_def 'string', qw(algo=s from=s to=s string hex-string);
272 add_match_def 'tcpmss', qw(!mss);
273 add_match_def 'time', qw(timestart=s timestop=s days=c datestart=s datestop=s),
274 qw(!monthday=c !weekdays=c utc*0 localtz*0);
275 add_match_def 'tos', qw(!tos);
276 add_match_def 'ttl', qw(ttl-eq ttl-lt=s ttl-gt=s);
277 add_match_def 'u32', qw(!u32=m);
279 add_target_def 'BALANCE', qw(to-destination to:=to-destination);
280 add_target_def 'CLASSIFY', qw(set-class);
281 add_target_def 'CLUSTERIP', qw(new*0 hashmode clustermac total-nodes local-node hash-init);
282 add_target_def 'CONNMARK', qw(set-mark save-mark*0 restore-mark*0 mask);
283 add_target_def 'CONNSECMARK', qw(save*0 restore*0);
284 add_target_def 'DNAT', qw(to-destination=m to:=to-destination random*0);
285 add_target_def 'DSCP', qw(set-dscp set-dscp-class);
286 add_target_def 'ECN', qw(ecn-tcp-remove*0);
287 add_target_def 'HL', qw(hl-set hl-dec hl-inc);
288 add_target_def 'IPV4OPTSSTRIP';
289 add_target_def 'LOG', qw(log-level log-prefix),
290 qw(log-tcp-sequence*0 log-tcp-options*0 log-ip-options*0 log-uid*0);
291 add_target_def 'MARK', qw(set-mark set-xmark and-mark or-mark xor-mark);
292 add_target_def 'MASQUERADE', qw(to-ports random*0);
293 add_target_def 'MIRROR';
294 add_target_def 'NETMAP', qw(to);
295 add_target_def 'NFLOG', qw(nflog-group nflog-prefix nflog-range nflog-threshold);
296 add_target_def 'NFQUEUE', qw(queue-num);
297 add_target_def 'NOTRACK';
298 add_target_def 'REDIRECT', qw(to-ports random*0);
299 add_target_def 'REJECT', qw(reject-with);
300 add_target_def 'ROUTE', qw(oif iif gw continue*0 tee*0);
301 add_target_def 'SAME', qw(to nodst*0 random*0);
302 add_target_def 'SECMARK', qw(selctx);
303 add_target_def 'SET', qw(add-set=sc del-set=sc);
304 add_target_def 'SNAT', qw(to-source=m to:=to-source random*0);
305 add_target_def 'TARPIT';
306 add_target_def 'TCPMSS', qw(set-mss clamp-mss-to-pmtu*0);
307 add_target_def 'TOS', qw(set-tos and-tos or-tos xor-tos);
308 add_target_def 'TRACE';
309 add_target_def 'TTL', qw(ttl-set ttl-dec ttl-inc);
310 add_target_def 'ULOG', qw(ulog-nlgroup ulog-prefix ulog-cprange ulog-qthreshold);
312 add_match_def_x 'arp', '',
313 # ip
314 qw(source-ip! destination-ip! saddr:=source-ip daddr:=destination-ip),
315 # mac
316 qw(source-mac! destination-mac!),
317 # --in-interface
318 qw(in-interface! interface:=in-interface if:=in-interface),
319 # --out-interface
320 qw(out-interface! outerface:=out-interface of:=out-interface),
321 # misc
322 qw(h-length=s opcode=s h-type=s proto-type=s),
323 qw(mangle-ip-s=s mangle-ip-d=s mangle-mac-s=s mangle-mac-d=s mangle-target=s);
325 add_match_def_x 'eb', '',
326 # protocol
327 qw(protocol! proto:=protocol),
328 # --in-interface
329 qw(in-interface! interface:=in-interface if:=in-interface),
330 # --out-interface
331 qw(out-interface! outerface:=out-interface of:=out-interface),
332 # logical interface
333 qw(logical-in! logical-out!),
334 # --source, --destination
335 qw(source! saddr:=source destination! daddr:=destination),
336 # 802.3
337 qw(802_3-sap! 802_3-type!),
338 # arp
339 qw(arp-opcode! arp-htype!=ss arp-ptype!=ss),
340 qw(arp-ip-src! arp-ip-dst! arp-mac-src! arp-mac-dst!),
341 # ip
342 qw(ip-source! ip-destination! ip-tos! ip-protocol! ip-sport! ip-dport!),
343 # mark_m
344 qw(mark!),
345 # pkttype
346 qw(pkttype-type!),
347 # stp
348 qw(stp-type! stp-flags! stp-root-prio! stp-root-addr! stp-root-cost!),
349 qw(stp-sender-prio! stp-sender-addr! stp-port! stp-msg-age! stp-max-age!),
350 qw(stp-hello-time! stp-forward-delay!),
351 # vlan
352 qw(vlan-id! vlan-prio! vlan-encap!),
353 # log
354 qw(log*0 log-level=s log-prefix=s log-ip*0 log-arp*0);
356 add_target_def_x 'eb', 'arpreply', qw(arpreply-mac arpreply-target);
357 add_target_def_x 'eb', 'dnat', qw(to-destination dnat-target);
358 add_target_def_x 'eb', 'mark', qw(set-mark mark-target);
359 add_target_def_x 'eb', 'redirect', qw(redirect-target);
360 add_target_def_x 'eb', 'snat', qw(to-source snat-target);
362 # import-ferm uses the above tables
363 return 1 if $0 =~ /import-ferm$/;
365 # parameter parser for ipt_multiport
366 sub multiport_params {
367 my $fw = shift;
369 # multiport only allows 15 ports at a time. For this
370 # reason, we do a little magic here: split the ports
371 # into portions of 15, and handle these portions as
372 # array elements
374 my $proto = $fw->{protocol};
375 error('To use multiport, you have to specify "proto tcp" or "proto udp" first')
376 unless defined $proto and grep { /^(?:tcp|udp|udplite)$/ } to_array($proto);
378 my $value = getvalues(undef, undef,
379 allow_negation => 1,
380 allow_array_negation => 1);
381 if (ref $value and ref $value eq 'ARRAY') {
382 my @value = @$value;
383 my @params;
385 while (@value) {
386 push @params, join(',', splice(@value, 0, 15));
389 return @params == 1
390 ? $params[0]
391 : \@params;
392 } else {
393 return join_value(',', $value);
397 # initialize stack: command line definitions
398 unshift @stack, {};
400 # Get command line stuff
401 if ($has_getopt) {
402 my ($opt_noexec, $opt_flush, $opt_noflush, $opt_lines, $opt_interactive,
403 $opt_help,
404 $opt_version, $opt_test, $opt_fast, $opt_shell,
405 $opt_domain);
407 Getopt::Long::Configure('bundling', 'auto_help', 'no_ignore_case',
408 'no_auto_abbrev');
410 sub opt_def {
411 my ($opt, $value) = @_;
412 die 'Invalid --def specification'
413 unless $value =~ /^\$?(\w+)=(.*)$/s;
414 my ($name, $unparsed_value) = ($1, $2);
415 my $tokens = tokenize_string($unparsed_value);
416 my $value = getvalues(\&next_array_token, $tokens);
417 die 'Extra tokens after --def'
418 if @$tokens > 0;
419 $stack[0]{vars}{$name} = $value;
422 local $SIG{__WARN__} = sub { die $_[0]; };
423 GetOptions('noexec|n' => \$opt_noexec,
424 'flush|F' => \$opt_flush,
425 'noflush' => \$opt_noflush,
426 'lines|l' => \$opt_lines,
427 'interactive|i' => \$opt_interactive,
428 'help|h' => \$opt_help,
429 'version|V' => \$opt_version,
430 test => \$opt_test,
431 remote => \$opt_test,
432 fast => \$opt_fast,
433 shell => \$opt_shell,
434 'domain=s' => \$opt_domain,
435 'def=s' => \&opt_def,
438 if (defined $opt_help) {
439 require Pod::Usage;
440 Pod::Usage::pod2usage(-exitstatus => 0);
443 if (defined $opt_version) {
444 printversion();
445 exit 0;
448 $option{noexec} = $opt_noexec || $opt_test;
449 $option{flush} = $opt_flush;
450 $option{noflush} = $opt_noflush;
451 $option{lines} = $opt_lines || $opt_test || $opt_shell;
452 $option{interactive} = $opt_interactive && !$opt_noexec;
453 $option{test} = $opt_test;
454 $option{fast} = $opt_fast || $opt_shell;
455 $option{shell} = $opt_shell;
457 mydie('ferm interactive mode not possible: /dev/stdin is not a tty')
458 if $option{interactive} and not -t STDIN;
459 mydie('ferm interactive mode not possible: /dev/stderr is not a tty')
460 if $option{interactive} and not -t STDERR;
462 $option{domain} = $opt_domain if defined $opt_domain;
463 } else {
464 # tiny getopt emulation for microperl
465 my $filename;
466 foreach (@ARGV) {
467 if ($_ eq '--noexec' or $_ eq '-n') {
468 $option{noexec} = 1;
469 } elsif ($_ eq '--lines' or $_ eq '-l') {
470 $option{lines} = 1;
471 } elsif ($_ eq '--fast') {
472 $option{fast} = 1;
473 } elsif ($_ eq '--test') {
474 $option{test} = 1;
475 $option{noexec} = 1;
476 $option{lines} = 1;
477 } elsif ($_ eq '--shell') {
478 $option{$_} = 1 foreach qw(shell fast lines);
479 } elsif (/^-/) {
480 printf STDERR "Usage: ferm [--noexec] [--lines] [--fast] [--shell] FILENAME\n";
481 exit 1;
482 } else {
483 $filename = $_;
486 undef @ARGV;
487 push @ARGV, $filename;
490 unless (@ARGV == 1) {
491 require Pod::Usage;
492 Pod::Usage::pod2usage(-exitstatus => 1);
495 if ($has_strict) {
496 open LINES, ">&STDOUT" if $option{lines};
497 open STDOUT, ">&STDERR" if $option{shell};
498 } else {
499 # microperl can't redirect file handles
500 *LINES = *STDOUT;
502 if ($option{fast} and not $option{noexec}) {
503 print STDERR "Sorry, ferm on microperl does not allow --fast without --noexec\n";
504 exit 1
508 unshift @stack, {};
509 open_script($ARGV[0]);
511 # parse all input recursively
512 enter(0);
513 die unless @stack == 2;
515 # execute all generated rules
516 my $status;
518 foreach my $cmd (@pre_hooks) {
519 print LINES "$cmd\n" if $option{lines};
520 system($cmd) unless $option{noexec};
523 while (my ($domain, $domain_info) = each %domains) {
524 next unless $domain_info->{enabled};
525 my $s = $option{fast} &&
526 defined $domain_info->{tools}{'tables-restore'}
527 ? execute_fast($domain, $domain_info)
528 : execute_slow($domain, $domain_info);
529 $status = $s if defined $s;
532 foreach my $cmd (@post_hooks) {
533 print "$cmd\n" if $option{lines};
534 system($cmd) unless $option{noexec};
537 if (defined $status) {
538 rollback();
539 exit $status;
542 # ask user, and rollback if there is no confirmation
544 confirm_rules() or rollback() if $option{interactive};
546 exit 0;
548 # end of program execution!
551 # funcs
553 sub printversion {
554 print "ferm $VERSION\n";
555 print "Copyright (C) 2001-2008 Auke Kok, Max Kellermann\n";
556 print "This program is free software released under GPLv2.\n";
557 print "See the included COPYING file for license details.\n";
561 sub mydie {
562 print STDERR @_;
563 print STDERR "\n";
564 exit 1;
568 sub error {
569 # returns a nice formatted error message, showing the
570 # location of the error.
571 my $tabs = 0;
572 my @lines;
573 my $l = 0;
574 my @words = map { @$_ } @{$script->{past_tokens}};
576 for my $w ( 0 .. $#words ) {
577 if ($words[$w] eq "\x29")
578 { $l++ ; $lines[$l] = " " x ($tabs-- -1) ;};
579 if ($words[$w] eq "\x28")
580 { $l++ ; $lines[$l] = " " x $tabs++ ;};
581 if ($words[$w] eq "\x7d")
582 { $l++ ; $lines[$l] = " " x ($tabs-- -1) ;};
583 if ($words[$w] eq "\x7b")
584 { $l++ ; $lines[$l] = " " x $tabs++ ;};
585 if ( $l > $#lines ) { $lines[$l] = "" };
586 $lines[$l] .= $words[$w] . " ";
587 if ($words[$w] eq "\x28")
588 { $l++ ; $lines[$l] = " " x $tabs ;};
589 if (($words[$w] eq "\x29") && ($words[$w+1] ne "\x7b"))
590 { $l++ ; $lines[$l] = " " x $tabs ;};
591 if ($words[$w] eq "\x7b")
592 { $l++ ; $lines[$l] = " " x $tabs ;};
593 if (($words[$w] eq "\x7d") && ($words[$w+1] ne "\x7d"))
594 { $l++ ; $lines[$l] = " " x $tabs ;};
595 if (($words[$w] eq "\x3b") && ($words[$w+1] ne "\x7d"))
596 { $l++ ; $lines[$l] = " " x $tabs ;}
597 if ($words[$w-1] eq "option")
598 { $l++ ; $lines[$l] = " " x $tabs ;}
600 my $start = $#lines - 4;
601 if ($start < 0) { $start = 0 } ;
602 print STDERR "Error in $script->{filename} line $script->{line}:\n";
603 for $l ( $start .. $#lines)
604 { print STDERR $lines[$l]; if ($l != $#lines ) {print STDERR "\n"} ; };
605 print STDERR "<--\n";
606 mydie(@_);
609 # print a warning message about code from an input file
610 sub warning {
611 print STDERR "Warning in $script->{filename} line $script->{line}: "
612 . (shift) . "\n";
615 sub find_tool($) {
616 my $name = shift;
617 return $name if $option{test};
618 for my $path ('/sbin', split ':', $ENV{PATH}) {
619 my $ret = "$path/$name";
620 return $ret if -x $ret;
622 die "$name not found in PATH\n";
625 sub initialize_domain {
626 my $domain = shift;
627 my $domain_info = $domains{$domain} ||= {};
629 return if exists $domain_info->{initialized};
631 die "Invalid domain '$domain'\n" unless $domain =~ /^(?:ip6?|arp|eb)$/;
633 my @tools = qw(tables);
634 push @tools, qw(tables-save tables-restore)
635 if $domain =~ /^ip6?$/;
637 # determine the location of this domain's tools
638 my %tools = map { $_ => find_tool($domain . $_) } @tools;
639 $domain_info->{tools} = \%tools;
641 # make tables-save tell us about the state of this domain
642 # (which tables and chains do exist?), also remember the old
643 # save data which may be used later by the rollback function
644 local *SAVE;
645 if (!$option{test} &&
646 exists $tools{'tables-save'} &&
647 open(SAVE, "$tools{'tables-save'}|")) {
648 my $save = '';
650 my $table_info;
651 while (<SAVE>) {
652 $save .= $_;
654 if (/^\*(\w+)/) {
655 my $table = $1;
656 $table_info = $domain_info->{tables}{$table} ||= {};
657 } elsif (defined $table_info and /^:(\w+)\s+(\S+)/
658 and $2 ne '-') {
659 $table_info->{chains}{$1}{builtin} = 1;
660 $table_info->{has_builtin} = 1;
664 # for rollback
665 $domain_info->{previous} = $save;
668 $domain_info->{initialized} = 1;
671 # split the an input string into words and delete comments
672 sub tokenize_string($) {
673 my $string = shift;
675 my @ret;
677 foreach my $word ($string =~ m/(".*?"|'.*?'|`.*?`|[!,=&\$\%\(\){};]|[-+\w\/\.:]+|@\w+|#)/g) {
678 last if $word eq '#';
679 push @ret, $word;
682 return \@ret;
685 # shift an array; helper function to be passed to &getvar / &getvalues
686 sub next_array_token {
687 my $array = shift;
688 shift @$array;
691 # read some more tokens from the input file into a buffer
692 sub prepare_tokens() {
693 my $tokens = $script->{tokens};
694 while (@$tokens == 0) {
695 my $handle = $script->{handle};
696 my $line = <$handle>;
697 return unless defined $line;
699 $script->{line} ++;
701 # the next parser stage eats this
702 push @$tokens, @{tokenize_string($line)};
705 return 1;
708 # open a ferm sub script
709 sub open_script($) {
710 my $filename = shift;
712 for (my $s = $script; defined $s; $s = $s->{parent}) {
713 mydie("Circular reference in $script->{filename} line $script->{line}: $filename")
714 if $s->{filename} eq $filename;
717 local *FILE;
718 open FILE, "<$filename"
719 or mydie("Failed to open $filename: $!");
720 my $handle = *FILE;
722 $script = { filename => $filename,
723 handle => $handle,
724 line => 0,
725 past_tokens => [],
726 tokens => [],
727 parent => $script,
730 return $script;
733 # collect script filenames which are being included
734 sub collect_filenames(@) {
735 my @ret;
737 # determine the current script's parent directory for relative
738 # file names
739 die unless defined $script;
740 my $parent_dir = $script->{filename} =~ m,^(.*/),
741 ? $1 : './';
743 foreach my $pathname (@_) {
744 # non-absolute file names are relative to the parent script's
745 # file name
746 $pathname = $parent_dir . $pathname
747 unless $pathname =~ m,^/,;
749 if ($pathname =~ m,/$,) {
750 # include all regular files in a directory
752 error("'$pathname' is not a directory")
753 unless -d $pathname;
755 local *DIR;
756 opendir DIR, $pathname
757 or error("Failed to open directory '$pathname': $!");
758 my @names = readdir DIR;
759 closedir DIR;
761 # sort those names for a well-defined order
762 foreach my $name (sort { $a cmp $b } @names) {
763 # don't include hidden and backup files
764 next if /^\.|~$/;
766 my $filename = $pathname . $name;
767 push @ret, $filename
768 if -f $filename;
770 } elsif ($pathname =~ m,\|$,) {
771 # run a program and use its output
772 push @ret, $pathname;
773 } elsif ($pathname =~ m,^\|,) {
774 error('This kind of pipe is not allowed');
775 } else {
776 # include a regular file
778 error("'$pathname' is a directory; maybe use trailing '/' to include a directory?")
779 if -d $pathname;
780 error("'$pathname' is not a file")
781 unless -f $pathname;
783 push @ret, $pathname;
787 return @ret;
790 # peek a token from the queue, but don't remove it
791 sub peek_token() {
792 return unless prepare_tokens();
793 return $script->{tokens}[0];
796 # get a token from the queue
797 sub next_token() {
798 return unless prepare_tokens();
799 my $token = shift @{$script->{tokens}};
801 # update $script->{past_tokens}
802 my $past_tokens = $script->{past_tokens};
804 if (@$past_tokens > 0) {
805 my $prev_token = $past_tokens->[-1][-1];
806 $past_tokens->[-1] = @$past_tokens > 1 ? ['{'] : []
807 if $prev_token eq ';';
808 pop @$past_tokens
809 if $prev_token eq '}';
812 push @$past_tokens, [] if $token eq '{' or @$past_tokens == 0;
813 push @{$past_tokens->[-1]}, $token;
815 # return
816 return $token;
819 sub expect_token($;$) {
820 my $expect = shift;
821 my $msg = shift;
822 my $token = next_token();
823 error($msg || "'$expect' expected")
824 unless defined $token and $token eq $expect;
827 # require that another token exists, and that it's not a "special"
828 # token, e.g. ";" and "{"
829 sub require_next_token {
830 my $code = shift || \&next_token;
832 my $token = &$code(@_);
834 error('unexpected end of file')
835 unless defined $token;
837 error("'$token' not allowed here")
838 if $token =~ /^[;{}]$/;
840 return $token;
843 # return the value of a variable
844 sub variable_value($) {
845 my $name = shift;
847 foreach (@stack) {
848 return $_->{vars}{$name}
849 if exists $_->{vars}{$name};
852 return $stack[0]{auto}{$name}
853 if exists $stack[0]{auto}{$name};
855 return;
858 # determine the value of a variable, die if the value is an array
859 sub string_variable_value($) {
860 my $name = shift;
861 my $value = variable_value($name);
863 error("variable '$name' must be a string, but it is an array")
864 if ref $value;
866 return $value;
869 # similar to the built-in "join" function, but also handle negated
870 # values in a special way
871 sub join_value($$) {
872 my ($expr, $value) = @_;
874 unless (ref $value) {
875 return $value;
876 } elsif (ref $value eq 'ARRAY') {
877 return join($expr, @$value);
878 } elsif (ref $value eq 'negated') {
879 # bless'negated' is a special marker for negated values
880 $value = join_value($expr, $value->[0]);
881 return bless [ $value ], 'negated';
882 } else {
883 die;
887 # returns the next parameter, which may either be a scalar or an array
888 sub getvalues {
889 my ($code, $param) = (shift, shift);
890 my %options = @_;
892 my $token = require_next_token($code, $param);
894 if ($token eq '(') {
895 # read an array until ")"
896 my @wordlist;
898 for (;;) {
899 $token = getvalues($code, $param,
900 parenthesis_allowed => 1,
901 comma_allowed => 1);
903 unless (ref $token) {
904 last if $token eq ')';
906 if ($token eq ',') {
907 error('Comma is not allowed within arrays, please use only a space');
908 next;
911 push @wordlist, $token;
912 } elsif (ref $token eq 'ARRAY') {
913 push @wordlist, @$token;
914 } else {
915 error('unknown toke type');
919 error('empty array not allowed here')
920 unless @wordlist or not $options{non_empty};
922 return @wordlist == 1
923 ? $wordlist[0]
924 : \@wordlist;
925 } elsif ($token =~ /^\`(.*)\`$/s) {
926 # execute a shell command, insert output
927 my $command = $1;
928 my $output = `$command`;
929 unless ($? == 0) {
930 if ($? == -1) {
931 error("failed to execute: $!");
932 } elsif ($? & 0x7f) {
933 error("child died with signal " . ($? & 0x7f));
934 } elsif ($? >> 8) {
935 error("child exited with status " . ($? >> 8));
939 # remove comments
940 $output =~ s/#.*//mg;
942 # tokenize
943 my @tokens = grep { length } split /\s+/s, $output;
945 my @values;
946 while (@tokens) {
947 my $value = getvalues(\&next_array_token, \@tokens);
948 push @values, to_array($value);
951 # and recurse
952 return @values == 1
953 ? $values[0]
954 : \@values;
955 } elsif ($token =~ /^\'(.*)\'$/s) {
956 # single quotes: a string
957 return $1;
958 } elsif ($token =~ /^\"(.*)\"$/s) {
959 # double quotes: a string with escapes
960 $token = $1;
961 $token =~ s,\$(\w+),string_variable_value($1),eg;
962 return $token;
963 } elsif ($token eq '!') {
964 error('negation is not allowed here')
965 unless $options{allow_negation};
967 $token = getvalues($code, $param);
969 error('it is not possible to negate an array')
970 if ref $token and not $options{allow_array_negation};
972 return bless [ $token ], 'negated';
973 } elsif ($token eq ',') {
974 return $token
975 if $options{comma_allowed};
977 error('comma is not allowed here');
978 } elsif ($token eq '=') {
979 error('equals operator ("=") is not allowed here');
980 } elsif ($token eq '$') {
981 my $name = require_next_token($code, $param);
982 error('variable name expected - if you want to concatenate strings, try using double quotes')
983 unless $name =~ /^\w+$/;
985 my $value = variable_value($name);
987 error("no such variable: \$$name")
988 unless defined $value;
990 return $value;
991 } elsif ($token eq '&') {
992 error("function calls are not allowed as keyword parameter");
993 } elsif ($token eq ')' and not $options{parenthesis_allowed}) {
994 error('Syntax error');
995 } elsif ($token =~ /^@/) {
996 if ($token eq '@resolve') {
997 my @params = get_function_params();
998 error('Usage: @resolve((hostname ...))')
999 unless @params == 1;
1000 eval { require Net::DNS; };
1001 error('For the @resolve() function, you need the Perl library Net::DNS')
1002 if $@;
1003 my $type = 'A';
1004 my $resolver = new Net::DNS::Resolver;
1005 my @result;
1006 foreach my $hostname (to_array($params[0])) {
1007 my $query = $resolver->search($hostname, $type);
1008 error("DNS query for '$hostname' failed: " . $resolver->errorstring)
1009 unless $query;
1010 foreach my $rr ($query->answer) {
1011 next unless $rr->type eq $type;
1012 push @result, $rr->address;
1015 return \@result;
1016 } else {
1017 error("unknown ferm built-in function");
1019 } else {
1020 return $token;
1024 # returns the next parameter, but only allow a scalar
1025 sub getvar {
1026 my $token = getvalues(@_);
1028 error('array not allowed here')
1029 if ref $token and ref $token eq 'ARRAY';
1031 return $token;
1034 sub get_function_params(%) {
1035 expect_token('(', 'function name must be followed by "()"');
1037 my $token = peek_token();
1038 if ($token eq ')') {
1039 require_next_token;
1040 return;
1043 my @params;
1045 while (1) {
1046 if (@params > 0) {
1047 $token = require_next_token();
1048 last
1049 if $token eq ')';
1051 error('"," expected')
1052 unless $token eq ',';
1055 push @params, getvalues(undef, undef, @_);
1058 return @params;
1061 # collect all tokens in a flat array reference until the end of the
1062 # command is reached
1063 sub collect_tokens() {
1064 my @level;
1065 my @tokens;
1067 while (1) {
1068 my $keyword = next_token();
1069 error('unexpected end of file within function/variable declaration')
1070 unless defined $keyword;
1072 if ($keyword =~ /^[\{\(]$/) {
1073 push @level, $keyword;
1074 } elsif ($keyword =~ /^[\}\)]$/) {
1075 my $expected = $keyword;
1076 $expected =~ tr/\}\)/\{\(/;
1077 my $opener = pop @level;
1078 error("unmatched '$keyword'")
1079 unless defined $opener and $opener eq $expected;
1080 } elsif ($keyword eq ';' and @level == 0) {
1081 last;
1084 push @tokens, $keyword;
1086 last
1087 if $keyword eq '}' and @level == 0;
1090 return \@tokens;
1094 # returns the specified value as an array. dereference arrayrefs
1095 sub to_array($) {
1096 my $value = shift;
1097 die unless wantarray;
1098 die if @_;
1099 unless (ref $value) {
1100 return $value;
1101 } elsif (ref $value eq 'ARRAY') {
1102 return @$value;
1103 } else {
1104 die;
1108 # evaluate the specified value as bool
1109 sub eval_bool($) {
1110 my $value = shift;
1111 die if wantarray;
1112 die if @_;
1113 unless (ref $value) {
1114 return $value;
1115 } elsif (ref $value eq 'ARRAY') {
1116 return @$value > 0;
1117 } else {
1118 die;
1122 sub is_netfilter_core_target($) {
1123 my $target = shift;
1124 die unless defined $target and length $target;
1126 return $target =~ /^(?:ACCEPT|DROP|RETURN|QUEUE)$/;
1129 sub is_netfilter_module_target($$) {
1130 my ($domain_family, $target) = @_;
1131 die unless defined $target and length $target;
1133 return defined $domain_family &&
1134 exists $target_defs{$domain_family} &&
1135 $target_defs{$domain_family}{$target};
1138 sub is_netfilter_builtin_chain($$) {
1139 my ($table, $chain) = @_;
1141 return grep { $_ eq $chain }
1142 qw(PREROUTING INPUT FORWARD OUTPUT POSTROUTING);
1145 sub netfilter_canonical_protocol($) {
1146 my $proto = shift;
1147 return 'icmpv6'
1148 if $proto eq 'ipv6-icmp';
1149 return 'mh'
1150 if $proto eq 'ipv6-mh';
1151 return $proto;
1154 sub netfilter_protocol_module($) {
1155 my $proto = shift;
1156 return unless defined $proto;
1157 return 'icmp6'
1158 if $proto eq 'icmpv6';
1159 return $proto;
1162 # escape the string in a way safe for the shell
1163 sub shell_escape($) {
1164 my $token = shift;
1166 return $token if $token =~ /^[-_a-zA-Z0-9]+$/s;
1168 if ($option{fast}) {
1169 # iptables-save/iptables-restore are quite buggy concerning
1170 # escaping and special characters... we're trying our best
1171 # here
1173 $token =~ s,",',g;
1174 $token = '"' . $token . '"'
1175 if $token =~ /[\s\'\\;&]/s;
1176 } else {
1177 return $token
1178 if $token =~ /^\`.*\`$/;
1179 $token =~ s/'/\\'/g;
1180 $token = '\'' . $token . '\''
1181 if $token =~ /[\s\"\\;<>&|]/s;
1184 return $token;
1187 # append an option to the shell command line, using information from
1188 # the module definition (see %match_defs etc.)
1189 sub shell_append_option($$$) {
1190 my ($ref, $keyword, $value) = @_;
1192 if (ref $value) {
1193 if (ref $value eq 'negated') {
1194 $value = $value->[0];
1195 $keyword .= ' !';
1196 } elsif (ref $value eq 'pre_negated') {
1197 $value = $value->[0];
1198 $$ref .= ' !';
1202 unless (defined $value) {
1203 $$ref .= " --$keyword";
1204 } elsif (ref $value) {
1205 if (ref $value eq 'params') {
1206 $$ref .= " --$keyword ";
1207 $$ref .= join(' ', map { shell_escape($_) } @$value);
1208 } elsif (ref $value eq 'multi') {
1209 foreach (@$value) {
1210 $$ref .= " --$keyword " . shell_escape($_);
1212 } else {
1213 die;
1215 } else {
1216 $$ref .= " --$keyword " . shell_escape($value);
1220 sub transform_rule($$) {
1221 my ($domain, $rule) = @_;
1223 $rule->{options}[$rule->{protocol_index}][1] = 'icmpv6'
1224 if $domain eq 'ip6' and $rule->{protocol} eq 'icmp';
1227 sub printrule($$$) {
1228 my ($domain, $chain_rules, $rule) = @_;
1230 transform_rule($domain, $rule);
1232 # return if this is a declaration-only rule
1233 return if $option{flush} or not $rule->{has_rule};
1235 # format iptables options
1236 my $rr = '';
1237 foreach my $option (@{$rule->{options}}) {
1238 shell_append_option(\$rr, $option->[0], $option->[1]);
1241 # append to rule list
1242 push @$chain_rules, { rule => $rr,
1243 script => $rule->{script},
1247 sub check_unfold(\@$$) {
1248 my ($unfold, $parent, $key) = @_;
1250 return unless ref $parent->{$key} and
1251 ref $parent->{$key} eq 'ARRAY';
1253 push @$unfold, $parent, $key, $parent->{$key};
1256 sub mkrules2($$$) {
1257 my ($domain, $chain_rules, $fw) = @_;
1259 my @unfold;
1260 foreach my $option (@{$fw->{options}}) {
1261 push @unfold, $option
1262 if ref $option->[1] and ref $option->[1] eq 'ARRAY';
1265 if (@unfold == 0) {
1266 printrule($domain, $chain_rules, $fw);
1267 return;
1270 sub dofr {
1271 my $fw = shift;
1272 my ($domain, $chain_rules) = (shift, shift);
1273 my $option = shift;
1274 my @values = @{$option->[1]};
1276 foreach my $value (@values) {
1277 $option->[1] = $value;
1278 $fw->{protocol} = $value if $option->[0] eq 'protocol';
1280 if (@_) {
1281 dofr($fw, $domain, $chain_rules, @_);
1282 } else {
1283 printrule($domain, $chain_rules, $fw);
1288 dofr($fw, $domain, $chain_rules, @unfold);
1291 # convert a bunch of internal rule structures in iptables calls,
1292 # unfold arrays during that
1293 sub mkrules($) {
1294 my $fw = shift;
1296 foreach my $domain (to_array $fw->{domain}) {
1297 my $domain_info = $domains{$domain};
1298 $domain_info->{enabled} = 1;
1300 foreach my $table (to_array $fw->{table}) {
1301 my $table_info = $domain_info->{tables}{$table} ||= {};
1303 foreach my $chain (to_array $fw->{chain}) {
1304 my $chain_rules = $table_info->{chains}{$chain}{rules} ||= [];
1305 mkrules2($domain, $chain_rules, $fw);
1311 sub filter_domains($) {
1312 my $domains = shift;
1313 my $result = [];
1315 foreach my $domain (to_array $domains) {
1316 next if exists $option{domain}
1317 and $domain ne $option{domain};
1319 eval {
1320 initialize_domain($domain);
1322 error($@) if $@;
1324 push @$result, $domain;
1327 return @$result == 1 ? $result->[0] : $result;
1330 # parse a keyword from a module definition
1331 sub parse_keyword($$$$) {
1332 my ($current, $def, $keyword, $negated_ref) = @_;
1334 my $params = $def->{params};
1336 my $value;
1338 my $negated;
1339 if ($$negated_ref && exists $def->{pre_negation}) {
1340 $negated = 1;
1341 undef $$negated_ref;
1344 unless (defined $params) {
1345 undef $value;
1346 } elsif (ref $params && ref $params eq 'CODE') {
1347 $value = &$params($current);
1348 } elsif ($params eq 'm') {
1349 $value = bless [ to_array getvalues() ], 'multi';
1350 } elsif ($params =~ /^[a-z]/) {
1351 if (exists $def->{negation} and not $negated) {
1352 my $token = peek_token();
1353 if ($token eq '!') {
1354 require_next_token;
1355 $negated = 1;
1359 my @params;
1360 foreach my $p (split(//, $params)) {
1361 if ($p eq 's') {
1362 push @params, getvar();
1363 } elsif ($p eq 'c') {
1364 my @v = to_array getvalues(undef, undef,
1365 non_empty => 1);
1366 push @params, join(',', @v);
1367 } else {
1368 die;
1372 $value = @params == 1
1373 ? $params[0]
1374 : bless \@params, 'params';
1375 } elsif ($params == 1) {
1376 if (exists $def->{negation} and not $negated) {
1377 my $token = peek_token();
1378 if ($token eq '!') {
1379 require_next_token;
1380 $negated = 1;
1384 $value = getvalues();
1386 warning("log-prefix is too long; truncating to 29 characters: '$1'")
1387 if $keyword eq 'log-prefix' && $value =~ s,^(.{29}).+$,$1,;
1388 } else {
1389 if (exists $def->{negation} and not $negated) {
1390 my $token = peek_token();
1391 if ($token eq '!') {
1392 require_next_token;
1393 $negated = 1;
1397 $value = bless [ map {
1398 getvar()
1399 } (1..$params) ], 'params';
1402 $value = bless [ $value ], exists $def->{pre_negation} ? 'pre_negated' : 'negated'
1403 if $negated;
1405 return $value;
1408 sub append_option(\%$$) {
1409 my ($rule, $name, $value) = @_;
1410 push @{$rule->{options}}, [ $name, $value ];
1413 # parse options of a module
1414 sub parse_option($$$$) {
1415 my ($def, $current, $keyword, $negated_ref) = @_;
1417 while (exists $def->{alias}) {
1418 ($keyword, $def) = @{$def->{alias}};
1419 die unless defined $def;
1422 append_option(%$current, $keyword,
1423 parse_keyword($current, $def, $keyword, $negated_ref));
1424 return 1;
1427 sub copy_on_write($$) {
1428 my ($rule, $key) = @_;
1429 return unless exists $rule->{cow}{$key};
1430 $rule->{$key} = {%{$rule->{$key}}};
1431 delete $rule->{cow}{$key};
1434 sub new_level(\%$) {
1435 my ($current, $prev) = @_;
1437 %$current = ();
1438 if (defined $prev) {
1439 # copy data from previous level
1440 $current->{cow} = { keywords => 1, };
1441 $current->{keywords} = $prev->{keywords};
1442 $current->{match} = { %{$prev->{match}} };
1443 $current->{options} = [@{$prev->{options}}];
1444 foreach my $key (qw(domain domain_family table chain protocol protocol_index has_action)) {
1445 $current->{$key} = $prev->{$key}
1446 if exists $prev->{$key};
1448 } else {
1449 $current->{cow} = {};
1450 $current->{keywords} = {};
1451 $current->{match} = {};
1452 $current->{options} = [];
1456 sub merge_keywords(\%$) {
1457 my ($rule, $keywords) = @_;
1458 copy_on_write($rule, 'keywords');
1459 while (my ($name, $def) = each %$keywords) {
1460 $rule->{keywords}{$name} = $def;
1464 sub set_domain(\%$) {
1465 my ($rule, $domain) = @_;
1467 my $filtered_domain = filter_domains($domain);
1468 my $domain_family;
1469 unless (ref $domain) {
1470 $domain_family = $domain eq 'ip6' ? 'ip' : $domain;
1471 } elsif (@$domain == 0) {
1472 $domain_family = 'none';
1473 } elsif (grep { not /^ip6?$/s } @$domain) {
1474 error('Cannot combine non-IP domains');
1475 } else {
1476 $domain_family = 'ip';
1479 $rule->{domain_family} = $domain_family;
1480 $rule->{keywords} = $match_defs{$domain_family}{''}{keywords};
1481 $rule->{cow}{keywords} = 1;
1483 $rule->{domain} = $stack[0]{auto}{DOMAIN} = $filtered_domain;
1486 sub set_module_target(\%$$) {
1487 my ($rule, $name, $defs) = @_;
1489 if ($name eq 'TCPMSS') {
1490 my $protos = $rule->{protocol};
1491 error('No protocol specified before TCPMSS')
1492 unless defined $protos;
1493 foreach my $proto (to_array $protos) {
1494 error('TCPMSS not available for protocol "$proto"')
1495 unless $proto eq 'tcp';
1499 merge_keywords(%$rule, $defs->{keywords});
1502 # the main parser loop: read tokens, convert them into internal rule
1503 # structures
1504 sub enter($$) {
1505 my $lev = shift; # current recursion depth
1506 my $prev = shift; # previous rule hash
1508 # enter is the core of the firewall setup, it is a
1509 # simple parser program that recognizes keywords and
1510 # retreives parameters to set up the kernel routing
1511 # chains
1513 my $base_level = $script->{base_level} || 0;
1514 die if $base_level > $lev;
1516 my %current;
1517 new_level(%current, $prev);
1519 # read keywords 1 by 1 and dump into parser
1520 while (defined (my $keyword = next_token())) {
1521 # check if the current rule should be negated
1522 my $negated = $keyword eq '!';
1523 if ($negated) {
1524 # negation. get the next word which contains the 'real'
1525 # rule
1526 $keyword = getvar();
1528 error('unexpected end of file after negation')
1529 unless defined $keyword;
1532 # the core: parse all data
1533 for ($keyword)
1535 # deprecated keyword?
1536 if (exists $deprecated_keywords{$keyword}) {
1537 my $new_keyword = $deprecated_keywords{$keyword};
1538 warning("'$keyword' is deprecated, please use '$new_keyword' instead");
1539 $keyword = $new_keyword;
1542 # effectuation operator
1543 if ($keyword eq ';') {
1544 if ($current{has_rule} and not exists $current{has_action}) {
1545 # something is wrong when a rule was specified,
1546 # but no action
1547 error('No action defined; did you mean "NOP"?');
1550 error('No chain defined') unless exists $current{chain};
1552 $current{script} = { filename => $script->{filename},
1553 line => $script->{line},
1556 mkrules(\%current);
1558 # and clean up variables set in this level
1559 new_level(%current, $prev);
1561 next;
1564 # conditional expression
1565 if ($keyword eq '@if') {
1566 unless (eval_bool(getvalues)) {
1567 collect_tokens;
1568 my $token = peek_token();
1569 require_next_token() if $token and $token eq '@else';
1572 next;
1575 if ($keyword eq '@else') {
1576 # hack: if this "else" has not been eaten by the "if"
1577 # handler above, we believe it came from an if clause
1578 # which evaluated "true" - remove the "else" part now.
1579 collect_tokens;
1580 next;
1583 # hooks for custom shell commands
1584 if ($keyword eq 'hook') {
1585 error('"hook" must be the first token in a command')
1586 if exists $current{domain};
1588 my $position = getvar();
1589 my $hooks;
1590 if ($position eq 'pre') {
1591 $hooks = \@pre_hooks;
1592 } elsif ($position eq 'post') {
1593 $hooks = \@post_hooks;
1594 } else {
1595 error("Invalid hook position: '$position'");
1598 push @$hooks, getvar();
1600 expect_token(';');
1601 next;
1604 # recursing operators
1605 if ($keyword eq '{') {
1606 # push stack
1607 my $old_stack_depth = @stack;
1609 unshift @stack, { auto => { %{$stack[0]{auto} || {}} } };
1611 # recurse
1612 enter($lev + 1, \%current);
1614 # pop stack
1615 shift @stack;
1616 die unless @stack == $old_stack_depth;
1618 # after a block, the command is finished, clear this
1619 # level
1620 new_level(%current, $prev);
1622 next;
1625 if ($keyword eq '}') {
1626 error('Unmatched "}"')
1627 if $lev <= $base_level;
1629 # consistency check: check if they havn't forgotten
1630 # the ';' before the last statement
1631 error('Missing semicolon before "}"')
1632 if $current{has_rule};
1634 # and exit
1635 return;
1638 # include another file
1639 if ($keyword eq '@include' or $keyword eq 'include') {
1640 my @files = collect_filenames to_array getvalues;
1641 $keyword = next_token;
1642 error('Missing ";" - "include FILENAME" must be the last command in a rule')
1643 unless defined $keyword and $keyword eq ';';
1645 foreach my $filename (@files) {
1646 # save old script, open new script
1647 my $old_script = $script;
1648 open_script($filename);
1649 $script->{base_level} = $lev + 1;
1651 # push stack
1652 my $old_stack_depth = @stack;
1654 my $stack = {};
1656 if (@stack > 0) {
1657 # include files may set variables for their parent
1658 $stack->{vars} = ($stack[0]{vars} ||= {});
1659 $stack->{functions} = ($stack[0]{functions} ||= {});
1660 $stack->{auto} = { %{ $stack[0]{auto} || {} } };
1663 unshift @stack, $stack;
1665 # parse the script
1666 enter($lev + 1, \%current);
1668 # pop stack
1669 shift @stack;
1670 die unless @stack == $old_stack_depth;
1672 # restore old script
1673 $script = $old_script;
1676 next;
1679 # definition of a variable or function
1680 if ($keyword eq '@def' or $keyword eq 'def') {
1681 error('"def" must be the first token in a command')
1682 if $current{has_rule};
1684 my $type = require_next_token();
1685 if ($type eq '$') {
1686 my $name = require_next_token();
1687 error('invalid variable name')
1688 unless $name =~ /^\w+$/;
1690 expect_token('=');
1692 my $value = getvalues(undef, undef, allow_negation => 1);
1694 expect_token(';');
1696 $stack[0]{vars}{$name} = $value
1697 unless exists $stack[-1]{vars}{$name};
1698 } elsif ($type eq '&') {
1699 my $name = require_next_token();
1700 error('invalid function name')
1701 unless $name =~ /^\w+$/;
1703 expect_token('(', 'function parameter list or "()" expected');
1705 my @params;
1706 while (1) {
1707 my $token = require_next_token();
1708 last if $token eq ')';
1710 if (@params > 0) {
1711 error('"," expected')
1712 unless $token eq ',';
1714 $token = require_next_token();
1717 error('"$" and parameter name expected')
1718 unless $token eq '$';
1720 $token = require_next_token();
1721 error('invalid function parameter name')
1722 unless $token =~ /^\w+$/;
1724 push @params, $token;
1727 my %function;
1729 $function{params} = \@params;
1731 expect_token('=');
1733 my $tokens = collect_tokens();
1734 $function{block} = 1 if grep { $_ eq '{' } @$tokens;
1735 $function{tokens} = $tokens;
1737 $stack[0]{functions}{$name} = \%function
1738 unless exists $stack[-1]{functions}{$name};
1739 } else {
1740 error('"$" (variable) or "&" (function) expected');
1743 next;
1746 # def references
1747 if ($keyword eq '$') {
1748 error('variable references are only allowed as keyword parameter');
1751 if ($keyword eq '&') {
1752 my $name = require_next_token;
1753 error('function name expected')
1754 unless $name =~ /^\w+$/;
1756 my $function;
1757 foreach (@stack) {
1758 $function = $_->{functions}{$name};
1759 last if defined $function;
1761 error("no such function: \&$name")
1762 unless defined $function;
1764 my $paramdef = $function->{params};
1765 die unless defined $paramdef;
1767 my @params = get_function_params(allow_negation => 1);
1769 error("Wrong number of parameters for function '\&$name': "
1770 . @$paramdef . " expected, " . @params . " given")
1771 unless @params == @$paramdef;
1773 my %vars;
1774 for (my $i = 0; $i < @params; $i++) {
1775 $vars{$paramdef->[$i]} = $params[$i];
1778 if ($function->{block}) {
1779 # block {} always ends the current rule, so if the
1780 # function contains a block, we have to require
1781 # the calling rule also ends here
1782 expect_token(';');
1785 my @tokens = @{$function->{tokens}};
1786 for (my $i = 0; $i < @tokens; $i++) {
1787 if ($tokens[$i] eq '$' and $i + 1 < @tokens and
1788 exists $vars{$tokens[$i + 1]}) {
1789 my @value = to_array($vars{$tokens[$i + 1]});
1790 @value = ('(', @value, ')')
1791 unless @tokens == 1;
1792 splice(@tokens, $i, 2, @value);
1793 $i += @value - 2;
1794 } elsif ($tokens[$i] =~ m,^"(.*)"$,) {
1795 $tokens[$i] =~ s,\$(\w+),exists $vars{$1} ? $vars{$1} : "\$$1",eg;
1799 unshift @{$script->{tokens}}, @tokens;
1801 next;
1804 # where to put the rule?
1805 if ($keyword eq 'domain') {
1806 error('Domain is already specified')
1807 if exists $current{domain};
1809 set_domain(%current, getvalues());
1810 next;
1813 if ($keyword eq 'table') {
1814 error('Table is already specified')
1815 if exists $current{table};
1816 $current{table} = $stack[0]{auto}{TABLE} = getvalues();
1818 set_domain(%current, 'ip')
1819 unless exists $current{domain};
1821 next;
1824 if ($keyword eq 'chain') {
1825 error('Chain is already specified')
1826 if exists $current{chain};
1827 $current{chain} = $stack[0]{auto}{CHAIN} = getvalues();
1829 # ferm 1.1 allowed lower case built-in chain names
1830 foreach (ref $current{chain} ? @{$current{chain}} : $current{chain}) {
1831 error('Please write built-in chain names in upper case')
1832 if /^(?:input|forward|output|prerouting|postrouting)$/;
1835 set_domain(%current, 'ip')
1836 unless exists $current{domain};
1838 $current{table} = 'filter'
1839 unless exists $current{table};
1841 next;
1844 error('Chain must be specified')
1845 unless exists $current{chain};
1847 # policy for built-in chain
1848 if ($keyword eq 'policy') {
1849 error('Cannot specify matches for policy')
1850 if $current{has_rule};
1852 my $policy = getvar();
1853 error("Invalid policy target: $policy")
1854 unless $policy =~ /^(?:ACCEPT|DROP)$/;
1856 expect_token(';');
1858 foreach my $domain (to_array $current{domain}) {
1859 foreach my $table (to_array $current{table}) {
1860 foreach my $chain (to_array $current{chain}) {
1861 $domains{$domain}{tables}{$table}{chains}{$chain}{policy} = $policy;
1866 new_level(%current, $prev);
1867 next;
1870 # create a subchain
1871 if ($keyword eq '@subchain' or $keyword eq 'subchain') {
1872 error('Chain must be specified')
1873 unless exists $current{chain};
1875 error('No rule specified before "@subchain"')
1876 unless $current{has_rule};
1878 my $subchain;
1879 $keyword = next_token();
1881 if ($keyword =~ /^(["'])(.*)\1$/s) {
1882 $subchain = $2;
1883 $keyword = next_token();
1884 } else {
1885 $subchain = 'ferm_auto_' . ++$auto_chain;
1888 error('"{" or chain name expected after "@subchain"')
1889 unless $keyword eq '{';
1891 # create a deep copy of %current, only containing values
1892 # which must be in the subchain
1893 my %inner = ( cow => { keywords => 1, },
1894 keywords => $current{keywords},
1895 match => {},
1896 options => [],
1898 $inner{domain} = $current{domain};
1899 $inner{domain_family} = $current{domain_family};
1900 $inner{table} = $current{table};
1901 $inner{chain} = $inner{auto}{CHAIN} = $subchain;
1903 if (exists $current{protocol}) {
1904 $inner{protocol} = $current{protocol};
1905 $inner{protocol_index} = 0;
1906 append_option(%inner, 'protocol', $inner{protocol});
1909 # enter the block
1910 enter(1, \%inner);
1912 # now handle the parent - it's a jump to the sub chain
1913 $current{has_action} = 1;
1914 append_option(%current, 'jump', $subchain);
1916 $current{script} = { filename => $script->{filename},
1917 line => $script->{line},
1920 mkrules(\%current);
1922 # and clean up variables set in this level
1923 new_level(%current, $prev);
1925 next;
1928 # everything else must be part of a "real" rule, not just
1929 # "policy only"
1930 $current{has_rule}++;
1932 # extended parameters:
1933 if ($keyword =~ /^mod(?:ule)?$/) {
1934 foreach my $module (to_array getvalues) {
1935 next if exists $current{match}{$module};
1937 my $domain_family = $current{domain_family};
1938 my $defs = $match_defs{$domain_family}{$module};
1940 append_option(%current, 'match', $module);
1941 $current{match}{$module} = 1;
1943 merge_keywords(%current, $defs->{keywords})
1944 if defined $defs;
1947 next;
1950 # keywords from $current{keywords}
1952 if (exists $current{keywords}{$keyword}) {
1953 my $def = $current{keywords}{$keyword};
1954 parse_option($def, \%current, $keyword, \$negated);
1955 next;
1959 # actions
1962 # jump action
1963 if ($keyword eq 'jump') {
1964 error('There can only one action per rule')
1965 if exists $current{has_action};
1966 my $chain = getvar();
1967 if (my $defs = is_netfilter_module_target($current{domain_family}, $chain)) {
1968 set_module_target(%current, $chain, $defs);
1970 $current{has_action} = 1;
1971 append_option(%current, 'jump', $chain);
1972 next;
1975 # goto action
1976 if ($keyword eq 'realgoto') {
1977 error('There can only one action per rule')
1978 if exists $current{has_action};
1979 append_option(%current, 'goto', getvar());
1980 $current{has_action} = 1;
1981 next;
1984 # action keywords
1985 if (is_netfilter_core_target($keyword)) {
1986 error('There can only one action per rule')
1987 if exists $current{has_action};
1988 $current{has_action} = 1;
1989 append_option(%current, 'jump', $keyword);
1990 next;
1993 if ($keyword eq 'NOP') {
1994 error('There can only one action per rule')
1995 if exists $current{has_action};
1996 $current{has_action} = 1;
1997 next;
2000 if (my $defs = is_netfilter_module_target($current{domain_family}, $keyword)) {
2001 error('There can only one action per rule')
2002 if exists $current{has_action};
2004 set_module_target(%current, $keyword, $defs);
2005 $current{has_action} = 1;
2006 append_option(%current, 'jump', $keyword);
2007 next;
2010 my $proto = $current{protocol};
2013 # protocol specific options
2016 if ($keyword eq 'proto') {
2017 my $protocol = parse_keyword(\%current,
2018 { params => 1, negation => 1 },
2019 'proto', \$negated);
2020 $current{protocol} = $protocol;
2021 $current{protocol_index} = scalar(@{$current{options}});
2022 append_option(%current, 'protocol', $current{protocol});
2024 unless (ref $protocol) {
2025 $protocol = netfilter_canonical_protocol($protocol);
2026 my $domain_family = $current{domain_family};
2027 my $defs = $proto_defs{$domain_family}{$protocol};
2028 if (defined $defs) {
2029 merge_keywords(%current, $defs->{keywords});
2030 my $module = netfilter_protocol_module($protocol);
2031 $current{match}{$module} = 1;
2034 next;
2037 # port switches
2038 if ($keyword =~ /^[sd]port$/) {
2039 error('To use sport or dport, you have to specify "proto tcp" or "proto udp" first')
2040 unless defined $proto and grep { /^(?:tcp|udp|udplite|dccp|sctp)$/ } to_array $proto;
2042 append_option(%current, $keyword,
2043 getvalues(undef, undef,
2044 allow_negation => 1));
2045 next;
2048 # default
2049 error("Unrecognized keyword: $keyword");
2052 # if the rule didn't reset the negated flag, it's not
2053 # supported
2054 error("Doesn't support negation: $keyword")
2055 if $negated;
2058 error('Missing "}" at end of file')
2059 if $lev > $base_level;
2061 # consistency check: check if they havn't forgotten
2062 # the ';' before the last statement
2063 error("Missing semicolon before end of file")
2064 if exists $current{domain};
2067 sub execute_command {
2068 my ($command, $script) = @_;
2070 print LINES "$command\n"
2071 if $option{lines};
2072 return if $option{noexec};
2074 my $ret = system($command);
2075 unless ($ret == 0) {
2076 if ($? == -1) {
2077 print STDERR "failed to execute: $!\n";
2078 exit 1;
2079 } elsif ($? & 0x7f) {
2080 printf STDERR "child died with signal %d\n", $? & 0x7f;
2081 return 1;
2082 } else {
2083 print STDERR "(rule declared in $script->{filename}:$script->{line})\n"
2084 if defined $script;
2085 return $? >> 8;
2089 return;
2092 sub execute_slow($$) {
2093 my ($domain, $domain_info) = @_;
2095 my $domain_cmd = $domain_info->{tools}{tables};
2097 my $status;
2098 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2099 my $table_cmd = "$domain_cmd -t $table";
2101 # reset chain policies
2102 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2103 next unless $chain_info->{builtin} or
2104 (not $table_info->{has_builtin} and
2105 is_netfilter_builtin_chain($table, $chain));
2106 $status ||= execute_command("$table_cmd -P $chain ACCEPT")
2107 unless $option{noflush};
2110 # clear
2111 unless ($option{noflush}) {
2112 $status ||= execute_command("$table_cmd -F");
2113 $status ||= execute_command("$table_cmd -X");
2116 next if $option{flush};
2118 # create chains / set policy
2119 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2120 if (exists $chain_info->{policy}) {
2121 $status ||= execute_command("$table_cmd -P $chain $chain_info->{policy}")
2122 unless $chain_info->{policy} eq 'ACCEPT';
2123 } elsif (not is_netfilter_builtin_chain($table, $chain)) {
2124 $status ||= execute_command("$table_cmd -N $chain");
2128 # dump rules
2129 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2130 my $chain_cmd = "$table_cmd -A $chain";
2131 foreach my $rule (@{$chain_info->{rules}}) {
2132 $status ||= execute_command($chain_cmd . $rule->{rule});
2137 return $status;
2140 sub rules_to_save($$) {
2141 my ($domain, $domain_info) = @_;
2143 # convert this into an iptables-save text
2144 my $result = "# Generated by ferm $VERSION on " . localtime() . "\n";
2146 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2147 # select table
2148 $result .= '*' . $table . "\n";
2150 # create chains / set policy
2151 foreach my $chain (sort keys %{$table_info->{chains}}) {
2152 my $chain_info = $table_info->{chains}{$chain};
2153 my $policy = $option{flush} ? 'ACCEPT' : $chain_info->{policy};
2154 unless (defined $policy) {
2155 if (is_netfilter_builtin_chain($table, $chain)) {
2156 $policy = 'ACCEPT';
2157 } else {
2158 $policy = '-';
2161 $result .= ":$chain $policy\ [0:0]\n";
2164 next if $option{flush};
2166 # dump rules
2167 foreach my $chain (sort keys %{$table_info->{chains}}) {
2168 my $chain_info = $table_info->{chains}{$chain};
2169 foreach my $rule (@{$chain_info->{rules}}) {
2170 $result .= "-A $chain$rule->{rule}\n";
2174 # do it
2175 $result .= "COMMIT\n";
2178 return $result;
2181 sub restore_domain($$) {
2182 my ($domain, $save) = @_;
2184 my $path = $domains{$domain}{tools}{'tables-restore'};
2186 local *RESTORE;
2187 open RESTORE, "|$path"
2188 or die "Failed to run $path: $!\n";
2190 print RESTORE $save;
2192 close RESTORE
2193 or die "Failed to run $path\n";
2196 sub execute_fast($$) {
2197 my ($domain, $domain_info) = @_;
2199 my $save = rules_to_save($domain, $domain_info);
2201 if ($option{lines}) {
2202 print LINES "$domain_info->{tools}{'tables-restore'} <<EOT\n"
2203 if $option{shell};
2204 print LINES $save;
2205 print LINES "EOT\n"
2206 if $option{shell};
2209 return if $option{noexec};
2211 eval {
2212 restore_domain($domain, $save);
2214 if ($@) {
2215 print STDERR $@;
2216 return 1;
2219 return;
2222 sub rollback() {
2223 my $error;
2224 while (my ($domain, $domain_info) = each %domains) {
2225 next unless $domain_info->{enabled};
2226 unless (defined $domain_info->{tools}{'tables-restore'}) {
2227 print STDERR "Cannot rollback domain '$domain' because there is no ${domain}tables-restore\n";
2228 next;
2231 my $reset = '';
2232 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2233 my $reset_chain = '';
2234 foreach my $chain (keys %{$table_info->{chains}{$table}}) {
2235 next unless is_netfilter_builtin_chain($table, $chain);
2236 $reset_chain .= ":${chain} ACCEPT [0:0]\n";
2238 $reset .= "*${table}\n${reset_chain}COMMIT\n"
2239 if length $reset_chain;
2242 $reset .= $domain_info->{previous}
2243 if defined $domain_info->{previous};
2245 restore_domain($domain, $reset);
2248 print STDERR "\nFirewall rules rolled back.\n" unless $error;
2249 exit 1;
2252 sub alrm_handler {
2253 # do nothing, just interrupt a system call
2256 sub confirm_rules() {
2257 $SIG{ALRM} = \&alrm_handler;
2259 alarm(5);
2261 print STDERR "\n"
2262 . "ferm has applied the new firewall rules.\n"
2263 . "Please type 'yes' to confirm:\n";
2264 STDERR->flush();
2266 alarm(30);
2268 my $line = '';
2269 STDIN->sysread($line, 3);
2271 eval {
2272 require POSIX;
2273 POSIX::tcflush(*STDIN, 2);
2275 print STDERR "$@" if $@;
2277 $SIG{ALRM} = 'DEFAULT';
2279 return $line eq 'yes';
2282 # end of ferm
2284 __END__
2286 =head1 NAME
2288 ferm - a firewall rule parser for linux
2290 =head1 SYNOPSIS
2292 B<ferm> I<options> I<inputfiles>
2294 =head1 OPTIONS
2296 -n, --noexec Do not execute the rules, just simulate
2297 -F, --flush Flush all netfilter tables managed by ferm
2298 -l, --lines Show all rules that were created
2299 -i, --interactive Interactive mode: revert if user does not confirm
2300 --remote Remote mode; ignore host specific configuration.
2301 This implies --noexec and --lines.
2302 -V, --version Show current version number
2303 -h, --help Look at this text
2304 --fast Generate an iptables-save file, used by iptables-restore
2305 --shell Generate a shell script which calls iptables-restore
2306 --domain {ip|ip6} Handle only the specified domain
2307 --def '$name=v' Override a variable
2309 =cut