eliminated get_builtin_keywords()
[ferm.git] / src / ferm
blob904606d6b3e0d5990a463cdaa614e5455f362b55
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_verbose, $opt_debug,
404 $opt_help,
405 $opt_version, $opt_test, $opt_fast, $opt_shell,
406 $opt_domain);
408 Getopt::Long::Configure('bundling', 'auto_help', 'no_ignore_case',
409 'no_auto_abbrev');
411 sub opt_def {
412 my ($opt, $value) = @_;
413 die 'Invalid --def specification'
414 unless $value =~ /^\$?(\w+)=(.*)$/s;
415 my ($name, $unparsed_value) = ($1, $2);
416 my $tokens = tokenize_string($unparsed_value);
417 my $value = getvalues(\&next_array_token, $tokens);
418 die 'Extra tokens after --def'
419 if @$tokens > 0;
420 $stack[0]{vars}{$name} = $value;
423 local $SIG{__WARN__} = sub { die $_[0]; };
424 GetOptions('noexec|n' => \$opt_noexec,
425 'flush|F' => \$opt_flush,
426 'noflush' => \$opt_noflush,
427 'lines|l' => \$opt_lines,
428 'interactive|i' => \$opt_interactive,
429 'verbose|v' => \$opt_verbose,
430 'debug|d' => \$opt_debug,
431 'help|h' => \$opt_help,
432 'version|V' => \$opt_version,
433 test => \$opt_test,
434 remote => \$opt_test,
435 fast => \$opt_fast,
436 shell => \$opt_shell,
437 'domain=s' => \$opt_domain,
438 'def=s' => \&opt_def,
441 if (defined $opt_help) {
442 require Pod::Usage;
443 Pod::Usage::pod2usage(-exitstatus => 0);
446 if (defined $opt_version) {
447 printversion();
448 exit 0;
451 $option{'noexec'} = (defined $opt_noexec);
452 $option{flush} = defined $opt_flush;
453 $option{noflush} = defined $opt_noflush;
454 $option{'lines'} = (defined $opt_lines);
455 $option{interactive} = (defined $opt_interactive);
456 $option{test} = (defined $opt_test);
458 if ($option{test}) {
459 $option{noexec} = 1;
460 $option{lines} = 1;
463 delete $option{interactive} if $option{noexec};
465 mydie('ferm interactive mode not possible: /dev/stdin is not a tty')
466 if $option{interactive} and not -t STDIN;
467 mydie('ferm interactive mode not possible: /dev/stderr is not a tty')
468 if $option{interactive} and not -t STDERR;
470 $option{fast} = 1 if defined $opt_fast;
472 if (defined $opt_shell) {
473 $option{$_} = 1 foreach qw(shell fast lines);
476 $option{domain} = $opt_domain if defined $opt_domain;
478 print STDERR "Warning: ignoring the obsolete --debug option\n"
479 if defined $opt_debug;
480 print STDERR "Warning: ignoring the obsolete --verbose option\n"
481 if defined $opt_verbose;
482 } else {
483 # tiny getopt emulation for microperl
484 my $filename;
485 foreach (@ARGV) {
486 if ($_ eq '--noexec' or $_ eq '-n') {
487 $option{noexec} = 1;
488 } elsif ($_ eq '--lines' or $_ eq '-l') {
489 $option{lines} = 1;
490 } elsif ($_ eq '--fast') {
491 $option{fast} = 1;
492 } elsif ($_ eq '--test') {
493 $option{test} = 1;
494 $option{noexec} = 1;
495 $option{lines} = 1;
496 } elsif ($_ eq '--shell') {
497 $option{$_} = 1 foreach qw(shell fast lines);
498 } elsif (/^-/) {
499 printf STDERR "Usage: ferm [--noexec] [--lines] [--fast] [--shell] FILENAME\n";
500 exit 1;
501 } else {
502 $filename = $_;
505 undef @ARGV;
506 push @ARGV, $filename;
509 unless (@ARGV == 1) {
510 require Pod::Usage;
511 Pod::Usage::pod2usage(-exitstatus => 1);
514 if ($has_strict) {
515 open LINES, ">&STDOUT" if $option{lines};
516 open STDOUT, ">&STDERR" if $option{shell};
517 } else {
518 # microperl can't redirect file handles
519 *LINES = *STDOUT;
521 if ($option{fast} and not $option{noexec}) {
522 print STDERR "Sorry, ferm on microperl does not allow --fast without --noexec\n";
523 exit 1
527 unshift @stack, {};
528 open_script($ARGV[0]);
530 # parse all input recursively
531 enter(0);
532 die unless @stack == 2;
534 # execute all generated rules
535 my $status;
537 foreach my $cmd (@pre_hooks) {
538 print LINES "$cmd\n" if $option{lines};
539 system($cmd) unless $option{noexec};
542 while (my ($domain, $domain_info) = each %domains) {
543 next unless $domain_info->{enabled};
544 my $s = $option{fast} &&
545 defined $domain_info->{tools}{'tables-restore'}
546 ? execute_fast($domain, $domain_info)
547 : execute_slow($domain, $domain_info);
548 $status = $s if defined $s;
551 foreach my $cmd (@post_hooks) {
552 print "$cmd\n" if $option{lines};
553 system($cmd) unless $option{noexec};
556 if (defined $status) {
557 rollback();
558 exit $status;
561 # ask user, and rollback if there is no confirmation
563 confirm_rules() or rollback() if $option{interactive};
565 exit 0;
567 # end of program execution!
570 # funcs
572 sub printversion {
573 print "ferm $VERSION\n";
574 print "Copyright (C) 2001-2008 Auke Kok, Max Kellermann\n";
575 print "This program is free software released under GPLv2.\n";
576 print "See the included COPYING file for license details.\n";
580 sub mydie {
581 print STDERR @_;
582 print STDERR "\n";
583 exit 1;
587 sub error {
588 # returns a nice formatted error message, showing the
589 # location of the error.
590 my $tabs = 0;
591 my @lines;
592 my $l = 0;
593 my @words = map { @$_ } @{$script->{past_tokens}};
595 for my $w ( 0 .. $#words ) {
596 if ($words[$w] eq "\x29")
597 { $l++ ; $lines[$l] = " " x ($tabs-- -1) ;};
598 if ($words[$w] eq "\x28")
599 { $l++ ; $lines[$l] = " " x $tabs++ ;};
600 if ($words[$w] eq "\x7d")
601 { $l++ ; $lines[$l] = " " x ($tabs-- -1) ;};
602 if ($words[$w] eq "\x7b")
603 { $l++ ; $lines[$l] = " " x $tabs++ ;};
604 if ( $l > $#lines ) { $lines[$l] = "" };
605 $lines[$l] .= $words[$w] . " ";
606 if ($words[$w] eq "\x28")
607 { $l++ ; $lines[$l] = " " x $tabs ;};
608 if (($words[$w] eq "\x29") && ($words[$w+1] ne "\x7b"))
609 { $l++ ; $lines[$l] = " " x $tabs ;};
610 if ($words[$w] eq "\x7b")
611 { $l++ ; $lines[$l] = " " x $tabs ;};
612 if (($words[$w] eq "\x7d") && ($words[$w+1] ne "\x7d"))
613 { $l++ ; $lines[$l] = " " x $tabs ;};
614 if (($words[$w] eq "\x3b") && ($words[$w+1] ne "\x7d"))
615 { $l++ ; $lines[$l] = " " x $tabs ;}
616 if ($words[$w-1] eq "option")
617 { $l++ ; $lines[$l] = " " x $tabs ;}
619 my $start = $#lines - 4;
620 if ($start < 0) { $start = 0 } ;
621 print STDERR "Error in $script->{filename} line $script->{line}:\n";
622 for $l ( $start .. $#lines)
623 { print STDERR $lines[$l]; if ($l != $#lines ) {print STDERR "\n"} ; };
624 print STDERR "<--\n";
625 mydie(@_);
628 # print a warning message about code from an input file
629 sub warning {
630 print STDERR "Warning in $script->{filename} line $script->{line}: "
631 . (shift) . "\n";
634 sub find_tool($) {
635 my $name = shift;
636 return $name if $option{test};
637 for my $path ('/sbin', split ':', $ENV{PATH}) {
638 my $ret = "$path/$name";
639 return $ret if -x $ret;
641 die "$name not found in PATH\n";
644 sub initialize_domain {
645 my $domain = shift;
646 my $domain_info = $domains{$domain} ||= {};
648 return if exists $domain_info->{initialized};
650 die "Invalid domain '$domain'\n" unless $domain =~ /^(?:ip6?|arp|eb)$/;
652 my @tools = qw(tables);
653 push @tools, qw(tables-save tables-restore)
654 if $domain =~ /^ip6?$/;
656 # determine the location of this domain's tools
657 my %tools = map { $_ => find_tool($domain . $_) } @tools;
658 $domain_info->{tools} = \%tools;
660 # make tables-save tell us about the state of this domain
661 # (which tables and chains do exist?), also remember the old
662 # save data which may be used later by the rollback function
663 local *SAVE;
664 if (!$option{test} &&
665 exists $tools{'tables-save'} &&
666 open(SAVE, "$tools{'tables-save'}|")) {
667 my $save = '';
669 my $table_info;
670 while (<SAVE>) {
671 $save .= $_;
673 if (/^\*(\w+)/) {
674 my $table = $1;
675 $table_info = $domain_info->{tables}{$table} ||= {};
676 } elsif (defined $table_info and /^:(\w+)\s+(\S+)/
677 and $2 ne '-') {
678 $table_info->{chains}{$1}{builtin} = 1;
679 $table_info->{has_builtin} = 1;
683 # for rollback
684 $domain_info->{previous} = $save;
687 $domain_info->{initialized} = 1;
690 # split the an input string into words and delete comments
691 sub tokenize_string($) {
692 my $string = shift;
694 my @ret;
696 foreach my $word ($string =~ m/(".*?"|'.*?'|`.*?`|[!,=&\$\%\(\){};]|[-+\w\/\.:]+|@\w+|#)/g) {
697 last if $word eq '#';
698 push @ret, $word;
701 return \@ret;
704 # shift an array; helper function to be passed to &getvar / &getvalues
705 sub next_array_token {
706 my $array = shift;
707 shift @$array;
710 # read some more tokens from the input file into a buffer
711 sub prepare_tokens() {
712 my $tokens = $script->{tokens};
713 while (@$tokens == 0) {
714 my $handle = $script->{handle};
715 my $line = <$handle>;
716 return unless defined $line;
718 $script->{line} ++;
720 # the next parser stage eats this
721 push @$tokens, @{tokenize_string($line)};
724 return 1;
727 # open a ferm sub script
728 sub open_script($) {
729 my $filename = shift;
731 for (my $s = $script; defined $s; $s = $s->{parent}) {
732 mydie("Circular reference in $script->{filename} line $script->{line}: $filename")
733 if $s->{filename} eq $filename;
736 local *FILE;
737 open FILE, "<$filename"
738 or mydie("Failed to open $filename: $!");
739 my $handle = *FILE;
741 $script = { filename => $filename,
742 handle => $handle,
743 line => 0,
744 past_tokens => [],
745 tokens => [],
746 parent => $script,
749 return $script;
752 # collect script filenames which are being included
753 sub collect_filenames(@) {
754 my @ret;
756 # determine the current script's parent directory for relative
757 # file names
758 die unless defined $script;
759 my $parent_dir = $script->{filename} =~ m,^(.*/),
760 ? $1 : './';
762 foreach my $pathname (@_) {
763 # non-absolute file names are relative to the parent script's
764 # file name
765 $pathname = $parent_dir . $pathname
766 unless $pathname =~ m,^/,;
768 if ($pathname =~ m,/$,) {
769 # include all regular files in a directory
771 error("'$pathname' is not a directory")
772 unless -d $pathname;
774 local *DIR;
775 opendir DIR, $pathname
776 or error("Failed to open directory '$pathname': $!");
777 my @names = readdir DIR;
778 closedir DIR;
780 # sort those names for a well-defined order
781 foreach my $name (sort { $a cmp $b } @names) {
782 # don't include hidden and backup files
783 next if /^\.|~$/;
785 my $filename = $pathname . $name;
786 push @ret, $filename
787 if -f $filename;
789 } elsif ($pathname =~ m,\|$,) {
790 # run a program and use its output
791 push @ret, $pathname;
792 } elsif ($pathname =~ m,^\|,) {
793 error('This kind of pipe is not allowed');
794 } else {
795 # include a regular file
797 error("'$pathname' is a directory; maybe use trailing '/' to include a directory?")
798 if -d $pathname;
799 error("'$pathname' is not a file")
800 unless -f $pathname;
802 push @ret, $pathname;
806 return @ret;
809 # peek a token from the queue, but don't remove it
810 sub peek_token() {
811 return unless prepare_tokens();
812 return $script->{tokens}[0];
815 # get a token from the queue
816 sub next_token() {
817 return unless prepare_tokens();
818 my $token = shift @{$script->{tokens}};
820 # update $script->{past_tokens}
821 my $past_tokens = $script->{past_tokens};
823 if (@$past_tokens > 0) {
824 my $prev_token = $past_tokens->[-1][-1];
825 $past_tokens->[-1] = @$past_tokens > 1 ? ['{'] : []
826 if $prev_token eq ';';
827 pop @$past_tokens
828 if $prev_token eq '}';
831 push @$past_tokens, [] if $token eq '{' or @$past_tokens == 0;
832 push @{$past_tokens->[-1]}, $token;
834 # return
835 return $token;
838 sub expect_token($;$) {
839 my $expect = shift;
840 my $msg = shift;
841 my $token = next_token();
842 error($msg || "'$expect' expected")
843 unless defined $token and $token eq $expect;
846 # require that another token exists, and that it's not a "special"
847 # token, e.g. ";" and "{"
848 sub require_next_token {
849 my $code = shift || \&next_token;
851 my $token = &$code(@_);
853 error('unexpected end of file')
854 unless defined $token;
856 error("'$token' not allowed here")
857 if $token =~ /^[;{}]$/;
859 return $token;
862 # return the value of a variable
863 sub variable_value($) {
864 my $name = shift;
866 foreach (@stack) {
867 return $_->{vars}{$name}
868 if exists $_->{vars}{$name};
871 return $stack[0]{auto}{$name}
872 if exists $stack[0]{auto}{$name};
874 return;
877 # determine the value of a variable, die if the value is an array
878 sub string_variable_value($) {
879 my $name = shift;
880 my $value = variable_value($name);
882 error("variable '$name' must be a string, but it is an array")
883 if ref $value;
885 return $value;
888 # similar to the built-in "join" function, but also handle negated
889 # values in a special way
890 sub join_value($$) {
891 my ($expr, $value) = @_;
893 unless (ref $value) {
894 return $value;
895 } elsif (ref $value eq 'ARRAY') {
896 return join($expr, @$value);
897 } elsif (ref $value eq 'negated') {
898 # bless'negated' is a special marker for negated values
899 $value = join_value($expr, $value->[0]);
900 return bless [ $value ], 'negated';
901 } else {
902 die;
906 # returns the next parameter, which may either be a scalar or an array
907 sub getvalues {
908 my ($code, $param) = (shift, shift);
909 my %options = @_;
911 my $token = require_next_token($code, $param);
913 if ($token eq '(') {
914 # read an array until ")"
915 my @wordlist;
917 for (;;) {
918 $token = getvalues($code, $param,
919 parenthesis_allowed => 1,
920 comma_allowed => 1);
922 unless (ref $token) {
923 last if $token eq ')';
925 if ($token eq ',') {
926 error('Comma is not allowed within arrays, please use only a space');
927 next;
930 push @wordlist, $token;
931 } elsif (ref $token eq 'ARRAY') {
932 push @wordlist, @$token;
933 } else {
934 error('unknown toke type');
938 error('empty array not allowed here')
939 unless @wordlist or not $options{non_empty};
941 return @wordlist == 1
942 ? $wordlist[0]
943 : \@wordlist;
944 } elsif ($token =~ /^\`(.*)\`$/s) {
945 # execute a shell command, insert output
946 my $command = $1;
947 my $output = `$command`;
948 unless ($? == 0) {
949 if ($? == -1) {
950 error("failed to execute: $!");
951 } elsif ($? & 0x7f) {
952 error("child died with signal " . ($? & 0x7f));
953 } elsif ($? >> 8) {
954 error("child exited with status " . ($? >> 8));
958 # remove comments
959 $output =~ s/#.*//mg;
961 # tokenize
962 my @tokens = grep { length } split /\s+/s, $output;
964 my @values;
965 while (@tokens) {
966 my $value = getvalues(\&next_array_token, \@tokens);
967 push @values, to_array($value);
970 # and recurse
971 return @values == 1
972 ? $values[0]
973 : \@values;
974 } elsif ($token =~ /^\'(.*)\'$/s) {
975 # single quotes: a string
976 return $1;
977 } elsif ($token =~ /^\"(.*)\"$/s) {
978 # double quotes: a string with escapes
979 $token = $1;
980 $token =~ s,\$(\w+),string_variable_value($1),eg;
981 return $token;
982 } elsif ($token eq '!') {
983 error('negation is not allowed here')
984 unless $options{allow_negation};
986 $token = getvalues($code, $param);
988 error('it is not possible to negate an array')
989 if ref $token and not $options{allow_array_negation};
991 return bless [ $token ], 'negated';
992 } elsif ($token eq ',') {
993 return $token
994 if $options{comma_allowed};
996 error('comma is not allowed here');
997 } elsif ($token eq '=') {
998 error('equals operator ("=") is not allowed here');
999 } elsif ($token eq '$') {
1000 my $name = require_next_token($code, $param);
1001 error('variable name expected - if you want to concatenate strings, try using double quotes')
1002 unless $name =~ /^\w+$/;
1004 my $value = variable_value($name);
1006 error("no such variable: \$$name")
1007 unless defined $value;
1009 return $value;
1010 } elsif ($token eq '&') {
1011 error("function calls are not allowed as keyword parameter");
1012 } elsif ($token eq ')' and not $options{parenthesis_allowed}) {
1013 error('Syntax error');
1014 } elsif ($token =~ /^@/) {
1015 if ($token eq '@resolve') {
1016 my @params = get_function_params();
1017 error('Usage: @resolve((hostname ...))')
1018 unless @params == 1;
1019 eval { require Net::DNS; };
1020 error('For the @resolve() function, you need the Perl library Net::DNS')
1021 if $@;
1022 my $type = 'A';
1023 my $resolver = new Net::DNS::Resolver;
1024 my @result;
1025 foreach my $hostname (to_array($params[0])) {
1026 my $query = $resolver->search($hostname, $type);
1027 error("DNS query for '$hostname' failed: " . $resolver->errorstring)
1028 unless $query;
1029 foreach my $rr ($query->answer) {
1030 next unless $rr->type eq $type;
1031 push @result, $rr->address;
1034 return \@result;
1035 } else {
1036 error("unknown ferm built-in function");
1038 } else {
1039 return $token;
1043 # returns the next parameter, but only allow a scalar
1044 sub getvar {
1045 my $token = getvalues(@_);
1047 error('array not allowed here')
1048 if ref $token and ref $token eq 'ARRAY';
1050 return $token;
1053 sub get_function_params(%) {
1054 expect_token('(', 'function name must be followed by "()"');
1056 my $token = peek_token();
1057 if ($token eq ')') {
1058 require_next_token;
1059 return;
1062 my @params;
1064 while (1) {
1065 if (@params > 0) {
1066 $token = require_next_token();
1067 last
1068 if $token eq ')';
1070 error('"," expected')
1071 unless $token eq ',';
1074 push @params, getvalues(undef, undef, @_);
1077 return @params;
1080 # collect all tokens in a flat array reference until the end of the
1081 # command is reached
1082 sub collect_tokens() {
1083 my @level;
1084 my @tokens;
1086 while (1) {
1087 my $keyword = next_token();
1088 error('unexpected end of file within function/variable declaration')
1089 unless defined $keyword;
1091 if ($keyword =~ /^[\{\(]$/) {
1092 push @level, $keyword;
1093 } elsif ($keyword =~ /^[\}\)]$/) {
1094 my $expected = $keyword;
1095 $expected =~ tr/\}\)/\{\(/;
1096 my $opener = pop @level;
1097 error("unmatched '$keyword'")
1098 unless defined $opener and $opener eq $expected;
1099 } elsif ($keyword eq ';' and @level == 0) {
1100 last;
1103 push @tokens, $keyword;
1105 last
1106 if $keyword eq '}' and @level == 0;
1109 return \@tokens;
1113 # returns the specified value as an array. dereference arrayrefs
1114 sub to_array($) {
1115 my $value = shift;
1116 die unless wantarray;
1117 die if @_;
1118 unless (ref $value) {
1119 return $value;
1120 } elsif (ref $value eq 'ARRAY') {
1121 return @$value;
1122 } else {
1123 die;
1127 # evaluate the specified value as bool
1128 sub eval_bool($) {
1129 my $value = shift;
1130 die if wantarray;
1131 die if @_;
1132 unless (ref $value) {
1133 return $value;
1134 } elsif (ref $value eq 'ARRAY') {
1135 return @$value > 0;
1136 } else {
1137 die;
1141 sub is_netfilter_core_target($) {
1142 my $target = shift;
1143 die unless defined $target and length $target;
1145 return $target =~ /^(?:ACCEPT|DROP|RETURN|QUEUE)$/;
1148 sub is_netfilter_module_target($$) {
1149 my ($domain_family, $target) = @_;
1150 die unless defined $target and length $target;
1152 return defined $domain_family &&
1153 exists $target_defs{$domain_family} &&
1154 $target_defs{$domain_family}{$target};
1157 sub is_netfilter_builtin_chain($$) {
1158 my ($table, $chain) = @_;
1160 return grep { $_ eq $chain }
1161 qw(PREROUTING INPUT FORWARD OUTPUT POSTROUTING);
1164 sub netfilter_canonical_protocol($) {
1165 my $proto = shift;
1166 return 'icmpv6'
1167 if $proto eq 'ipv6-icmp';
1168 return 'mh'
1169 if $proto eq 'ipv6-mh';
1170 return $proto;
1173 sub netfilter_protocol_module($) {
1174 my $proto = shift;
1175 return unless defined $proto;
1176 return 'icmp6'
1177 if $proto eq 'icmpv6';
1178 return $proto;
1181 # escape the string in a way safe for the shell
1182 sub shell_escape($) {
1183 my $token = shift;
1185 return $token if $token =~ /^[-_a-zA-Z0-9]+$/s;
1187 if ($option{fast}) {
1188 # iptables-save/iptables-restore are quite buggy concerning
1189 # escaping and special characters... we're trying our best
1190 # here
1192 $token =~ s,",',g;
1193 $token = '"' . $token . '"'
1194 if $token =~ /[\s\'\\;&]/s;
1195 } else {
1196 return $token
1197 if $token =~ /^\`.*\`$/;
1198 $token =~ s/'/\\'/g;
1199 $token = '\'' . $token . '\''
1200 if $token =~ /[\s\"\\;<>&|]/s;
1203 return $token;
1206 # append an option to the shell command line, using information from
1207 # the module definition (see %match_defs etc.)
1208 sub shell_append_option($$$) {
1209 my ($ref, $keyword, $value) = @_;
1211 if (ref $value) {
1212 if (ref $value eq 'negated') {
1213 $value = $value->[0];
1214 $keyword .= ' !';
1215 } elsif (ref $value eq 'pre_negated') {
1216 $value = $value->[0];
1217 $$ref .= ' !';
1221 unless (defined $value) {
1222 $$ref .= " --$keyword";
1223 } elsif (ref $value) {
1224 if (ref $value eq 'params') {
1225 $$ref .= " --$keyword ";
1226 $$ref .= join(' ', map { shell_escape($_) } @$value);
1227 } elsif (ref $value eq 'multi') {
1228 foreach (@$value) {
1229 $$ref .= " --$keyword " . shell_escape($_);
1231 } else {
1232 die;
1234 } else {
1235 $$ref .= " --$keyword " . shell_escape($value);
1239 # convert an internal rule structure into an iptables call
1240 sub tables($$$) {
1241 my ($table_info, $chain_info, $rule) = @_;
1243 return if $option{flush};
1245 # return if this is a declaration-only rule
1246 return
1247 unless $rule->{has_rule};
1249 my $rr = '';
1251 # general iptables options
1253 foreach my $option (@{$rule->{options}}) {
1254 shell_append_option(\$rr, $option->[0], $option->[1]);
1257 # this line is done
1258 my $chain_rules = $chain_info->{rules} ||= [];
1259 push @$chain_rules, { rule => $rr,
1260 script => $rule->{script},
1264 sub transform_rule($$) {
1265 my ($domain, $rule) = @_;
1267 $rule->{options}[$rule->{protocol_index}][1] = 'icmpv6'
1268 if $domain eq 'ip6' and $rule->{protocol} eq 'icmp';
1271 sub printrule($$$$) {
1272 my ($domain, $table, $chain, $rule) = @_;
1274 transform_rule($domain, $rule);
1276 my $domain_info = $domains{$domain};
1277 $domain_info->{enabled} = 1;
1278 my $table_info = $domain_info->{tables}{$table} ||= {};
1279 my $chain_info = $table_info->{chains}{$chain} ||= {};
1281 # prints all rules in a hash
1282 tables($table_info, $chain_info, $rule);
1286 sub check_unfold(\@$$) {
1287 my ($unfold, $parent, $key) = @_;
1289 return unless ref $parent->{$key} and
1290 ref $parent->{$key} eq 'ARRAY';
1292 push @$unfold, $parent, $key, $parent->{$key};
1295 sub mkrules2($$$$) {
1296 my ($domain, $table, $chain, $fw) = @_;
1298 my @unfold;
1299 foreach my $option (@{$fw->{options}}) {
1300 push @unfold, $option
1301 if ref $option->[1] and ref $option->[1] eq 'ARRAY';
1304 if (@unfold == 0) {
1305 printrule($domain, $table, $chain, $fw);
1306 return;
1309 sub dofr {
1310 my $fw = shift;
1311 my ($domain, $table, $chain) = (shift, shift, shift);
1312 my $option = shift;
1313 my @values = @{$option->[1]};
1315 foreach my $value (@values) {
1316 $option->[1] = $value;
1317 $fw->{protocol} = $value if $option->[0] eq 'protocol';
1319 if (@_) {
1320 dofr($fw, $domain, $table, $chain, @_);
1321 } else {
1322 printrule($domain, $table, $chain, $fw);
1327 dofr($fw, $domain, $table, $chain, @unfold);
1330 # convert a bunch of internal rule structures in iptables calls,
1331 # unfold arrays during that
1332 sub mkrules($) {
1333 my $fw = shift;
1335 foreach my $domain (to_array $fw->{domain}) {
1336 foreach my $table (to_array $fw->{table}) {
1337 foreach my $chain (to_array $fw->{chain}) {
1338 mkrules2($domain, $table, $chain, $fw);
1344 sub filter_domains($) {
1345 my $domains = shift;
1346 my $result = [];
1348 foreach my $domain (to_array $domains) {
1349 next if exists $option{domain}
1350 and $domain ne $option{domain};
1352 eval {
1353 initialize_domain($domain);
1355 error($@) if $@;
1357 push @$result, $domain;
1360 return @$result == 1 ? $result->[0] : $result;
1363 # parse a keyword from a module definition
1364 sub parse_keyword($$$$) {
1365 my ($current, $def, $keyword, $negated_ref) = @_;
1367 my $params = $def->{params};
1369 my $value;
1371 my $negated;
1372 if ($$negated_ref && exists $def->{pre_negation}) {
1373 $negated = 1;
1374 undef $$negated_ref;
1377 unless (defined $params) {
1378 undef $value;
1379 } elsif (ref $params && ref $params eq 'CODE') {
1380 $value = &$params($current);
1381 } elsif ($params eq 'm') {
1382 $value = bless [ to_array getvalues() ], 'multi';
1383 } elsif ($params =~ /^[a-z]/) {
1384 if (exists $def->{negation} and not $negated) {
1385 my $token = peek_token();
1386 if ($token eq '!') {
1387 require_next_token;
1388 $negated = 1;
1392 my @params;
1393 foreach my $p (split(//, $params)) {
1394 if ($p eq 's') {
1395 push @params, getvar();
1396 } elsif ($p eq 'c') {
1397 my @v = to_array getvalues(undef, undef,
1398 non_empty => 1);
1399 push @params, join(',', @v);
1400 } else {
1401 die;
1405 $value = @params == 1
1406 ? $params[0]
1407 : bless \@params, 'params';
1408 } elsif ($params == 1) {
1409 if (exists $def->{negation} and not $negated) {
1410 my $token = peek_token();
1411 if ($token eq '!') {
1412 require_next_token;
1413 $negated = 1;
1417 $value = getvalues();
1419 warning("log-prefix is too long; truncating to 29 characters: '$1'")
1420 if $keyword eq 'log-prefix' && $value =~ s,^(.{29}).+$,$1,;
1421 } else {
1422 if (exists $def->{negation} and not $negated) {
1423 my $token = peek_token();
1424 if ($token eq '!') {
1425 require_next_token;
1426 $negated = 1;
1430 $value = bless [ map {
1431 getvar()
1432 } (1..$params) ], 'params';
1435 $value = bless [ $value ], exists $def->{pre_negation} ? 'pre_negated' : 'negated'
1436 if $negated;
1438 return $value;
1441 sub append_option(\%$$) {
1442 my ($rule, $name, $value) = @_;
1443 push @{$rule->{options}}, [ $name, $value ];
1446 # parse options of a module
1447 sub parse_option($$$$) {
1448 my ($def, $current, $keyword, $negated_ref) = @_;
1450 while (exists $def->{alias}) {
1451 ($keyword, $def) = @{$def->{alias}};
1452 die unless defined $def;
1455 append_option(%$current, $keyword,
1456 parse_keyword($current, $def, $keyword, $negated_ref));
1457 return 1;
1460 sub copy_on_write($$) {
1461 my ($rule, $key) = @_;
1462 return unless exists $rule->{cow}{$key};
1463 $rule->{$key} = {%{$rule->{$key}}};
1464 delete $rule->{cow}{$key};
1467 sub new_level(\%$) {
1468 my ($current, $prev) = @_;
1470 %$current = ();
1471 if (defined $prev) {
1472 # copy data from previous level
1473 $current->{cow} = { keywords => 1, };
1474 $current->{keywords} = $prev->{keywords};
1475 $current->{match} = { %{$prev->{match}} };
1476 $current->{options} = [@{$prev->{options}}];
1477 foreach my $key (qw(domain domain_family table chain protocol protocol_index has_action)) {
1478 $current->{$key} = $prev->{$key}
1479 if exists $prev->{$key};
1481 } else {
1482 $current->{cow} = {};
1483 $current->{keywords} = {};
1484 $current->{match} = {};
1485 $current->{options} = [];
1489 sub merge_keywords(\%$) {
1490 my ($rule, $keywords) = @_;
1491 copy_on_write($rule, 'keywords');
1492 while (my ($name, $def) = each %$keywords) {
1493 $rule->{keywords}{$name} = $def;
1497 sub set_domain(\%$) {
1498 my ($rule, $domain) = @_;
1500 my $filtered_domain = filter_domains($domain);
1501 my $domain_family;
1502 unless (ref $domain) {
1503 $domain_family = $domain eq 'ip6' ? 'ip' : $domain;
1504 } elsif (@$domain == 0) {
1505 $domain_family = 'none';
1506 } elsif (grep { not /^ip6?$/s } @$domain) {
1507 error('Cannot combine non-IP domains');
1508 } else {
1509 $domain_family = 'ip';
1512 $rule->{domain_family} = $domain_family;
1513 $rule->{keywords} = {%{$match_defs{$domain_family}{''}{keywords}}};
1514 delete $rule->{cow}{keywords};
1516 $rule->{domain} = $stack[0]{auto}{DOMAIN} = $filtered_domain;
1519 sub set_module_target(\%$$) {
1520 my ($rule, $name, $defs) = @_;
1522 if ($name eq 'TCPMSS') {
1523 my $protos = $rule->{protocol};
1524 error('No protocol specified before TCPMSS')
1525 unless defined $protos;
1526 foreach my $proto (to_array $protos) {
1527 error('TCPMSS not available for protocol "$proto"')
1528 unless $proto eq 'tcp';
1532 merge_keywords(%$rule, $defs->{keywords});
1535 # the main parser loop: read tokens, convert them into internal rule
1536 # structures
1537 sub enter($$) {
1538 my $lev = shift; # current recursion depth
1539 my $prev = shift; # previous rule hash
1541 # enter is the core of the firewall setup, it is a
1542 # simple parser program that recognizes keywords and
1543 # retreives parameters to set up the kernel routing
1544 # chains
1546 my $base_level = $script->{base_level} || 0;
1547 die if $base_level > $lev;
1549 my %current;
1550 new_level(%current, $prev);
1552 # read keywords 1 by 1 and dump into parser
1553 while (defined (my $keyword = next_token())) {
1554 # check if the current rule should be negated
1555 my $negated = $keyword eq '!';
1556 if ($negated) {
1557 # negation. get the next word which contains the 'real'
1558 # rule
1559 $keyword = getvar();
1561 error('unexpected end of file after negation')
1562 unless defined $keyword;
1565 # the core: parse all data
1566 for ($keyword)
1568 # deprecated keyword?
1569 if (exists $deprecated_keywords{$keyword}) {
1570 my $new_keyword = $deprecated_keywords{$keyword};
1571 warning("'$keyword' is deprecated, please use '$new_keyword' instead");
1572 $keyword = $new_keyword;
1575 # effectuation operator
1576 if ($keyword eq ';') {
1577 if ($current{has_rule} and not exists $current{has_action}) {
1578 # something is wrong when a rule was specifiedd,
1579 # but no action
1580 error('No action defined; did you mean "NOP"?');
1583 error('No chain defined') unless exists $current{chain};
1585 $current{script} = { filename => $script->{filename},
1586 line => $script->{line},
1589 mkrules(\%current);
1591 # and clean up variables set in this level
1592 new_level(%current, $prev);
1594 next;
1597 # conditional expression
1598 if ($keyword eq '@if') {
1599 unless (eval_bool(getvalues)) {
1600 collect_tokens;
1601 my $token = peek_token();
1602 require_next_token() if $token and $token eq '@else';
1605 next;
1608 if ($keyword eq '@else') {
1609 # hack: if this "else" has not been eaten by the "if"
1610 # handler above, we believe it came from an if clause
1611 # which evaluated "true" - remove the "else" part now.
1612 collect_tokens;
1613 next;
1616 # hooks for custom shell commands
1617 if ($keyword eq 'hook') {
1618 error('"hook" must be the first token in a command')
1619 if exists $current{domain};
1621 my $position = getvar();
1622 my $hooks;
1623 if ($position eq 'pre') {
1624 $hooks = \@pre_hooks;
1625 } elsif ($position eq 'post') {
1626 $hooks = \@post_hooks;
1627 } else {
1628 error("Invalid hook position: '$position'");
1631 push @$hooks, getvar();
1633 expect_token(';');
1634 next;
1637 # recursing operators
1638 if ($keyword eq '{') {
1639 # push stack
1640 my $old_stack_depth = @stack;
1642 unshift @stack, { auto => { %{$stack[0]{auto} || {}} } };
1644 # recurse
1645 enter($lev + 1, \%current);
1647 # pop stack
1648 shift @stack;
1649 die unless @stack == $old_stack_depth;
1651 # after a block, the command is finished, clear this
1652 # level
1653 new_level(%current, $prev);
1655 next;
1658 if ($keyword eq '}') {
1659 error('Unmatched "}"')
1660 if $lev <= $base_level;
1662 # consistency check: check if they havn't forgotten
1663 # the ';' before the last statement
1664 error('Missing semicolon before "}"')
1665 if $current{has_rule};
1667 # and exit
1668 return;
1671 # include another file
1672 if ($keyword eq '@include' or $keyword eq 'include') {
1673 my @files = collect_filenames to_array getvalues;
1674 $keyword = next_token;
1675 error('Missing ";" - "include FILENAME" must be the last command in a rule')
1676 unless defined $keyword and $keyword eq ';';
1678 foreach my $filename (@files) {
1679 # save old script, open new script
1680 my $old_script = $script;
1681 open_script($filename);
1682 $script->{base_level} = $lev + 1;
1684 # push stack
1685 my $old_stack_depth = @stack;
1687 my $stack = {};
1689 if (@stack > 0) {
1690 # include files may set variables for their parent
1691 $stack->{vars} = ($stack[0]{vars} ||= {});
1692 $stack->{functions} = ($stack[0]{functions} ||= {});
1693 $stack->{auto} = { %{ $stack[0]{auto} || {} } };
1696 unshift @stack, $stack;
1698 # parse the script
1699 enter($lev + 1, \%current);
1701 # pop stack
1702 shift @stack;
1703 die unless @stack == $old_stack_depth;
1705 # restore old script
1706 $script = $old_script;
1709 next;
1712 # definition of a variable or function
1713 if ($keyword eq '@def' or $keyword eq 'def') {
1714 error('"def" must be the first token in a command')
1715 if $current{has_rule};
1717 my $type = require_next_token();
1718 if ($type eq '$') {
1719 my $name = require_next_token();
1720 error('invalid variable name')
1721 unless $name =~ /^\w+$/;
1723 expect_token('=');
1725 my $value = getvalues(undef, undef, allow_negation => 1);
1727 expect_token(';');
1729 $stack[0]{vars}{$name} = $value
1730 unless exists $stack[-1]{vars}{$name};
1731 } elsif ($type eq '&') {
1732 my $name = require_next_token();
1733 error('invalid function name')
1734 unless $name =~ /^\w+$/;
1736 expect_token('(', 'function parameter list or "()" expected');
1738 my @params;
1739 while (1) {
1740 my $token = require_next_token();
1741 last if $token eq ')';
1743 if (@params > 0) {
1744 error('"," expected')
1745 unless $token eq ',';
1747 $token = require_next_token();
1750 error('"$" and parameter name expected')
1751 unless $token eq '$';
1753 $token = require_next_token();
1754 error('invalid function parameter name')
1755 unless $token =~ /^\w+$/;
1757 push @params, $token;
1760 my %function;
1762 $function{params} = \@params;
1764 expect_token('=');
1766 my $tokens = collect_tokens();
1767 $function{block} = 1 if grep { $_ eq '{' } @$tokens;
1768 $function{tokens} = $tokens;
1770 $stack[0]{functions}{$name} = \%function
1771 unless exists $stack[-1]{functions}{$name};
1772 } else {
1773 error('"$" (variable) or "&" (function) expected');
1776 next;
1779 # def references
1780 if ($keyword eq '$') {
1781 error('variable references are only allowed as keyword parameter');
1784 if ($keyword eq '&') {
1785 my $name = require_next_token;
1786 error('function name expected')
1787 unless $name =~ /^\w+$/;
1789 my $function;
1790 foreach (@stack) {
1791 $function = $_->{functions}{$name};
1792 last if defined $function;
1794 error("no such function: \&$name")
1795 unless defined $function;
1797 my $paramdef = $function->{params};
1798 die unless defined $paramdef;
1800 my @params = get_function_params(allow_negation => 1);
1802 error("Wrong number of parameters for function '\&$name': "
1803 . @$paramdef . " expected, " . @params . " given")
1804 unless @params == @$paramdef;
1806 my %vars;
1807 for (my $i = 0; $i < @params; $i++) {
1808 $vars{$paramdef->[$i]} = $params[$i];
1811 if ($function->{block}) {
1812 # block {} always ends the current rule, so if the
1813 # function contains a block, we have to require
1814 # the calling rule also ends here
1815 expect_token(';');
1818 my @tokens = @{$function->{tokens}};
1819 for (my $i = 0; $i < @tokens; $i++) {
1820 if ($tokens[$i] eq '$' and $i + 1 < @tokens and
1821 exists $vars{$tokens[$i + 1]}) {
1822 my @value = to_array($vars{$tokens[$i + 1]});
1823 @value = ('(', @value, ')')
1824 unless @tokens == 1;
1825 splice(@tokens, $i, 2, @value);
1826 $i += @value - 2;
1827 } elsif ($tokens[$i] =~ m,^"(.*)"$,) {
1828 $tokens[$i] =~ s,\$(\w+),exists $vars{$1} ? $vars{$1} : "\$$1",eg;
1832 unshift @{$script->{tokens}}, @tokens;
1834 next;
1837 # where to put the rule?
1838 if ($keyword eq 'domain') {
1839 error('Domain is already specified')
1840 if exists $current{domain};
1842 set_domain(%current, getvalues());
1843 next;
1846 if ($keyword eq 'table') {
1847 error('Table is already specified')
1848 if exists $current{table};
1849 $current{table} = $stack[0]{auto}{TABLE} = getvalues();
1851 set_domain(%current, 'ip')
1852 unless exists $current{domain};
1854 next;
1857 if ($keyword eq 'chain') {
1858 error('Chain is already specified')
1859 if exists $current{chain};
1860 $current{chain} = $stack[0]{auto}{CHAIN} = getvalues();
1862 # ferm 1.1 allowed lower case built-in chain names
1863 foreach (ref $current{chain} ? @{$current{chain}} : $current{chain}) {
1864 error('Please write built-in chain names in upper case')
1865 if /^(?:input|forward|output|prerouting|postrouting)$/;
1868 set_domain(%current, 'ip')
1869 unless exists $current{domain};
1871 $current{table} = 'filter'
1872 unless exists $current{table};
1874 next;
1877 error('Chain must be specified')
1878 unless exists $current{chain};
1880 # policy for built-in chain
1881 if ($keyword eq 'policy') {
1882 error('Cannot specify matches for policy')
1883 if $current{has_rule};
1885 my $policy = getvar();
1886 error("Invalid policy target: $policy")
1887 unless $policy =~ /^(?:ACCEPT|DROP)$/;
1889 expect_token(';');
1891 foreach my $domain (to_array $current{domain}) {
1892 foreach my $table (to_array $current{table}) {
1893 foreach my $chain (to_array $current{chain}) {
1894 $domains{$domain}{tables}{$table}{chains}{$chain}{policy} = $policy;
1899 new_level(%current, $prev);
1900 next;
1903 # create a subchain
1904 if ($keyword eq '@subchain' or $keyword eq 'subchain') {
1905 error('Chain must be specified')
1906 unless exists $current{chain};
1908 error('No rule specified before "@subchain"')
1909 unless $current{has_rule};
1911 my $subchain;
1912 $keyword = next_token();
1914 if ($keyword =~ /^(["'])(.*)\1$/s) {
1915 $subchain = $2;
1916 $keyword = next_token();
1917 } else {
1918 $subchain = 'ferm_auto_' . ++$auto_chain;
1921 error('"{" or chain name expected after "@subchain"')
1922 unless $keyword eq '{';
1924 # create a deep copy of %current, only containing values
1925 # which must be in the subchain
1926 my %inner = ( cow => { keywords => 1, },
1927 keywords => $current{keywords},
1928 match => {},
1929 options => [],
1931 $inner{domain} = $current{domain};
1932 $inner{domain_family} = $current{domain_family};
1933 $inner{table} = $current{table};
1934 $inner{chain} = $inner{auto}{CHAIN} = $subchain;
1936 if (exists $current{protocol}) {
1937 $inner{protocol} = $current{protocol};
1938 $inner{protocol_index} = 0;
1939 append_option(%inner, 'protocol', $inner{protocol});
1942 # enter the block
1943 enter(1, \%inner);
1945 # now handle the parent - it's a jump to the sub chain
1946 $current{has_action} = 1;
1947 append_option(%current, 'jump', $subchain);
1949 $current{script} = { filename => $script->{filename},
1950 line => $script->{line},
1953 mkrules(\%current);
1955 # and clean up variables set in this level
1956 new_level(%current, $prev);
1958 next;
1961 # everything else must be part of a "real" rule, not just
1962 # "policy only"
1963 $current{has_rule}++;
1965 # extended parameters:
1966 if ($keyword =~ /^mod(?:ule)?$/) {
1967 foreach my $module (to_array getvalues) {
1968 next if exists $current{match}{$module};
1970 my $domain_family = $current{domain_family};
1971 my $defs = $match_defs{$domain_family}{$module};
1973 append_option(%current, 'match', $module);
1974 $current{match}{$module} = 1;
1976 merge_keywords(%current, $defs->{keywords})
1977 if defined $defs;
1980 next;
1983 # keywords from $current{keywords}
1985 if (exists $current{keywords}{$keyword}) {
1986 my $def = $current{keywords}{$keyword};
1987 parse_option($def, \%current, $keyword, \$negated);
1988 next;
1992 # actions
1995 # jump action
1996 if ($keyword eq 'jump') {
1997 error('There can only one action per rule')
1998 if exists $current{has_action};
1999 my $chain = getvar();
2000 if (my $defs = is_netfilter_module_target($current{domain_family}, $chain)) {
2001 set_module_target(%current, $chain, $defs);
2003 $current{has_action} = 1;
2004 append_option(%current, 'jump', $chain);
2005 next;
2008 # goto action
2009 if ($keyword eq 'realgoto') {
2010 error('There can only one action per rule')
2011 if exists $current{has_action};
2012 append_option(%current, 'goto', getvar());
2013 $current{has_action} = 1;
2014 next;
2017 # action keywords
2018 if (is_netfilter_core_target($keyword)) {
2019 error('There can only one action per rule')
2020 if exists $current{has_action};
2021 $current{has_action} = 1;
2022 append_option(%current, 'jump', $keyword);
2023 next;
2026 if ($keyword eq 'NOP') {
2027 error('There can only one action per rule')
2028 if exists $current{has_action};
2029 $current{has_action} = 1;
2030 next;
2033 if (my $defs = is_netfilter_module_target($current{domain_family}, $keyword)) {
2034 error('There can only one action per rule')
2035 if exists $current{has_action};
2037 set_module_target(%current, $keyword, $defs);
2038 $current{has_action} = 1;
2039 append_option(%current, 'jump', $keyword);
2040 next;
2043 my $proto = $current{protocol};
2046 # protocol specific options
2049 if ($keyword eq 'proto') {
2050 my $protocol = parse_keyword(\%current,
2051 { params => 1, negation => 1 },
2052 'proto', \$negated);
2053 $current{protocol} = $protocol;
2054 $current{protocol_index} = scalar(@{$current{options}});
2055 append_option(%current, 'protocol', $current{protocol});
2057 unless (ref $protocol) {
2058 $protocol = netfilter_canonical_protocol($protocol);
2059 my $domain_family = $current{domain_family};
2060 my $defs = $proto_defs{$domain_family}{$protocol};
2061 if (defined $defs) {
2062 merge_keywords(%current, $defs->{keywords});
2063 my $module = netfilter_protocol_module($protocol);
2064 $current{match}{$module} = 1;
2067 next;
2070 # port switches
2071 if ($keyword =~ /^[sd]port$/) {
2072 error('To use sport or dport, you have to specify "proto tcp" or "proto udp" first')
2073 unless defined $proto and grep { /^(?:tcp|udp|udplite|dccp|sctp)$/ } to_array $proto;
2075 append_option(%current, $keyword,
2076 getvalues(undef, undef,
2077 allow_negation => 1));
2078 next;
2081 # default
2082 error("Unrecognized keyword: $keyword");
2085 # if the rule didn't reset the negated flag, it's not
2086 # supported
2087 error("Doesn't support negation: $keyword")
2088 if $negated;
2091 error('Missing "}" at end of file')
2092 if $lev > $base_level;
2094 # consistency check: check if they havn't forgotten
2095 # the ';' before the last statement
2096 error("Missing semicolon before end of file")
2097 if exists $current{domain};
2100 sub execute_command {
2101 my ($command, $script) = @_;
2103 print LINES "$command\n"
2104 if $option{lines};
2105 return if $option{noexec};
2107 my $ret = system($command);
2108 unless ($ret == 0) {
2109 if ($? == -1) {
2110 print STDERR "failed to execute: $!\n";
2111 exit 1;
2112 } elsif ($? & 0x7f) {
2113 printf STDERR "child died with signal %d\n", $? & 0x7f;
2114 return 1;
2115 } else {
2116 print STDERR "(rule declared in $script->{filename}:$script->{line})\n"
2117 if defined $script;
2118 return $? >> 8;
2122 return;
2125 sub execute_slow($$) {
2126 my ($domain, $domain_info) = @_;
2128 my $domain_cmd = $domain_info->{tools}{tables};
2130 my $status;
2131 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2132 my $table_cmd = "$domain_cmd -t $table";
2134 # reset chain policies
2135 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2136 next unless $chain_info->{builtin} or
2137 (not $table_info->{has_builtin} and
2138 is_netfilter_builtin_chain($table, $chain));
2139 $status ||= execute_command("$table_cmd -P $chain ACCEPT")
2140 unless $option{noflush};
2143 # clear
2144 unless ($option{noflush}) {
2145 $status ||= execute_command("$table_cmd -F");
2146 $status ||= execute_command("$table_cmd -X");
2149 next if $option{flush};
2151 # create chains / set policy
2152 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2153 if (exists $chain_info->{policy}) {
2154 $status ||= execute_command("$table_cmd -P $chain $chain_info->{policy}")
2155 unless $chain_info->{policy} eq 'ACCEPT';
2156 } elsif (not is_netfilter_builtin_chain($table, $chain)) {
2157 $status ||= execute_command("$table_cmd -N $chain");
2161 # dump rules
2162 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2163 my $chain_cmd = "$table_cmd -A $chain";
2164 foreach my $rule (@{$chain_info->{rules}}) {
2165 $status ||= execute_command($chain_cmd . $rule->{rule});
2170 return $status;
2173 sub rules_to_save($$) {
2174 my ($domain, $domain_info) = @_;
2176 # convert this into an iptables-save text
2177 my $result = "# Generated by ferm $VERSION on " . localtime() . "\n";
2179 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2180 # select table
2181 $result .= '*' . $table . "\n";
2183 # create chains / set policy
2184 foreach my $chain (sort keys %{$table_info->{chains}}) {
2185 my $chain_info = $table_info->{chains}{$chain};
2186 my $policy = $option{flush} ? 'ACCEPT' : $chain_info->{policy};
2187 unless (defined $policy) {
2188 if (is_netfilter_builtin_chain($table, $chain)) {
2189 $policy = 'ACCEPT';
2190 } else {
2191 $policy = '-';
2194 $result .= ":$chain $policy\ [0:0]\n";
2197 next if $option{flush};
2199 # dump rules
2200 foreach my $chain (sort keys %{$table_info->{chains}}) {
2201 my $chain_info = $table_info->{chains}{$chain};
2202 foreach my $rule (@{$chain_info->{rules}}) {
2203 $result .= "-A $chain$rule->{rule}\n";
2207 # do it
2208 $result .= "COMMIT\n";
2211 return $result;
2214 sub restore_domain($$) {
2215 my ($domain, $save) = @_;
2217 my $path = $domains{$domain}{tools}{'tables-restore'};
2219 local *RESTORE;
2220 open RESTORE, "|$path"
2221 or die "Failed to run $path: $!\n";
2223 print RESTORE $save;
2225 close RESTORE
2226 or die "Failed to run $path\n";
2229 sub execute_fast($$) {
2230 my ($domain, $domain_info) = @_;
2232 my $save = rules_to_save($domain, $domain_info);
2234 if ($option{lines}) {
2235 print LINES "$domain_info->{tools}{'tables-restore'} <<EOT\n"
2236 if $option{shell};
2237 print LINES $save;
2238 print LINES "EOT\n"
2239 if $option{shell};
2242 return if $option{noexec};
2244 eval {
2245 restore_domain($domain, $save);
2247 if ($@) {
2248 print STDERR $@;
2249 return 1;
2252 return;
2255 sub rollback() {
2256 my $error;
2257 while (my ($domain, $domain_info) = each %domains) {
2258 next unless $domain_info->{enabled};
2259 unless (defined $domain_info->{tools}{'tables-restore'}) {
2260 print STDERR "Cannot rollback domain '$domain' because there is no ${domain}tables-restore\n";
2261 next;
2264 my $reset = '';
2265 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2266 my $reset_chain = '';
2267 foreach my $chain (keys %{$table_info->{chains}{$table}}) {
2268 next unless is_netfilter_builtin_chain($table, $chain);
2269 $reset_chain .= ":${chain} ACCEPT [0:0]\n";
2271 $reset .= "*${table}\n${reset_chain}COMMIT\n"
2272 if length $reset_chain;
2275 $reset .= $domain_info->{previous}
2276 if defined $domain_info->{previous};
2278 restore_domain($domain, $reset);
2281 print STDERR "\nFirewall rules rolled back.\n" unless $error;
2282 exit 1;
2285 sub alrm_handler {
2286 # do nothing, just interrupt a system call
2289 sub confirm_rules() {
2290 $SIG{ALRM} = \&alrm_handler;
2292 alarm(5);
2294 print STDERR "\n"
2295 . "ferm has applied the new firewall rules.\n"
2296 . "Please type 'yes' to confirm:\n";
2297 STDERR->flush();
2299 alarm(30);
2301 my $line = '';
2302 STDIN->sysread($line, 3);
2304 eval {
2305 require POSIX;
2306 POSIX::tcflush(*STDIN, 2);
2308 print STDERR "$@" if $@;
2310 $SIG{ALRM} = 'DEFAULT';
2312 return $line eq 'yes';
2315 # end of ferm
2317 __END__
2319 =head1 NAME
2321 ferm - a firewall rule parser for linux
2323 =head1 SYNOPSIS
2325 B<ferm> I<options> I<inputfiles>
2327 =head1 OPTIONS
2329 -n, --noexec Do not execute the rules, just simulate
2330 -F, --flush Flush all netfilter tables managed by ferm
2331 -l, --lines Show all rules that were created
2332 -i, --interactive Interactive mode: revert if user does not confirm
2333 --remote Remote mode; ignore host specific configuration.
2334 This implies --noexec and --lines.
2335 -V, --version Show current version number
2336 -h, --help Look at this text
2337 --fast Generate an iptables-save file, used by iptables-restore
2338 --shell Generate a shell script which calls iptables-restore
2339 --domain {ip|ip6} Handle only the specified domain
2340 --def '$name=v' Override a variable
2342 =cut