pass $name,$value to format_option()
[ferm.git] / src / ferm
blob08b4e8a45100ed7dd5da4fa245ed66fb5e95fc00
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 $rule = 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 = $rule->{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_format_option($$) {
1190 my ($keyword, $value) = @_;
1192 my $cmd = '';
1193 if (ref $value) {
1194 if (ref $value eq 'negated') {
1195 $value = $value->[0];
1196 $keyword .= ' !';
1197 } elsif (ref $value eq 'pre_negated') {
1198 $value = $value->[0];
1199 $cmd = ' !';
1203 unless (defined $value) {
1204 $cmd .= " --$keyword";
1205 } elsif (ref $value) {
1206 if (ref $value eq 'params') {
1207 $cmd .= " --$keyword ";
1208 $cmd .= join(' ', map { shell_escape($_) } @$value);
1209 } elsif (ref $value eq 'multi') {
1210 foreach (@$value) {
1211 $cmd .= " --$keyword " . shell_escape($_);
1213 } else {
1214 die;
1216 } else {
1217 $cmd .= " --$keyword " . shell_escape($value);
1220 return $cmd;
1223 sub format_option($$$) {
1224 my ($domain, $name, $value) = @_;
1225 $value = 'icmpv6' if $domain eq 'ip6' and $name eq 'protocol'
1226 and $value eq 'icmp';
1227 return shell_format_option($name, $value);
1230 sub printrule($$$) {
1231 my ($domain, $chain_rules, $rule) = @_;
1233 my $cmd = join('', map { format_option($domain, $_->[0], $_->[1]) }
1234 @{$rule->{options}});
1235 push @$chain_rules, { rule => $cmd,
1236 script => $rule->{script},
1240 sub mkrules2($$$) {
1241 my ($domain, $chain_rules, $rule) = @_;
1243 my @unfold;
1244 foreach my $option (@{$rule->{options}}) {
1245 push @unfold, $option
1246 if ref $option->[1] and ref $option->[1] eq 'ARRAY';
1249 sub dofr {
1250 my ($domain, $chain_rules, $rule) = (shift, shift, shift);
1251 my $option = shift;
1252 my @values = @{$option->[1]};
1254 foreach my $value (@values) {
1255 $option->[1] = $value;
1256 $rule->{protocol} = $value if $option->[0] eq 'protocol';
1258 if (@_) {
1259 dofr($domain, $chain_rules, $rule, @_);
1260 } else {
1261 printrule($domain, $chain_rules, $rule);
1265 $option->[1] = \@values;
1268 if (@unfold) {
1269 dofr($domain, $chain_rules, $rule, @unfold);
1270 } else {
1271 printrule($domain, $chain_rules, $rule);
1275 # convert a bunch of internal rule structures in iptables calls,
1276 # unfold arrays during that
1277 sub mkrules($) {
1278 my $rule = shift;
1280 foreach my $domain (to_array $rule->{domain}) {
1281 my $domain_info = $domains{$domain};
1282 $domain_info->{enabled} = 1;
1284 foreach my $table (to_array $rule->{table}) {
1285 my $table_info = $domain_info->{tables}{$table} ||= {};
1287 foreach my $chain (to_array $rule->{chain}) {
1288 my $chain_rules = $table_info->{chains}{$chain}{rules} ||= [];
1289 mkrules2($domain, $chain_rules, $rule)
1290 if $rule->{has_rule} and not $option{flush};
1296 sub filter_domains($) {
1297 my $domains = shift;
1298 my $result = [];
1300 foreach my $domain (to_array $domains) {
1301 next if exists $option{domain}
1302 and $domain ne $option{domain};
1304 eval {
1305 initialize_domain($domain);
1307 error($@) if $@;
1309 push @$result, $domain;
1312 return @$result == 1 ? $result->[0] : $result;
1315 # parse a keyword from a module definition
1316 sub parse_keyword($$$$) {
1317 my ($rule, $def, $keyword, $negated_ref) = @_;
1319 my $params = $def->{params};
1321 my $value;
1323 my $negated;
1324 if ($$negated_ref && exists $def->{pre_negation}) {
1325 $negated = 1;
1326 undef $$negated_ref;
1329 unless (defined $params) {
1330 undef $value;
1331 } elsif (ref $params && ref $params eq 'CODE') {
1332 $value = &$params($rule);
1333 } elsif ($params eq 'm') {
1334 $value = bless [ to_array getvalues() ], 'multi';
1335 } elsif ($params =~ /^[a-z]/) {
1336 if (exists $def->{negation} and not $negated) {
1337 my $token = peek_token();
1338 if ($token eq '!') {
1339 require_next_token;
1340 $negated = 1;
1344 my @params;
1345 foreach my $p (split(//, $params)) {
1346 if ($p eq 's') {
1347 push @params, getvar();
1348 } elsif ($p eq 'c') {
1349 my @v = to_array getvalues(undef, undef,
1350 non_empty => 1);
1351 push @params, join(',', @v);
1352 } else {
1353 die;
1357 $value = @params == 1
1358 ? $params[0]
1359 : bless \@params, 'params';
1360 } elsif ($params == 1) {
1361 if (exists $def->{negation} and not $negated) {
1362 my $token = peek_token();
1363 if ($token eq '!') {
1364 require_next_token;
1365 $negated = 1;
1369 $value = getvalues();
1371 warning("log-prefix is too long; truncating to 29 characters: '$1'")
1372 if $keyword eq 'log-prefix' && $value =~ s,^(.{29}).+$,$1,;
1373 } else {
1374 if (exists $def->{negation} and not $negated) {
1375 my $token = peek_token();
1376 if ($token eq '!') {
1377 require_next_token;
1378 $negated = 1;
1382 $value = bless [ map {
1383 getvar()
1384 } (1..$params) ], 'params';
1387 $value = bless [ $value ], exists $def->{pre_negation} ? 'pre_negated' : 'negated'
1388 if $negated;
1390 return $value;
1393 sub append_option(\%$$) {
1394 my ($rule, $name, $value) = @_;
1395 push @{$rule->{options}}, [ $name, $value ];
1398 # parse options of a module
1399 sub parse_option($$$$) {
1400 my ($def, $rule, $keyword, $negated_ref) = @_;
1402 while (exists $def->{alias}) {
1403 ($keyword, $def) = @{$def->{alias}};
1404 die unless defined $def;
1407 append_option(%$rule, $keyword,
1408 parse_keyword($rule, $def, $keyword, $negated_ref));
1409 return 1;
1412 sub copy_on_write($$) {
1413 my ($rule, $key) = @_;
1414 return unless exists $rule->{cow}{$key};
1415 $rule->{$key} = {%{$rule->{$key}}};
1416 delete $rule->{cow}{$key};
1419 sub new_level(\%$) {
1420 my ($rule, $prev) = @_;
1422 %$rule = ();
1423 if (defined $prev) {
1424 # copy data from previous level
1425 $rule->{cow} = { keywords => 1, };
1426 $rule->{keywords} = $prev->{keywords};
1427 $rule->{match} = { %{$prev->{match}} };
1428 $rule->{options} = [@{$prev->{options}}];
1429 foreach my $key (qw(domain domain_family table chain protocol has_action)) {
1430 $rule->{$key} = $prev->{$key}
1431 if exists $prev->{$key};
1433 } else {
1434 $rule->{cow} = {};
1435 $rule->{keywords} = {};
1436 $rule->{match} = {};
1437 $rule->{options} = [];
1441 sub merge_keywords(\%$) {
1442 my ($rule, $keywords) = @_;
1443 copy_on_write($rule, 'keywords');
1444 while (my ($name, $def) = each %$keywords) {
1445 $rule->{keywords}{$name} = $def;
1449 sub set_domain(\%$) {
1450 my ($rule, $domain) = @_;
1452 my $filtered_domain = filter_domains($domain);
1453 my $domain_family;
1454 unless (ref $domain) {
1455 $domain_family = $domain eq 'ip6' ? 'ip' : $domain;
1456 } elsif (@$domain == 0) {
1457 $domain_family = 'none';
1458 } elsif (grep { not /^ip6?$/s } @$domain) {
1459 error('Cannot combine non-IP domains');
1460 } else {
1461 $domain_family = 'ip';
1464 $rule->{domain_family} = $domain_family;
1465 $rule->{keywords} = $match_defs{$domain_family}{''}{keywords};
1466 $rule->{cow}{keywords} = 1;
1468 $rule->{domain} = $stack[0]{auto}{DOMAIN} = $filtered_domain;
1471 sub set_module_target(\%$$) {
1472 my ($rule, $name, $defs) = @_;
1474 if ($name eq 'TCPMSS') {
1475 my $protos = $rule->{protocol};
1476 error('No protocol specified before TCPMSS')
1477 unless defined $protos;
1478 foreach my $proto (to_array $protos) {
1479 error('TCPMSS not available for protocol "$proto"')
1480 unless $proto eq 'tcp';
1484 merge_keywords(%$rule, $defs->{keywords});
1487 # the main parser loop: read tokens, convert them into internal rule
1488 # structures
1489 sub enter($$) {
1490 my $lev = shift; # current recursion depth
1491 my $prev = shift; # previous rule hash
1493 # enter is the core of the firewall setup, it is a
1494 # simple parser program that recognizes keywords and
1495 # retreives parameters to set up the kernel routing
1496 # chains
1498 my $base_level = $script->{base_level} || 0;
1499 die if $base_level > $lev;
1501 my %rule;
1502 new_level(%rule, $prev);
1504 # read keywords 1 by 1 and dump into parser
1505 while (defined (my $keyword = next_token())) {
1506 # check if the current rule should be negated
1507 my $negated = $keyword eq '!';
1508 if ($negated) {
1509 # negation. get the next word which contains the 'real'
1510 # rule
1511 $keyword = getvar();
1513 error('unexpected end of file after negation')
1514 unless defined $keyword;
1517 # the core: parse all data
1518 for ($keyword)
1520 # deprecated keyword?
1521 if (exists $deprecated_keywords{$keyword}) {
1522 my $new_keyword = $deprecated_keywords{$keyword};
1523 warning("'$keyword' is deprecated, please use '$new_keyword' instead");
1524 $keyword = $new_keyword;
1527 # effectuation operator
1528 if ($keyword eq ';') {
1529 if ($rule{has_rule} and not exists $rule{has_action}) {
1530 # something is wrong when a rule was specified,
1531 # but no action
1532 error('No action defined; did you mean "NOP"?');
1535 error('No chain defined') unless exists $rule{chain};
1537 $rule{script} = { filename => $script->{filename},
1538 line => $script->{line},
1541 mkrules(\%rule);
1543 # and clean up variables set in this level
1544 new_level(%rule, $prev);
1546 next;
1549 # conditional expression
1550 if ($keyword eq '@if') {
1551 unless (eval_bool(getvalues)) {
1552 collect_tokens;
1553 my $token = peek_token();
1554 require_next_token() if $token and $token eq '@else';
1557 next;
1560 if ($keyword eq '@else') {
1561 # hack: if this "else" has not been eaten by the "if"
1562 # handler above, we believe it came from an if clause
1563 # which evaluated "true" - remove the "else" part now.
1564 collect_tokens;
1565 next;
1568 # hooks for custom shell commands
1569 if ($keyword eq 'hook') {
1570 error('"hook" must be the first token in a command')
1571 if exists $rule{domain};
1573 my $position = getvar();
1574 my $hooks;
1575 if ($position eq 'pre') {
1576 $hooks = \@pre_hooks;
1577 } elsif ($position eq 'post') {
1578 $hooks = \@post_hooks;
1579 } else {
1580 error("Invalid hook position: '$position'");
1583 push @$hooks, getvar();
1585 expect_token(';');
1586 next;
1589 # recursing operators
1590 if ($keyword eq '{') {
1591 # push stack
1592 my $old_stack_depth = @stack;
1594 unshift @stack, { auto => { %{$stack[0]{auto} || {}} } };
1596 # recurse
1597 enter($lev + 1, \%rule);
1599 # pop stack
1600 shift @stack;
1601 die unless @stack == $old_stack_depth;
1603 # after a block, the command is finished, clear this
1604 # level
1605 new_level(%rule, $prev);
1607 next;
1610 if ($keyword eq '}') {
1611 error('Unmatched "}"')
1612 if $lev <= $base_level;
1614 # consistency check: check if they havn't forgotten
1615 # the ';' before the last statement
1616 error('Missing semicolon before "}"')
1617 if $rule{has_rule};
1619 # and exit
1620 return;
1623 # include another file
1624 if ($keyword eq '@include' or $keyword eq 'include') {
1625 my @files = collect_filenames to_array getvalues;
1626 $keyword = next_token;
1627 error('Missing ";" - "include FILENAME" must be the last command in a rule')
1628 unless defined $keyword and $keyword eq ';';
1630 foreach my $filename (@files) {
1631 # save old script, open new script
1632 my $old_script = $script;
1633 open_script($filename);
1634 $script->{base_level} = $lev + 1;
1636 # push stack
1637 my $old_stack_depth = @stack;
1639 my $stack = {};
1641 if (@stack > 0) {
1642 # include files may set variables for their parent
1643 $stack->{vars} = ($stack[0]{vars} ||= {});
1644 $stack->{functions} = ($stack[0]{functions} ||= {});
1645 $stack->{auto} = { %{ $stack[0]{auto} || {} } };
1648 unshift @stack, $stack;
1650 # parse the script
1651 enter($lev + 1, \%rule);
1653 # pop stack
1654 shift @stack;
1655 die unless @stack == $old_stack_depth;
1657 # restore old script
1658 $script = $old_script;
1661 next;
1664 # definition of a variable or function
1665 if ($keyword eq '@def' or $keyword eq 'def') {
1666 error('"def" must be the first token in a command')
1667 if $rule{has_rule};
1669 my $type = require_next_token();
1670 if ($type eq '$') {
1671 my $name = require_next_token();
1672 error('invalid variable name')
1673 unless $name =~ /^\w+$/;
1675 expect_token('=');
1677 my $value = getvalues(undef, undef, allow_negation => 1);
1679 expect_token(';');
1681 $stack[0]{vars}{$name} = $value
1682 unless exists $stack[-1]{vars}{$name};
1683 } elsif ($type eq '&') {
1684 my $name = require_next_token();
1685 error('invalid function name')
1686 unless $name =~ /^\w+$/;
1688 expect_token('(', 'function parameter list or "()" expected');
1690 my @params;
1691 while (1) {
1692 my $token = require_next_token();
1693 last if $token eq ')';
1695 if (@params > 0) {
1696 error('"," expected')
1697 unless $token eq ',';
1699 $token = require_next_token();
1702 error('"$" and parameter name expected')
1703 unless $token eq '$';
1705 $token = require_next_token();
1706 error('invalid function parameter name')
1707 unless $token =~ /^\w+$/;
1709 push @params, $token;
1712 my %function;
1714 $function{params} = \@params;
1716 expect_token('=');
1718 my $tokens = collect_tokens();
1719 $function{block} = 1 if grep { $_ eq '{' } @$tokens;
1720 $function{tokens} = $tokens;
1722 $stack[0]{functions}{$name} = \%function
1723 unless exists $stack[-1]{functions}{$name};
1724 } else {
1725 error('"$" (variable) or "&" (function) expected');
1728 next;
1731 # def references
1732 if ($keyword eq '$') {
1733 error('variable references are only allowed as keyword parameter');
1736 if ($keyword eq '&') {
1737 my $name = require_next_token;
1738 error('function name expected')
1739 unless $name =~ /^\w+$/;
1741 my $function;
1742 foreach (@stack) {
1743 $function = $_->{functions}{$name};
1744 last if defined $function;
1746 error("no such function: \&$name")
1747 unless defined $function;
1749 my $paramdef = $function->{params};
1750 die unless defined $paramdef;
1752 my @params = get_function_params(allow_negation => 1);
1754 error("Wrong number of parameters for function '\&$name': "
1755 . @$paramdef . " expected, " . @params . " given")
1756 unless @params == @$paramdef;
1758 my %vars;
1759 for (my $i = 0; $i < @params; $i++) {
1760 $vars{$paramdef->[$i]} = $params[$i];
1763 if ($function->{block}) {
1764 # block {} always ends the current rule, so if the
1765 # function contains a block, we have to require
1766 # the calling rule also ends here
1767 expect_token(';');
1770 my @tokens = @{$function->{tokens}};
1771 for (my $i = 0; $i < @tokens; $i++) {
1772 if ($tokens[$i] eq '$' and $i + 1 < @tokens and
1773 exists $vars{$tokens[$i + 1]}) {
1774 my @value = to_array($vars{$tokens[$i + 1]});
1775 @value = ('(', @value, ')')
1776 unless @tokens == 1;
1777 splice(@tokens, $i, 2, @value);
1778 $i += @value - 2;
1779 } elsif ($tokens[$i] =~ m,^"(.*)"$,) {
1780 $tokens[$i] =~ s,\$(\w+),exists $vars{$1} ? $vars{$1} : "\$$1",eg;
1784 unshift @{$script->{tokens}}, @tokens;
1786 next;
1789 # where to put the rule?
1790 if ($keyword eq 'domain') {
1791 error('Domain is already specified')
1792 if exists $rule{domain};
1794 set_domain(%rule, getvalues());
1795 next;
1798 if ($keyword eq 'table') {
1799 error('Table is already specified')
1800 if exists $rule{table};
1801 $rule{table} = $stack[0]{auto}{TABLE} = getvalues();
1803 set_domain(%rule, 'ip')
1804 unless exists $rule{domain};
1806 next;
1809 if ($keyword eq 'chain') {
1810 error('Chain is already specified')
1811 if exists $rule{chain};
1812 $rule{chain} = $stack[0]{auto}{CHAIN} = getvalues();
1814 # ferm 1.1 allowed lower case built-in chain names
1815 foreach (ref $rule{chain} ? @{$rule{chain}} : $rule{chain}) {
1816 error('Please write built-in chain names in upper case')
1817 if /^(?:input|forward|output|prerouting|postrouting)$/;
1820 set_domain(%rule, 'ip')
1821 unless exists $rule{domain};
1823 $rule{table} = 'filter'
1824 unless exists $rule{table};
1826 next;
1829 error('Chain must be specified')
1830 unless exists $rule{chain};
1832 # policy for built-in chain
1833 if ($keyword eq 'policy') {
1834 error('Cannot specify matches for policy')
1835 if $rule{has_rule};
1837 my $policy = getvar();
1838 error("Invalid policy target: $policy")
1839 unless $policy =~ /^(?:ACCEPT|DROP)$/;
1841 expect_token(';');
1843 foreach my $domain (to_array $rule{domain}) {
1844 foreach my $table (to_array $rule{table}) {
1845 foreach my $chain (to_array $rule{chain}) {
1846 $domains{$domain}{tables}{$table}{chains}{$chain}{policy} = $policy;
1851 new_level(%rule, $prev);
1852 next;
1855 # create a subchain
1856 if ($keyword eq '@subchain' or $keyword eq 'subchain') {
1857 error('Chain must be specified')
1858 unless exists $rule{chain};
1860 error('No rule specified before "@subchain"')
1861 unless $rule{has_rule};
1863 my $subchain;
1864 $keyword = next_token();
1866 if ($keyword =~ /^(["'])(.*)\1$/s) {
1867 $subchain = $2;
1868 $keyword = next_token();
1869 } else {
1870 $subchain = 'ferm_auto_' . ++$auto_chain;
1873 error('"{" or chain name expected after "@subchain"')
1874 unless $keyword eq '{';
1876 # create a deep copy of %rule, only containing values
1877 # which must be in the subchain
1878 my %inner = ( cow => { keywords => 1, },
1879 keywords => $rule{keywords},
1880 match => {},
1881 options => [],
1883 $inner{domain} = $rule{domain};
1884 $inner{domain_family} = $rule{domain_family};
1885 $inner{table} = $rule{table};
1886 $inner{chain} = $inner{auto}{CHAIN} = $subchain;
1888 if (exists $rule{protocol}) {
1889 $inner{protocol} = $rule{protocol};
1890 append_option(%inner, 'protocol', $inner{protocol});
1893 # enter the block
1894 enter(1, \%inner);
1896 # now handle the parent - it's a jump to the sub chain
1897 $rule{has_action} = 1;
1898 append_option(%rule, 'jump', $subchain);
1900 $rule{script} = { filename => $script->{filename},
1901 line => $script->{line},
1904 mkrules(\%rule);
1906 # and clean up variables set in this level
1907 new_level(%rule, $prev);
1909 next;
1912 # everything else must be part of a "real" rule, not just
1913 # "policy only"
1914 $rule{has_rule}++;
1916 # extended parameters:
1917 if ($keyword =~ /^mod(?:ule)?$/) {
1918 foreach my $module (to_array getvalues) {
1919 next if exists $rule{match}{$module};
1921 my $domain_family = $rule{domain_family};
1922 my $defs = $match_defs{$domain_family}{$module};
1924 append_option(%rule, 'match', $module);
1925 $rule{match}{$module} = 1;
1927 merge_keywords(%rule, $defs->{keywords})
1928 if defined $defs;
1931 next;
1934 # keywords from $rule{keywords}
1936 if (exists $rule{keywords}{$keyword}) {
1937 my $def = $rule{keywords}{$keyword};
1938 parse_option($def, \%rule, $keyword, \$negated);
1939 next;
1943 # actions
1946 # jump action
1947 if ($keyword eq 'jump') {
1948 error('There can only one action per rule')
1949 if exists $rule{has_action};
1950 my $chain = getvar();
1951 if (my $defs = is_netfilter_module_target($rule{domain_family}, $chain)) {
1952 set_module_target(%rule, $chain, $defs);
1954 $rule{has_action} = 1;
1955 append_option(%rule, 'jump', $chain);
1956 next;
1959 # goto action
1960 if ($keyword eq 'realgoto') {
1961 error('There can only one action per rule')
1962 if exists $rule{has_action};
1963 append_option(%rule, 'goto', getvar());
1964 $rule{has_action} = 1;
1965 next;
1968 # action keywords
1969 if (is_netfilter_core_target($keyword)) {
1970 error('There can only one action per rule')
1971 if exists $rule{has_action};
1972 $rule{has_action} = 1;
1973 append_option(%rule, 'jump', $keyword);
1974 next;
1977 if ($keyword eq 'NOP') {
1978 error('There can only one action per rule')
1979 if exists $rule{has_action};
1980 $rule{has_action} = 1;
1981 next;
1984 if (my $defs = is_netfilter_module_target($rule{domain_family}, $keyword)) {
1985 error('There can only one action per rule')
1986 if exists $rule{has_action};
1988 set_module_target(%rule, $keyword, $defs);
1989 $rule{has_action} = 1;
1990 append_option(%rule, 'jump', $keyword);
1991 next;
1994 my $proto = $rule{protocol};
1997 # protocol specific options
2000 if ($keyword eq 'proto') {
2001 my $protocol = parse_keyword(\%rule,
2002 { params => 1, negation => 1 },
2003 'proto', \$negated);
2004 $rule{protocol} = $protocol;
2005 append_option(%rule, 'protocol', $rule{protocol});
2007 unless (ref $protocol) {
2008 $protocol = netfilter_canonical_protocol($protocol);
2009 my $domain_family = $rule{domain_family};
2010 my $defs = $proto_defs{$domain_family}{$protocol};
2011 if (defined $defs) {
2012 merge_keywords(%rule, $defs->{keywords});
2013 my $module = netfilter_protocol_module($protocol);
2014 $rule{match}{$module} = 1;
2017 next;
2020 # port switches
2021 if ($keyword =~ /^[sd]port$/) {
2022 error('To use sport or dport, you have to specify "proto tcp" or "proto udp" first')
2023 unless defined $proto and grep { /^(?:tcp|udp|udplite|dccp|sctp)$/ } to_array $proto;
2025 append_option(%rule, $keyword,
2026 getvalues(undef, undef,
2027 allow_negation => 1));
2028 next;
2031 # default
2032 error("Unrecognized keyword: $keyword");
2035 # if the rule didn't reset the negated flag, it's not
2036 # supported
2037 error("Doesn't support negation: $keyword")
2038 if $negated;
2041 error('Missing "}" at end of file')
2042 if $lev > $base_level;
2044 # consistency check: check if they havn't forgotten
2045 # the ';' before the last statement
2046 error("Missing semicolon before end of file")
2047 if exists $rule{domain};
2050 sub execute_command {
2051 my ($command, $script) = @_;
2053 print LINES "$command\n"
2054 if $option{lines};
2055 return if $option{noexec};
2057 my $ret = system($command);
2058 unless ($ret == 0) {
2059 if ($? == -1) {
2060 print STDERR "failed to execute: $!\n";
2061 exit 1;
2062 } elsif ($? & 0x7f) {
2063 printf STDERR "child died with signal %d\n", $? & 0x7f;
2064 return 1;
2065 } else {
2066 print STDERR "(rule declared in $script->{filename}:$script->{line})\n"
2067 if defined $script;
2068 return $? >> 8;
2072 return;
2075 sub execute_slow($$) {
2076 my ($domain, $domain_info) = @_;
2078 my $domain_cmd = $domain_info->{tools}{tables};
2080 my $status;
2081 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2082 my $table_cmd = "$domain_cmd -t $table";
2084 # reset chain policies
2085 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2086 next unless $chain_info->{builtin} or
2087 (not $table_info->{has_builtin} and
2088 is_netfilter_builtin_chain($table, $chain));
2089 $status ||= execute_command("$table_cmd -P $chain ACCEPT")
2090 unless $option{noflush};
2093 # clear
2094 unless ($option{noflush}) {
2095 $status ||= execute_command("$table_cmd -F");
2096 $status ||= execute_command("$table_cmd -X");
2099 next if $option{flush};
2101 # create chains / set policy
2102 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2103 if (exists $chain_info->{policy}) {
2104 $status ||= execute_command("$table_cmd -P $chain $chain_info->{policy}")
2105 unless $chain_info->{policy} eq 'ACCEPT';
2106 } elsif (not is_netfilter_builtin_chain($table, $chain)) {
2107 $status ||= execute_command("$table_cmd -N $chain");
2111 # dump rules
2112 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2113 my $chain_cmd = "$table_cmd -A $chain";
2114 foreach my $rule (@{$chain_info->{rules}}) {
2115 $status ||= execute_command($chain_cmd . $rule->{rule});
2120 return $status;
2123 sub rules_to_save($$) {
2124 my ($domain, $domain_info) = @_;
2126 # convert this into an iptables-save text
2127 my $result = "# Generated by ferm $VERSION on " . localtime() . "\n";
2129 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2130 # select table
2131 $result .= '*' . $table . "\n";
2133 # create chains / set policy
2134 foreach my $chain (sort keys %{$table_info->{chains}}) {
2135 my $chain_info = $table_info->{chains}{$chain};
2136 my $policy = $option{flush} ? 'ACCEPT' : $chain_info->{policy};
2137 unless (defined $policy) {
2138 if (is_netfilter_builtin_chain($table, $chain)) {
2139 $policy = 'ACCEPT';
2140 } else {
2141 $policy = '-';
2144 $result .= ":$chain $policy\ [0:0]\n";
2147 next if $option{flush};
2149 # dump rules
2150 foreach my $chain (sort keys %{$table_info->{chains}}) {
2151 my $chain_info = $table_info->{chains}{$chain};
2152 foreach my $rule (@{$chain_info->{rules}}) {
2153 $result .= "-A $chain$rule->{rule}\n";
2157 # do it
2158 $result .= "COMMIT\n";
2161 return $result;
2164 sub restore_domain($$) {
2165 my ($domain, $save) = @_;
2167 my $path = $domains{$domain}{tools}{'tables-restore'};
2169 local *RESTORE;
2170 open RESTORE, "|$path"
2171 or die "Failed to run $path: $!\n";
2173 print RESTORE $save;
2175 close RESTORE
2176 or die "Failed to run $path\n";
2179 sub execute_fast($$) {
2180 my ($domain, $domain_info) = @_;
2182 my $save = rules_to_save($domain, $domain_info);
2184 if ($option{lines}) {
2185 print LINES "$domain_info->{tools}{'tables-restore'} <<EOT\n"
2186 if $option{shell};
2187 print LINES $save;
2188 print LINES "EOT\n"
2189 if $option{shell};
2192 return if $option{noexec};
2194 eval {
2195 restore_domain($domain, $save);
2197 if ($@) {
2198 print STDERR $@;
2199 return 1;
2202 return;
2205 sub rollback() {
2206 my $error;
2207 while (my ($domain, $domain_info) = each %domains) {
2208 next unless $domain_info->{enabled};
2209 unless (defined $domain_info->{tools}{'tables-restore'}) {
2210 print STDERR "Cannot rollback domain '$domain' because there is no ${domain}tables-restore\n";
2211 next;
2214 my $reset = '';
2215 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2216 my $reset_chain = '';
2217 foreach my $chain (keys %{$table_info->{chains}{$table}}) {
2218 next unless is_netfilter_builtin_chain($table, $chain);
2219 $reset_chain .= ":${chain} ACCEPT [0:0]\n";
2221 $reset .= "*${table}\n${reset_chain}COMMIT\n"
2222 if length $reset_chain;
2225 $reset .= $domain_info->{previous}
2226 if defined $domain_info->{previous};
2228 restore_domain($domain, $reset);
2231 print STDERR "\nFirewall rules rolled back.\n" unless $error;
2232 exit 1;
2235 sub alrm_handler {
2236 # do nothing, just interrupt a system call
2239 sub confirm_rules() {
2240 $SIG{ALRM} = \&alrm_handler;
2242 alarm(5);
2244 print STDERR "\n"
2245 . "ferm has applied the new firewall rules.\n"
2246 . "Please type 'yes' to confirm:\n";
2247 STDERR->flush();
2249 alarm(30);
2251 my $line = '';
2252 STDIN->sysread($line, 3);
2254 eval {
2255 require POSIX;
2256 POSIX::tcflush(*STDIN, 2);
2258 print STDERR "$@" if $@;
2260 $SIG{ALRM} = 'DEFAULT';
2262 return $line eq 'yes';
2265 # end of ferm
2267 __END__
2269 =head1 NAME
2271 ferm - a firewall rule parser for linux
2273 =head1 SYNOPSIS
2275 B<ferm> I<options> I<inputfiles>
2277 =head1 OPTIONS
2279 -n, --noexec Do not execute the rules, just simulate
2280 -F, --flush Flush all netfilter tables managed by ferm
2281 -l, --lines Show all rules that were created
2282 -i, --interactive Interactive mode: revert if user does not confirm
2283 --remote Remote mode; ignore host specific configuration.
2284 This implies --noexec and --lines.
2285 -V, --version Show current version number
2286 -h, --help Look at this text
2287 --fast Generate an iptables-save file, used by iptables-restore
2288 --shell Generate a shell script which calls iptables-restore
2289 --domain {ip|ip6} Handle only the specified domain
2290 --def '$name=v' Override a variable
2292 =cut