moved dofr() out of mkrules2()
[ferm.git] / src / ferm
blobd0aae538461a24061efe1aff4e94bd3fe304cec2
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 ($chain_rules, $rule) = @_;
1233 my $cmd = join('', map { $_->[2] } @{$rule->{options}});
1234 push @$chain_rules, { rule => $cmd,
1235 script => $rule->{script},
1239 sub dofr {
1240 my ($domain, $chain_rules, $rule) = (shift, shift, shift);
1241 my $option = shift;
1242 my @values = @{$option->[1]};
1244 foreach my $value (@values) {
1245 $option->[2] = format_option($domain, $option->[0], $value);
1247 if (@_) {
1248 dofr($domain, $chain_rules, $rule, @_);
1249 } else {
1250 printrule($chain_rules, $rule);
1255 sub mkrules2($$$) {
1256 my ($domain, $chain_rules, $rule) = @_;
1258 my @unfold;
1259 foreach my $option (@{$rule->{options}}) {
1260 if (ref $option->[1] and ref $option->[1] eq 'ARRAY') {
1261 push @unfold, $option
1262 } else {
1263 $option->[2] = format_option($domain, $option->[0], $option->[1]);
1267 if (@unfold) {
1268 dofr($domain, $chain_rules, $rule, @unfold);
1269 } else {
1270 printrule($chain_rules, $rule);
1274 # convert a bunch of internal rule structures in iptables calls,
1275 # unfold arrays during that
1276 sub mkrules($) {
1277 my $rule = shift;
1279 foreach my $domain (to_array $rule->{domain}) {
1280 my $domain_info = $domains{$domain};
1281 $domain_info->{enabled} = 1;
1283 foreach my $table (to_array $rule->{table}) {
1284 my $table_info = $domain_info->{tables}{$table} ||= {};
1286 foreach my $chain (to_array $rule->{chain}) {
1287 my $chain_rules = $table_info->{chains}{$chain}{rules} ||= [];
1288 mkrules2($domain, $chain_rules, $rule)
1289 if $rule->{has_rule} and not $option{flush};
1295 sub filter_domains($) {
1296 my $domains = shift;
1297 my $result = [];
1299 foreach my $domain (to_array $domains) {
1300 next if exists $option{domain}
1301 and $domain ne $option{domain};
1303 eval {
1304 initialize_domain($domain);
1306 error($@) if $@;
1308 push @$result, $domain;
1311 return @$result == 1 ? $result->[0] : $result;
1314 # parse a keyword from a module definition
1315 sub parse_keyword($$$$) {
1316 my ($rule, $def, $keyword, $negated_ref) = @_;
1318 my $params = $def->{params};
1320 my $value;
1322 my $negated;
1323 if ($$negated_ref && exists $def->{pre_negation}) {
1324 $negated = 1;
1325 undef $$negated_ref;
1328 unless (defined $params) {
1329 undef $value;
1330 } elsif (ref $params && ref $params eq 'CODE') {
1331 $value = &$params($rule);
1332 } elsif ($params eq 'm') {
1333 $value = bless [ to_array getvalues() ], 'multi';
1334 } elsif ($params =~ /^[a-z]/) {
1335 if (exists $def->{negation} and not $negated) {
1336 my $token = peek_token();
1337 if ($token eq '!') {
1338 require_next_token;
1339 $negated = 1;
1343 my @params;
1344 foreach my $p (split(//, $params)) {
1345 if ($p eq 's') {
1346 push @params, getvar();
1347 } elsif ($p eq 'c') {
1348 my @v = to_array getvalues(undef, undef,
1349 non_empty => 1);
1350 push @params, join(',', @v);
1351 } else {
1352 die;
1356 $value = @params == 1
1357 ? $params[0]
1358 : bless \@params, 'params';
1359 } elsif ($params == 1) {
1360 if (exists $def->{negation} and not $negated) {
1361 my $token = peek_token();
1362 if ($token eq '!') {
1363 require_next_token;
1364 $negated = 1;
1368 $value = getvalues();
1370 warning("log-prefix is too long; truncating to 29 characters: '$1'")
1371 if $keyword eq 'log-prefix' && $value =~ s,^(.{29}).+$,$1,;
1372 } else {
1373 if (exists $def->{negation} and not $negated) {
1374 my $token = peek_token();
1375 if ($token eq '!') {
1376 require_next_token;
1377 $negated = 1;
1381 $value = bless [ map {
1382 getvar()
1383 } (1..$params) ], 'params';
1386 $value = bless [ $value ], exists $def->{pre_negation} ? 'pre_negated' : 'negated'
1387 if $negated;
1389 return $value;
1392 sub append_option(\%$$) {
1393 my ($rule, $name, $value) = @_;
1394 push @{$rule->{options}}, [ $name, $value ];
1397 # parse options of a module
1398 sub parse_option($$$$) {
1399 my ($def, $rule, $keyword, $negated_ref) = @_;
1401 while (exists $def->{alias}) {
1402 ($keyword, $def) = @{$def->{alias}};
1403 die unless defined $def;
1406 append_option(%$rule, $keyword,
1407 parse_keyword($rule, $def, $keyword, $negated_ref));
1408 return 1;
1411 sub copy_on_write($$) {
1412 my ($rule, $key) = @_;
1413 return unless exists $rule->{cow}{$key};
1414 $rule->{$key} = {%{$rule->{$key}}};
1415 delete $rule->{cow}{$key};
1418 sub new_level(\%$) {
1419 my ($rule, $prev) = @_;
1421 %$rule = ();
1422 if (defined $prev) {
1423 # copy data from previous level
1424 $rule->{cow} = { keywords => 1, };
1425 $rule->{keywords} = $prev->{keywords};
1426 $rule->{match} = { %{$prev->{match}} };
1427 $rule->{options} = [@{$prev->{options}}];
1428 foreach my $key (qw(domain domain_family table chain protocol has_action)) {
1429 $rule->{$key} = $prev->{$key}
1430 if exists $prev->{$key};
1432 } else {
1433 $rule->{cow} = {};
1434 $rule->{keywords} = {};
1435 $rule->{match} = {};
1436 $rule->{options} = [];
1440 sub merge_keywords(\%$) {
1441 my ($rule, $keywords) = @_;
1442 copy_on_write($rule, 'keywords');
1443 while (my ($name, $def) = each %$keywords) {
1444 $rule->{keywords}{$name} = $def;
1448 sub set_domain(\%$) {
1449 my ($rule, $domain) = @_;
1451 my $filtered_domain = filter_domains($domain);
1452 my $domain_family;
1453 unless (ref $domain) {
1454 $domain_family = $domain eq 'ip6' ? 'ip' : $domain;
1455 } elsif (@$domain == 0) {
1456 $domain_family = 'none';
1457 } elsif (grep { not /^ip6?$/s } @$domain) {
1458 error('Cannot combine non-IP domains');
1459 } else {
1460 $domain_family = 'ip';
1463 $rule->{domain_family} = $domain_family;
1464 $rule->{keywords} = $match_defs{$domain_family}{''}{keywords};
1465 $rule->{cow}{keywords} = 1;
1467 $rule->{domain} = $stack[0]{auto}{DOMAIN} = $filtered_domain;
1470 sub set_module_target(\%$$) {
1471 my ($rule, $name, $defs) = @_;
1473 if ($name eq 'TCPMSS') {
1474 my $protos = $rule->{protocol};
1475 error('No protocol specified before TCPMSS')
1476 unless defined $protos;
1477 foreach my $proto (to_array $protos) {
1478 error('TCPMSS not available for protocol "$proto"')
1479 unless $proto eq 'tcp';
1483 merge_keywords(%$rule, $defs->{keywords});
1486 # the main parser loop: read tokens, convert them into internal rule
1487 # structures
1488 sub enter($$) {
1489 my $lev = shift; # current recursion depth
1490 my $prev = shift; # previous rule hash
1492 # enter is the core of the firewall setup, it is a
1493 # simple parser program that recognizes keywords and
1494 # retreives parameters to set up the kernel routing
1495 # chains
1497 my $base_level = $script->{base_level} || 0;
1498 die if $base_level > $lev;
1500 my %rule;
1501 new_level(%rule, $prev);
1503 # read keywords 1 by 1 and dump into parser
1504 while (defined (my $keyword = next_token())) {
1505 # check if the current rule should be negated
1506 my $negated = $keyword eq '!';
1507 if ($negated) {
1508 # negation. get the next word which contains the 'real'
1509 # rule
1510 $keyword = getvar();
1512 error('unexpected end of file after negation')
1513 unless defined $keyword;
1516 # the core: parse all data
1517 for ($keyword)
1519 # deprecated keyword?
1520 if (exists $deprecated_keywords{$keyword}) {
1521 my $new_keyword = $deprecated_keywords{$keyword};
1522 warning("'$keyword' is deprecated, please use '$new_keyword' instead");
1523 $keyword = $new_keyword;
1526 # effectuation operator
1527 if ($keyword eq ';') {
1528 if ($rule{has_rule} and not exists $rule{has_action}) {
1529 # something is wrong when a rule was specified,
1530 # but no action
1531 error('No action defined; did you mean "NOP"?');
1534 error('No chain defined') unless exists $rule{chain};
1536 $rule{script} = { filename => $script->{filename},
1537 line => $script->{line},
1540 mkrules(\%rule);
1542 # and clean up variables set in this level
1543 new_level(%rule, $prev);
1545 next;
1548 # conditional expression
1549 if ($keyword eq '@if') {
1550 unless (eval_bool(getvalues)) {
1551 collect_tokens;
1552 my $token = peek_token();
1553 require_next_token() if $token and $token eq '@else';
1556 next;
1559 if ($keyword eq '@else') {
1560 # hack: if this "else" has not been eaten by the "if"
1561 # handler above, we believe it came from an if clause
1562 # which evaluated "true" - remove the "else" part now.
1563 collect_tokens;
1564 next;
1567 # hooks for custom shell commands
1568 if ($keyword eq 'hook') {
1569 error('"hook" must be the first token in a command')
1570 if exists $rule{domain};
1572 my $position = getvar();
1573 my $hooks;
1574 if ($position eq 'pre') {
1575 $hooks = \@pre_hooks;
1576 } elsif ($position eq 'post') {
1577 $hooks = \@post_hooks;
1578 } else {
1579 error("Invalid hook position: '$position'");
1582 push @$hooks, getvar();
1584 expect_token(';');
1585 next;
1588 # recursing operators
1589 if ($keyword eq '{') {
1590 # push stack
1591 my $old_stack_depth = @stack;
1593 unshift @stack, { auto => { %{$stack[0]{auto} || {}} } };
1595 # recurse
1596 enter($lev + 1, \%rule);
1598 # pop stack
1599 shift @stack;
1600 die unless @stack == $old_stack_depth;
1602 # after a block, the command is finished, clear this
1603 # level
1604 new_level(%rule, $prev);
1606 next;
1609 if ($keyword eq '}') {
1610 error('Unmatched "}"')
1611 if $lev <= $base_level;
1613 # consistency check: check if they havn't forgotten
1614 # the ';' before the last statement
1615 error('Missing semicolon before "}"')
1616 if $rule{has_rule};
1618 # and exit
1619 return;
1622 # include another file
1623 if ($keyword eq '@include' or $keyword eq 'include') {
1624 my @files = collect_filenames to_array getvalues;
1625 $keyword = next_token;
1626 error('Missing ";" - "include FILENAME" must be the last command in a rule')
1627 unless defined $keyword and $keyword eq ';';
1629 foreach my $filename (@files) {
1630 # save old script, open new script
1631 my $old_script = $script;
1632 open_script($filename);
1633 $script->{base_level} = $lev + 1;
1635 # push stack
1636 my $old_stack_depth = @stack;
1638 my $stack = {};
1640 if (@stack > 0) {
1641 # include files may set variables for their parent
1642 $stack->{vars} = ($stack[0]{vars} ||= {});
1643 $stack->{functions} = ($stack[0]{functions} ||= {});
1644 $stack->{auto} = { %{ $stack[0]{auto} || {} } };
1647 unshift @stack, $stack;
1649 # parse the script
1650 enter($lev + 1, \%rule);
1652 # pop stack
1653 shift @stack;
1654 die unless @stack == $old_stack_depth;
1656 # restore old script
1657 $script = $old_script;
1660 next;
1663 # definition of a variable or function
1664 if ($keyword eq '@def' or $keyword eq 'def') {
1665 error('"def" must be the first token in a command')
1666 if $rule{has_rule};
1668 my $type = require_next_token();
1669 if ($type eq '$') {
1670 my $name = require_next_token();
1671 error('invalid variable name')
1672 unless $name =~ /^\w+$/;
1674 expect_token('=');
1676 my $value = getvalues(undef, undef, allow_negation => 1);
1678 expect_token(';');
1680 $stack[0]{vars}{$name} = $value
1681 unless exists $stack[-1]{vars}{$name};
1682 } elsif ($type eq '&') {
1683 my $name = require_next_token();
1684 error('invalid function name')
1685 unless $name =~ /^\w+$/;
1687 expect_token('(', 'function parameter list or "()" expected');
1689 my @params;
1690 while (1) {
1691 my $token = require_next_token();
1692 last if $token eq ')';
1694 if (@params > 0) {
1695 error('"," expected')
1696 unless $token eq ',';
1698 $token = require_next_token();
1701 error('"$" and parameter name expected')
1702 unless $token eq '$';
1704 $token = require_next_token();
1705 error('invalid function parameter name')
1706 unless $token =~ /^\w+$/;
1708 push @params, $token;
1711 my %function;
1713 $function{params} = \@params;
1715 expect_token('=');
1717 my $tokens = collect_tokens();
1718 $function{block} = 1 if grep { $_ eq '{' } @$tokens;
1719 $function{tokens} = $tokens;
1721 $stack[0]{functions}{$name} = \%function
1722 unless exists $stack[-1]{functions}{$name};
1723 } else {
1724 error('"$" (variable) or "&" (function) expected');
1727 next;
1730 # def references
1731 if ($keyword eq '$') {
1732 error('variable references are only allowed as keyword parameter');
1735 if ($keyword eq '&') {
1736 my $name = require_next_token;
1737 error('function name expected')
1738 unless $name =~ /^\w+$/;
1740 my $function;
1741 foreach (@stack) {
1742 $function = $_->{functions}{$name};
1743 last if defined $function;
1745 error("no such function: \&$name")
1746 unless defined $function;
1748 my $paramdef = $function->{params};
1749 die unless defined $paramdef;
1751 my @params = get_function_params(allow_negation => 1);
1753 error("Wrong number of parameters for function '\&$name': "
1754 . @$paramdef . " expected, " . @params . " given")
1755 unless @params == @$paramdef;
1757 my %vars;
1758 for (my $i = 0; $i < @params; $i++) {
1759 $vars{$paramdef->[$i]} = $params[$i];
1762 if ($function->{block}) {
1763 # block {} always ends the current rule, so if the
1764 # function contains a block, we have to require
1765 # the calling rule also ends here
1766 expect_token(';');
1769 my @tokens = @{$function->{tokens}};
1770 for (my $i = 0; $i < @tokens; $i++) {
1771 if ($tokens[$i] eq '$' and $i + 1 < @tokens and
1772 exists $vars{$tokens[$i + 1]}) {
1773 my @value = to_array($vars{$tokens[$i + 1]});
1774 @value = ('(', @value, ')')
1775 unless @tokens == 1;
1776 splice(@tokens, $i, 2, @value);
1777 $i += @value - 2;
1778 } elsif ($tokens[$i] =~ m,^"(.*)"$,) {
1779 $tokens[$i] =~ s,\$(\w+),exists $vars{$1} ? $vars{$1} : "\$$1",eg;
1783 unshift @{$script->{tokens}}, @tokens;
1785 next;
1788 # where to put the rule?
1789 if ($keyword eq 'domain') {
1790 error('Domain is already specified')
1791 if exists $rule{domain};
1793 set_domain(%rule, getvalues());
1794 next;
1797 if ($keyword eq 'table') {
1798 error('Table is already specified')
1799 if exists $rule{table};
1800 $rule{table} = $stack[0]{auto}{TABLE} = getvalues();
1802 set_domain(%rule, 'ip')
1803 unless exists $rule{domain};
1805 next;
1808 if ($keyword eq 'chain') {
1809 error('Chain is already specified')
1810 if exists $rule{chain};
1811 $rule{chain} = $stack[0]{auto}{CHAIN} = getvalues();
1813 # ferm 1.1 allowed lower case built-in chain names
1814 foreach (ref $rule{chain} ? @{$rule{chain}} : $rule{chain}) {
1815 error('Please write built-in chain names in upper case')
1816 if /^(?:input|forward|output|prerouting|postrouting)$/;
1819 set_domain(%rule, 'ip')
1820 unless exists $rule{domain};
1822 $rule{table} = 'filter'
1823 unless exists $rule{table};
1825 next;
1828 error('Chain must be specified')
1829 unless exists $rule{chain};
1831 # policy for built-in chain
1832 if ($keyword eq 'policy') {
1833 error('Cannot specify matches for policy')
1834 if $rule{has_rule};
1836 my $policy = getvar();
1837 error("Invalid policy target: $policy")
1838 unless $policy =~ /^(?:ACCEPT|DROP)$/;
1840 expect_token(';');
1842 foreach my $domain (to_array $rule{domain}) {
1843 foreach my $table (to_array $rule{table}) {
1844 foreach my $chain (to_array $rule{chain}) {
1845 $domains{$domain}{tables}{$table}{chains}{$chain}{policy} = $policy;
1850 new_level(%rule, $prev);
1851 next;
1854 # create a subchain
1855 if ($keyword eq '@subchain' or $keyword eq 'subchain') {
1856 error('Chain must be specified')
1857 unless exists $rule{chain};
1859 error('No rule specified before "@subchain"')
1860 unless $rule{has_rule};
1862 my $subchain;
1863 $keyword = next_token();
1865 if ($keyword =~ /^(["'])(.*)\1$/s) {
1866 $subchain = $2;
1867 $keyword = next_token();
1868 } else {
1869 $subchain = 'ferm_auto_' . ++$auto_chain;
1872 error('"{" or chain name expected after "@subchain"')
1873 unless $keyword eq '{';
1875 # create a deep copy of %rule, only containing values
1876 # which must be in the subchain
1877 my %inner = ( cow => { keywords => 1, },
1878 keywords => $rule{keywords},
1879 match => {},
1880 options => [],
1882 $inner{domain} = $rule{domain};
1883 $inner{domain_family} = $rule{domain_family};
1884 $inner{table} = $rule{table};
1885 $inner{chain} = $inner{auto}{CHAIN} = $subchain;
1887 if (exists $rule{protocol}) {
1888 $inner{protocol} = $rule{protocol};
1889 append_option(%inner, 'protocol', $inner{protocol});
1892 # enter the block
1893 enter(1, \%inner);
1895 # now handle the parent - it's a jump to the sub chain
1896 $rule{has_action} = 1;
1897 append_option(%rule, 'jump', $subchain);
1899 $rule{script} = { filename => $script->{filename},
1900 line => $script->{line},
1903 mkrules(\%rule);
1905 # and clean up variables set in this level
1906 new_level(%rule, $prev);
1908 next;
1911 # everything else must be part of a "real" rule, not just
1912 # "policy only"
1913 $rule{has_rule}++;
1915 # extended parameters:
1916 if ($keyword =~ /^mod(?:ule)?$/) {
1917 foreach my $module (to_array getvalues) {
1918 next if exists $rule{match}{$module};
1920 my $domain_family = $rule{domain_family};
1921 my $defs = $match_defs{$domain_family}{$module};
1923 append_option(%rule, 'match', $module);
1924 $rule{match}{$module} = 1;
1926 merge_keywords(%rule, $defs->{keywords})
1927 if defined $defs;
1930 next;
1933 # keywords from $rule{keywords}
1935 if (exists $rule{keywords}{$keyword}) {
1936 my $def = $rule{keywords}{$keyword};
1937 parse_option($def, \%rule, $keyword, \$negated);
1938 next;
1942 # actions
1945 # jump action
1946 if ($keyword eq 'jump') {
1947 error('There can only one action per rule')
1948 if exists $rule{has_action};
1949 my $chain = getvar();
1950 if (my $defs = is_netfilter_module_target($rule{domain_family}, $chain)) {
1951 set_module_target(%rule, $chain, $defs);
1953 $rule{has_action} = 1;
1954 append_option(%rule, 'jump', $chain);
1955 next;
1958 # goto action
1959 if ($keyword eq 'realgoto') {
1960 error('There can only one action per rule')
1961 if exists $rule{has_action};
1962 append_option(%rule, 'goto', getvar());
1963 $rule{has_action} = 1;
1964 next;
1967 # action keywords
1968 if (is_netfilter_core_target($keyword)) {
1969 error('There can only one action per rule')
1970 if exists $rule{has_action};
1971 $rule{has_action} = 1;
1972 append_option(%rule, 'jump', $keyword);
1973 next;
1976 if ($keyword eq 'NOP') {
1977 error('There can only one action per rule')
1978 if exists $rule{has_action};
1979 $rule{has_action} = 1;
1980 next;
1983 if (my $defs = is_netfilter_module_target($rule{domain_family}, $keyword)) {
1984 error('There can only one action per rule')
1985 if exists $rule{has_action};
1987 set_module_target(%rule, $keyword, $defs);
1988 $rule{has_action} = 1;
1989 append_option(%rule, 'jump', $keyword);
1990 next;
1993 my $proto = $rule{protocol};
1996 # protocol specific options
1999 if ($keyword eq 'proto') {
2000 my $protocol = parse_keyword(\%rule,
2001 { params => 1, negation => 1 },
2002 'proto', \$negated);
2003 $rule{protocol} = $protocol;
2004 append_option(%rule, 'protocol', $rule{protocol});
2006 unless (ref $protocol) {
2007 $protocol = netfilter_canonical_protocol($protocol);
2008 my $domain_family = $rule{domain_family};
2009 my $defs = $proto_defs{$domain_family}{$protocol};
2010 if (defined $defs) {
2011 merge_keywords(%rule, $defs->{keywords});
2012 my $module = netfilter_protocol_module($protocol);
2013 $rule{match}{$module} = 1;
2016 next;
2019 # port switches
2020 if ($keyword =~ /^[sd]port$/) {
2021 error('To use sport or dport, you have to specify "proto tcp" or "proto udp" first')
2022 unless defined $proto and grep { /^(?:tcp|udp|udplite|dccp|sctp)$/ } to_array $proto;
2024 append_option(%rule, $keyword,
2025 getvalues(undef, undef,
2026 allow_negation => 1));
2027 next;
2030 # default
2031 error("Unrecognized keyword: $keyword");
2034 # if the rule didn't reset the negated flag, it's not
2035 # supported
2036 error("Doesn't support negation: $keyword")
2037 if $negated;
2040 error('Missing "}" at end of file')
2041 if $lev > $base_level;
2043 # consistency check: check if they havn't forgotten
2044 # the ';' before the last statement
2045 error("Missing semicolon before end of file")
2046 if exists $rule{domain};
2049 sub execute_command {
2050 my ($command, $script) = @_;
2052 print LINES "$command\n"
2053 if $option{lines};
2054 return if $option{noexec};
2056 my $ret = system($command);
2057 unless ($ret == 0) {
2058 if ($? == -1) {
2059 print STDERR "failed to execute: $!\n";
2060 exit 1;
2061 } elsif ($? & 0x7f) {
2062 printf STDERR "child died with signal %d\n", $? & 0x7f;
2063 return 1;
2064 } else {
2065 print STDERR "(rule declared in $script->{filename}:$script->{line})\n"
2066 if defined $script;
2067 return $? >> 8;
2071 return;
2074 sub execute_slow($$) {
2075 my ($domain, $domain_info) = @_;
2077 my $domain_cmd = $domain_info->{tools}{tables};
2079 my $status;
2080 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2081 my $table_cmd = "$domain_cmd -t $table";
2083 # reset chain policies
2084 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2085 next unless $chain_info->{builtin} or
2086 (not $table_info->{has_builtin} and
2087 is_netfilter_builtin_chain($table, $chain));
2088 $status ||= execute_command("$table_cmd -P $chain ACCEPT")
2089 unless $option{noflush};
2092 # clear
2093 unless ($option{noflush}) {
2094 $status ||= execute_command("$table_cmd -F");
2095 $status ||= execute_command("$table_cmd -X");
2098 next if $option{flush};
2100 # create chains / set policy
2101 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2102 if (exists $chain_info->{policy}) {
2103 $status ||= execute_command("$table_cmd -P $chain $chain_info->{policy}")
2104 unless $chain_info->{policy} eq 'ACCEPT';
2105 } elsif (not is_netfilter_builtin_chain($table, $chain)) {
2106 $status ||= execute_command("$table_cmd -N $chain");
2110 # dump rules
2111 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2112 my $chain_cmd = "$table_cmd -A $chain";
2113 foreach my $rule (@{$chain_info->{rules}}) {
2114 $status ||= execute_command($chain_cmd . $rule->{rule});
2119 return $status;
2122 sub rules_to_save($$) {
2123 my ($domain, $domain_info) = @_;
2125 # convert this into an iptables-save text
2126 my $result = "# Generated by ferm $VERSION on " . localtime() . "\n";
2128 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2129 # select table
2130 $result .= '*' . $table . "\n";
2132 # create chains / set policy
2133 foreach my $chain (sort keys %{$table_info->{chains}}) {
2134 my $chain_info = $table_info->{chains}{$chain};
2135 my $policy = $option{flush} ? 'ACCEPT' : $chain_info->{policy};
2136 unless (defined $policy) {
2137 if (is_netfilter_builtin_chain($table, $chain)) {
2138 $policy = 'ACCEPT';
2139 } else {
2140 $policy = '-';
2143 $result .= ":$chain $policy\ [0:0]\n";
2146 next if $option{flush};
2148 # dump rules
2149 foreach my $chain (sort keys %{$table_info->{chains}}) {
2150 my $chain_info = $table_info->{chains}{$chain};
2151 foreach my $rule (@{$chain_info->{rules}}) {
2152 $result .= "-A $chain$rule->{rule}\n";
2156 # do it
2157 $result .= "COMMIT\n";
2160 return $result;
2163 sub restore_domain($$) {
2164 my ($domain, $save) = @_;
2166 my $path = $domains{$domain}{tools}{'tables-restore'};
2168 local *RESTORE;
2169 open RESTORE, "|$path"
2170 or die "Failed to run $path: $!\n";
2172 print RESTORE $save;
2174 close RESTORE
2175 or die "Failed to run $path\n";
2178 sub execute_fast($$) {
2179 my ($domain, $domain_info) = @_;
2181 my $save = rules_to_save($domain, $domain_info);
2183 if ($option{lines}) {
2184 print LINES "$domain_info->{tools}{'tables-restore'} <<EOT\n"
2185 if $option{shell};
2186 print LINES $save;
2187 print LINES "EOT\n"
2188 if $option{shell};
2191 return if $option{noexec};
2193 eval {
2194 restore_domain($domain, $save);
2196 if ($@) {
2197 print STDERR $@;
2198 return 1;
2201 return;
2204 sub rollback() {
2205 my $error;
2206 while (my ($domain, $domain_info) = each %domains) {
2207 next unless $domain_info->{enabled};
2208 unless (defined $domain_info->{tools}{'tables-restore'}) {
2209 print STDERR "Cannot rollback domain '$domain' because there is no ${domain}tables-restore\n";
2210 next;
2213 my $reset = '';
2214 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2215 my $reset_chain = '';
2216 foreach my $chain (keys %{$table_info->{chains}{$table}}) {
2217 next unless is_netfilter_builtin_chain($table, $chain);
2218 $reset_chain .= ":${chain} ACCEPT [0:0]\n";
2220 $reset .= "*${table}\n${reset_chain}COMMIT\n"
2221 if length $reset_chain;
2224 $reset .= $domain_info->{previous}
2225 if defined $domain_info->{previous};
2227 restore_domain($domain, $reset);
2230 print STDERR "\nFirewall rules rolled back.\n" unless $error;
2231 exit 1;
2234 sub alrm_handler {
2235 # do nothing, just interrupt a system call
2238 sub confirm_rules() {
2239 $SIG{ALRM} = \&alrm_handler;
2241 alarm(5);
2243 print STDERR "\n"
2244 . "ferm has applied the new firewall rules.\n"
2245 . "Please type 'yes' to confirm:\n";
2246 STDERR->flush();
2248 alarm(30);
2250 my $line = '';
2251 STDIN->sysread($line, 3);
2253 eval {
2254 require POSIX;
2255 POSIX::tcflush(*STDIN, 2);
2257 print STDERR "$@" if $@;
2259 $SIG{ALRM} = 'DEFAULT';
2261 return $line eq 'yes';
2264 # end of ferm
2266 __END__
2268 =head1 NAME
2270 ferm - a firewall rule parser for linux
2272 =head1 SYNOPSIS
2274 B<ferm> I<options> I<inputfiles>
2276 =head1 OPTIONS
2278 -n, --noexec Do not execute the rules, just simulate
2279 -F, --flush Flush all netfilter tables managed by ferm
2280 -l, --lines Show all rules that were created
2281 -i, --interactive Interactive mode: revert if user does not confirm
2282 --remote Remote mode; ignore host specific configuration.
2283 This implies --noexec and --lines.
2284 -V, --version Show current version number
2285 -h, --help Look at this text
2286 --fast Generate an iptables-save file, used by iptables-restore
2287 --shell Generate a shell script which calls iptables-restore
2288 --domain {ip|ip6} Handle only the specified domain
2289 --def '$name=v' Override a variable
2291 =cut