merged {has_action} setters
[ferm.git] / src / ferm
blob672c5e56a575256d38acffc8b671707beac56684
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 use vars qw(%builtin_keywords);
367 sub get_builtin_keywords($) {
368 my $domain_family = shift;
369 return {} unless defined $domain_family;
371 return {%{$builtin_keywords{$domain_family}}}
372 if exists $builtin_keywords{$domain_family};
374 return {} unless exists $match_defs{$domain_family};
375 my $defs_kw = $match_defs{$domain_family}{''}{keywords};
376 my %keywords = map { $_ => ['builtin', '', $defs_kw->{$_} ] } keys %$defs_kw;
378 $builtin_keywords{$domain_family} = \%keywords;
379 return {%keywords};
382 # parameter parser for ipt_multiport
383 sub multiport_params {
384 my $fw = shift;
386 # multiport only allows 15 ports at a time. For this
387 # reason, we do a little magic here: split the ports
388 # into portions of 15, and handle these portions as
389 # array elements
391 my $proto = $fw->{protocol};
392 error('To use multiport, you have to specify "proto tcp" or "proto udp" first')
393 unless defined $proto and grep { /^(?:tcp|udp|udplite)$/ } to_array($proto);
395 my $value = getvalues(undef, undef,
396 allow_negation => 1,
397 allow_array_negation => 1);
398 if (ref $value and ref $value eq 'ARRAY') {
399 my @value = @$value;
400 my @params;
402 while (@value) {
403 push @params, join(',', splice(@value, 0, 15));
406 return @params == 1
407 ? $params[0]
408 : \@params;
409 } else {
410 return join_value(',', $value);
414 # initialize stack: command line definitions
415 unshift @stack, {};
417 # Get command line stuff
418 if ($has_getopt) {
419 my ($opt_noexec, $opt_flush, $opt_lines, $opt_interactive,
420 $opt_verbose, $opt_debug,
421 $opt_help,
422 $opt_version, $opt_test, $opt_fast, $opt_shell,
423 $opt_domain);
425 Getopt::Long::Configure('bundling', 'auto_help', 'no_ignore_case',
426 'no_auto_abbrev');
428 sub opt_def {
429 my ($opt, $value) = @_;
430 die 'Invalid --def specification'
431 unless $value =~ /^\$?(\w+)=(.*)$/s;
432 my ($name, $unparsed_value) = ($1, $2);
433 my $tokens = tokenize_string($unparsed_value);
434 my $value = getvalues(\&next_array_token, $tokens);
435 die 'Extra tokens after --def'
436 if @$tokens > 0;
437 $stack[0]{vars}{$name} = $value;
440 local $SIG{__WARN__} = sub { die $_[0]; };
441 GetOptions('noexec|n' => \$opt_noexec,
442 'flush|F' => \$opt_flush,
443 'lines|l' => \$opt_lines,
444 'interactive|i' => \$opt_interactive,
445 'verbose|v' => \$opt_verbose,
446 'debug|d' => \$opt_debug,
447 'help|h' => \$opt_help,
448 'version|V' => \$opt_version,
449 test => \$opt_test,
450 remote => \$opt_test,
451 fast => \$opt_fast,
452 shell => \$opt_shell,
453 'domain=s' => \$opt_domain,
454 'def=s' => \&opt_def,
457 if (defined $opt_help) {
458 require Pod::Usage;
459 Pod::Usage::pod2usage(-exitstatus => 0);
462 if (defined $opt_version) {
463 printversion();
464 exit 0;
467 $option{'noexec'} = (defined $opt_noexec);
468 $option{flush} = defined $opt_flush;
469 $option{'lines'} = (defined $opt_lines);
470 $option{interactive} = (defined $opt_interactive);
471 $option{test} = (defined $opt_test);
473 if ($option{test}) {
474 $option{noexec} = 1;
475 $option{lines} = 1;
478 delete $option{interactive} if $option{noexec};
480 mydie('ferm interactive mode not possible: /dev/stdin is not a tty')
481 if $option{interactive} and not -t STDIN;
482 mydie('ferm interactive mode not possible: /dev/stderr is not a tty')
483 if $option{interactive} and not -t STDERR;
485 $option{fast} = 1 if defined $opt_fast;
487 if (defined $opt_shell) {
488 $option{$_} = 1 foreach qw(shell fast lines);
491 $option{domain} = $opt_domain if defined $opt_domain;
493 print STDERR "Warning: ignoring the obsolete --debug option\n"
494 if defined $opt_debug;
495 print STDERR "Warning: ignoring the obsolete --verbose option\n"
496 if defined $opt_verbose;
497 } else {
498 # tiny getopt emulation for microperl
499 my $filename;
500 foreach (@ARGV) {
501 if ($_ eq '--noexec' or $_ eq '-n') {
502 $option{noexec} = 1;
503 } elsif ($_ eq '--lines' or $_ eq '-l') {
504 $option{lines} = 1;
505 } elsif ($_ eq '--fast') {
506 $option{fast} = 1;
507 } elsif ($_ eq '--test') {
508 $option{test} = 1;
509 $option{noexec} = 1;
510 $option{lines} = 1;
511 } elsif ($_ eq '--shell') {
512 $option{$_} = 1 foreach qw(shell fast lines);
513 } elsif (/^-/) {
514 printf STDERR "Usage: ferm [--noexec] [--lines] [--fast] [--shell] FILENAME\n";
515 exit 1;
516 } else {
517 $filename = $_;
520 undef @ARGV;
521 push @ARGV, $filename;
524 unless (@ARGV == 1) {
525 require Pod::Usage;
526 Pod::Usage::pod2usage(-exitstatus => 1);
529 if ($has_strict) {
530 open LINES, ">&STDOUT" if $option{lines};
531 open STDOUT, ">&STDERR" if $option{shell};
532 } else {
533 # microperl can't redirect file handles
534 *LINES = *STDOUT;
536 if ($option{fast} and not $option{noexec}) {
537 print STDERR "Sorry, ferm on microperl does not allow --fast without --noexec\n";
538 exit 1
542 unshift @stack, {};
543 open_script($ARGV[0]);
545 # parse all input recursively
546 enter(0);
547 die unless @stack == 2;
549 # execute all generated rules
550 my $status;
552 foreach my $cmd (@pre_hooks) {
553 print LINES "$cmd\n" if $option{lines};
554 system($cmd) unless $option{noexec};
557 while (my ($domain, $domain_info) = each %domains) {
558 next unless $domain_info->{enabled};
559 my $s = $option{fast} &&
560 defined $domain_info->{tools}{'tables-restore'}
561 ? execute_fast($domain, $domain_info)
562 : execute_slow($domain, $domain_info);
563 $status = $s if defined $s;
566 foreach my $cmd (@post_hooks) {
567 print "$cmd\n" if $option{lines};
568 system($cmd) unless $option{noexec};
571 if (defined $status) {
572 rollback();
573 exit $status;
576 # ask user, and rollback if there is no confirmation
578 confirm_rules() or rollback() if $option{interactive};
580 exit 0;
582 # end of program execution!
585 # funcs
587 sub printversion {
588 print "ferm $VERSION\n";
589 print "Copyright (C) 2001-2008 Auke Kok, Max Kellermann\n";
590 print "This program is free software released under GPLv2.\n";
591 print "See the included COPYING file for license details.\n";
595 sub mydie {
596 print STDERR @_;
597 print STDERR "\n";
598 exit 1;
602 sub error {
603 # returns a nice formatted error message, showing the
604 # location of the error.
605 my $tabs = 0;
606 my @lines;
607 my $l = 0;
608 my @words = map { @$_ } @{$script->{past_tokens}};
610 for my $w ( 0 .. $#words ) {
611 if ($words[$w] eq "\x29")
612 { $l++ ; $lines[$l] = " " x ($tabs-- -1) ;};
613 if ($words[$w] eq "\x28")
614 { $l++ ; $lines[$l] = " " x $tabs++ ;};
615 if ($words[$w] eq "\x7d")
616 { $l++ ; $lines[$l] = " " x ($tabs-- -1) ;};
617 if ($words[$w] eq "\x7b")
618 { $l++ ; $lines[$l] = " " x $tabs++ ;};
619 if ( $l > $#lines ) { $lines[$l] = "" };
620 $lines[$l] .= $words[$w] . " ";
621 if ($words[$w] eq "\x28")
622 { $l++ ; $lines[$l] = " " x $tabs ;};
623 if (($words[$w] eq "\x29") && ($words[$w+1] ne "\x7b"))
624 { $l++ ; $lines[$l] = " " x $tabs ;};
625 if ($words[$w] eq "\x7b")
626 { $l++ ; $lines[$l] = " " x $tabs ;};
627 if (($words[$w] eq "\x7d") && ($words[$w+1] ne "\x7d"))
628 { $l++ ; $lines[$l] = " " x $tabs ;};
629 if (($words[$w] eq "\x3b") && ($words[$w+1] ne "\x7d"))
630 { $l++ ; $lines[$l] = " " x $tabs ;}
631 if ($words[$w-1] eq "option")
632 { $l++ ; $lines[$l] = " " x $tabs ;}
634 my $start = $#lines - 4;
635 if ($start < 0) { $start = 0 } ;
636 print STDERR "Error in $script->{filename} line $script->{line}:\n";
637 for $l ( $start .. $#lines)
638 { print STDERR $lines[$l]; if ($l != $#lines ) {print STDERR "\n"} ; };
639 print STDERR "<--\n";
640 mydie(@_);
643 # print a warning message about code from an input file
644 sub warning {
645 print STDERR "Warning in $script->{filename} line $script->{line}: "
646 . (shift) . "\n";
649 sub find_tool($) {
650 my $name = shift;
651 return $name if $option{test};
652 for my $path ('/sbin', split ':', $ENV{PATH}) {
653 my $ret = "$path/$name";
654 return $ret if -x $ret;
656 die "$name not found in PATH\n";
659 sub initialize_domain {
660 my $domain = shift;
661 my $domain_info = $domains{$domain} ||= {};
663 return if exists $domain_info->{initialized};
665 die "Invalid domain '$domain'\n" unless $domain =~ /^(?:ip6?|arp|eb)$/;
667 my @tools = qw(tables);
668 push @tools, qw(tables-save tables-restore)
669 if $domain =~ /^ip6?$/;
671 # determine the location of this domain's tools
672 my %tools = map { $_ => find_tool($domain . $_) } @tools;
673 $domain_info->{tools} = \%tools;
675 # make tables-save tell us about the state of this domain
676 # (which tables and chains do exist?), also remember the old
677 # save data which may be used later by the rollback function
678 local *SAVE;
679 if (!$option{test} &&
680 exists $tools{'tables-save'} &&
681 open(SAVE, "$tools{'tables-save'}|")) {
682 my $save = '';
684 my $table_info;
685 while (<SAVE>) {
686 $save .= $_;
688 if (/^\*(\w+)/) {
689 my $table = $1;
690 $table_info = $domain_info->{tables}{$table} ||= {};
691 } elsif (defined $table_info and /^:(\w+)\s+(\S+)/
692 and $2 ne '-') {
693 $table_info->{chains}{$1}{builtin} = 1;
694 $table_info->{has_builtin} = 1;
698 # for rollback
699 $domain_info->{previous} = $save;
702 $domain_info->{initialized} = 1;
705 # split the an input string into words and delete comments
706 sub tokenize_string($) {
707 my $string = shift;
709 my @ret;
711 foreach my $word ($string =~ m/(".*?"|'.*?'|`.*?`|[!,=&\$\%\(\){};]|[-+\w\/\.:]+|@\w+|#)/g) {
712 last if $word eq '#';
713 push @ret, $word;
716 return \@ret;
719 # shift an array; helper function to be passed to &getvar / &getvalues
720 sub next_array_token {
721 my $array = shift;
722 shift @$array;
725 # read some more tokens from the input file into a buffer
726 sub prepare_tokens() {
727 my $tokens = $script->{tokens};
728 while (@$tokens == 0) {
729 my $handle = $script->{handle};
730 my $line = <$handle>;
731 return unless defined $line;
733 $script->{line} ++;
735 # the next parser stage eats this
736 push @$tokens, @{tokenize_string($line)};
739 return 1;
742 # open a ferm sub script
743 sub open_script($) {
744 my $filename = shift;
746 for (my $s = $script; defined $s; $s = $s->{parent}) {
747 mydie("Circular reference in $script->{filename} line $script->{line}: $filename")
748 if $s->{filename} eq $filename;
751 local *FILE;
752 open FILE, "<$filename"
753 or mydie("Failed to open $filename: $!");
754 my $handle = *FILE;
756 $script = { filename => $filename,
757 handle => $handle,
758 line => 0,
759 past_tokens => [],
760 tokens => [],
761 parent => $script,
764 return $script;
767 # collect script filenames which are being included
768 sub collect_filenames(@) {
769 my @ret;
771 # determine the current script's parent directory for relative
772 # file names
773 die unless defined $script;
774 my $parent_dir = $script->{filename} =~ m,^(.*/),
775 ? $1 : './';
777 foreach my $pathname (@_) {
778 # non-absolute file names are relative to the parent script's
779 # file name
780 $pathname = $parent_dir . $pathname
781 unless $pathname =~ m,^/,;
783 if ($pathname =~ m,/$,) {
784 # include all regular files in a directory
786 error("'$pathname' is not a directory")
787 unless -d $pathname;
789 local *DIR;
790 opendir DIR, $pathname
791 or error("Failed to open directory '$pathname': $!");
792 my @names = readdir DIR;
793 closedir DIR;
795 # sort those names for a well-defined order
796 foreach my $name (sort { $a cmp $b } @names) {
797 # don't include hidden and backup files
798 next if /^\.|~$/;
800 my $filename = $pathname . $name;
801 push @ret, $filename
802 if -f $filename;
804 } elsif ($pathname =~ m,\|$,) {
805 # run a program and use its output
806 push @ret, $pathname;
807 } elsif ($pathname =~ m,^\|,) {
808 error('This kind of pipe is not allowed');
809 } else {
810 # include a regular file
812 error("'$pathname' is a directory; maybe use trailing '/' to include a directory?")
813 if -d $pathname;
814 error("'$pathname' is not a file")
815 unless -f $pathname;
817 push @ret, $pathname;
821 return @ret;
824 # peek a token from the queue, but don't remove it
825 sub peek_token() {
826 return unless prepare_tokens();
827 return $script->{tokens}[0];
830 # get a token from the queue
831 sub next_token() {
832 return unless prepare_tokens();
833 my $token = shift @{$script->{tokens}};
835 # update $script->{past_tokens}
836 my $past_tokens = $script->{past_tokens};
838 if (@$past_tokens > 0) {
839 my $prev_token = $past_tokens->[-1][-1];
840 $past_tokens->[-1] = @$past_tokens > 1 ? ['{'] : []
841 if $prev_token eq ';';
842 pop @$past_tokens
843 if $prev_token eq '}';
846 push @$past_tokens, [] if $token eq '{' or @$past_tokens == 0;
847 push @{$past_tokens->[-1]}, $token;
849 # return
850 return $token;
853 sub expect_token($;$) {
854 my $expect = shift;
855 my $msg = shift;
856 my $token = next_token();
857 error($msg || "'$expect' expected")
858 unless defined $token and $token eq $expect;
861 # require that another token exists, and that it's not a "special"
862 # token, e.g. ";" and "{"
863 sub require_next_token {
864 my $code = shift || \&next_token;
866 my $token = &$code(@_);
868 error('unexpected end of file')
869 unless defined $token;
871 error("'$token' not allowed here")
872 if $token =~ /^[;{}]$/;
874 return $token;
877 # return the value of a variable
878 sub variable_value($) {
879 my $name = shift;
881 foreach (@stack) {
882 return $_->{vars}{$name}
883 if exists $_->{vars}{$name};
886 return $stack[0]{auto}{$name}
887 if exists $stack[0]{auto}{$name};
889 return;
892 # determine the value of a variable, die if the value is an array
893 sub string_variable_value($) {
894 my $name = shift;
895 my $value = variable_value($name);
897 error("variable '$name' must be a string, but it is an array")
898 if ref $value;
900 return $value;
903 # similar to the built-in "join" function, but also handle negated
904 # values in a special way
905 sub join_value($$) {
906 my ($expr, $value) = @_;
908 unless (ref $value) {
909 return $value;
910 } elsif (ref $value eq 'ARRAY') {
911 return join($expr, @$value);
912 } elsif (ref $value eq 'negated') {
913 # bless'negated' is a special marker for negated values
914 $value = join_value($expr, $value->[0]);
915 return bless [ $value ], 'negated';
916 } else {
917 die;
921 # returns the next parameter, which may either be a scalar or an array
922 sub getvalues {
923 my ($code, $param) = (shift, shift);
924 my %options = @_;
926 my $token = require_next_token($code, $param);
928 if ($token eq '(') {
929 # read an array until ")"
930 my @wordlist;
932 for (;;) {
933 $token = getvalues($code, $param,
934 parenthesis_allowed => 1,
935 comma_allowed => 1);
937 unless (ref $token) {
938 last if $token eq ')';
940 if ($token eq ',') {
941 error('Comma is not allowed within arrays, please use only a space');
942 next;
945 push @wordlist, $token;
946 } elsif (ref $token eq 'ARRAY') {
947 push @wordlist, @$token;
948 } else {
949 error('unknown toke type');
953 error('empty array not allowed here')
954 unless @wordlist or not $options{non_empty};
956 return @wordlist == 1
957 ? $wordlist[0]
958 : \@wordlist;
959 } elsif ($token =~ /^\`(.*)\`$/s) {
960 # execute a shell command, insert output
961 my $command = $1;
962 my $output = `$command`;
963 unless ($? == 0) {
964 if ($? == -1) {
965 error("failed to execute: $!");
966 } elsif ($? & 0x7f) {
967 error("child died with signal " . ($? & 0x7f));
968 } elsif ($? >> 8) {
969 error("child exited with status " . ($? >> 8));
973 # remove comments
974 $output =~ s/#.*//mg;
976 # tokenize
977 my @tokens = grep { length } split /\s+/s, $output;
979 my @values;
980 while (@tokens) {
981 my $value = getvalues(\&next_array_token, \@tokens);
982 push @values, to_array($value);
985 # and recurse
986 return @values == 1
987 ? $values[0]
988 : \@values;
989 } elsif ($token =~ /^\'(.*)\'$/s) {
990 # single quotes: a string
991 return $1;
992 } elsif ($token =~ /^\"(.*)\"$/s) {
993 # double quotes: a string with escapes
994 $token = $1;
995 $token =~ s,\$(\w+),string_variable_value($1),eg;
996 return $token;
997 } elsif ($token eq '!') {
998 error('negation is not allowed here')
999 unless $options{allow_negation};
1001 $token = getvalues($code, $param);
1003 error('it is not possible to negate an array')
1004 if ref $token and not $options{allow_array_negation};
1006 return bless [ $token ], 'negated';
1007 } elsif ($token eq ',') {
1008 return $token
1009 if $options{comma_allowed};
1011 error('comma is not allowed here');
1012 } elsif ($token eq '=') {
1013 error('equals operator ("=") is not allowed here');
1014 } elsif ($token eq '$') {
1015 my $name = require_next_token($code, $param);
1016 error('variable name expected - if you want to concatenate strings, try using double quotes')
1017 unless $name =~ /^\w+$/;
1019 my $value = variable_value($name);
1021 error("no such variable: \$$name")
1022 unless defined $value;
1024 return $value;
1025 } elsif ($token eq '&') {
1026 error("function calls are not allowed as keyword parameter");
1027 } elsif ($token eq ')' and not $options{parenthesis_allowed}) {
1028 error('Syntax error');
1029 } elsif ($token =~ /^@/) {
1030 if ($token eq '@resolve') {
1031 my @params = get_function_params();
1032 error('Usage: @resolve((hostname ...))')
1033 unless @params == 1;
1034 eval { require Net::DNS; };
1035 error('For the @resolve() function, you need the Perl library Net::DNS')
1036 if $@;
1037 my $type = 'A';
1038 my $resolver = new Net::DNS::Resolver;
1039 my @result;
1040 foreach my $hostname (to_array($params[0])) {
1041 my $query = $resolver->search($hostname, $type);
1042 error("DNS query for '$hostname' failed: " . $resolver->errorstring)
1043 unless $query;
1044 foreach my $rr ($query->answer) {
1045 next unless $rr->type eq $type;
1046 push @result, $rr->address;
1049 return \@result;
1050 } else {
1051 error("unknown ferm built-in function");
1053 } else {
1054 return $token;
1058 # returns the next parameter, but only allow a scalar
1059 sub getvar {
1060 my $token = getvalues(@_);
1062 error('array not allowed here')
1063 if ref $token and ref $token eq 'ARRAY';
1065 return $token;
1068 sub get_function_params(%) {
1069 expect_token('(', 'function name must be followed by "()"');
1071 my $token = peek_token();
1072 if ($token eq ')') {
1073 require_next_token;
1074 return;
1077 my @params;
1079 while (1) {
1080 if (@params > 0) {
1081 $token = require_next_token();
1082 last
1083 if $token eq ')';
1085 error('"," expected')
1086 unless $token eq ',';
1089 push @params, getvalues(undef, undef, @_);
1092 return @params;
1095 # collect all tokens in a flat array reference until the end of the
1096 # command is reached
1097 sub collect_tokens() {
1098 my @level;
1099 my @tokens;
1101 while (1) {
1102 my $keyword = next_token();
1103 error('unexpected end of file within function/variable declaration')
1104 unless defined $keyword;
1106 if ($keyword =~ /^[\{\(]$/) {
1107 push @level, $keyword;
1108 } elsif ($keyword =~ /^[\}\)]$/) {
1109 my $expected = $keyword;
1110 $expected =~ tr/\}\)/\{\(/;
1111 my $opener = pop @level;
1112 error("unmatched '$keyword'")
1113 unless defined $opener and $opener eq $expected;
1114 } elsif ($keyword eq ';' and @level == 0) {
1115 last;
1118 push @tokens, $keyword;
1120 last
1121 if $keyword eq '}' and @level == 0;
1124 return \@tokens;
1128 # returns the specified value as an array. dereference arrayrefs
1129 sub to_array($) {
1130 my $value = shift;
1131 die unless wantarray;
1132 die if @_;
1133 unless (ref $value) {
1134 return $value;
1135 } elsif (ref $value eq 'ARRAY') {
1136 return @$value;
1137 } else {
1138 die;
1142 # evaluate the specified value as bool
1143 sub eval_bool($) {
1144 my $value = shift;
1145 die if wantarray;
1146 die if @_;
1147 unless (ref $value) {
1148 return $value;
1149 } elsif (ref $value eq 'ARRAY') {
1150 return @$value > 0;
1151 } else {
1152 die;
1156 sub is_netfilter_core_target($) {
1157 my $target = shift;
1158 die unless defined $target and length $target;
1160 return $target =~ /^(?:ACCEPT|DROP|RETURN|QUEUE)$/;
1163 sub is_netfilter_module_target($$) {
1164 my ($domain_family, $target) = @_;
1165 die unless defined $target and length $target;
1167 return defined $domain_family &&
1168 exists $target_defs{$domain_family} &&
1169 $target_defs{$domain_family}{$target};
1172 sub is_netfilter_builtin_chain($$) {
1173 my ($table, $chain) = @_;
1175 return grep { $_ eq $chain }
1176 qw(PREROUTING INPUT FORWARD OUTPUT POSTROUTING);
1179 sub netfilter_canonical_protocol($) {
1180 my $proto = shift;
1181 return 'icmpv6'
1182 if $proto eq 'ipv6-icmp';
1183 return 'mh'
1184 if $proto eq 'ipv6-mh';
1185 return $proto;
1188 sub netfilter_protocol_module($) {
1189 my $proto = shift;
1190 return unless defined $proto;
1191 return 'icmp6'
1192 if $proto eq 'icmpv6';
1193 return $proto;
1196 # escape the string in a way safe for the shell
1197 sub shell_escape($) {
1198 my $token = shift;
1200 return $token if $token =~ /^[-_a-zA-Z0-9]+$/s;
1202 if ($option{fast}) {
1203 # iptables-save/iptables-restore are quite buggy concerning
1204 # escaping and special characters... we're trying our best
1205 # here
1207 $token =~ s,",',g;
1208 $token = '"' . $token . '"'
1209 if $token =~ /[\s\'\\;&]/s;
1210 } else {
1211 return $token
1212 if $token =~ /^\`.*\`$/;
1213 $token =~ s/'/\\'/g;
1214 $token = '\'' . $token . '\''
1215 if $token =~ /[\s\"\\;<>&|]/s;
1218 return $token;
1221 # append an option to the shell command line, using information from
1222 # the module definition (see %match_defs etc.)
1223 sub shell_append_option($$$) {
1224 my ($ref, $keyword, $value) = @_;
1226 if (ref $value) {
1227 if (ref $value eq 'negated') {
1228 $value = $value->[0];
1229 $keyword .= ' !';
1230 } elsif (ref $value eq 'pre_negated') {
1231 $value = $value->[0];
1232 $$ref .= ' !';
1236 unless (defined $value) {
1237 $$ref .= " --$keyword";
1238 } elsif (ref $value) {
1239 if (ref $value eq 'params') {
1240 $$ref .= " --$keyword ";
1241 $$ref .= join(' ', map { shell_escape($_) } @$value);
1242 } elsif (ref $value eq 'multi') {
1243 foreach (@$value) {
1244 $$ref .= " --$keyword " . shell_escape($_);
1246 } else {
1247 die;
1249 } else {
1250 $$ref .= " --$keyword " . shell_escape($value);
1254 # convert an internal rule structure into an iptables call
1255 sub tables($$$) {
1256 my ($table_info, $chain_info, $rule) = @_;
1258 return if $option{flush};
1260 # return if this is a declaration-only rule
1261 return
1262 unless $rule->{has_rule};
1264 my $rr = '';
1266 # general iptables options
1268 my $protocol_module = $rule->{protocol_module};
1270 foreach my $option (@{$rule->{options}}) {
1271 shell_append_option(\$rr, $option->[0], $option->[1]);
1273 if ($protocol_module and $option->[0] eq 'protocol') {
1274 $rr .= " --match $option->[1]"
1275 unless exists $rule->{match}{$option->[1]};
1276 undef $protocol_module;
1280 # this line is done
1281 my $chain_rules = $chain_info->{rules} ||= [];
1282 push @$chain_rules, { rule => $rr,
1283 script => $rule->{script},
1287 sub transform_rule($$) {
1288 my ($domain, $rule) = @_;
1290 $rule->{options}[$rule->{protocol_index}][1] = 'icmpv6'
1291 if $domain eq 'ip6' and $rule->{protocol} eq 'icmp';
1294 sub printrule($$$$) {
1295 my ($domain, $table, $chain, $rule) = @_;
1297 transform_rule($domain, $rule);
1299 my $domain_info = $domains{$domain};
1300 $domain_info->{enabled} = 1;
1301 my $table_info = $domain_info->{tables}{$table} ||= {};
1302 my $chain_info = $table_info->{chains}{$chain} ||= {};
1304 # prints all rules in a hash
1305 tables($table_info, $chain_info, $rule);
1309 sub check_unfold(\@$$) {
1310 my ($unfold, $parent, $key) = @_;
1312 return unless ref $parent->{$key} and
1313 ref $parent->{$key} eq 'ARRAY';
1315 push @$unfold, $parent, $key, $parent->{$key};
1318 sub mkrules2($$$$) {
1319 my ($domain, $table, $chain, $fw) = @_;
1321 my @unfold;
1322 foreach my $option (@{$fw->{options}}) {
1323 push @unfold, $option
1324 if ref $option->[1] and ref $option->[1] eq 'ARRAY';
1327 if (@unfold == 0) {
1328 printrule($domain, $table, $chain, $fw);
1329 return;
1332 sub dofr {
1333 my $fw = shift;
1334 my ($domain, $table, $chain) = (shift, shift, shift);
1335 my $option = shift;
1336 my @values = @{$option->[1]};
1338 foreach my $value (@values) {
1339 $option->[1] = $value;
1340 $fw->{protocol} = $value if $option->[0] eq 'protocol';
1342 if (@_) {
1343 dofr($fw, $domain, $table, $chain, @_);
1344 } else {
1345 printrule($domain, $table, $chain, $fw);
1350 dofr($fw, $domain, $table, $chain, @unfold);
1353 # convert a bunch of internal rule structures in iptables calls,
1354 # unfold arrays during that
1355 sub mkrules($) {
1356 my $fw = shift;
1358 foreach my $domain (to_array $fw->{domain}) {
1359 foreach my $table (to_array $fw->{table}) {
1360 foreach my $chain (to_array $fw->{chain}) {
1361 mkrules2($domain, $table, $chain, $fw);
1367 sub filter_domains($) {
1368 my $domains = shift;
1369 my $result = [];
1371 foreach my $domain (to_array $domains) {
1372 next if exists $option{domain}
1373 and $domain ne $option{domain};
1375 eval {
1376 initialize_domain($domain);
1378 error($@) if $@;
1380 push @$result, $domain;
1383 return @$result == 1 ? $result->[0] : $result;
1386 # parse a keyword from a module definition
1387 sub parse_keyword($$$$) {
1388 my ($current, $def, $keyword, $negated_ref) = @_;
1390 my $params = $def->{params};
1392 my $value;
1394 my $negated;
1395 if ($$negated_ref && exists $def->{pre_negation}) {
1396 $negated = 1;
1397 undef $$negated_ref;
1400 unless (defined $params) {
1401 undef $value;
1402 } elsif (ref $params && ref $params eq 'CODE') {
1403 $value = &$params($current);
1404 } elsif ($params eq 'm') {
1405 $value = bless [ to_array getvalues() ], 'multi';
1406 } elsif ($params =~ /^[a-z]/) {
1407 if (exists $def->{negation} and not $negated) {
1408 my $token = peek_token();
1409 if ($token eq '!') {
1410 require_next_token;
1411 $negated = 1;
1415 my @params;
1416 foreach my $p (split(//, $params)) {
1417 if ($p eq 's') {
1418 push @params, getvar();
1419 } elsif ($p eq 'c') {
1420 my @v = to_array getvalues(undef, undef,
1421 non_empty => 1);
1422 push @params, join(',', @v);
1423 } else {
1424 die;
1428 $value = @params == 1
1429 ? $params[0]
1430 : bless \@params, 'params';
1431 } elsif ($params == 1) {
1432 if (exists $def->{negation} and not $negated) {
1433 my $token = peek_token();
1434 if ($token eq '!') {
1435 require_next_token;
1436 $negated = 1;
1440 $value = getvalues();
1442 warning("log-prefix is too long; truncating to 29 characters: '$1'")
1443 if $keyword eq 'log-prefix' && $value =~ s,^(.{29}).+$,$1,;
1444 } else {
1445 if (exists $def->{negation} and not $negated) {
1446 my $token = peek_token();
1447 if ($token eq '!') {
1448 require_next_token;
1449 $negated = 1;
1453 $value = bless [ map {
1454 getvar()
1455 } (1..$params) ], 'params';
1458 $value = bless [ $value ], exists $def->{pre_negation} ? 'pre_negated' : 'negated'
1459 if $negated;
1461 return $value;
1464 sub append_option(\%$$) {
1465 my ($rule, $name, $value) = @_;
1466 push @{$rule->{options}}, [ $name, $value ];
1469 # parse options of a module
1470 sub parse_option($$$$) {
1471 my ($def, $current, $keyword, $negated_ref) = @_;
1473 while (exists $def->{alias}) {
1474 ($keyword, $def) = @{$def->{alias}};
1475 die unless defined $def;
1478 append_option(%$current, $keyword,
1479 parse_keyword($current, $def, $keyword, $negated_ref));
1480 return 1;
1483 # parse options for a protocol module definition
1484 sub parse_protocol_options($$$$) {
1485 my ($current, $proto, $keyword, $negated_ref) = @_;
1487 my $domain_family = $current->{'domain_family'};
1488 my $proto_defs = $proto_defs{$domain_family};
1489 return unless defined $proto_defs;
1491 my $proto_def = $proto_defs->{$proto};
1492 return unless defined $proto_def and
1493 exists $proto_def->{keywords}{$keyword};
1495 my $module_name = $proto eq 'icmpv6' ? 'icmp6' : $proto;
1496 unless (exists $current->{match}{$module_name}) {
1497 append_option(%$current, 'match', $module_name);
1498 $current->{match}{$module_name} = 1;
1501 return parse_option($proto_def->{keywords}{$keyword},
1502 $current,
1503 $keyword, $negated_ref);
1506 sub copy_on_write($$) {
1507 my ($rule, $key) = @_;
1508 return unless exists $rule->{cow}{$key};
1509 $rule->{$key} = {%{$rule->{$key}}};
1510 delete $rule->{cow}{$key};
1513 sub new_level(\%$) {
1514 my ($current, $prev) = @_;
1516 %$current = ();
1517 if (defined $prev) {
1518 # copy data from previous level
1519 $current->{cow} = { keywords => 1, };
1520 $current->{keywords} = $prev->{keywords};
1521 $current->{match} = { %{$prev->{match}} };
1522 $current->{options} = [@{$prev->{options}}];
1523 foreach my $key (qw(domain domain_family table chain protocol protocol_index protocol_module has_action)) {
1524 $current->{$key} = $prev->{$key}
1525 if exists $prev->{$key};
1527 } else {
1528 $current->{cow} = {};
1529 $current->{keywords} = {};
1530 $current->{match} = {};
1531 $current->{options} = [];
1535 sub merge_keywords(\%$$$) {
1536 my ($rule, $type, $module, $keywords) = @_;
1537 copy_on_write($rule, 'keywords');
1538 while (my ($name, $def) = each %$keywords) {
1539 $rule->{keywords}{$name} = [ $type, $module, $def ];
1543 sub set_domain(\%$) {
1544 my ($rule, $domain) = @_;
1546 my $filtered_domain = filter_domains($domain);
1547 my $domain_family;
1548 unless (ref $domain) {
1549 $domain_family = $domain eq 'ip6' ? 'ip' : $domain;
1550 } elsif (@$domain == 0) {
1551 $domain_family = 'none';
1552 } elsif (grep { not /^ip6?$/s } @$domain) {
1553 error('Cannot combine non-IP domains');
1554 } else {
1555 $domain_family = 'ip';
1558 $rule->{domain_family} = $domain_family;
1559 $rule->{keywords} = get_builtin_keywords($domain_family);
1560 delete $rule->{cow}{keywords};
1562 $rule->{domain} = $stack[0]{auto}{DOMAIN} = $filtered_domain;
1565 sub set_module_target(\%$$) {
1566 my ($rule, $name, $defs) = @_;
1568 if ($name eq 'TCPMSS') {
1569 my $protos = $rule->{protocol};
1570 error('No protocol specified before TCPMSS')
1571 unless defined $protos;
1572 foreach my $proto (to_array $protos) {
1573 error('TCPMSS not available for protocol "$proto"')
1574 unless $proto eq 'tcp';
1578 merge_keywords(%$rule, 'target', $name, $defs->{keywords});
1581 # the main parser loop: read tokens, convert them into internal rule
1582 # structures
1583 sub enter($$) {
1584 my $lev = shift; # current recursion depth
1585 my $prev = shift; # previous rule hash
1587 # enter is the core of the firewall setup, it is a
1588 # simple parser program that recognizes keywords and
1589 # retreives parameters to set up the kernel routing
1590 # chains
1592 my $base_level = $script->{base_level} || 0;
1593 die if $base_level > $lev;
1595 my %current;
1596 new_level(%current, $prev);
1598 # read keywords 1 by 1 and dump into parser
1599 while (defined (my $keyword = next_token())) {
1600 # check if the current rule should be negated
1601 my $negated = $keyword eq '!';
1602 if ($negated) {
1603 # negation. get the next word which contains the 'real'
1604 # rule
1605 $keyword = getvar();
1607 error('unexpected end of file after negation')
1608 unless defined $keyword;
1611 # the core: parse all data
1612 for ($keyword)
1614 # deprecated keyword?
1615 if (exists $deprecated_keywords{$keyword}) {
1616 my $new_keyword = $deprecated_keywords{$keyword};
1617 warning("'$keyword' is deprecated, please use '$new_keyword' instead");
1618 $keyword = $new_keyword;
1621 # effectuation operator
1622 if ($keyword eq ';') {
1623 if ($current{has_rule} and not exists $current{has_action}) {
1624 # something is wrong when a rule was specifiedd,
1625 # but no action
1626 error('No action defined; did you mean "NOP"?');
1629 error('No chain defined') unless exists $current{chain};
1631 $current{script} = { filename => $script->{filename},
1632 line => $script->{line},
1635 mkrules(\%current);
1637 # and clean up variables set in this level
1638 new_level(%current, $prev);
1640 next;
1643 # conditional expression
1644 if ($keyword eq '@if') {
1645 unless (eval_bool(getvalues)) {
1646 collect_tokens;
1647 my $token = peek_token();
1648 require_next_token() if $token and $token eq '@else';
1651 next;
1654 if ($keyword eq '@else') {
1655 # hack: if this "else" has not been eaten by the "if"
1656 # handler above, we believe it came from an if clause
1657 # which evaluated "true" - remove the "else" part now.
1658 collect_tokens;
1659 next;
1662 # hooks for custom shell commands
1663 if ($keyword eq 'hook') {
1664 error('"hook" must be the first token in a command')
1665 if exists $current{domain};
1667 my $position = getvar();
1668 my $hooks;
1669 if ($position eq 'pre') {
1670 $hooks = \@pre_hooks;
1671 } elsif ($position eq 'post') {
1672 $hooks = \@post_hooks;
1673 } else {
1674 error("Invalid hook position: '$position'");
1677 push @$hooks, getvar();
1679 expect_token(';');
1680 next;
1683 # recursing operators
1684 if ($keyword eq '{') {
1685 # push stack
1686 my $old_stack_depth = @stack;
1688 unshift @stack, { auto => { %{$stack[0]{auto} || {}} } };
1690 # recurse
1691 enter($lev + 1, \%current);
1693 # pop stack
1694 shift @stack;
1695 die unless @stack == $old_stack_depth;
1697 # after a block, the command is finished, clear this
1698 # level
1699 new_level(%current, $prev);
1701 next;
1704 if ($keyword eq '}') {
1705 error('Unmatched "}"')
1706 if $lev <= $base_level;
1708 # consistency check: check if they havn't forgotten
1709 # the ';' before the last statement
1710 error('Missing semicolon before "}"')
1711 if $current{has_rule};
1713 # and exit
1714 return;
1717 # include another file
1718 if ($keyword eq '@include' or $keyword eq 'include') {
1719 my @files = collect_filenames to_array getvalues;
1720 $keyword = next_token;
1721 error('Missing ";" - "include FILENAME" must be the last command in a rule')
1722 unless defined $keyword and $keyword eq ';';
1724 foreach my $filename (@files) {
1725 # save old script, open new script
1726 my $old_script = $script;
1727 open_script($filename);
1728 $script->{base_level} = $lev + 1;
1730 # push stack
1731 my $old_stack_depth = @stack;
1733 my $stack = {};
1735 if (@stack > 0) {
1736 # include files may set variables for their parent
1737 $stack->{vars} = ($stack[0]{vars} ||= {});
1738 $stack->{functions} = ($stack[0]{functions} ||= {});
1739 $stack->{auto} = { %{ $stack[0]{auto} || {} } };
1742 unshift @stack, $stack;
1744 # parse the script
1745 enter($lev + 1, \%current);
1747 # pop stack
1748 shift @stack;
1749 die unless @stack == $old_stack_depth;
1751 # restore old script
1752 $script = $old_script;
1755 next;
1758 # definition of a variable or function
1759 if ($keyword eq '@def' or $keyword eq 'def') {
1760 error('"def" must be the first token in a command')
1761 if $current{has_rule};
1763 my $type = require_next_token();
1764 if ($type eq '$') {
1765 my $name = require_next_token();
1766 error('invalid variable name')
1767 unless $name =~ /^\w+$/;
1769 expect_token('=');
1771 my $value = getvalues(undef, undef, allow_negation => 1);
1773 expect_token(';');
1775 $stack[0]{vars}{$name} = $value
1776 unless exists $stack[-1]{vars}{$name};
1777 } elsif ($type eq '&') {
1778 my $name = require_next_token();
1779 error('invalid function name')
1780 unless $name =~ /^\w+$/;
1782 expect_token('(', 'function parameter list or "()" expected');
1784 my @params;
1785 while (1) {
1786 my $token = require_next_token();
1787 last if $token eq ')';
1789 if (@params > 0) {
1790 error('"," expected')
1791 unless $token eq ',';
1793 $token = require_next_token();
1796 error('"$" and parameter name expected')
1797 unless $token eq '$';
1799 $token = require_next_token();
1800 error('invalid function parameter name')
1801 unless $token =~ /^\w+$/;
1803 push @params, $token;
1806 my %function;
1808 $function{params} = \@params;
1810 expect_token('=');
1812 my $tokens = collect_tokens();
1813 $function{block} = 1 if grep { $_ eq '{' } @$tokens;
1814 $function{tokens} = $tokens;
1816 $stack[0]{functions}{$name} = \%function
1817 unless exists $stack[-1]{functions}{$name};
1818 } else {
1819 error('"$" (variable) or "&" (function) expected');
1822 next;
1825 # def references
1826 if ($keyword eq '$') {
1827 error('variable references are only allowed as keyword parameter');
1830 if ($keyword eq '&') {
1831 my $name = require_next_token;
1832 error('function name expected')
1833 unless $name =~ /^\w+$/;
1835 my $function;
1836 foreach (@stack) {
1837 $function = $_->{functions}{$name};
1838 last if defined $function;
1840 error("no such function: \&$name")
1841 unless defined $function;
1843 my $paramdef = $function->{params};
1844 die unless defined $paramdef;
1846 my @params = get_function_params(allow_negation => 1);
1848 error("Wrong number of parameters for function '\&$name': "
1849 . @$paramdef . " expected, " . @params . " given")
1850 unless @params == @$paramdef;
1852 my %vars;
1853 for (my $i = 0; $i < @params; $i++) {
1854 $vars{$paramdef->[$i]} = $params[$i];
1857 if ($function->{block}) {
1858 # block {} always ends the current rule, so if the
1859 # function contains a block, we have to require
1860 # the calling rule also ends here
1861 expect_token(';');
1864 my @tokens = @{$function->{tokens}};
1865 for (my $i = 0; $i < @tokens; $i++) {
1866 if ($tokens[$i] eq '$' and $i + 1 < @tokens and
1867 exists $vars{$tokens[$i + 1]}) {
1868 my @value = to_array($vars{$tokens[$i + 1]});
1869 @value = ('(', @value, ')')
1870 unless @tokens == 1;
1871 splice(@tokens, $i, 2, @value);
1872 $i += @value - 2;
1873 } elsif ($tokens[$i] =~ m,^"(.*)"$,) {
1874 $tokens[$i] =~ s,\$(\w+),exists $vars{$1} ? $vars{$1} : "\$$1",eg;
1878 unshift @{$script->{tokens}}, @tokens;
1880 next;
1883 # where to put the rule?
1884 if ($keyword eq 'domain') {
1885 error('Domain is already specified')
1886 if exists $current{domain};
1888 set_domain(%current, getvalues());
1889 next;
1892 if ($keyword eq 'table') {
1893 error('Table is already specified')
1894 if exists $current{table};
1895 $current{table} = $stack[0]{auto}{TABLE} = getvalues();
1897 set_domain(%current, 'ip')
1898 unless exists $current{domain};
1900 next;
1903 if ($keyword eq 'chain') {
1904 error('Chain is already specified')
1905 if exists $current{chain};
1906 $current{chain} = $stack[0]{auto}{CHAIN} = getvalues();
1908 # ferm 1.1 allowed lower case built-in chain names
1909 foreach (ref $current{chain} ? @{$current{chain}} : $current{chain}) {
1910 error('Please write built-in chain names in upper case')
1911 if /^(?:input|forward|output|prerouting|postrouting)$/;
1914 set_domain(%current, 'ip')
1915 unless exists $current{domain};
1917 $current{table} = 'filter'
1918 unless exists $current{table};
1920 next;
1923 error('Chain must be specified')
1924 unless exists $current{chain};
1926 # policy for built-in chain
1927 if ($keyword eq 'policy') {
1928 error('Cannot specify matches for policy')
1929 if $current{has_rule};
1931 my $policy = getvar();
1932 error("Invalid policy target: $policy")
1933 unless $policy =~ /^(?:ACCEPT|DROP)$/;
1935 expect_token(';');
1937 foreach my $domain (to_array $current{domain}) {
1938 foreach my $table (to_array $current{table}) {
1939 foreach my $chain (to_array $current{chain}) {
1940 $domains{$domain}{tables}{$table}{chains}{$chain}{policy} = $policy;
1945 new_level(%current, $prev);
1946 next;
1949 # create a subchain
1950 if ($keyword eq '@subchain' or $keyword eq 'subchain') {
1951 error('Chain must be specified')
1952 unless exists $current{chain};
1954 error('No rule specified before "@subchain"')
1955 unless $current{has_rule};
1957 my $subchain;
1958 $keyword = next_token();
1960 if ($keyword =~ /^(["'])(.*)\1$/s) {
1961 $subchain = $2;
1962 $keyword = next_token();
1963 } else {
1964 $subchain = 'ferm_auto_' . ++$auto_chain;
1967 error('"{" or chain name expected after "@subchain"')
1968 unless $keyword eq '{';
1970 # create a deep copy of %current, only containing values
1971 # which must be in the subchain
1972 my %inner = ( cow => { keywords => 1, },
1973 keywords => $current{keywords},
1974 match => {},
1975 options => [],
1977 $inner{domain} = $current{domain};
1978 $inner{domain_family} = $current{domain_family};
1979 $inner{table} = $current{table};
1980 $inner{chain} = $inner{auto}{CHAIN} = $subchain;
1982 if (exists $current{protocol}) {
1983 $inner{protocol} = $current{protocol};
1984 $inner{protocol_index} = 0;
1985 append_option(%inner, 'protocol', $inner{protocol});
1988 # enter the block
1989 enter(1, \%inner);
1991 # now handle the parent - it's a jump to the sub chain
1992 $current{has_action} = 1;
1993 append_option(%current, 'jump', $subchain);
1995 $current{script} = { filename => $script->{filename},
1996 line => $script->{line},
1999 mkrules(\%current);
2001 # and clean up variables set in this level
2002 new_level(%current, $prev);
2004 next;
2007 # everything else must be part of a "real" rule, not just
2008 # "policy only"
2009 $current{has_rule}++;
2011 # extended parameters:
2012 if ($keyword =~ /^mod(?:ule)?$/) {
2013 foreach my $module (to_array getvalues) {
2014 next if exists $current{match}{$module};
2016 my $domain_family = $current{domain_family};
2017 my $defs = $match_defs{$domain_family}{$module};
2018 if (not defined $defs and exists $current{protocol}) {
2019 my $proto = $current{protocol};
2020 unless (ref $proto) {
2021 $proto = netfilter_canonical_protocol($current{protocol});
2022 $defs = $proto_defs{$domain_family}{$proto}
2023 if netfilter_protocol_module($proto) eq $module;
2027 $current{match}{$module} = 1;
2029 merge_keywords(%current, 'match', $module, $defs->{keywords})
2030 if defined $defs;
2032 append_option(%current, 'match', $module);
2035 next;
2038 # keywords from $current{keywords}
2040 if (exists $current{keywords}{$keyword}) {
2041 my ($type, $module, $def) = @{$current{keywords}{$keyword}};
2042 parse_option($def, \%current, $keyword, \$negated);
2043 next;
2047 # actions
2050 # jump action
2051 if ($keyword eq 'jump') {
2052 error('There can only one action per rule')
2053 if exists $current{has_action};
2054 my $chain = getvar();
2055 if (my $defs = is_netfilter_module_target($current{domain_family}, $chain)) {
2056 set_module_target(%current, $chain, $defs);
2058 $current{has_action} = 1;
2059 append_option(%current, 'jump', $chain);
2060 next;
2063 # goto action
2064 if ($keyword eq 'realgoto') {
2065 error('There can only one action per rule')
2066 if exists $current{has_action};
2067 $current{has_action} = 1;
2068 my $chain = getvar();
2069 append_option(%current, 'goto', $chain);
2070 next;
2073 # action keywords
2074 if (is_netfilter_core_target($keyword)) {
2075 error('There can only one action per rule')
2076 if exists $current{has_action};
2077 $current{has_action} = 1;
2078 append_option(%current, 'jump', $keyword);
2079 next;
2082 if ($keyword eq 'NOP') {
2083 error('There can only one action per rule')
2084 if exists $current{has_action};
2085 $current{has_action} = 1;
2086 next;
2089 if (my $defs = is_netfilter_module_target($current{domain_family}, $keyword)) {
2090 error('There can only one action per rule')
2091 if exists $current{has_action};
2093 set_module_target(%current, $keyword, $defs);
2094 $current{has_action} = 1;
2095 append_option(%current, 'jump', $keyword);
2096 next;
2099 my $proto = $current{protocol};
2102 # protocol specific options
2105 if (defined $proto and not ref $proto) {
2106 $proto = netfilter_canonical_protocol($proto);
2108 if ($proto eq 'icmp') {
2109 my $domains = $current{domain};
2110 $proto = 'icmpv6' if not ref $domains and $domains eq 'ip6';
2113 parse_protocol_options(\%current, $proto, $keyword, \$negated)
2114 and next;
2117 if ($keyword eq 'proto') {
2118 $current{protocol} = parse_keyword(\%current,
2119 { params => 1,
2120 negation => 1 },
2121 'proto', \$negated);
2122 $current{protocol_index} = scalar(@{$current{options}});
2123 append_option(%current, 'protocol', $current{protocol});
2124 next;
2127 # port switches
2128 if ($keyword =~ /^[sd]port$/) {
2129 error('To use sport or dport, you have to specify "proto tcp" or "proto udp" first')
2130 unless defined $proto and grep { /^(?:tcp|udp|udplite|dccp|sctp)$/ } to_array $proto;
2132 append_option(%current, $keyword,
2133 getvalues(undef, undef,
2134 allow_negation => 1));
2135 $current{protocol_module} = 1;
2136 next;
2139 # default
2140 error("Unrecognized keyword: $keyword");
2143 # if the rule didn't reset the negated flag, it's not
2144 # supported
2145 error("Doesn't support negation: $keyword")
2146 if $negated;
2149 error('Missing "}" at end of file')
2150 if $lev > $base_level;
2152 # consistency check: check if they havn't forgotten
2153 # the ';' before the last statement
2154 error("Missing semicolon before end of file")
2155 if exists $current{domain};
2158 sub execute_command {
2159 my ($command, $script) = @_;
2161 print LINES "$command\n"
2162 if $option{lines};
2163 return if $option{noexec};
2165 my $ret = system($command);
2166 unless ($ret == 0) {
2167 if ($? == -1) {
2168 print STDERR "failed to execute: $!\n";
2169 exit 1;
2170 } elsif ($? & 0x7f) {
2171 printf STDERR "child died with signal %d\n", $? & 0x7f;
2172 return 1;
2173 } else {
2174 print STDERR "(rule declared in $script->{filename}:$script->{line})\n"
2175 if defined $script;
2176 return $? >> 8;
2180 return;
2183 sub execute_slow($$) {
2184 my ($domain, $domain_info) = @_;
2186 my $domain_cmd = $domain_info->{tools}{tables};
2188 my $status;
2189 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2190 my $table_cmd = "$domain_cmd -t $table";
2192 # reset chain policies
2193 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2194 next unless $chain_info->{builtin} or
2195 (not $table_info->{has_builtin} and
2196 is_netfilter_builtin_chain($table, $chain));
2197 $status ||= execute_command("$table_cmd -P $chain ACCEPT");
2200 # clear
2201 $status ||= execute_command("$table_cmd -F");
2202 $status ||= execute_command("$table_cmd -X");
2204 next if $option{flush};
2206 # create chains / set policy
2207 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2208 if (exists $chain_info->{policy}) {
2209 $status ||= execute_command("$table_cmd -P $chain $chain_info->{policy}")
2210 unless $chain_info->{policy} eq 'ACCEPT';
2211 } elsif (not is_netfilter_builtin_chain($table, $chain)) {
2212 $status ||= execute_command("$table_cmd -N $chain");
2216 # dump rules
2217 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2218 my $chain_cmd = "$table_cmd -A $chain";
2219 foreach my $rule (@{$chain_info->{rules}}) {
2220 $status ||= execute_command($chain_cmd . $rule->{rule});
2225 return $status;
2228 sub rules_to_save($$) {
2229 my ($domain, $domain_info) = @_;
2231 # convert this into an iptables-save text
2232 my $result = "# Generated by ferm $VERSION on " . localtime() . "\n";
2234 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2235 # select table
2236 $result .= '*' . $table . "\n";
2238 # create chains / set policy
2239 foreach my $chain (sort keys %{$table_info->{chains}}) {
2240 my $chain_info = $table_info->{chains}{$chain};
2241 my $policy = $option{flush} ? 'ACCEPT' : $chain_info->{policy};
2242 unless (defined $policy) {
2243 if (is_netfilter_builtin_chain($table, $chain)) {
2244 $policy = 'ACCEPT';
2245 } else {
2246 $policy = '-';
2249 $result .= ":$chain $policy\ [0:0]\n";
2252 next if $option{flush};
2254 # dump rules
2255 foreach my $chain (sort keys %{$table_info->{chains}}) {
2256 my $chain_info = $table_info->{chains}{$chain};
2257 foreach my $rule (@{$chain_info->{rules}}) {
2258 $result .= "-A $chain$rule->{rule}\n";
2262 # do it
2263 $result .= "COMMIT\n";
2266 return $result;
2269 sub restore_domain($$) {
2270 my ($domain, $save) = @_;
2272 my $path = $domains{$domain}{tools}{'tables-restore'};
2274 local *RESTORE;
2275 open RESTORE, "|$path"
2276 or die "Failed to run $path: $!\n";
2278 print RESTORE $save;
2280 close RESTORE
2281 or die "Failed to run $path\n";
2284 sub execute_fast($$) {
2285 my ($domain, $domain_info) = @_;
2287 my $save = rules_to_save($domain, $domain_info);
2289 if ($option{lines}) {
2290 print LINES "$domain_info->{tools}{'tables-restore'} <<EOT\n"
2291 if $option{shell};
2292 print LINES $save;
2293 print LINES "EOT\n"
2294 if $option{shell};
2297 return if $option{noexec};
2299 eval {
2300 restore_domain($domain, $save);
2302 if ($@) {
2303 print STDERR $@;
2304 return 1;
2307 return;
2310 sub rollback() {
2311 my $error;
2312 while (my ($domain, $domain_info) = each %domains) {
2313 next unless $domain_info->{enabled};
2314 unless (defined $domain_info->{tools}{'tables-restore'}) {
2315 print STDERR "Cannot rollback domain '$domain' because there is no ${domain}tables-restore\n";
2316 next;
2319 my $reset = '';
2320 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2321 my $reset_chain = '';
2322 foreach my $chain (keys %{$table_info->{chains}{$table}}) {
2323 next unless is_netfilter_builtin_chain($table, $chain);
2324 $reset_chain .= ":${chain} ACCEPT [0:0]\n";
2326 $reset .= "*${table}\n${reset_chain}COMMIT\n"
2327 if length $reset_chain;
2330 $reset .= $domain_info->{previous}
2331 if defined $domain_info->{previous};
2333 restore_domain($domain, $reset);
2336 print STDERR "\nFirewall rules rolled back.\n" unless $error;
2337 exit 1;
2340 sub alrm_handler {
2341 # do nothing, just interrupt a system call
2344 sub confirm_rules() {
2345 $SIG{ALRM} = \&alrm_handler;
2347 alarm(5);
2349 print STDERR "\n"
2350 . "ferm has applied the new firewall rules.\n"
2351 . "Please type 'yes' to confirm:\n";
2352 STDERR->flush();
2354 alarm(30);
2356 my $line = '';
2357 STDIN->sysread($line, 3);
2359 eval {
2360 require POSIX;
2361 POSIX::tcflush(*STDIN, 2);
2363 print STDERR "$@" if $@;
2365 $SIG{ALRM} = 'DEFAULT';
2367 return $line eq 'yes';
2370 # end of ferm
2372 __END__
2374 =head1 NAME
2376 ferm - a firewall rule parser for linux
2378 =head1 SYNOPSIS
2380 B<ferm> I<options> I<inputfiles>
2382 =head1 OPTIONS
2384 -n, --noexec Do not execute the rules, just simulate
2385 -F, --flush Flush all netfilter tables managed by ferm
2386 -l, --lines Show all rules that were created
2387 -i, --interactive Interactive mode: revert if user does not confirm
2388 --remote Remote mode; ignore host specific configuration.
2389 This implies --noexec and --lines.
2390 -V, --version Show current version number
2391 -h, --help Look at this text
2392 --fast Generate an iptables-save file, used by iptables-restore
2393 --shell Generate a shell script which calls iptables-restore
2394 --domain {ip|ip6} Handle only the specified domain
2395 --def '$name=v' Override a variable
2397 =cut