release v2.0.6
[ferm.git] / src / ferm
blob3189b19b57ac4f0d8c9fa015ac83e41d3e8f3107
1 #!/usr/bin/perl
4 # ferm, a firewall setup program that makes firewall rules easy!
6 # Copyright (C) 2001-2009 Max Kellermann, Auke Kok
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($VERSION);
49 $VERSION = '2.0.6';
50 #$VERSION .= '~git';
52 ## interface variables
53 # %option = command line and other options
54 use vars qw(%option);
56 ## hooks
57 use vars qw(@pre_hooks @post_hooks @flush_hooks);
59 ## parser variables
60 # $script: current script file
61 # @stack = ferm's parser stack containing local variables
62 # $auto_chain = index for the next auto-generated chain
63 use vars qw($script @stack $auto_chain);
65 ## netfilter variables
66 # %domains = state information about all domains ("ip" and "ip6")
67 # - initialized: domain initialization is done
68 # - tools: hash providing the paths of the domain's tools
69 # - previous: save file of the previous ruleset, for rollback
70 # - tables{$name}: ferm state information about tables
71 # - has_builtin: whether built-in chains have been determined in this table
72 # - chains{$chain}: ferm state information about the chains
73 # - builtin: whether this is a built-in chain
74 use vars qw(%domains);
76 ## constants
77 use vars qw(%deprecated_keywords);
79 # keywords from ferm 1.1 which are deprecated, and the new one; these
80 # are automatically replaced, and a warning is printed
81 %deprecated_keywords = ( goto => 'jump',
84 # these hashes provide the Netfilter module definitions
85 use vars qw(%proto_defs %match_defs %target_defs);
88 # This subsubsystem allows you to support (most) new netfilter modules
89 # in ferm. Add a call to one of the "add_XY_def()" functions below.
91 # Ok, now about the cryptic syntax: the function "add_XY_def()"
92 # registers a new module. There are three kinds of modules: protocol
93 # module (e.g. TCP, ICMP), match modules (e.g. state, physdev) and
94 # target modules (e.g. DNAT, MARK).
96 # The first parameter is always the module name which is passed to
97 # iptables with "-p", "-m" or "-j" (depending on which kind of module
98 # this is).
100 # After that, you add an encoded string for each option the module
101 # supports. This is where it becomes tricky.
103 # foo defaults to an option with one argument (which may be a ferm
104 # array)
106 # foo*0 option without any arguments
108 # foo=s one argument which must not be a ferm array ('s' stands for
109 # 'scalar')
111 # u32=m an array which renders into multiple iptables options in one
112 # rule
114 # ctstate=c one argument, if it's an array, pass it to iptables as a
115 # single comma separated value; example:
116 # ctstate (ESTABLISHED RELATED) translates to:
117 # --ctstate ESTABLISHED,RELATED
119 # foo=sac three arguments: scalar, array, comma separated; you may
120 # concatenate more than one letter code after the '='
122 # foo&bar one argument; call the perl function '&bar()' which parses
123 # the argument
125 # !foo negation is allowed and the '!' is written before the keyword
127 # foo! same as above, but '!' is after the keyword and before the
128 # parameters
130 # to:=to-destination makes "to" an alias for "to-destination"; you have
131 # to add a declaration for option "to-destination"
134 # add a module definition
135 sub add_def_x {
136 my $defs = shift;
137 my $domain_family = shift;
138 my $params_default = shift;
139 my $name = shift;
140 die if exists $defs->{$domain_family}{$name};
141 my $def = $defs->{$domain_family}{$name} = {};
142 foreach (@_) {
143 my $keyword = $_;
144 my $k;
146 if ($keyword =~ s,:=(\S+)$,,) {
147 $k = $def->{keywords}{$1} || die;
148 $k->{ferm_name} ||= $keyword;
149 } else {
150 my $params = $params_default;
151 $params = $1 if $keyword =~ s,\*(\d+)$,,;
152 $params = $1 if $keyword =~ s,=([acs]+|m)$,,;
153 if ($keyword =~ s,&(\S+)$,,) {
154 $params = eval "\\&$1";
155 die $@ if $@;
158 $k = {};
159 $k->{params} = $params if $params;
161 $k->{negation} = $k->{pre_negation} = 1 if $keyword =~ s,^!,,;
162 $k->{negation} = 1 if $keyword =~ s,!$,,;
163 $k->{name} = $keyword;
166 $def->{keywords}{$keyword} = $k;
169 return $def;
172 # add a protocol module definition
173 sub add_proto_def_x(@) {
174 my $domain_family = shift;
175 add_def_x(\%proto_defs, $domain_family, 1, @_);
178 # add a match module definition
179 sub add_match_def_x(@) {
180 my $domain_family = shift;
181 add_def_x(\%match_defs, $domain_family, 1, @_);
184 # add a target module definition
185 sub add_target_def_x(@) {
186 my $domain_family = shift;
187 add_def_x(\%target_defs, $domain_family, 's', @_);
190 sub add_def {
191 my $defs = shift;
192 add_def_x($defs, 'ip', @_);
195 # add a protocol module definition
196 sub add_proto_def(@) {
197 add_def(\%proto_defs, 1, @_);
200 # add a match module definition
201 sub add_match_def(@) {
202 add_def(\%match_defs, 1, @_);
205 # add a target module definition
206 sub add_target_def(@) {
207 add_def(\%target_defs, 's', @_);
210 add_proto_def 'dccp', qw(dccp-types!=c dccp-option!);
211 add_proto_def 'mh', qw(mh-type!);
212 add_proto_def 'icmp', qw(icmp-type!);
213 add_proto_def 'icmpv6', qw(icmpv6-type! icmp-type:=icmpv6-type);
214 add_proto_def 'sctp', qw(chunk-types!=sc);
215 add_proto_def 'tcp', qw(tcp-flags!=cc !syn*0 tcp-option! mss);
216 add_proto_def 'udp', qw();
218 add_match_def '',
219 # --source, --destination
220 qw(source! saddr:=source destination! daddr:=destination),
221 # --in-interface
222 qw(in-interface! interface:=in-interface if:=in-interface),
223 # --out-interface
224 qw(out-interface! outerface:=out-interface of:=out-interface),
225 # --fragment
226 qw(!fragment*0);
227 add_match_def 'account', qw(aaddr=s aname=s ashort*0);
228 add_match_def 'addrtype', qw(src-type dst-type);
229 add_match_def 'ah', qw(ahspi! ahlen! ahres*0);
230 add_match_def 'comment', qw(comment=s);
231 add_match_def 'condition', qw(condition!);
232 add_match_def 'connbytes', qw(!connbytes connbytes-dir connbytes-mode);
233 add_match_def 'connlimit', qw(!connlimit-above connlimit-mask);
234 add_match_def 'connmark', qw(!mark);
235 add_match_def 'conntrack', qw(ctstate=c ctproto ctorigsrc! ctorigdst!),
236 qw(ctreplsrc! ctrepldst! ctstatus ctexpire=s);
237 add_match_def 'dscp', qw(dscp dscp-class);
238 add_match_def 'ecn', qw(ecn-tcp-cwr*0 ecn-tcp-ece*0 ecn-ip-ect);
239 add_match_def 'esp', qw(espspi!);
240 add_match_def 'eui64';
241 add_match_def 'fuzzy', qw(lower-limit=s upper-limit=s);
242 add_match_def 'hbh', qw(hbh-len! hbh-opts=c);
243 add_match_def 'helper', qw(helper);
244 add_match_def 'hl', qw(hl-eq! hl-lt=s hl-gt=s);
245 add_match_def 'hashlimit', qw(hashlimit=s hashlimit-burst=s hashlimit-mode=s hashlimit-name=s),
246 qw(hashlimit-htable-size=s hashlimit-htable-max=s),
247 qw(hashlimit-htable-expire=s hashlimit-htable-gcinterval=s);
248 add_match_def 'iprange', qw(!src-range !dst-range);
249 add_match_def 'ipv4options', qw(ssrr*0 lsrr*0 no-srr*0 !rr*0 !ts*0 !ra*0 !any-opt*0);
250 add_match_def 'ipv6header', qw(header!=c soft*0);
251 add_match_def 'length', qw(length!);
252 add_match_def 'limit', qw(limit=s limit-burst=s);
253 add_match_def 'mac', qw(mac-source!);
254 add_match_def 'mark', qw(!mark);
255 add_match_def 'multiport', qw(source-ports!&multiport_params),
256 qw(destination-ports!&multiport_params ports!&multiport_params);
257 add_match_def 'nth', qw(every counter start packet);
258 add_match_def 'owner', qw(uid-owner gid-owner pid-owner sid-owner cmd-owner);
259 add_match_def 'physdev', qw(physdev-in! physdev-out!),
260 qw(!physdev-is-in*0 !physdev-is-out*0 !physdev-is-bridged*0);
261 add_match_def 'pkttype', qw(pkt-type),
262 add_match_def 'policy',
263 qw(dir pol strict*0 reqid spi proto mode tunnel-src tunnel-dst next*0);
264 add_match_def 'psd', qw(psd-weight-threshold psd-delay-threshold),
265 qw(psd-lo-ports-weight psd-hi-ports-weight);
266 add_match_def 'quota', qw(quota=s);
267 add_match_def 'random', qw(average);
268 add_match_def 'realm', qw(realm!);
269 add_match_def 'recent', qw(name=s !set*0 !remove*0 !rcheck*0 !update*0 !seconds !hitcount rttl*0 rsource*0 rdest*0);
270 add_match_def 'rt', qw(rt-type! rt-segsleft! rt-len! rt-0-res*0 rt-0-addrs=c rt-0-not-strict*0);
271 add_match_def 'set', qw(!set=sc);
272 add_match_def 'state', qw(state=c);
273 add_match_def 'statistic', qw(mode=s probability=s every=s packet=s);
274 add_match_def 'string', qw(algo=s from=s to=s string hex-string);
275 add_match_def 'tcpmss', qw(!mss);
276 add_match_def 'time', qw(timestart=s timestop=s days=c datestart=s datestop=s),
277 qw(!monthday=c !weekdays=c utc*0 localtz*0);
278 add_match_def 'tos', qw(!tos);
279 add_match_def 'ttl', qw(ttl-eq ttl-lt=s ttl-gt=s);
280 add_match_def 'u32', qw(!u32=m);
282 add_target_def 'BALANCE', qw(to-destination to:=to-destination);
283 add_target_def 'CLASSIFY', qw(set-class);
284 add_target_def 'CLUSTERIP', qw(new*0 hashmode clustermac total-nodes local-node hash-init);
285 add_target_def 'CONNMARK', qw(set-mark save-mark*0 restore-mark*0 mask);
286 add_target_def 'CONNSECMARK', qw(save*0 restore*0);
287 add_target_def 'DNAT', qw(to-destination=m to:=to-destination random*0);
288 add_target_def 'DSCP', qw(set-dscp set-dscp-class);
289 add_target_def 'ECN', qw(ecn-tcp-remove*0);
290 add_target_def 'HL', qw(hl-set hl-dec hl-inc);
291 add_target_def 'IPV4OPTSSTRIP';
292 add_target_def 'LOG', qw(log-level log-prefix),
293 qw(log-tcp-sequence*0 log-tcp-options*0 log-ip-options*0 log-uid*0);
294 add_target_def 'MARK', qw(set-mark set-xmark and-mark or-mark xor-mark);
295 add_target_def 'MASQUERADE', qw(to-ports random*0);
296 add_target_def 'MIRROR';
297 add_target_def 'NETMAP', qw(to);
298 add_target_def 'NFLOG', qw(nflog-group nflog-prefix nflog-range nflog-threshold);
299 add_target_def 'NFQUEUE', qw(queue-num);
300 add_target_def 'NOTRACK';
301 add_target_def 'REDIRECT', qw(to-ports random*0);
302 add_target_def 'REJECT', qw(reject-with);
303 add_target_def 'ROUTE', qw(oif iif gw continue*0 tee*0);
304 add_target_def 'SAME', qw(to nodst*0 random*0);
305 add_target_def 'SECMARK', qw(selctx);
306 add_target_def 'SET', qw(add-set=sc del-set=sc);
307 add_target_def 'SNAT', qw(to-source=m to:=to-source random*0);
308 add_target_def 'TARPIT';
309 add_target_def 'TCPMSS', qw(set-mss clamp-mss-to-pmtu*0);
310 add_target_def 'TOS', qw(set-tos and-tos or-tos xor-tos);
311 add_target_def 'TRACE';
312 add_target_def 'TTL', qw(ttl-set ttl-dec ttl-inc);
313 add_target_def 'ULOG', qw(ulog-nlgroup ulog-prefix ulog-cprange ulog-qthreshold);
315 add_match_def_x 'arp', '',
316 # ip
317 qw(source-ip! destination-ip! saddr:=source-ip daddr:=destination-ip),
318 # mac
319 qw(source-mac! destination-mac!),
320 # --in-interface
321 qw(in-interface! interface:=in-interface if:=in-interface),
322 # --out-interface
323 qw(out-interface! outerface:=out-interface of:=out-interface),
324 # misc
325 qw(h-length=s opcode=s h-type=s proto-type=s),
326 qw(mangle-ip-s=s mangle-ip-d=s mangle-mac-s=s mangle-mac-d=s mangle-target=s);
328 add_match_def_x 'eb', '',
329 # protocol
330 qw(protocol! proto:=protocol),
331 # --in-interface
332 qw(in-interface! interface:=in-interface if:=in-interface),
333 # --out-interface
334 qw(out-interface! outerface:=out-interface of:=out-interface),
335 # logical interface
336 qw(logical-in! logical-out!),
337 # --source, --destination
338 qw(source! saddr:=source destination! daddr:=destination),
339 # 802.3
340 qw(802_3-sap! 802_3-type!),
341 # arp
342 qw(arp-opcode! arp-htype!=ss arp-ptype!=ss),
343 qw(arp-ip-src! arp-ip-dst! arp-mac-src! arp-mac-dst!),
344 # ip
345 qw(ip-source! ip-destination! ip-tos! ip-protocol! ip-sport! ip-dport!),
346 # mark_m
347 qw(mark!),
348 # pkttype
349 qw(pkttype-type!),
350 # stp
351 qw(stp-type! stp-flags! stp-root-prio! stp-root-addr! stp-root-cost!),
352 qw(stp-sender-prio! stp-sender-addr! stp-port! stp-msg-age! stp-max-age!),
353 qw(stp-hello-time! stp-forward-delay!),
354 # vlan
355 qw(vlan-id! vlan-prio! vlan-encap!),
356 # log
357 qw(log*0 log-level=s log-prefix=s log-ip*0 log-arp*0);
359 add_target_def_x 'eb', 'arpreply', qw(arpreply-mac arpreply-target);
360 add_target_def_x 'eb', 'dnat', qw(to-destination dnat-target);
361 add_target_def_x 'eb', 'MARK', qw(set-mark mark-target);
362 add_target_def_x 'eb', 'redirect', qw(redirect-target);
363 add_target_def_x 'eb', 'snat', qw(to-source snat-target);
365 # import-ferm uses the above tables
366 return 1 if $0 =~ /import-ferm$/;
368 # parameter parser for ipt_multiport
369 sub multiport_params {
370 my $rule = shift;
372 # multiport only allows 15 ports at a time. For this
373 # reason, we do a little magic here: split the ports
374 # into portions of 15, and handle these portions as
375 # array elements
377 my $proto = $rule->{protocol};
378 error('To use multiport, you have to specify "proto tcp" or "proto udp" first')
379 unless defined $proto and grep { /^(?:tcp|udp|udplite)$/ } to_array($proto);
381 my $value = getvalues(undef, allow_negation => 1,
382 allow_array_negation => 1);
383 if (ref $value and ref $value eq 'ARRAY') {
384 my @value = @$value;
385 my @params;
387 while (@value) {
388 push @params, join(',', splice(@value, 0, 15));
391 return @params == 1
392 ? $params[0]
393 : \@params;
394 } else {
395 return join_value(',', $value);
399 # initialize stack: command line definitions
400 unshift @stack, {};
402 # Get command line stuff
403 if ($has_getopt) {
404 my ($opt_noexec, $opt_flush, $opt_noflush, $opt_lines, $opt_interactive,
405 $opt_help,
406 $opt_version, $opt_test, $opt_fast, $opt_slow, $opt_shell,
407 $opt_domain);
409 Getopt::Long::Configure('bundling', 'auto_help', 'no_ignore_case',
410 'no_auto_abbrev');
412 sub opt_def {
413 my ($opt, $value) = @_;
414 die 'Invalid --def specification'
415 unless $value =~ /^\$?(\w+)=(.*)$/s;
416 my ($name, $unparsed_value) = ($1, $2);
417 my $tokens = tokenize_string($unparsed_value);
418 my $value = getvalues(sub { shift @$tokens; });
419 die 'Extra tokens after --def'
420 if @$tokens > 0;
421 $stack[0]{vars}{$name} = $value;
424 local $SIG{__WARN__} = sub { die $_[0]; };
425 GetOptions('noexec|n' => \$opt_noexec,
426 'flush|F' => \$opt_flush,
427 'noflush' => \$opt_noflush,
428 'lines|l' => \$opt_lines,
429 'interactive|i' => \$opt_interactive,
430 'help|h' => \$opt_help,
431 'version|V' => \$opt_version,
432 test => \$opt_test,
433 remote => \$opt_test,
434 fast => \$opt_fast,
435 slow => \$opt_slow,
436 shell => \$opt_shell,
437 'domain=s' => \$opt_domain,
438 'def=s' => \&opt_def,
441 if (defined $opt_help) {
442 require Pod::Usage;
443 Pod::Usage::pod2usage(-exitstatus => 0);
446 if (defined $opt_version) {
447 printversion();
448 exit 0;
451 $option{noexec} = $opt_noexec || $opt_test;
452 $option{flush} = $opt_flush;
453 $option{noflush} = $opt_noflush;
454 $option{lines} = $opt_lines || $opt_test || $opt_shell;
455 $option{interactive} = $opt_interactive && !$opt_noexec;
456 $option{test} = $opt_test;
457 $option{fast} = !$opt_slow;
458 $option{shell} = $opt_shell;
460 die("ferm interactive mode not possible: /dev/stdin is not a tty\n")
461 if $option{interactive} and not -t STDIN;
462 die("ferm interactive mode not possible: /dev/stderr is not a tty\n")
463 if $option{interactive} and not -t STDERR;
465 $option{domain} = $opt_domain if defined $opt_domain;
466 } else {
467 # tiny getopt emulation for microperl
468 my $filename;
469 foreach (@ARGV) {
470 if ($_ eq '--noexec' or $_ eq '-n') {
471 $option{noexec} = 1;
472 } elsif ($_ eq '--lines' or $_ eq '-l') {
473 $option{lines} = 1;
474 } elsif ($_ eq '--fast') {
475 $option{fast} = 1;
476 } elsif ($_ eq '--test') {
477 $option{test} = 1;
478 $option{noexec} = 1;
479 $option{lines} = 1;
480 } elsif ($_ eq '--shell') {
481 $option{$_} = 1 foreach qw(shell fast lines);
482 } elsif (/^-/) {
483 printf STDERR "Usage: ferm [--noexec] [--lines] [--fast] [--shell] FILENAME\n";
484 exit 1;
485 } else {
486 $filename = $_;
489 undef @ARGV;
490 push @ARGV, $filename;
493 unless (@ARGV == 1) {
494 require Pod::Usage;
495 Pod::Usage::pod2usage(-exitstatus => 1);
498 if ($has_strict) {
499 open LINES, ">&STDOUT" if $option{lines};
500 open STDOUT, ">&STDERR" if $option{shell};
501 } else {
502 # microperl can't redirect file handles
503 *LINES = *STDOUT;
505 if ($option{fast} and not $option{noexec}) {
506 print STDERR "Sorry, ferm on microperl does not allow --fast without --noexec\n";
507 exit 1
511 unshift @stack, {};
512 open_script($ARGV[0]);
513 $stack[0]{auto}{FILENAME} = $ARGV[0];
515 # parse all input recursively
516 enter(0);
517 die unless @stack == 2;
519 # enable/disable hooks depending on --flush
521 if ($option{flush}) {
522 undef @pre_hooks;
523 undef @post_hooks;
524 } else {
525 undef @flush_hooks;
528 # execute all generated rules
529 my $status;
531 foreach my $cmd (@pre_hooks) {
532 print LINES "$cmd\n" if $option{lines};
533 system($cmd) unless $option{noexec};
536 while (my ($domain, $domain_info) = each %domains) {
537 next unless $domain_info->{enabled};
538 my $s = $option{fast} &&
539 defined $domain_info->{tools}{'tables-restore'}
540 ? execute_fast($domain_info) : execute_slow($domain_info);
541 $status = $s if defined $s;
544 foreach my $cmd (@post_hooks, @flush_hooks) {
545 print "$cmd\n" if $option{lines};
546 system($cmd) unless $option{noexec};
549 if (defined $status) {
550 rollback();
551 exit $status;
554 # ask user, and rollback if there is no confirmation
556 confirm_rules() or rollback() if $option{interactive};
558 exit 0;
560 # end of program execution!
563 # funcs
565 sub printversion {
566 print "ferm $VERSION\n";
567 print "Copyright (C) 2001-2009 Max Kellermann, Auke Kok\n";
568 print "This program is free software released under GPLv2.\n";
569 print "See the included COPYING file for license details.\n";
573 sub error {
574 # returns a nice formatted error message, showing the
575 # location of the error.
576 my $tabs = 0;
577 my @lines;
578 my $l = 0;
579 my @words = map { @$_ } @{$script->{past_tokens}};
581 for my $w ( 0 .. $#words ) {
582 if ($words[$w] eq "\x29")
583 { $l++ ; $lines[$l] = " " x ($tabs-- -1) ;};
584 if ($words[$w] eq "\x28")
585 { $l++ ; $lines[$l] = " " x $tabs++ ;};
586 if ($words[$w] eq "\x7d")
587 { $l++ ; $lines[$l] = " " x ($tabs-- -1) ;};
588 if ($words[$w] eq "\x7b")
589 { $l++ ; $lines[$l] = " " x $tabs++ ;};
590 if ( $l > $#lines ) { $lines[$l] = "" };
591 $lines[$l] .= $words[$w] . " ";
592 if ($words[$w] eq "\x28")
593 { $l++ ; $lines[$l] = " " x $tabs ;};
594 if (($words[$w] eq "\x29") && ($words[$w+1] ne "\x7b"))
595 { $l++ ; $lines[$l] = " " x $tabs ;};
596 if ($words[$w] eq "\x7b")
597 { $l++ ; $lines[$l] = " " x $tabs ;};
598 if (($words[$w] eq "\x7d") && ($words[$w+1] ne "\x7d"))
599 { $l++ ; $lines[$l] = " " x $tabs ;};
600 if (($words[$w] eq "\x3b") && ($words[$w+1] ne "\x7d"))
601 { $l++ ; $lines[$l] = " " x $tabs ;}
602 if ($words[$w-1] eq "option")
603 { $l++ ; $lines[$l] = " " x $tabs ;}
605 my $start = $#lines - 4;
606 if ($start < 0) { $start = 0 } ;
607 print STDERR "Error in $script->{filename} line $script->{line}:\n";
608 for $l ( $start .. $#lines)
609 { print STDERR $lines[$l]; if ($l != $#lines ) {print STDERR "\n"} ; };
610 print STDERR "<--\n";
611 die("@_\n");
614 # print a warning message about code from an input file
615 sub warning {
616 print STDERR "Warning in $script->{filename} line $script->{line}: "
617 . (shift) . "\n";
620 sub find_tool($) {
621 my $name = shift;
622 return $name if $option{test};
623 for my $path ('/sbin', split ':', $ENV{PATH}) {
624 my $ret = "$path/$name";
625 return $ret if -x $ret;
627 die "$name not found in PATH\n";
630 sub initialize_domain {
631 my $domain = shift;
632 my $domain_info = $domains{$domain} ||= {};
634 return if exists $domain_info->{initialized};
636 die "Invalid domain '$domain'\n" unless $domain =~ /^(?:ip6?|arp|eb)$/;
638 my @tools = qw(tables);
639 push @tools, qw(tables-save tables-restore)
640 if $domain =~ /^ip6?$/;
642 # determine the location of this domain's tools
643 my %tools = map { $_ => find_tool($domain . $_) } @tools;
644 $domain_info->{tools} = \%tools;
646 # make tables-save tell us about the state of this domain
647 # (which tables and chains do exist?), also remember the old
648 # save data which may be used later by the rollback function
649 local *SAVE;
650 if (!$option{test} &&
651 exists $tools{'tables-save'} &&
652 open(SAVE, "$tools{'tables-save'}|")) {
653 my $save = '';
655 my $table_info;
656 while (<SAVE>) {
657 $save .= $_;
659 if (/^\*(\w+)/) {
660 my $table = $1;
661 $table_info = $domain_info->{tables}{$table} ||= {};
662 } elsif (defined $table_info and /^:(\w+)\s+(\S+)/
663 and $2 ne '-') {
664 $table_info->{chains}{$1}{builtin} = 1;
665 $table_info->{has_builtin} = 1;
669 # for rollback
670 $domain_info->{previous} = $save;
673 $domain_info->{initialized} = 1;
676 sub filter_domains($) {
677 my $domains = shift;
678 my @result;
680 foreach my $domain (to_array($domains)) {
681 next if exists $option{domain}
682 and $domain ne $option{domain};
684 eval {
685 initialize_domain($domain);
687 error($@) if $@;
689 push @result, $domain;
692 return @result == 1 ? @result[0] : \@result;
695 # split the input string into words and delete comments
696 sub tokenize_string($) {
697 my $string = shift;
699 my @ret;
701 foreach my $word ($string =~ m/(".*?"|'.*?'|`.*?`|[!,=&\$\%\(\){};]|[-+\w\/\.:]+|@\w+|#)/g) {
702 last if $word eq '#';
703 push @ret, $word;
706 return \@ret;
709 # read some more tokens from the input file into a buffer
710 sub prepare_tokens() {
711 my $tokens = $script->{tokens};
712 while (@$tokens == 0) {
713 my $handle = $script->{handle};
714 my $line = <$handle>;
715 return unless defined $line;
717 $script->{line} ++;
719 # the next parser stage eats this
720 push @$tokens, @{tokenize_string($line)};
723 return 1;
726 # open a ferm sub script
727 sub open_script($) {
728 my $filename = shift;
730 for (my $s = $script; defined $s; $s = $s->{parent}) {
731 die("Circular reference in $script->{filename} line $script->{line}: $filename\n")
732 if $s->{filename} eq $filename;
735 local *FILE;
736 open FILE, "$filename" or die("Failed to open $filename: $!\n");
737 my $handle = *FILE;
739 $script = { filename => $filename,
740 handle => $handle,
741 line => 0,
742 past_tokens => [],
743 tokens => [],
744 parent => $script,
747 return $script;
750 # collect script filenames which are being included
751 sub collect_filenames(@) {
752 my @ret;
754 # determine the current script's parent directory for relative
755 # file names
756 die unless defined $script;
757 my $parent_dir = $script->{filename} =~ m,^(.*/),
758 ? $1 : './';
760 foreach my $pathname (@_) {
761 # non-absolute file names are relative to the parent script's
762 # file name
763 $pathname = $parent_dir . $pathname
764 unless $pathname =~ m,^/|\|$,;
766 if ($pathname =~ m,/$,) {
767 # include all regular files in a directory
769 error("'$pathname' is not a directory")
770 unless -d $pathname;
772 local *DIR;
773 opendir DIR, $pathname
774 or error("Failed to open directory '$pathname': $!");
775 my @names = readdir DIR;
776 closedir DIR;
778 # sort those names for a well-defined order
779 foreach my $name (sort { $a cmp $b } @names) {
780 # ignore dpkg's backup files
781 next if $name =~ /\.dpkg-(old|dist|new|tmp)$/;
782 # don't include hidden and backup files
783 next if $name =~ /^\.|~$/;
785 my $filename = $pathname . $name;
786 push @ret, $filename
787 if -f $filename;
789 } elsif ($pathname =~ m,\|$,) {
790 # run a program and use its output
791 push @ret, $pathname;
792 } elsif ($pathname =~ m,^\|,) {
793 error('This kind of pipe is not allowed');
794 } else {
795 # include a regular file
797 error("'$pathname' is a directory; maybe use trailing '/' to include a directory?")
798 if -d $pathname;
799 error("'$pathname' is not a file")
800 unless -f $pathname;
802 push @ret, $pathname;
806 return @ret;
809 # peek a token from the queue, but don't remove it
810 sub peek_token() {
811 return unless prepare_tokens();
812 return $script->{tokens}[0];
815 # get a token from the queue
816 sub next_token() {
817 return unless prepare_tokens();
818 my $token = shift @{$script->{tokens}};
820 # update $script->{past_tokens}
821 my $past_tokens = $script->{past_tokens};
823 if (@$past_tokens > 0) {
824 my $prev_token = $past_tokens->[-1][-1];
825 $past_tokens->[-1] = @$past_tokens > 1 ? ['{'] : []
826 if $prev_token eq ';';
827 if ($prev_token eq '}') {
828 pop @$past_tokens;
829 $past_tokens->[-1] = $past_tokens->[-1][0] eq '{'
830 ? [ '{' ] : []
831 if @$past_tokens > 0;
835 push @$past_tokens, [] if $token eq '{' or @$past_tokens == 0;
836 push @{$past_tokens->[-1]}, $token;
838 # return
839 return $token;
842 sub expect_token($;$) {
843 my $expect = shift;
844 my $msg = shift;
845 my $token = next_token();
846 error($msg || "'$expect' expected")
847 unless defined $token and $token eq $expect;
850 # require that another token exists, and that it's not a "special"
851 # token, e.g. ";" and "{"
852 sub require_next_token {
853 my $code = shift || \&next_token;
855 my $token = &$code(@_);
857 error('unexpected end of file')
858 unless defined $token;
860 error("'$token' not allowed here")
861 if $token =~ /^[;{}]$/;
863 return $token;
866 # return the value of a variable
867 sub variable_value($) {
868 my $name = shift;
870 foreach (@stack) {
871 return $_->{vars}{$name}
872 if exists $_->{vars}{$name};
875 return $stack[0]{auto}{$name}
876 if exists $stack[0]{auto}{$name};
878 return;
881 # determine the value of a variable, die if the value is an array
882 sub string_variable_value($) {
883 my $name = shift;
884 my $value = variable_value($name);
886 error("variable '$name' must be a string, but it is an array")
887 if ref $value;
889 return $value;
892 # similar to the built-in "join" function, but also handle negated
893 # values in a special way
894 sub join_value($$) {
895 my ($expr, $value) = @_;
897 unless (ref $value) {
898 return $value;
899 } elsif (ref $value eq 'ARRAY') {
900 return join($expr, @$value);
901 } elsif (ref $value eq 'negated') {
902 # bless'negated' is a special marker for negated values
903 $value = join_value($expr, $value->[0]);
904 return bless [ $value ], 'negated';
905 } else {
906 die;
910 sub negate_value($$;$) {
911 my ($value, $class, $allow_array) = @_;
913 if (ref $value) {
914 error('double negation is not allowed')
915 if ref $value eq 'negated' or ref $value eq 'pre_negated';
917 error('it is not possible to negate an array')
918 if ref $value eq 'ARRAY' and not $allow_array;
921 return bless [ $value ], $class || 'negated';
924 # returns the next parameter, which may either be a scalar or an array
925 sub getvalues {
926 my $code = shift;
927 my %options = @_;
929 my $token = require_next_token($code);
931 if ($token eq '(') {
932 # read an array until ")"
933 my @wordlist;
935 for (;;) {
936 $token = getvalues($code,
937 parenthesis_allowed => 1,
938 comma_allowed => 1);
940 unless (ref $token) {
941 last if $token eq ')';
943 if ($token eq ',') {
944 error('Comma is not allowed within arrays, please use only a space');
945 next;
948 push @wordlist, $token;
949 } elsif (ref $token eq 'ARRAY') {
950 push @wordlist, @$token;
951 } else {
952 error('unknown toke type');
956 error('empty array not allowed here')
957 unless @wordlist or not $options{non_empty};
959 return @wordlist == 1
960 ? $wordlist[0]
961 : \@wordlist;
962 } elsif ($token =~ /^\`(.*)\`$/s) {
963 # execute a shell command, insert output
964 my $command = $1;
965 my $output = `$command`;
966 unless ($? == 0) {
967 if ($? == -1) {
968 error("failed to execute: $!");
969 } elsif ($? & 0x7f) {
970 error("child died with signal " . ($? & 0x7f));
971 } elsif ($? >> 8) {
972 error("child exited with status " . ($? >> 8));
976 # remove comments
977 $output =~ s/#.*//mg;
979 # tokenize
980 my @tokens = grep { length } split /\s+/s, $output;
982 my @values;
983 while (@tokens) {
984 my $value = getvalues(sub { shift @tokens });
985 push @values, to_array($value);
988 # and recurse
989 return @values == 1
990 ? $values[0]
991 : \@values;
992 } elsif ($token =~ /^\'(.*)\'$/s) {
993 # single quotes: a string
994 return $1;
995 } elsif ($token =~ /^\"(.*)\"$/s) {
996 # double quotes: a string with escapes
997 $token = $1;
998 $token =~ s,\$(\w+),string_variable_value($1),eg;
999 return $token;
1000 } elsif ($token eq '!') {
1001 error('negation is not allowed here')
1002 unless $options{allow_negation};
1004 $token = getvalues($code);
1006 return negate_value($token, undef, $options{allow_array_negation});
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);
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, @_);
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;
1159 return grep { $_ eq $target } qw(ACCEPT DROP RETURN QUEUE);
1162 sub is_netfilter_module_target($$) {
1163 my ($domain_family, $target) = @_;
1164 die unless defined $target and length $target;
1166 return defined $domain_family &&
1167 exists $target_defs{$domain_family} &&
1168 $target_defs{$domain_family}{$target};
1171 sub is_netfilter_builtin_chain($$) {
1172 my ($table, $chain) = @_;
1174 return grep { $_ eq $chain }
1175 qw(PREROUTING INPUT FORWARD OUTPUT POSTROUTING);
1178 sub netfilter_canonical_protocol($) {
1179 my $proto = shift;
1180 return 'icmpv6'
1181 if $proto eq 'ipv6-icmp';
1182 return 'mh'
1183 if $proto eq 'ipv6-mh';
1184 return $proto;
1187 sub netfilter_protocol_module($) {
1188 my $proto = shift;
1189 return unless defined $proto;
1190 return 'icmp6'
1191 if $proto eq 'icmpv6';
1192 return $proto;
1195 # escape the string in a way safe for the shell
1196 sub shell_escape($) {
1197 my $token = shift;
1199 return $token if $token =~ /^[-_a-zA-Z0-9]+$/s;
1201 if ($option{fast}) {
1202 # iptables-save/iptables-restore are quite buggy concerning
1203 # escaping and special characters... we're trying our best
1204 # here
1206 $token =~ s,",\\",g;
1207 $token = '"' . $token . '"'
1208 if $token =~ /[\s\'\\;&]/s or length($token) == 0;
1209 } else {
1210 return $token
1211 if $token =~ /^\`.*\`$/;
1212 $token =~ s/'/'\\''/g;
1213 $token = '\'' . $token . '\''
1214 if $token =~ /[\s\"\\;<>&|]/s or length($token) == 0;
1217 return $token;
1220 # append an option to the shell command line, using information from
1221 # the module definition (see %match_defs etc.)
1222 sub shell_format_option($$) {
1223 my ($keyword, $value) = @_;
1225 my $cmd = '';
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 $cmd = ' !';
1236 unless (defined $value) {
1237 $cmd .= " --$keyword";
1238 } elsif (ref $value) {
1239 if (ref $value eq 'params') {
1240 $cmd .= " --$keyword ";
1241 $cmd .= join(' ', map { shell_escape($_) } @$value);
1242 } elsif (ref $value eq 'multi') {
1243 foreach (@$value) {
1244 $cmd .= " --$keyword " . shell_escape($_);
1246 } else {
1247 die;
1249 } else {
1250 $cmd .= " --$keyword " . shell_escape($value);
1253 return $cmd;
1256 sub format_option($$$) {
1257 my ($domain, $name, $value) = @_;
1258 $value = 'icmpv6' if $domain eq 'ip6' and $name eq 'protocol'
1259 and $value eq 'icmp';
1260 return shell_format_option($name, $value);
1263 sub append_rule($$) {
1264 my ($chain_rules, $rule) = @_;
1266 my $cmd = join('', map { $_->[2] } @{$rule->{options}});
1267 push @$chain_rules, { rule => $cmd,
1268 script => $rule->{script},
1272 sub format_option($$$) {
1273 my ($domain, $name, $value) = @_;
1274 $value = 'icmpv6' if $domain eq 'ip6' and $name eq 'protocol'
1275 and $value eq 'icmp';
1276 return shell_format_option($name, $value);
1279 sub unfold_rule {
1280 my ($domain, $chain_rules, $rule) = (shift, shift, shift);
1281 return append_rule($chain_rules, $rule) unless @_;
1283 my $option = shift;
1284 my @values = @{$option->[1]};
1286 foreach my $value (@values) {
1287 $option->[2] = format_option($domain, $option->[0], $value);
1288 unfold_rule($domain, $chain_rules, $rule, @_);
1292 sub mkrules2($$$) {
1293 my ($domain, $chain_rules, $rule) = @_;
1295 my @unfold;
1296 foreach my $option (@{$rule->{options}}) {
1297 if (ref $option->[1] and ref $option->[1] eq 'ARRAY') {
1298 push @unfold, $option
1299 } else {
1300 $option->[2] = format_option($domain, $option->[0], $option->[1]);
1304 unfold_rule($domain, $chain_rules, $rule, @unfold);
1307 # convert a bunch of internal rule structures in iptables calls,
1308 # unfold arrays during that
1309 sub mkrules($) {
1310 my $rule = shift;
1312 foreach my $domain (to_array $rule->{domain}) {
1313 my $domain_info = $domains{$domain};
1314 $domain_info->{enabled} = 1;
1316 foreach my $table (to_array $rule->{table}) {
1317 my $table_info = $domain_info->{tables}{$table} ||= {};
1319 foreach my $chain (to_array $rule->{chain}) {
1320 my $chain_rules = $table_info->{chains}{$chain}{rules} ||= [];
1321 mkrules2($domain, $chain_rules, $rule)
1322 if $rule->{has_rule} and not $option{flush};
1328 # parse a keyword from a module definition
1329 sub parse_keyword(\%$$) {
1330 my ($rule, $def, $negated_ref) = @_;
1332 my $params = $def->{params};
1334 my $value;
1336 my $negated;
1337 if ($$negated_ref && exists $def->{pre_negation}) {
1338 $negated = 1;
1339 undef $$negated_ref;
1342 unless (defined $params) {
1343 undef $value;
1344 } elsif (ref $params && ref $params eq 'CODE') {
1345 $value = &$params($rule);
1346 } elsif ($params eq 'm') {
1347 $value = bless [ to_array getvalues() ], 'multi';
1348 } elsif ($params =~ /^[a-z]/) {
1349 if (exists $def->{negation} and not $negated) {
1350 my $token = peek_token();
1351 if ($token eq '!') {
1352 require_next_token();
1353 $negated = 1;
1357 my @params;
1358 foreach my $p (split(//, $params)) {
1359 if ($p eq 's') {
1360 push @params, getvar();
1361 } elsif ($p eq 'c') {
1362 my @v = to_array getvalues(undef, non_empty => 1);
1363 push @params, join(',', @v);
1364 } else {
1365 die;
1369 $value = @params == 1
1370 ? $params[0]
1371 : bless \@params, 'params';
1372 } elsif ($params == 1) {
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 = getvalues();
1383 warning("log-prefix is too long; truncating to 29 characters: '$1'")
1384 if $def->{name} eq 'log-prefix' && $value =~ s,^(.{29}).+$,$1,;
1385 } else {
1386 if (exists $def->{negation} and not $negated) {
1387 my $token = peek_token();
1388 if ($token eq '!') {
1389 require_next_token();
1390 $negated = 1;
1394 $value = bless [ map {
1395 getvar()
1396 } (1..$params) ], 'params';
1399 $value = negate_value($value, exists $def->{pre_negation} && 'pre_negated')
1400 if $negated;
1402 return $value;
1405 sub append_option(\%$$) {
1406 my ($rule, $name, $value) = @_;
1407 push @{$rule->{options}}, [ $name, $value ];
1410 # parse options of a module
1411 sub parse_option($\%$) {
1412 my ($def, $rule, $negated_ref) = @_;
1414 append_option(%$rule, $def->{name},
1415 parse_keyword(%$rule, $def, $negated_ref));
1418 sub copy_on_write($$) {
1419 my ($rule, $key) = @_;
1420 return unless exists $rule->{cow}{$key};
1421 $rule->{$key} = {%{$rule->{$key}}};
1422 delete $rule->{cow}{$key};
1425 sub new_level(\%$) {
1426 my ($rule, $prev) = @_;
1428 %$rule = ();
1429 if (defined $prev) {
1430 # copy data from previous level
1431 $rule->{cow} = { keywords => 1, };
1432 $rule->{keywords} = $prev->{keywords};
1433 $rule->{match} = { %{$prev->{match}} };
1434 $rule->{options} = [@{$prev->{options}}];
1435 foreach my $key (qw(domain domain_family table chain protocol has_rule has_action)) {
1436 $rule->{$key} = $prev->{$key}
1437 if exists $prev->{$key};
1439 } else {
1440 $rule->{cow} = {};
1441 $rule->{keywords} = {};
1442 $rule->{match} = {};
1443 $rule->{options} = [];
1447 sub merge_keywords(\%$) {
1448 my ($rule, $keywords) = @_;
1449 copy_on_write($rule, 'keywords');
1450 while (my ($name, $def) = each %$keywords) {
1451 $rule->{keywords}{$name} = $def;
1455 sub set_domain(\%$) {
1456 my ($rule, $domain) = @_;
1458 my $filtered_domain = filter_domains($domain);
1459 my $domain_family;
1460 unless (ref $domain) {
1461 $domain_family = $domain eq 'ip6' ? 'ip' : $domain;
1462 } elsif (@$domain == 0) {
1463 $domain_family = 'none';
1464 } elsif (grep { not /^ip6?$/s } @$domain) {
1465 error('Cannot combine non-IP domains');
1466 } else {
1467 $domain_family = 'ip';
1470 $rule->{domain_family} = $domain_family;
1471 $rule->{keywords} = $match_defs{$domain_family}{''}{keywords};
1472 $rule->{cow}{keywords} = 1;
1474 $rule->{domain} = $stack[0]{auto}{DOMAIN} = $filtered_domain;
1477 sub set_target(\%$$) {
1478 my ($rule, $name, $value) = @_;
1479 error('There can only one action per rule')
1480 if exists $rule->{has_action};
1481 $rule->{has_action} = 1;
1482 append_option(%$rule, $name, $value);
1485 sub set_module_target(\%$$) {
1486 my ($rule, $name, $defs) = @_;
1488 if ($name eq 'TCPMSS') {
1489 my $protos = $rule->{protocol};
1490 error('No protocol specified before TCPMSS')
1491 unless defined $protos;
1492 foreach my $proto (to_array $protos) {
1493 error('TCPMSS not available for protocol "$proto"')
1494 unless $proto eq 'tcp';
1498 # in ebtables, there is both "--mark" and "-j mark"... workaround:
1499 $name = 'mark' if $name eq 'MARK' and $rule->{domain_family} eq 'eb';
1501 set_target(%$rule, 'jump', $name);
1502 merge_keywords(%$rule, $defs->{keywords});
1505 # the main parser loop: read tokens, convert them into internal rule
1506 # structures
1507 sub enter($$) {
1508 my $lev = shift; # current recursion depth
1509 my $prev = shift; # previous rule hash
1511 # enter is the core of the firewall setup, it is a
1512 # simple parser program that recognizes keywords and
1513 # retreives parameters to set up the kernel routing
1514 # chains
1516 my $base_level = $script->{base_level} || 0;
1517 die if $base_level > $lev;
1519 my %rule;
1520 new_level(%rule, $prev);
1522 # read keywords 1 by 1 and dump into parser
1523 while (defined (my $keyword = next_token())) {
1524 # check if the current rule should be negated
1525 my $negated = $keyword eq '!';
1526 if ($negated) {
1527 # negation. get the next word which contains the 'real'
1528 # rule
1529 $keyword = getvar();
1531 error('unexpected end of file after negation')
1532 unless defined $keyword;
1535 # the core: parse all data
1536 for ($keyword)
1538 # deprecated keyword?
1539 if (exists $deprecated_keywords{$keyword}) {
1540 my $new_keyword = $deprecated_keywords{$keyword};
1541 warning("'$keyword' is deprecated, please use '$new_keyword' instead");
1542 $keyword = $new_keyword;
1545 # effectuation operator
1546 if ($keyword eq ';') {
1547 error('Empty rule before ";" not allowed')
1548 unless $rule{non_empty};
1550 if ($rule{has_rule} and not exists $rule{has_action}) {
1551 # something is wrong when a rule was specified,
1552 # but no action
1553 error('No action defined; did you mean "NOP"?');
1556 error('No chain defined') unless exists $rule{chain};
1558 $rule{script} = { filename => $script->{filename},
1559 line => $script->{line},
1562 mkrules(\%rule);
1564 # and clean up variables set in this level
1565 new_level(%rule, $prev);
1567 next;
1570 # conditional expression
1571 if ($keyword eq '@if') {
1572 unless (eval_bool(getvalues)) {
1573 collect_tokens;
1574 my $token = peek_token();
1575 require_next_token() if $token and $token eq '@else';
1578 next;
1581 if ($keyword eq '@else') {
1582 # hack: if this "else" has not been eaten by the "if"
1583 # handler above, we believe it came from an if clause
1584 # which evaluated "true" - remove the "else" part now.
1585 collect_tokens;
1586 next;
1589 # hooks for custom shell commands
1590 if ($keyword eq 'hook') {
1591 warning("'hook' is deprecated, use '\@hook'");
1592 $keyword = '@hook';
1595 if ($keyword eq '@hook') {
1596 error('"hook" must be the first token in a command')
1597 if exists $rule{domain};
1599 my $position = getvar();
1600 my $hooks;
1601 if ($position eq 'pre') {
1602 $hooks = \@pre_hooks;
1603 } elsif ($position eq 'post') {
1604 $hooks = \@post_hooks;
1605 } elsif ($position eq 'flush') {
1606 $hooks = \@flush_hooks;
1607 } else {
1608 error("Invalid hook position: '$position'");
1611 push @$hooks, getvar();
1613 expect_token(';');
1614 next;
1617 # recursing operators
1618 if ($keyword eq '{') {
1619 # push stack
1620 my $old_stack_depth = @stack;
1622 unshift @stack, { auto => { %{$stack[0]{auto} || {}} } };
1624 # recurse
1625 enter($lev + 1, \%rule);
1627 # pop stack
1628 shift @stack;
1629 die unless @stack == $old_stack_depth;
1631 # after a block, the command is finished, clear this
1632 # level
1633 new_level(%rule, $prev);
1635 next;
1638 if ($keyword eq '}') {
1639 error('Unmatched "}"')
1640 if $lev <= $base_level;
1642 # consistency check: check if they havn't forgotten
1643 # the ';' after the last statement
1644 error('Missing semicolon before "}"')
1645 if $rule{non_empty};
1647 # and exit
1648 return;
1651 # include another file
1652 if ($keyword eq '@include' or $keyword eq 'include') {
1653 my @files = collect_filenames to_array getvalues;
1654 $keyword = next_token;
1655 error('Missing ";" - "include FILENAME" must be the last command in a rule')
1656 unless defined $keyword and $keyword eq ';';
1658 foreach my $filename (@files) {
1659 # save old script, open new script
1660 my $old_script = $script;
1661 open_script($filename);
1662 $script->{base_level} = $lev + 1;
1664 # push stack
1665 my $old_stack_depth = @stack;
1667 my $stack = {};
1669 if (@stack > 0) {
1670 # include files may set variables for their parent
1671 $stack->{vars} = ($stack[0]{vars} ||= {});
1672 $stack->{functions} = ($stack[0]{functions} ||= {});
1673 $stack->{auto} = { %{ $stack[0]{auto} || {} } };
1676 $stack->{auto}{FILENAME} = $filename;
1678 unshift @stack, $stack;
1680 # parse the script
1681 enter($lev + 1, \%rule);
1683 # pop stack
1684 shift @stack;
1685 die unless @stack == $old_stack_depth;
1687 # restore old script
1688 $script = $old_script;
1691 next;
1694 # definition of a variable or function
1695 if ($keyword eq '@def' or $keyword eq 'def') {
1696 error('"def" must be the first token in a command')
1697 if $rule{non_empty};
1699 my $type = require_next_token();
1700 if ($type eq '$') {
1701 my $name = require_next_token();
1702 error('invalid variable name')
1703 unless $name =~ /^\w+$/;
1705 expect_token('=');
1707 my $value = getvalues(undef, allow_negation => 1);
1709 expect_token(';');
1711 $stack[0]{vars}{$name} = $value
1712 unless exists $stack[-1]{vars}{$name};
1713 } elsif ($type eq '&') {
1714 my $name = require_next_token();
1715 error('invalid function name')
1716 unless $name =~ /^\w+$/;
1718 expect_token('(', 'function parameter list or "()" expected');
1720 my @params;
1721 while (1) {
1722 my $token = require_next_token();
1723 last if $token eq ')';
1725 if (@params > 0) {
1726 error('"," expected')
1727 unless $token eq ',';
1729 $token = require_next_token();
1732 error('"$" and parameter name expected')
1733 unless $token eq '$';
1735 $token = require_next_token();
1736 error('invalid function parameter name')
1737 unless $token =~ /^\w+$/;
1739 push @params, $token;
1742 my %function;
1744 $function{params} = \@params;
1746 expect_token('=');
1748 my $tokens = collect_tokens();
1749 $function{block} = 1 if grep { $_ eq '{' } @$tokens;
1750 $function{tokens} = $tokens;
1752 $stack[0]{functions}{$name} = \%function
1753 unless exists $stack[-1]{functions}{$name};
1754 } else {
1755 error('"$" (variable) or "&" (function) expected');
1758 next;
1761 # this rule has something which isn't inherited by its
1762 # parent closure. This variable is used in a lot of
1763 # syntax checks.
1765 $rule{non_empty} = 1;
1767 # def references
1768 if ($keyword eq '$') {
1769 error('variable references are only allowed as keyword parameter');
1772 if ($keyword eq '&') {
1773 my $name = require_next_token();
1774 error('function name expected')
1775 unless $name =~ /^\w+$/;
1777 my $function;
1778 foreach (@stack) {
1779 $function = $_->{functions}{$name};
1780 last if defined $function;
1782 error("no such function: \&$name")
1783 unless defined $function;
1785 my $paramdef = $function->{params};
1786 die unless defined $paramdef;
1788 my @params = get_function_params(allow_negation => 1);
1790 error("Wrong number of parameters for function '\&$name': "
1791 . @$paramdef . " expected, " . @params . " given")
1792 unless @params == @$paramdef;
1794 my %vars;
1795 for (my $i = 0; $i < @params; $i++) {
1796 $vars{$paramdef->[$i]} = $params[$i];
1799 if ($function->{block}) {
1800 # block {} always ends the current rule, so if the
1801 # function contains a block, we have to require
1802 # the calling rule also ends here
1803 expect_token(';');
1806 my @tokens = @{$function->{tokens}};
1807 for (my $i = 0; $i < @tokens; $i++) {
1808 if ($tokens[$i] eq '$' and $i + 1 < @tokens and
1809 exists $vars{$tokens[$i + 1]}) {
1810 my @value = to_array($vars{$tokens[$i + 1]});
1811 @value = ('(', @value, ')')
1812 unless @tokens == 1;
1813 splice(@tokens, $i, 2, @value);
1814 $i += @value - 2;
1815 } elsif ($tokens[$i] =~ m,^"(.*)"$,) {
1816 $tokens[$i] =~ s,\$(\w+),exists $vars{$1} ? $vars{$1} : "\$$1",eg;
1820 unshift @{$script->{tokens}}, @tokens;
1822 next;
1825 # where to put the rule?
1826 if ($keyword eq 'domain') {
1827 error('Domain is already specified')
1828 if exists $rule{domain};
1830 set_domain(%rule, getvalues());
1831 next;
1834 if ($keyword eq 'table') {
1835 warning('Table is already specified')
1836 if exists $rule{table};
1837 $rule{table} = $stack[0]{auto}{TABLE} = getvalues();
1839 set_domain(%rule, 'ip')
1840 unless exists $rule{domain};
1842 next;
1845 if ($keyword eq 'chain') {
1846 warning('Chain is already specified')
1847 if exists $rule{chain};
1849 my $chain = $rule{chain} = $stack[0]{auto}{CHAIN} = getvalues();
1851 # ferm 1.1 allowed lower case built-in chain names
1852 foreach (ref $rule{chain} ? @{$rule{chain}} : $rule{chain}) {
1853 error('Please write built-in chain names in upper case')
1854 if /^(?:input|forward|output|prerouting|postrouting)$/;
1857 set_domain(%rule, 'ip')
1858 unless exists $rule{domain};
1860 $rule{table} = 'filter'
1861 unless exists $rule{table};
1863 foreach my $domain (to_array $rule{domain}) {
1864 foreach my $table (to_array $rule{table}) {
1865 foreach my $c (to_array $chain) {
1866 $domains{$domain}{tables}{$table}{chains}{$c} ||= {};
1871 next;
1874 error('Chain must be specified')
1875 unless exists $rule{chain};
1877 # policy for built-in chain
1878 if ($keyword eq 'policy') {
1879 error('Cannot specify matches for policy')
1880 if $rule{has_rule};
1882 my $policy = getvar();
1883 error("Invalid policy target: $policy")
1884 unless $policy =~ /^(?:ACCEPT|DROP)$/;
1886 expect_token(';');
1888 foreach my $domain (to_array $rule{domain}) {
1889 my $domain_info = $domains{$domain};
1890 $domain_info->{enabled} = 1;
1892 foreach my $table (to_array $rule{table}) {
1893 foreach my $chain (to_array $rule{chain}) {
1894 $domain_info->{tables}{$table}{chains}{$chain}{policy} = $policy;
1899 new_level(%rule, $prev);
1900 next;
1903 # create a subchain
1904 if ($keyword eq '@subchain' or $keyword eq 'subchain') {
1905 error('Chain must be specified')
1906 unless exists $rule{chain};
1908 error('No rule specified before "@subchain"')
1909 unless $rule{has_rule};
1911 my $subchain;
1912 $keyword = next_token();
1914 if ($keyword =~ /^(["'])(.*)\1$/s) {
1915 $subchain = $2;
1916 $keyword = next_token();
1917 } else {
1918 $subchain = 'ferm_auto_' . ++$auto_chain;
1921 foreach my $domain (to_array $rule{domain}) {
1922 foreach my $table (to_array $rule{table}) {
1923 $domains{$domain}{tables}{$table}{chains}{$subchain} ||= {};
1927 set_target(%rule, 'jump', $subchain);
1929 error('"{" or chain name expected after "@subchain"')
1930 unless $keyword eq '{';
1932 # create a deep copy of %rule, only containing values
1933 # which must be in the subchain
1934 my %inner = ( cow => { keywords => 1, },
1935 match => {},
1936 options => [],
1938 $inner{$_} = $rule{$_} foreach qw(domain domain_family table keywords);
1939 $inner{chain} = $inner{auto}{CHAIN} = $subchain;
1941 if (exists $rule{protocol}) {
1942 $inner{protocol} = $rule{protocol};
1943 append_option(%inner, 'protocol', $inner{protocol});
1946 # create a new stack frame
1947 my $old_stack_depth = @stack;
1948 my $stack = { auto => { %{$stack[0]{auto} || {}} } };
1949 $stack->{auto}{CHAIN} = $subchain;
1950 unshift @stack, $stack;
1952 # enter the block
1953 enter($lev + 1, \%inner);
1955 # pop stack frame
1956 shift @stack;
1957 die unless @stack == $old_stack_depth;
1959 # now handle the parent - it's a jump to the sub chain
1960 $rule{script} = {
1961 filename => $script->{filename},
1962 line => $script->{line},
1965 mkrules(\%rule);
1967 # and clean up variables set in this level
1968 new_level(%rule, $prev);
1969 delete $rule{has_rule};
1971 next;
1974 # everything else must be part of a "real" rule, not just
1975 # "policy only"
1976 $rule{has_rule} = 1;
1978 # extended parameters:
1979 if ($keyword =~ /^mod(?:ule)?$/) {
1980 foreach my $module (to_array getvalues) {
1981 next if exists $rule{match}{$module};
1983 my $domain_family = $rule{domain_family};
1984 my $defs = $match_defs{$domain_family}{$module};
1986 append_option(%rule, 'match', $module);
1987 $rule{match}{$module} = 1;
1989 merge_keywords(%rule, $defs->{keywords})
1990 if defined $defs;
1993 next;
1996 # keywords from $rule{keywords}
1998 if (exists $rule{keywords}{$keyword}) {
1999 my $def = $rule{keywords}{$keyword};
2000 parse_option($def, %rule, \$negated);
2001 next;
2005 # actions
2008 # jump action
2009 if ($keyword eq 'jump') {
2010 set_target(%rule, 'jump', getvar());
2011 next;
2014 # goto action
2015 if ($keyword eq 'realgoto') {
2016 set_target(%rule, 'goto', getvar());
2017 next;
2020 # action keywords
2021 if (is_netfilter_core_target($keyword)) {
2022 set_target(%rule, 'jump', $keyword);
2023 next;
2026 if ($keyword eq 'NOP') {
2027 error('There can only one action per rule')
2028 if exists $rule{has_action};
2029 $rule{has_action} = 1;
2030 next;
2033 if (my $defs = is_netfilter_module_target($rule{domain_family}, $keyword)) {
2034 set_module_target(%rule, $keyword, $defs);
2035 next;
2039 # protocol specific options
2042 if ($keyword eq 'proto' or $keyword eq 'protocol') {
2043 my $protocol = parse_keyword(%rule,
2044 { params => 1, negation => 1 },
2045 \$negated);
2046 $rule{protocol} = $protocol;
2047 append_option(%rule, 'protocol', $rule{protocol});
2049 unless (ref $protocol) {
2050 $protocol = netfilter_canonical_protocol($protocol);
2051 my $domain_family = $rule{domain_family};
2052 if (my $defs = $proto_defs{$domain_family}{$protocol}) {
2053 merge_keywords(%rule, $defs->{keywords});
2054 my $module = netfilter_protocol_module($protocol);
2055 $rule{match}{$module} = 1;
2058 next;
2061 # port switches
2062 if ($keyword =~ /^[sd]port$/) {
2063 my $proto = $rule{protocol};
2064 error('To use sport or dport, you have to specify "proto tcp" or "proto udp" first')
2065 unless defined $proto and grep { /^(?:tcp|udp|udplite|dccp|sctp)$/ } to_array $proto;
2067 append_option(%rule, $keyword,
2068 getvalues(undef, allow_negation => 1));
2069 next;
2072 # default
2073 error("Unrecognized keyword: $keyword");
2076 # if the rule didn't reset the negated flag, it's not
2077 # supported
2078 error("Doesn't support negation: $keyword")
2079 if $negated;
2082 error('Missing "}" at end of file')
2083 if $lev > $base_level;
2085 # consistency check: check if they havn't forgotten
2086 # the ';' before the last statement
2087 error("Missing semicolon before end of file")
2088 if $rule{non_empty};
2091 sub execute_command {
2092 my ($command, $script) = @_;
2094 print LINES "$command\n"
2095 if $option{lines};
2096 return if $option{noexec};
2098 my $ret = system($command);
2099 unless ($ret == 0) {
2100 if ($? == -1) {
2101 print STDERR "failed to execute: $!\n";
2102 exit 1;
2103 } elsif ($? & 0x7f) {
2104 printf STDERR "child died with signal %d\n", $? & 0x7f;
2105 return 1;
2106 } else {
2107 print STDERR "(rule declared in $script->{filename}:$script->{line})\n"
2108 if defined $script;
2109 return $? >> 8;
2113 return;
2116 sub execute_slow($) {
2117 my $domain_info = shift;
2119 my $domain_cmd = $domain_info->{tools}{tables};
2121 my $status;
2122 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2123 my $table_cmd = "$domain_cmd -t $table";
2125 # reset chain policies
2126 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2127 next unless $chain_info->{builtin} or
2128 (not $table_info->{has_builtin} and
2129 is_netfilter_builtin_chain($table, $chain));
2130 $status ||= execute_command("$table_cmd -P $chain ACCEPT")
2131 unless $option{noflush};
2134 # clear
2135 unless ($option{noflush}) {
2136 $status ||= execute_command("$table_cmd -F");
2137 $status ||= execute_command("$table_cmd -X");
2140 next if $option{flush};
2142 # create chains / set policy
2143 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2144 if (exists $chain_info->{policy}) {
2145 $status ||= execute_command("$table_cmd -P $chain $chain_info->{policy}")
2146 unless $chain_info->{policy} eq 'ACCEPT';
2147 } elsif (not is_netfilter_builtin_chain($table, $chain)) {
2148 $status ||= execute_command("$table_cmd -N $chain");
2152 # dump rules
2153 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2154 my $chain_cmd = "$table_cmd -A $chain";
2155 foreach my $rule (@{$chain_info->{rules}}) {
2156 $status ||= execute_command($chain_cmd . $rule->{rule});
2161 return $status;
2164 sub table_to_save($$) {
2165 my ($result_r, $table_info) = @_;
2167 foreach my $chain (sort keys %{$table_info->{chains}}) {
2168 my $chain_info = $table_info->{chains}{$chain};
2169 foreach my $rule (@{$chain_info->{rules}}) {
2170 $$result_r .= "-A $chain$rule->{rule}\n";
2175 sub rules_to_save($) {
2176 my ($domain_info) = @_;
2178 # convert this into an iptables-save text
2179 my $result = "# Generated by ferm $VERSION on " . localtime() . "\n";
2181 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2182 # select table
2183 $result .= '*' . $table . "\n";
2185 # create chains / set policy
2186 foreach my $chain (sort keys %{$table_info->{chains}}) {
2187 my $chain_info = $table_info->{chains}{$chain};
2188 my $policy = $option{flush} ? undef : $chain_info->{policy};
2189 unless (defined $policy) {
2190 if (is_netfilter_builtin_chain($table, $chain)) {
2191 $policy = 'ACCEPT';
2192 } else {
2193 next if $option{flush};
2194 $policy = '-';
2197 $result .= ":$chain $policy\ [0:0]\n";
2200 table_to_save(\$result, $table_info)
2201 unless $option{flush};
2203 # do it
2204 $result .= "COMMIT\n";
2207 return $result;
2210 sub restore_domain($$) {
2211 my ($domain_info, $save) = @_;
2213 my $path = $domain_info->{tools}{'tables-restore'};
2215 local *RESTORE;
2216 open RESTORE, "|$path"
2217 or die "Failed to run $path: $!\n";
2219 print RESTORE $save;
2221 close RESTORE
2222 or die "Failed to run $path\n";
2225 sub execute_fast($) {
2226 my $domain_info = shift;
2228 my $save = rules_to_save($domain_info);
2230 if ($option{lines}) {
2231 print LINES "$domain_info->{tools}{'tables-restore'} <<EOT\n"
2232 if $option{shell};
2233 print LINES $save;
2234 print LINES "EOT\n"
2235 if $option{shell};
2238 return if $option{noexec};
2240 eval {
2241 restore_domain($domain_info, $save);
2243 if ($@) {
2244 print STDERR $@;
2245 return 1;
2248 return;
2251 sub rollback() {
2252 my $error;
2253 while (my ($domain, $domain_info) = each %domains) {
2254 next unless $domain_info->{enabled};
2255 unless (defined $domain_info->{tools}{'tables-restore'}) {
2256 print STDERR "Cannot rollback domain '$domain' because there is no ${domain}tables-restore\n";
2257 next;
2260 my $reset = '';
2261 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2262 my $reset_chain = '';
2263 foreach my $chain (keys %{$table_info->{chains}}) {
2264 next unless is_netfilter_builtin_chain($table, $chain);
2265 $reset_chain .= ":${chain} ACCEPT [0:0]\n";
2267 $reset .= "*${table}\n${reset_chain}COMMIT\n"
2268 if length $reset_chain;
2271 $reset .= $domain_info->{previous}
2272 if defined $domain_info->{previous};
2274 restore_domain($domain_info, $reset);
2277 print STDERR "\nFirewall rules rolled back.\n" unless $error;
2278 exit 1;
2281 sub alrm_handler {
2282 # do nothing, just interrupt a system call
2285 sub confirm_rules() {
2286 $SIG{ALRM} = \&alrm_handler;
2288 alarm(5);
2290 print STDERR "\n"
2291 . "ferm has applied the new firewall rules.\n"
2292 . "Please type 'yes' to confirm:\n";
2293 STDERR->flush();
2295 alarm(30);
2297 my $line = '';
2298 STDIN->sysread($line, 3);
2300 eval {
2301 require POSIX;
2302 POSIX::tcflush(*STDIN, 2);
2304 print STDERR "$@" if $@;
2306 $SIG{ALRM} = 'DEFAULT';
2308 return $line eq 'yes';
2311 # end of ferm
2313 __END__
2315 =head1 NAME
2317 ferm - a firewall rule parser for linux
2319 =head1 SYNOPSIS
2321 B<ferm> I<options> I<inputfiles>
2323 =head1 OPTIONS
2325 -n, --noexec Do not execute the rules, just simulate
2326 -F, --flush Flush all netfilter tables managed by ferm
2327 -l, --lines Show all rules that were created
2328 -i, --interactive Interactive mode: revert if user does not confirm
2329 --remote Remote mode; ignore host specific configuration.
2330 This implies --noexec and --lines.
2331 -V, --version Show current version number
2332 -h, --help Look at this text
2333 --slow Slow mode, don't use iptables-restore
2334 --shell Generate a shell script which calls iptables-restore
2335 --domain {ip|ip6} Handle only the specified domain
2336 --def '$name=v' Override a variable
2338 =cut