added the "type" parameter to @resolve()
[ferm.git] / src / ferm
blob55662b2a6b5d9977d8f0efcb6780ac029a12e01c
1 #!/usr/bin/perl
4 # ferm, a firewall setup program that makes firewall rules easy!
6 # Copyright (C) 2001-2010 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.8';
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 qw(limit-iface-in*0 limit-iface-out*0);
230 add_match_def 'ah', qw(ahspi! ahlen! ahres*0);
231 add_match_def 'comment', qw(comment=s);
232 add_match_def 'condition', qw(condition!);
233 add_match_def 'connbytes', qw(!connbytes connbytes-dir connbytes-mode);
234 add_match_def 'connlimit', qw(!connlimit-above connlimit-mask);
235 add_match_def 'connmark', qw(!mark);
236 add_match_def 'conntrack', qw(!ctstate=c !ctproto ctorigsrc! ctorigdst!),
237 qw(ctreplsrc! ctrepldst! !ctstatus !ctexpire=s ctdir=s);
238 add_match_def 'dscp', qw(dscp dscp-class);
239 add_match_def 'ecn', qw(ecn-tcp-cwr*0 ecn-tcp-ece*0 ecn-ip-ect);
240 add_match_def 'esp', qw(espspi!);
241 add_match_def 'eui64';
242 add_match_def 'fuzzy', qw(lower-limit=s upper-limit=s);
243 add_match_def 'hbh', qw(hbh-len! hbh-opts=c);
244 add_match_def 'helper', qw(helper);
245 add_match_def 'hl', qw(hl-eq! hl-lt=s hl-gt=s);
246 add_match_def 'hashlimit', qw(hashlimit=s hashlimit-burst=s hashlimit-mode=s hashlimit-name=s),
247 qw(hashlimit-htable-size=s hashlimit-htable-max=s),
248 qw(hashlimit-htable-expire=s hashlimit-htable-gcinterval=s);
249 add_match_def 'iprange', qw(!src-range !dst-range);
250 add_match_def 'ipv4options', qw(ssrr*0 lsrr*0 no-srr*0 !rr*0 !ts*0 !ra*0 !any-opt*0);
251 add_match_def 'ipv6header', qw(header!=c soft*0);
252 add_match_def 'length', qw(length!);
253 add_match_def 'limit', qw(limit=s limit-burst=s);
254 add_match_def 'mac', qw(mac-source!);
255 add_match_def 'mark', qw(!mark);
256 add_match_def 'multiport', qw(source-ports!&multiport_params),
257 qw(destination-ports!&multiport_params ports!&multiport_params);
258 add_match_def 'nth', qw(every counter start packet);
259 add_match_def 'owner', qw(!uid-owner !gid-owner pid-owner sid-owner),
260 qw(cmd-owner !socket-exists=0);
261 add_match_def 'physdev', qw(physdev-in! physdev-out!),
262 qw(!physdev-is-in*0 !physdev-is-out*0 !physdev-is-bridged*0);
263 add_match_def 'pkttype', qw(pkt-type),
264 add_match_def 'policy',
265 qw(dir pol strict*0 !reqid !spi !proto !mode !tunnel-src !tunnel-dst next*0);
266 add_match_def 'psd', qw(psd-weight-threshold psd-delay-threshold),
267 qw(psd-lo-ports-weight psd-hi-ports-weight);
268 add_match_def 'quota', qw(quota=s);
269 add_match_def 'random', qw(average);
270 add_match_def 'realm', qw(realm!);
271 add_match_def 'recent', qw(name=s !set*0 !remove*0 !rcheck*0 !update*0 !seconds !hitcount rttl*0 rsource*0 rdest*0);
272 add_match_def 'rt', qw(rt-type! rt-segsleft! rt-len! rt-0-res*0 rt-0-addrs=c rt-0-not-strict*0);
273 add_match_def 'set', qw(!set=sc);
274 add_match_def 'state', qw(state=c);
275 add_match_def 'statistic', qw(mode=s probability=s every=s packet=s);
276 add_match_def 'string', qw(algo=s from=s to=s string hex-string);
277 add_match_def 'tcpmss', qw(!mss);
278 add_match_def 'time', qw(timestart=s timestop=s days=c datestart=s datestop=s),
279 qw(!monthday=c !weekdays=c utc*0 localtz*0);
280 add_match_def 'tos', qw(!tos);
281 add_match_def 'ttl', qw(ttl-eq ttl-lt=s ttl-gt=s);
282 add_match_def 'u32', qw(!u32=m);
284 add_target_def 'BALANCE', qw(to-destination to:=to-destination);
285 add_target_def 'CLASSIFY', qw(set-class);
286 add_target_def 'CLUSTERIP', qw(new*0 hashmode clustermac total-nodes local-node hash-init);
287 add_target_def 'CONNMARK', qw(set-mark save-mark*0 restore-mark*0 mask);
288 add_target_def 'CONNSECMARK', qw(save*0 restore*0);
289 add_target_def 'DNAT', qw(to-destination=m to:=to-destination random*0);
290 add_target_def 'DSCP', qw(set-dscp set-dscp-class);
291 add_target_def 'ECN', qw(ecn-tcp-remove*0);
292 add_target_def 'HL', qw(hl-set hl-dec hl-inc);
293 add_target_def 'IPV4OPTSSTRIP';
294 add_target_def 'LOG', qw(log-level log-prefix),
295 qw(log-tcp-sequence*0 log-tcp-options*0 log-ip-options*0 log-uid*0);
296 add_target_def 'MARK', qw(set-mark set-xmark and-mark or-mark xor-mark);
297 add_target_def 'MASQUERADE', qw(to-ports random*0);
298 add_target_def 'MIRROR';
299 add_target_def 'NETMAP', qw(to);
300 add_target_def 'NFLOG', qw(nflog-group nflog-prefix nflog-range nflog-threshold);
301 add_target_def 'NFQUEUE', qw(queue-num);
302 add_target_def 'NOTRACK';
303 add_target_def 'REDIRECT', qw(to-ports random*0);
304 add_target_def 'REJECT', qw(reject-with);
305 add_target_def 'ROUTE', qw(oif iif gw continue*0 tee*0);
306 add_target_def 'SAME', qw(to nodst*0 random*0);
307 add_target_def 'SECMARK', qw(selctx);
308 add_target_def 'SET', qw(add-set=sc del-set=sc);
309 add_target_def 'SNAT', qw(to-source=m to:=to-source random*0);
310 add_target_def 'TARPIT';
311 add_target_def 'TCPMSS', qw(set-mss clamp-mss-to-pmtu*0);
312 add_target_def 'TOS', qw(set-tos and-tos or-tos xor-tos);
313 add_target_def 'TRACE';
314 add_target_def 'TTL', qw(ttl-set ttl-dec ttl-inc);
315 add_target_def 'ULOG', qw(ulog-nlgroup ulog-prefix ulog-cprange ulog-qthreshold);
317 add_match_def_x 'arp', '',
318 # ip
319 qw(source-ip! destination-ip! saddr:=source-ip daddr:=destination-ip),
320 # mac
321 qw(source-mac! destination-mac!),
322 # --in-interface
323 qw(in-interface! interface:=in-interface if:=in-interface),
324 # --out-interface
325 qw(out-interface! outerface:=out-interface of:=out-interface),
326 # misc
327 qw(h-length=s opcode=s h-type=s proto-type=s),
328 qw(mangle-ip-s=s mangle-ip-d=s mangle-mac-s=s mangle-mac-d=s mangle-target=s);
330 add_match_def_x 'eb', '',
331 # protocol
332 qw(protocol! proto:=protocol),
333 # --in-interface
334 qw(in-interface! interface:=in-interface if:=in-interface),
335 # --out-interface
336 qw(out-interface! outerface:=out-interface of:=out-interface),
337 # logical interface
338 qw(logical-in! logical-out!),
339 # --source, --destination
340 qw(source! saddr:=source destination! daddr:=destination),
341 # 802.3
342 qw(802_3-sap! 802_3-type!),
343 # arp
344 qw(arp-opcode! arp-htype!=ss arp-ptype!=ss),
345 qw(arp-ip-src! arp-ip-dst! arp-mac-src! arp-mac-dst!),
346 # ip
347 qw(ip-source! ip-destination! ip-tos! ip-protocol! ip-sport! ip-dport!),
348 # mark_m
349 qw(mark!),
350 # pkttype
351 qw(pkttype-type!),
352 # stp
353 qw(stp-type! stp-flags! stp-root-prio! stp-root-addr! stp-root-cost!),
354 qw(stp-sender-prio! stp-sender-addr! stp-port! stp-msg-age! stp-max-age!),
355 qw(stp-hello-time! stp-forward-delay!),
356 # vlan
357 qw(vlan-id! vlan-prio! vlan-encap!),
358 # log
359 qw(log*0 log-level=s log-prefix=s log-ip*0 log-arp*0);
361 add_target_def_x 'eb', 'arpreply', qw(arpreply-mac arpreply-target);
362 add_target_def_x 'eb', 'dnat', qw(to-destination dnat-target);
363 add_target_def_x 'eb', 'MARK', qw(set-mark mark-target);
364 add_target_def_x 'eb', 'redirect', qw(redirect-target);
365 add_target_def_x 'eb', 'snat', qw(to-source snat-target);
367 # import-ferm uses the above tables
368 return 1 if $0 =~ /import-ferm$/;
370 # parameter parser for ipt_multiport
371 sub multiport_params {
372 my $rule = shift;
374 # multiport only allows 15 ports at a time. For this
375 # reason, we do a little magic here: split the ports
376 # into portions of 15, and handle these portions as
377 # array elements
379 my $proto = $rule->{protocol};
380 error('To use multiport, you have to specify "proto tcp" or "proto udp" first')
381 unless defined $proto and grep { /^(?:tcp|udp|udplite)$/ } to_array($proto);
383 my $value = getvalues(undef, allow_negation => 1,
384 allow_array_negation => 1);
385 if (ref $value and ref $value eq 'ARRAY') {
386 my @value = @$value;
387 my @params;
389 while (@value) {
390 push @params, join(',', splice(@value, 0, 15));
393 return @params == 1
394 ? $params[0]
395 : \@params;
396 } else {
397 return join_value(',', $value);
401 # initialize stack: command line definitions
402 unshift @stack, {};
404 # Get command line stuff
405 if ($has_getopt) {
406 my ($opt_noexec, $opt_flush, $opt_noflush, $opt_lines, $opt_interactive,
407 $opt_help,
408 $opt_version, $opt_test, $opt_fast, $opt_slow, $opt_shell,
409 $opt_domain);
411 Getopt::Long::Configure('bundling', 'auto_help', 'no_ignore_case',
412 'no_auto_abbrev');
414 sub opt_def {
415 my ($opt, $value) = @_;
416 die 'Invalid --def specification'
417 unless $value =~ /^\$?(\w+)=(.*)$/s;
418 my ($name, $unparsed_value) = ($1, $2);
419 my $tokens = tokenize_string($unparsed_value);
420 my $value = getvalues(sub { shift @$tokens; });
421 die 'Extra tokens after --def'
422 if @$tokens > 0;
423 $stack[0]{vars}{$name} = $value;
426 local $SIG{__WARN__} = sub { die $_[0]; };
427 GetOptions('noexec|n' => \$opt_noexec,
428 'flush|F' => \$opt_flush,
429 'noflush' => \$opt_noflush,
430 'lines|l' => \$opt_lines,
431 'interactive|i' => \$opt_interactive,
432 'help|h' => \$opt_help,
433 'version|V' => \$opt_version,
434 test => \$opt_test,
435 remote => \$opt_test,
436 fast => \$opt_fast,
437 slow => \$opt_slow,
438 shell => \$opt_shell,
439 'domain=s' => \$opt_domain,
440 'def=s' => \&opt_def,
443 if (defined $opt_help) {
444 require Pod::Usage;
445 Pod::Usage::pod2usage(-exitstatus => 0);
448 if (defined $opt_version) {
449 printversion();
450 exit 0;
453 $option{noexec} = $opt_noexec || $opt_test;
454 $option{flush} = $opt_flush;
455 $option{noflush} = $opt_noflush;
456 $option{lines} = $opt_lines || $opt_test || $opt_shell;
457 $option{interactive} = $opt_interactive && !$opt_noexec;
458 $option{test} = $opt_test;
459 $option{fast} = !$opt_slow;
460 $option{shell} = $opt_shell;
462 die("ferm interactive mode not possible: /dev/stdin is not a tty\n")
463 if $option{interactive} and not -t STDIN;
464 die("ferm interactive mode not possible: /dev/stderr is not a tty\n")
465 if $option{interactive} and not -t STDERR;
467 $option{domain} = $opt_domain if defined $opt_domain;
468 } else {
469 # tiny getopt emulation for microperl
470 my $filename;
471 foreach (@ARGV) {
472 if ($_ eq '--noexec' or $_ eq '-n') {
473 $option{noexec} = 1;
474 } elsif ($_ eq '--lines' or $_ eq '-l') {
475 $option{lines} = 1;
476 } elsif ($_ eq '--fast') {
477 $option{fast} = 1;
478 } elsif ($_ eq '--test') {
479 $option{test} = 1;
480 $option{noexec} = 1;
481 $option{lines} = 1;
482 } elsif ($_ eq '--shell') {
483 $option{$_} = 1 foreach qw(shell fast lines);
484 } elsif (/^-/) {
485 printf STDERR "Usage: ferm [--noexec] [--lines] [--fast] [--shell] FILENAME\n";
486 exit 1;
487 } else {
488 $filename = $_;
491 undef @ARGV;
492 push @ARGV, $filename;
495 unless (@ARGV == 1) {
496 require Pod::Usage;
497 Pod::Usage::pod2usage(-exitstatus => 1);
500 if ($has_strict) {
501 open LINES, ">&STDOUT" if $option{lines};
502 open STDOUT, ">&STDERR" if $option{shell};
503 } else {
504 # microperl can't redirect file handles
505 *LINES = *STDOUT;
507 if ($option{fast} and not $option{noexec}) {
508 print STDERR "Sorry, ferm on microperl does not allow --fast without --noexec\n";
509 exit 1
513 unshift @stack, {};
514 open_script($ARGV[0]);
515 $stack[0]{auto}{FILENAME} = $ARGV[0];
516 $stack[0]{auto}{DIRNAME} = $ARGV[0] =~ m,^(.*)/,s ? $1 : '.';
518 # parse all input recursively
519 enter(0);
520 die unless @stack == 2;
522 # enable/disable hooks depending on --flush
524 if ($option{flush}) {
525 undef @pre_hooks;
526 undef @post_hooks;
527 } else {
528 undef @flush_hooks;
531 # execute all generated rules
532 my $status;
534 foreach my $cmd (@pre_hooks) {
535 print LINES "$cmd\n" if $option{lines};
536 system($cmd) unless $option{noexec};
539 while (my ($domain, $domain_info) = each %domains) {
540 next unless $domain_info->{enabled};
541 my $s = $option{fast} &&
542 defined $domain_info->{tools}{'tables-restore'}
543 ? execute_fast($domain_info) : execute_slow($domain_info);
544 $status = $s if defined $s;
547 foreach my $cmd (@post_hooks, @flush_hooks) {
548 print LINES "$cmd\n" if $option{lines};
549 system($cmd) unless $option{noexec};
552 if (defined $status) {
553 rollback();
554 exit $status;
557 # ask user, and rollback if there is no confirmation
559 if ($option{interactive}) {
560 if ($option{shell}) {
561 print LINES "echo 'ferm has applied the new firewall rules.'\n";
562 print LINES "echo 'Please press Ctrl-C to confirm.'\n";
563 print LINES "sleep 30\n";
564 while (my ($domain, $domain_info) = each %domains) {
565 my $restore = $domain_info->{tools}{'tables-restore'};
566 next unless defined $restore;
567 print LINES "$restore <\$${domain}_tmp\n";
571 confirm_rules() or rollback() unless $option{noexec};
574 exit 0;
576 # end of program execution!
579 # funcs
581 sub printversion {
582 print "ferm $VERSION\n";
583 print "Copyright (C) 2001-2010 Max Kellermann, Auke Kok\n";
584 print "This program is free software released under GPLv2.\n";
585 print "See the included COPYING file for license details.\n";
589 sub error {
590 # returns a nice formatted error message, showing the
591 # location of the error.
592 my $tabs = 0;
593 my @lines;
594 my $l = 0;
595 my @words = map { @$_ } @{$script->{past_tokens}};
597 for my $w ( 0 .. $#words ) {
598 if ($words[$w] eq "\x29")
599 { $l++ ; $lines[$l] = " " x ($tabs-- -1) ;};
600 if ($words[$w] eq "\x28")
601 { $l++ ; $lines[$l] = " " x $tabs++ ;};
602 if ($words[$w] eq "\x7d")
603 { $l++ ; $lines[$l] = " " x ($tabs-- -1) ;};
604 if ($words[$w] eq "\x7b")
605 { $l++ ; $lines[$l] = " " x $tabs++ ;};
606 if ( $l > $#lines ) { $lines[$l] = "" };
607 $lines[$l] .= $words[$w] . " ";
608 if ($words[$w] eq "\x28")
609 { $l++ ; $lines[$l] = " " x $tabs ;};
610 if (($words[$w] eq "\x29") && ($words[$w+1] ne "\x7b"))
611 { $l++ ; $lines[$l] = " " x $tabs ;};
612 if ($words[$w] eq "\x7b")
613 { $l++ ; $lines[$l] = " " x $tabs ;};
614 if (($words[$w] eq "\x7d") && ($words[$w+1] ne "\x7d"))
615 { $l++ ; $lines[$l] = " " x $tabs ;};
616 if (($words[$w] eq "\x3b") && ($words[$w+1] ne "\x7d"))
617 { $l++ ; $lines[$l] = " " x $tabs ;}
618 if ($words[$w-1] eq "option")
619 { $l++ ; $lines[$l] = " " x $tabs ;}
621 my $start = $#lines - 4;
622 if ($start < 0) { $start = 0 } ;
623 print STDERR "Error in $script->{filename} line $script->{line}:\n";
624 for $l ( $start .. $#lines)
625 { print STDERR $lines[$l]; if ($l != $#lines ) {print STDERR "\n"} ; };
626 print STDERR "<--\n";
627 die("@_\n");
630 # print a warning message about code from an input file
631 sub warning {
632 print STDERR "Warning in $script->{filename} line $script->{line}: "
633 . (shift) . "\n";
636 sub find_tool($) {
637 my $name = shift;
638 return $name if $option{test};
639 for my $path ('/sbin', split ':', $ENV{PATH}) {
640 my $ret = "$path/$name";
641 return $ret if -x $ret;
643 die "$name not found in PATH\n";
646 sub initialize_domain {
647 my $domain = shift;
648 my $domain_info = $domains{$domain} ||= {};
650 return if exists $domain_info->{initialized};
652 die "Invalid domain '$domain'\n" unless $domain =~ /^(?:ip6?|arp|eb)$/;
654 my @tools = qw(tables);
655 push @tools, qw(tables-save tables-restore)
656 if $domain =~ /^ip6?$/;
658 # determine the location of this domain's tools
659 my %tools = map { $_ => find_tool($domain . $_) } @tools;
660 $domain_info->{tools} = \%tools;
662 # make tables-save tell us about the state of this domain
663 # (which tables and chains do exist?), also remember the old
664 # save data which may be used later by the rollback function
665 local *SAVE;
666 if (!$option{test} &&
667 exists $tools{'tables-save'} &&
668 open(SAVE, "$tools{'tables-save'}|")) {
669 my $save = '';
671 my $table_info;
672 while (<SAVE>) {
673 $save .= $_;
675 if (/^\*(\w+)/) {
676 my $table = $1;
677 $table_info = $domain_info->{tables}{$table} ||= {};
678 } elsif (defined $table_info and /^:(\w+)\s+(\S+)/
679 and $2 ne '-') {
680 $table_info->{chains}{$1}{builtin} = 1;
681 $table_info->{has_builtin} = 1;
685 # for rollback
686 $domain_info->{previous} = $save;
689 if ($option{shell} && $option{interactive} &&
690 exists $tools{'tables-save'}) {
691 print LINES "${domain}_tmp=\$(mktemp ferm.XXXXXXXXXX)\n";
692 print LINES "$tools{'tables-save'} >\$${domain}_tmp\n";
695 $domain_info->{initialized} = 1;
698 sub filter_domains($) {
699 my $domains = shift;
700 my @result;
702 foreach my $domain (to_array($domains)) {
703 next if exists $option{domain}
704 and $domain ne $option{domain};
706 eval {
707 initialize_domain($domain);
709 error($@) if $@;
711 push @result, $domain;
714 return @result == 1 ? @result[0] : \@result;
717 # split the input string into words and delete comments
718 sub tokenize_string($) {
719 my $string = shift;
721 my @ret;
723 foreach my $word ($string =~ m/(".*?"|'.*?'|`.*?`|[!,=&\$\%\(\){};]|[-+\w\/\.:]+|@\w+|#)/g) {
724 last if $word eq '#';
725 push @ret, $word;
728 return \@ret;
731 # read some more tokens from the input file into a buffer
732 sub prepare_tokens() {
733 my $tokens = $script->{tokens};
734 while (@$tokens == 0) {
735 my $handle = $script->{handle};
736 my $line = <$handle>;
737 return unless defined $line;
739 $script->{line} ++;
741 # the next parser stage eats this
742 push @$tokens, @{tokenize_string($line)};
745 return 1;
748 # open a ferm sub script
749 sub open_script($) {
750 my $filename = shift;
752 for (my $s = $script; defined $s; $s = $s->{parent}) {
753 die("Circular reference in $script->{filename} line $script->{line}: $filename\n")
754 if $s->{filename} eq $filename;
757 local *FILE;
758 open FILE, "$filename" or die("Failed to open $filename: $!\n");
759 my $handle = *FILE;
761 $script = { filename => $filename,
762 handle => $handle,
763 line => 0,
764 past_tokens => [],
765 tokens => [],
766 parent => $script,
769 return $script;
772 # collect script filenames which are being included
773 sub collect_filenames(@) {
774 my @ret;
776 # determine the current script's parent directory for relative
777 # file names
778 die unless defined $script;
779 my $parent_dir = $script->{filename} =~ m,^(.*/),
780 ? $1 : './';
782 foreach my $pathname (@_) {
783 # non-absolute file names are relative to the parent script's
784 # file name
785 $pathname = $parent_dir . $pathname
786 unless $pathname =~ m,^/|\|$,;
788 if ($pathname =~ m,/$,) {
789 # include all regular files in a directory
791 error("'$pathname' is not a directory")
792 unless -d $pathname;
794 local *DIR;
795 opendir DIR, $pathname
796 or error("Failed to open directory '$pathname': $!");
797 my @names = readdir DIR;
798 closedir DIR;
800 # sort those names for a well-defined order
801 foreach my $name (sort { $a cmp $b } @names) {
802 # ignore dpkg's backup files
803 next if $name =~ /\.dpkg-(old|dist|new|tmp)$/;
804 # don't include hidden and backup files
805 next if $name =~ /^\.|~$/;
807 my $filename = $pathname . $name;
808 push @ret, $filename
809 if -f $filename;
811 } elsif ($pathname =~ m,\|$,) {
812 # run a program and use its output
813 push @ret, $pathname;
814 } elsif ($pathname =~ m,^\|,) {
815 error('This kind of pipe is not allowed');
816 } else {
817 # include a regular file
819 error("'$pathname' is a directory; maybe use trailing '/' to include a directory?")
820 if -d $pathname;
821 error("'$pathname' is not a file")
822 unless -f $pathname;
824 push @ret, $pathname;
828 return @ret;
831 # peek a token from the queue, but don't remove it
832 sub peek_token() {
833 return unless prepare_tokens();
834 return $script->{tokens}[0];
837 # get a token from the queue
838 sub next_token() {
839 return unless prepare_tokens();
840 my $token = shift @{$script->{tokens}};
842 # update $script->{past_tokens}
843 my $past_tokens = $script->{past_tokens};
845 if (@$past_tokens > 0) {
846 my $prev_token = $past_tokens->[-1][-1];
847 $past_tokens->[-1] = @$past_tokens > 1 ? ['{'] : []
848 if $prev_token eq ';';
849 if ($prev_token eq '}') {
850 pop @$past_tokens;
851 $past_tokens->[-1] = $past_tokens->[-1][0] eq '{'
852 ? [ '{' ] : []
853 if @$past_tokens > 0;
857 push @$past_tokens, [] if $token eq '{' or @$past_tokens == 0;
858 push @{$past_tokens->[-1]}, $token;
860 # return
861 return $token;
864 sub expect_token($;$) {
865 my $expect = shift;
866 my $msg = shift;
867 my $token = next_token();
868 error($msg || "'$expect' expected")
869 unless defined $token and $token eq $expect;
872 # require that another token exists, and that it's not a "special"
873 # token, e.g. ";" and "{"
874 sub require_next_token {
875 my $code = shift || \&next_token;
877 my $token = &$code(@_);
879 error('unexpected end of file')
880 unless defined $token;
882 error("'$token' not allowed here")
883 if $token =~ /^[;{}]$/;
885 return $token;
888 # return the value of a variable
889 sub variable_value($) {
890 my $name = shift;
892 foreach (@stack) {
893 return $_->{vars}{$name}
894 if exists $_->{vars}{$name};
897 return $stack[0]{auto}{$name}
898 if exists $stack[0]{auto}{$name};
900 return;
903 # determine the value of a variable, die if the value is an array
904 sub string_variable_value($) {
905 my $name = shift;
906 my $value = variable_value($name);
908 error("variable '$name' must be a string, but it is an array")
909 if ref $value;
911 return $value;
914 # similar to the built-in "join" function, but also handle negated
915 # values in a special way
916 sub join_value($$) {
917 my ($expr, $value) = @_;
919 unless (ref $value) {
920 return $value;
921 } elsif (ref $value eq 'ARRAY') {
922 return join($expr, @$value);
923 } elsif (ref $value eq 'negated') {
924 # bless'negated' is a special marker for negated values
925 $value = join_value($expr, $value->[0]);
926 return bless [ $value ], 'negated';
927 } else {
928 die;
932 sub negate_value($$;$) {
933 my ($value, $class, $allow_array) = @_;
935 if (ref $value) {
936 error('double negation is not allowed')
937 if ref $value eq 'negated' or ref $value eq 'pre_negated';
939 error('it is not possible to negate an array')
940 if ref $value eq 'ARRAY' and not $allow_array;
943 return bless [ $value ], $class || 'negated';
946 sub resolve($\@$) {
947 my ($resolver, $names, $type) = @_;
949 my @result;
950 foreach my $hostname (@$names) {
951 my $query = $resolver->search($hostname, $type);
952 error("DNS query for '$hostname' failed: " . $resolver->errorstring)
953 unless $query;
955 foreach my $rr ($query->answer) {
956 next unless $rr->type eq $type;
958 if ($type eq 'NS') {
959 push @result, $rr->nsdname;
960 } elsif ($type eq 'MX') {
961 push @result, $rr->exchange;
962 } else {
963 push @result, $rr->address;
968 # NS/MX records return host names; resolve these again in the
969 # second pass (IPv4 only currently)
970 @result = resolve($resolver, \@result, 'A')
971 if $type eq 'NS' or $type eq 'MX';
973 return @result;
976 # returns the next parameter, which may either be a scalar or an array
977 sub getvalues {
978 my $code = shift;
979 my %options = @_;
981 my $token = require_next_token($code);
983 if ($token eq '(') {
984 # read an array until ")"
985 my @wordlist;
987 for (;;) {
988 $token = getvalues($code,
989 parenthesis_allowed => 1,
990 comma_allowed => 1);
992 unless (ref $token) {
993 last if $token eq ')';
995 if ($token eq ',') {
996 error('Comma is not allowed within arrays, please use only a space');
997 next;
1000 push @wordlist, $token;
1001 } elsif (ref $token eq 'ARRAY') {
1002 push @wordlist, @$token;
1003 } else {
1004 error('unknown toke type');
1008 error('empty array not allowed here')
1009 unless @wordlist or not $options{non_empty};
1011 return @wordlist == 1
1012 ? $wordlist[0]
1013 : \@wordlist;
1014 } elsif ($token =~ /^\`(.*)\`$/s) {
1015 # execute a shell command, insert output
1016 my $command = $1;
1017 my $output = `$command`;
1018 unless ($? == 0) {
1019 if ($? == -1) {
1020 error("failed to execute: $!");
1021 } elsif ($? & 0x7f) {
1022 error("child died with signal " . ($? & 0x7f));
1023 } elsif ($? >> 8) {
1024 error("child exited with status " . ($? >> 8));
1028 # remove comments
1029 $output =~ s/#.*//mg;
1031 # tokenize
1032 my @tokens = grep { length } split /\s+/s, $output;
1034 my @values;
1035 while (@tokens) {
1036 my $value = getvalues(sub { shift @tokens });
1037 push @values, to_array($value);
1040 # and recurse
1041 return @values == 1
1042 ? $values[0]
1043 : \@values;
1044 } elsif ($token =~ /^\'(.*)\'$/s) {
1045 # single quotes: a string
1046 return $1;
1047 } elsif ($token =~ /^\"(.*)\"$/s) {
1048 # double quotes: a string with escapes
1049 $token = $1;
1050 $token =~ s,\$(\w+),string_variable_value($1),eg;
1051 return $token;
1052 } elsif ($token eq '!') {
1053 error('negation is not allowed here')
1054 unless $options{allow_negation};
1056 $token = getvalues($code);
1058 return negate_value($token, undef, $options{allow_array_negation});
1059 } elsif ($token eq ',') {
1060 return $token
1061 if $options{comma_allowed};
1063 error('comma is not allowed here');
1064 } elsif ($token eq '=') {
1065 error('equals operator ("=") is not allowed here');
1066 } elsif ($token eq '$') {
1067 my $name = require_next_token($code);
1068 error('variable name expected - if you want to concatenate strings, try using double quotes')
1069 unless $name =~ /^\w+$/;
1071 my $value = variable_value($name);
1073 error("no such variable: \$$name")
1074 unless defined $value;
1076 return $value;
1077 } elsif ($token eq '&') {
1078 error("function calls are not allowed as keyword parameter");
1079 } elsif ($token eq ')' and not $options{parenthesis_allowed}) {
1080 error('Syntax error');
1081 } elsif ($token =~ /^@/) {
1082 if ($token eq '@resolve') {
1083 my @params = get_function_params();
1084 error('Usage: @resolve((hostname ...), [type])')
1085 unless @params == 1 or @params == 2;
1086 eval { require Net::DNS; };
1087 error('For the @resolve() function, you need the Perl library Net::DNS')
1088 if $@;
1089 my $type = $params[1] || 'A';
1090 my $resolver = new Net::DNS::Resolver;
1091 my @params = to_array($params[0]);
1092 return [resolve($resolver, @params, $type)];
1093 } else {
1094 error("unknown ferm built-in function");
1096 } else {
1097 return $token;
1101 # returns the next parameter, but only allow a scalar
1102 sub getvar() {
1103 my $token = getvalues();
1105 error('array not allowed here')
1106 if ref $token and ref $token eq 'ARRAY';
1108 return $token;
1111 sub get_function_params(%) {
1112 expect_token('(', 'function name must be followed by "()"');
1114 my $token = peek_token();
1115 if ($token eq ')') {
1116 require_next_token();
1117 return;
1120 my @params;
1122 while (1) {
1123 if (@params > 0) {
1124 $token = require_next_token();
1125 last
1126 if $token eq ')';
1128 error('"," expected')
1129 unless $token eq ',';
1132 push @params, getvalues(undef, @_);
1135 return @params;
1138 # collect all tokens in a flat array reference until the end of the
1139 # command is reached
1140 sub collect_tokens() {
1141 my @level;
1142 my @tokens;
1144 while (1) {
1145 my $keyword = next_token();
1146 error('unexpected end of file within function/variable declaration')
1147 unless defined $keyword;
1149 if ($keyword =~ /^[\{\(]$/) {
1150 push @level, $keyword;
1151 } elsif ($keyword =~ /^[\}\)]$/) {
1152 my $expected = $keyword;
1153 $expected =~ tr/\}\)/\{\(/;
1154 my $opener = pop @level;
1155 error("unmatched '$keyword'")
1156 unless defined $opener and $opener eq $expected;
1157 } elsif ($keyword eq ';' and @level == 0) {
1158 last;
1161 push @tokens, $keyword;
1163 last
1164 if $keyword eq '}' and @level == 0;
1167 return \@tokens;
1171 # returns the specified value as an array. dereference arrayrefs
1172 sub to_array($) {
1173 my $value = shift;
1174 die unless wantarray;
1175 die if @_;
1176 unless (ref $value) {
1177 return $value;
1178 } elsif (ref $value eq 'ARRAY') {
1179 return @$value;
1180 } else {
1181 die;
1185 # evaluate the specified value as bool
1186 sub eval_bool($) {
1187 my $value = shift;
1188 die if wantarray;
1189 die if @_;
1190 unless (ref $value) {
1191 return $value;
1192 } elsif (ref $value eq 'ARRAY') {
1193 return @$value > 0;
1194 } else {
1195 die;
1199 sub is_netfilter_core_target($) {
1200 my $target = shift;
1201 die unless defined $target and length $target;
1202 return grep { $_ eq $target } qw(ACCEPT DROP RETURN QUEUE);
1205 sub is_netfilter_module_target($$) {
1206 my ($domain_family, $target) = @_;
1207 die unless defined $target and length $target;
1209 return defined $domain_family &&
1210 exists $target_defs{$domain_family} &&
1211 $target_defs{$domain_family}{$target};
1214 sub is_netfilter_builtin_chain($$) {
1215 my ($table, $chain) = @_;
1217 return grep { $_ eq $chain }
1218 qw(PREROUTING INPUT FORWARD OUTPUT POSTROUTING);
1221 sub netfilter_canonical_protocol($) {
1222 my $proto = shift;
1223 return 'icmpv6'
1224 if $proto eq 'ipv6-icmp';
1225 return 'mh'
1226 if $proto eq 'ipv6-mh';
1227 return $proto;
1230 sub netfilter_protocol_module($) {
1231 my $proto = shift;
1232 return unless defined $proto;
1233 return 'icmp6'
1234 if $proto eq 'icmpv6';
1235 return $proto;
1238 # escape the string in a way safe for the shell
1239 sub shell_escape($) {
1240 my $token = shift;
1242 return $token if $token =~ /^[-_a-zA-Z0-9]+$/s;
1244 if ($option{fast}) {
1245 # iptables-save/iptables-restore are quite buggy concerning
1246 # escaping and special characters... we're trying our best
1247 # here
1249 $token =~ s,",\\",g;
1250 $token = '"' . $token . '"'
1251 if $token =~ /[\s\'\\;&]/s or length($token) == 0;
1252 } else {
1253 return $token
1254 if $token =~ /^\`.*\`$/;
1255 $token =~ s/'/'\\''/g;
1256 $token = '\'' . $token . '\''
1257 if $token =~ /[\s\"\\;<>&|]/s or length($token) == 0;
1260 return $token;
1263 # append an option to the shell command line, using information from
1264 # the module definition (see %match_defs etc.)
1265 sub shell_format_option($$) {
1266 my ($keyword, $value) = @_;
1268 my $cmd = '';
1269 if (ref $value) {
1270 if ((ref $value eq 'negated') || (ref $value eq 'pre_negated')) {
1271 $value = $value->[0];
1272 $cmd = ' !';
1276 unless (defined $value) {
1277 $cmd .= " --$keyword";
1278 } elsif (ref $value) {
1279 if (ref $value eq 'params') {
1280 $cmd .= " --$keyword ";
1281 $cmd .= join(' ', map { shell_escape($_) } @$value);
1282 } elsif (ref $value eq 'multi') {
1283 foreach (@$value) {
1284 $cmd .= " --$keyword " . shell_escape($_);
1286 } else {
1287 die;
1289 } else {
1290 $cmd .= " --$keyword " . shell_escape($value);
1293 return $cmd;
1296 sub format_option($$$) {
1297 my ($domain, $name, $value) = @_;
1298 $value = 'icmpv6' if $domain eq 'ip6' and $name eq 'protocol'
1299 and $value eq 'icmp';
1300 return shell_format_option($name, $value);
1303 sub append_rule($$) {
1304 my ($chain_rules, $rule) = @_;
1306 my $cmd = join('', map { $_->[2] } @{$rule->{options}});
1307 push @$chain_rules, { rule => $cmd,
1308 script => $rule->{script},
1312 sub format_option($$$) {
1313 my ($domain, $name, $value) = @_;
1314 $value = 'icmpv6' if $domain eq 'ip6' and $name eq 'protocol'
1315 and $value eq 'icmp';
1316 return shell_format_option($name, $value);
1319 sub unfold_rule {
1320 my ($domain, $chain_rules, $rule) = (shift, shift, shift);
1321 return append_rule($chain_rules, $rule) unless @_;
1323 my $option = shift;
1324 my @values = @{$option->[1]};
1326 foreach my $value (@values) {
1327 $option->[2] = format_option($domain, $option->[0], $value);
1328 unfold_rule($domain, $chain_rules, $rule, @_);
1332 sub mkrules2($$$) {
1333 my ($domain, $chain_rules, $rule) = @_;
1335 my @unfold;
1336 foreach my $option (@{$rule->{options}}) {
1337 if (ref $option->[1] and ref $option->[1] eq 'ARRAY') {
1338 push @unfold, $option
1339 } else {
1340 $option->[2] = format_option($domain, $option->[0], $option->[1]);
1344 unfold_rule($domain, $chain_rules, $rule, @unfold);
1347 # convert a bunch of internal rule structures in iptables calls,
1348 # unfold arrays during that
1349 sub mkrules($) {
1350 my $rule = shift;
1352 foreach my $domain (to_array $rule->{domain}) {
1353 my $domain_info = $domains{$domain};
1354 $domain_info->{enabled} = 1;
1356 foreach my $table (to_array $rule->{table}) {
1357 my $table_info = $domain_info->{tables}{$table} ||= {};
1359 foreach my $chain (to_array $rule->{chain}) {
1360 my $chain_rules = $table_info->{chains}{$chain}{rules} ||= [];
1361 mkrules2($domain, $chain_rules, $rule)
1362 if $rule->{has_rule} and not $option{flush};
1368 # parse a keyword from a module definition
1369 sub parse_keyword(\%$$) {
1370 my ($rule, $def, $negated_ref) = @_;
1372 my $params = $def->{params};
1374 my $value;
1376 my $negated;
1377 if ($$negated_ref && exists $def->{pre_negation}) {
1378 $negated = 1;
1379 undef $$negated_ref;
1382 unless (defined $params) {
1383 undef $value;
1384 } elsif (ref $params && ref $params eq 'CODE') {
1385 $value = &$params($rule);
1386 } elsif ($params eq 'm') {
1387 $value = bless [ to_array getvalues() ], 'multi';
1388 } elsif ($params =~ /^[a-z]/) {
1389 if (exists $def->{negation} and not $negated) {
1390 my $token = peek_token();
1391 if ($token eq '!') {
1392 require_next_token();
1393 $negated = 1;
1397 my @params;
1398 foreach my $p (split(//, $params)) {
1399 if ($p eq 's') {
1400 push @params, getvar();
1401 } elsif ($p eq 'c') {
1402 my @v = to_array getvalues(undef, non_empty => 1);
1403 push @params, join(',', @v);
1404 } else {
1405 die;
1409 $value = @params == 1
1410 ? $params[0]
1411 : bless \@params, 'params';
1412 } elsif ($params == 1) {
1413 if (exists $def->{negation} and not $negated) {
1414 my $token = peek_token();
1415 if ($token eq '!') {
1416 require_next_token();
1417 $negated = 1;
1421 $value = getvalues();
1423 warning("log-prefix is too long; truncating to 29 characters: '$1'")
1424 if $def->{name} eq 'log-prefix' && $value =~ s,^(.{29}).+$,$1,;
1425 } else {
1426 if (exists $def->{negation} and not $negated) {
1427 my $token = peek_token();
1428 if ($token eq '!') {
1429 require_next_token();
1430 $negated = 1;
1434 $value = bless [ map {
1435 getvar()
1436 } (1..$params) ], 'params';
1439 $value = negate_value($value, exists $def->{pre_negation} && 'pre_negated')
1440 if $negated;
1442 return $value;
1445 sub append_option(\%$$) {
1446 my ($rule, $name, $value) = @_;
1447 push @{$rule->{options}}, [ $name, $value ];
1450 # parse options of a module
1451 sub parse_option($\%$) {
1452 my ($def, $rule, $negated_ref) = @_;
1454 append_option(%$rule, $def->{name},
1455 parse_keyword(%$rule, $def, $negated_ref));
1458 sub copy_on_write($$) {
1459 my ($rule, $key) = @_;
1460 return unless exists $rule->{cow}{$key};
1461 $rule->{$key} = {%{$rule->{$key}}};
1462 delete $rule->{cow}{$key};
1465 sub new_level(\%$) {
1466 my ($rule, $prev) = @_;
1468 %$rule = ();
1469 if (defined $prev) {
1470 # copy data from previous level
1471 $rule->{cow} = { keywords => 1, };
1472 $rule->{keywords} = $prev->{keywords};
1473 $rule->{match} = { %{$prev->{match}} };
1474 $rule->{options} = [@{$prev->{options}}];
1475 foreach my $key (qw(domain domain_family table chain protocol has_rule has_action)) {
1476 $rule->{$key} = $prev->{$key}
1477 if exists $prev->{$key};
1479 } else {
1480 $rule->{cow} = {};
1481 $rule->{keywords} = {};
1482 $rule->{match} = {};
1483 $rule->{options} = [];
1487 sub merge_keywords(\%$) {
1488 my ($rule, $keywords) = @_;
1489 copy_on_write($rule, 'keywords');
1490 while (my ($name, $def) = each %$keywords) {
1491 $rule->{keywords}{$name} = $def;
1495 sub set_domain(\%$) {
1496 my ($rule, $domain) = @_;
1498 my $filtered_domain = filter_domains($domain);
1499 my $domain_family;
1500 unless (ref $domain) {
1501 $domain_family = $domain eq 'ip6' ? 'ip' : $domain;
1502 } elsif (@$domain == 0) {
1503 $domain_family = 'none';
1504 } elsif (grep { not /^ip6?$/s } @$domain) {
1505 error('Cannot combine non-IP domains');
1506 } else {
1507 $domain_family = 'ip';
1510 $rule->{domain_family} = $domain_family;
1511 $rule->{keywords} = $match_defs{$domain_family}{''}{keywords};
1512 $rule->{cow}{keywords} = 1;
1514 $rule->{domain} = $stack[0]{auto}{DOMAIN} = $filtered_domain;
1517 sub set_target(\%$$) {
1518 my ($rule, $name, $value) = @_;
1519 error('There can only one action per rule')
1520 if exists $rule->{has_action};
1521 $rule->{has_action} = 1;
1522 append_option(%$rule, $name, $value);
1525 sub set_module_target(\%$$) {
1526 my ($rule, $name, $defs) = @_;
1528 if ($name eq 'TCPMSS') {
1529 my $protos = $rule->{protocol};
1530 error('No protocol specified before TCPMSS')
1531 unless defined $protos;
1532 foreach my $proto (to_array $protos) {
1533 error('TCPMSS not available for protocol "$proto"')
1534 unless $proto eq 'tcp';
1538 # in ebtables, there is both "--mark" and "-j mark"... workaround:
1539 $name = 'mark' if $name eq 'MARK' and $rule->{domain_family} eq 'eb';
1541 set_target(%$rule, 'jump', $name);
1542 merge_keywords(%$rule, $defs->{keywords});
1545 # the main parser loop: read tokens, convert them into internal rule
1546 # structures
1547 sub enter($$) {
1548 my $lev = shift; # current recursion depth
1549 my $prev = shift; # previous rule hash
1551 # enter is the core of the firewall setup, it is a
1552 # simple parser program that recognizes keywords and
1553 # retreives parameters to set up the kernel routing
1554 # chains
1556 my $base_level = $script->{base_level} || 0;
1557 die if $base_level > $lev;
1559 my %rule;
1560 new_level(%rule, $prev);
1562 # read keywords 1 by 1 and dump into parser
1563 while (defined (my $keyword = next_token())) {
1564 # check if the current rule should be negated
1565 my $negated = $keyword eq '!';
1566 if ($negated) {
1567 # negation. get the next word which contains the 'real'
1568 # rule
1569 $keyword = getvar();
1571 error('unexpected end of file after negation')
1572 unless defined $keyword;
1575 # the core: parse all data
1576 for ($keyword)
1578 # deprecated keyword?
1579 if (exists $deprecated_keywords{$keyword}) {
1580 my $new_keyword = $deprecated_keywords{$keyword};
1581 warning("'$keyword' is deprecated, please use '$new_keyword' instead");
1582 $keyword = $new_keyword;
1585 # effectuation operator
1586 if ($keyword eq ';') {
1587 error('Empty rule before ";" not allowed')
1588 unless $rule{non_empty};
1590 if ($rule{has_rule} and not exists $rule{has_action}) {
1591 # something is wrong when a rule was specified,
1592 # but no action
1593 error('No action defined; did you mean "NOP"?');
1596 error('No chain defined') unless exists $rule{chain};
1598 $rule{script} = { filename => $script->{filename},
1599 line => $script->{line},
1602 mkrules(\%rule);
1604 # and clean up variables set in this level
1605 new_level(%rule, $prev);
1607 next;
1610 # conditional expression
1611 if ($keyword eq '@if') {
1612 unless (eval_bool(getvalues)) {
1613 collect_tokens;
1614 my $token = peek_token();
1615 require_next_token() if $token and $token eq '@else';
1618 next;
1621 if ($keyword eq '@else') {
1622 # hack: if this "else" has not been eaten by the "if"
1623 # handler above, we believe it came from an if clause
1624 # which evaluated "true" - remove the "else" part now.
1625 collect_tokens;
1626 next;
1629 # hooks for custom shell commands
1630 if ($keyword eq 'hook') {
1631 warning("'hook' is deprecated, use '\@hook'");
1632 $keyword = '@hook';
1635 if ($keyword eq '@hook') {
1636 error('"hook" must be the first token in a command')
1637 if exists $rule{domain};
1639 my $position = getvar();
1640 my $hooks;
1641 if ($position eq 'pre') {
1642 $hooks = \@pre_hooks;
1643 } elsif ($position eq 'post') {
1644 $hooks = \@post_hooks;
1645 } elsif ($position eq 'flush') {
1646 $hooks = \@flush_hooks;
1647 } else {
1648 error("Invalid hook position: '$position'");
1651 push @$hooks, getvar();
1653 expect_token(';');
1654 next;
1657 # recursing operators
1658 if ($keyword eq '{') {
1659 # push stack
1660 my $old_stack_depth = @stack;
1662 unshift @stack, { auto => { %{$stack[0]{auto} || {}} } };
1664 # recurse
1665 enter($lev + 1, \%rule);
1667 # pop stack
1668 shift @stack;
1669 die unless @stack == $old_stack_depth;
1671 # after a block, the command is finished, clear this
1672 # level
1673 new_level(%rule, $prev);
1675 next;
1678 if ($keyword eq '}') {
1679 error('Unmatched "}"')
1680 if $lev <= $base_level;
1682 # consistency check: check if they havn't forgotten
1683 # the ';' after the last statement
1684 error('Missing semicolon before "}"')
1685 if $rule{non_empty};
1687 # and exit
1688 return;
1691 # include another file
1692 if ($keyword eq '@include' or $keyword eq 'include') {
1693 my @files = collect_filenames to_array getvalues;
1694 $keyword = next_token;
1695 error('Missing ";" - "include FILENAME" must be the last command in a rule')
1696 unless defined $keyword and $keyword eq ';';
1698 foreach my $filename (@files) {
1699 # save old script, open new script
1700 my $old_script = $script;
1701 open_script($filename);
1702 $script->{base_level} = $lev + 1;
1704 # push stack
1705 my $old_stack_depth = @stack;
1707 my $stack = {};
1709 if (@stack > 0) {
1710 # include files may set variables for their parent
1711 $stack->{vars} = ($stack[0]{vars} ||= {});
1712 $stack->{functions} = ($stack[0]{functions} ||= {});
1713 $stack->{auto} = { %{ $stack[0]{auto} || {} } };
1716 $stack->{auto}{FILENAME} = $filename;
1717 $stack->{auto}{DIRNAME} = $filename =~ m,^(.*)/,s ? $1 : '.';
1719 unshift @stack, $stack;
1721 # parse the script
1722 enter($lev + 1, \%rule);
1724 # pop stack
1725 shift @stack;
1726 die unless @stack == $old_stack_depth;
1728 # restore old script
1729 $script = $old_script;
1732 next;
1735 # definition of a variable or function
1736 if ($keyword eq '@def' or $keyword eq 'def') {
1737 error('"def" must be the first token in a command')
1738 if $rule{non_empty};
1740 my $type = require_next_token();
1741 if ($type eq '$') {
1742 my $name = require_next_token();
1743 error('invalid variable name')
1744 unless $name =~ /^\w+$/;
1746 expect_token('=');
1748 my $value = getvalues(undef, allow_negation => 1);
1750 expect_token(';');
1752 $stack[0]{vars}{$name} = $value
1753 unless exists $stack[-1]{vars}{$name};
1754 } elsif ($type eq '&') {
1755 my $name = require_next_token();
1756 error('invalid function name')
1757 unless $name =~ /^\w+$/;
1759 expect_token('(', 'function parameter list or "()" expected');
1761 my @params;
1762 while (1) {
1763 my $token = require_next_token();
1764 last if $token eq ')';
1766 if (@params > 0) {
1767 error('"," expected')
1768 unless $token eq ',';
1770 $token = require_next_token();
1773 error('"$" and parameter name expected')
1774 unless $token eq '$';
1776 $token = require_next_token();
1777 error('invalid function parameter name')
1778 unless $token =~ /^\w+$/;
1780 push @params, $token;
1783 my %function;
1785 $function{params} = \@params;
1787 expect_token('=');
1789 my $tokens = collect_tokens();
1790 $function{block} = 1 if grep { $_ eq '{' } @$tokens;
1791 $function{tokens} = $tokens;
1793 $stack[0]{functions}{$name} = \%function
1794 unless exists $stack[-1]{functions}{$name};
1795 } else {
1796 error('"$" (variable) or "&" (function) expected');
1799 next;
1802 # this rule has something which isn't inherited by its
1803 # parent closure. This variable is used in a lot of
1804 # syntax checks.
1806 $rule{non_empty} = 1;
1808 # def references
1809 if ($keyword eq '$') {
1810 error('variable references are only allowed as keyword parameter');
1813 if ($keyword eq '&') {
1814 my $name = require_next_token();
1815 error('function name expected')
1816 unless $name =~ /^\w+$/;
1818 my $function;
1819 foreach (@stack) {
1820 $function = $_->{functions}{$name};
1821 last if defined $function;
1823 error("no such function: \&$name")
1824 unless defined $function;
1826 my $paramdef = $function->{params};
1827 die unless defined $paramdef;
1829 my @params = get_function_params(allow_negation => 1);
1831 error("Wrong number of parameters for function '\&$name': "
1832 . @$paramdef . " expected, " . @params . " given")
1833 unless @params == @$paramdef;
1835 my %vars;
1836 for (my $i = 0; $i < @params; $i++) {
1837 $vars{$paramdef->[$i]} = $params[$i];
1840 if ($function->{block}) {
1841 # block {} always ends the current rule, so if the
1842 # function contains a block, we have to require
1843 # the calling rule also ends here
1844 expect_token(';');
1847 my @tokens = @{$function->{tokens}};
1848 for (my $i = 0; $i < @tokens; $i++) {
1849 if ($tokens[$i] eq '$' and $i + 1 < @tokens and
1850 exists $vars{$tokens[$i + 1]}) {
1851 my @value = to_array($vars{$tokens[$i + 1]});
1852 @value = ('(', @value, ')')
1853 unless @tokens == 1;
1854 splice(@tokens, $i, 2, @value);
1855 $i += @value - 2;
1856 } elsif ($tokens[$i] =~ m,^"(.*)"$,) {
1857 $tokens[$i] =~ s,\$(\w+),exists $vars{$1} ? $vars{$1} : "\$$1",eg;
1861 unshift @{$script->{tokens}}, @tokens;
1863 next;
1866 # where to put the rule?
1867 if ($keyword eq 'domain') {
1868 error('Domain is already specified')
1869 if exists $rule{domain};
1871 set_domain(%rule, getvalues());
1872 next;
1875 if ($keyword eq 'table') {
1876 warning('Table is already specified')
1877 if exists $rule{table};
1878 $rule{table} = $stack[0]{auto}{TABLE} = getvalues();
1880 set_domain(%rule, 'ip')
1881 unless exists $rule{domain};
1883 next;
1886 if ($keyword eq 'chain') {
1887 warning('Chain is already specified')
1888 if exists $rule{chain};
1890 my $chain = $rule{chain} = $stack[0]{auto}{CHAIN} = getvalues();
1892 # ferm 1.1 allowed lower case built-in chain names
1893 foreach (ref $rule{chain} ? @{$rule{chain}} : $rule{chain}) {
1894 error('Please write built-in chain names in upper case')
1895 if /^(?:input|forward|output|prerouting|postrouting)$/;
1898 set_domain(%rule, 'ip')
1899 unless exists $rule{domain};
1901 $rule{table} = 'filter'
1902 unless exists $rule{table};
1904 foreach my $domain (to_array $rule{domain}) {
1905 foreach my $table (to_array $rule{table}) {
1906 foreach my $c (to_array $chain) {
1907 $domains{$domain}{tables}{$table}{chains}{$c} ||= {};
1912 next;
1915 error('Chain must be specified')
1916 unless exists $rule{chain};
1918 # policy for built-in chain
1919 if ($keyword eq 'policy') {
1920 error('Cannot specify matches for policy')
1921 if $rule{has_rule};
1923 my $policy = getvar();
1924 error("Invalid policy target: $policy")
1925 unless $policy =~ /^(?:ACCEPT|DROP)$/;
1927 expect_token(';');
1929 foreach my $domain (to_array $rule{domain}) {
1930 my $domain_info = $domains{$domain};
1931 $domain_info->{enabled} = 1;
1933 foreach my $table (to_array $rule{table}) {
1934 foreach my $chain (to_array $rule{chain}) {
1935 $domain_info->{tables}{$table}{chains}{$chain}{policy} = $policy;
1940 new_level(%rule, $prev);
1941 next;
1944 # create a subchain
1945 if ($keyword eq '@subchain' or $keyword eq 'subchain') {
1946 error('Chain must be specified')
1947 unless exists $rule{chain};
1949 error('No rule specified before "@subchain"')
1950 unless $rule{has_rule};
1952 my $subchain;
1953 $keyword = next_token();
1955 if ($keyword =~ /^(["'])(.*)\1$/s) {
1956 $subchain = $2;
1957 $keyword = next_token();
1958 } else {
1959 $subchain = 'ferm_auto_' . ++$auto_chain;
1962 foreach my $domain (to_array $rule{domain}) {
1963 foreach my $table (to_array $rule{table}) {
1964 $domains{$domain}{tables}{$table}{chains}{$subchain} ||= {};
1968 set_target(%rule, 'jump', $subchain);
1970 error('"{" or chain name expected after "@subchain"')
1971 unless $keyword eq '{';
1973 # create a deep copy of %rule, only containing values
1974 # which must be in the subchain
1975 my %inner = ( cow => { keywords => 1, },
1976 match => {},
1977 options => [],
1979 $inner{$_} = $rule{$_} foreach qw(domain domain_family table keywords);
1980 $inner{chain} = $inner{auto}{CHAIN} = $subchain;
1982 if (exists $rule{protocol}) {
1983 $inner{protocol} = $rule{protocol};
1984 append_option(%inner, 'protocol', $inner{protocol});
1987 # create a new stack frame
1988 my $old_stack_depth = @stack;
1989 my $stack = { auto => { %{$stack[0]{auto} || {}} } };
1990 $stack->{auto}{CHAIN} = $subchain;
1991 unshift @stack, $stack;
1993 # enter the block
1994 enter($lev + 1, \%inner);
1996 # pop stack frame
1997 shift @stack;
1998 die unless @stack == $old_stack_depth;
2000 # now handle the parent - it's a jump to the sub chain
2001 $rule{script} = {
2002 filename => $script->{filename},
2003 line => $script->{line},
2006 mkrules(\%rule);
2008 # and clean up variables set in this level
2009 new_level(%rule, $prev);
2010 delete $rule{has_rule};
2012 next;
2015 # everything else must be part of a "real" rule, not just
2016 # "policy only"
2017 $rule{has_rule} = 1;
2019 # extended parameters:
2020 if ($keyword =~ /^mod(?:ule)?$/) {
2021 foreach my $module (to_array getvalues) {
2022 next if exists $rule{match}{$module};
2024 my $domain_family = $rule{domain_family};
2025 my $defs = $match_defs{$domain_family}{$module};
2027 append_option(%rule, 'match', $module);
2028 $rule{match}{$module} = 1;
2030 merge_keywords(%rule, $defs->{keywords})
2031 if defined $defs;
2034 next;
2037 # keywords from $rule{keywords}
2039 if (exists $rule{keywords}{$keyword}) {
2040 my $def = $rule{keywords}{$keyword};
2041 parse_option($def, %rule, \$negated);
2042 next;
2046 # actions
2049 # jump action
2050 if ($keyword eq 'jump') {
2051 set_target(%rule, 'jump', getvar());
2052 next;
2055 # goto action
2056 if ($keyword eq 'realgoto') {
2057 set_target(%rule, 'goto', getvar());
2058 next;
2061 # action keywords
2062 if (is_netfilter_core_target($keyword)) {
2063 set_target(%rule, 'jump', $keyword);
2064 next;
2067 if ($keyword eq 'NOP') {
2068 error('There can only one action per rule')
2069 if exists $rule{has_action};
2070 $rule{has_action} = 1;
2071 next;
2074 if (my $defs = is_netfilter_module_target($rule{domain_family}, $keyword)) {
2075 set_module_target(%rule, $keyword, $defs);
2076 next;
2080 # protocol specific options
2083 if ($keyword eq 'proto' or $keyword eq 'protocol') {
2084 my $protocol = parse_keyword(%rule,
2085 { params => 1, negation => 1 },
2086 \$negated);
2087 $rule{protocol} = $protocol;
2088 append_option(%rule, 'protocol', $rule{protocol});
2090 unless (ref $protocol) {
2091 $protocol = netfilter_canonical_protocol($protocol);
2092 my $domain_family = $rule{domain_family};
2093 if (my $defs = $proto_defs{$domain_family}{$protocol}) {
2094 merge_keywords(%rule, $defs->{keywords});
2095 my $module = netfilter_protocol_module($protocol);
2096 $rule{match}{$module} = 1;
2099 next;
2102 # port switches
2103 if ($keyword =~ /^[sd]port$/) {
2104 my $proto = $rule{protocol};
2105 error('To use sport or dport, you have to specify "proto tcp" or "proto udp" first')
2106 unless defined $proto and grep { /^(?:tcp|udp|udplite|dccp|sctp)$/ } to_array $proto;
2108 append_option(%rule, $keyword,
2109 getvalues(undef, allow_negation => 1));
2110 next;
2113 # default
2114 error("Unrecognized keyword: $keyword");
2117 # if the rule didn't reset the negated flag, it's not
2118 # supported
2119 error("Doesn't support negation: $keyword")
2120 if $negated;
2123 error('Missing "}" at end of file')
2124 if $lev > $base_level;
2126 # consistency check: check if they havn't forgotten
2127 # the ';' before the last statement
2128 error("Missing semicolon before end of file")
2129 if $rule{non_empty};
2132 sub execute_command {
2133 my ($command, $script) = @_;
2135 print LINES "$command\n"
2136 if $option{lines};
2137 return if $option{noexec};
2139 my $ret = system($command);
2140 unless ($ret == 0) {
2141 if ($? == -1) {
2142 print STDERR "failed to execute: $!\n";
2143 exit 1;
2144 } elsif ($? & 0x7f) {
2145 printf STDERR "child died with signal %d\n", $? & 0x7f;
2146 return 1;
2147 } else {
2148 print STDERR "(rule declared in $script->{filename}:$script->{line})\n"
2149 if defined $script;
2150 return $? >> 8;
2154 return;
2157 sub execute_slow($) {
2158 my $domain_info = shift;
2160 my $domain_cmd = $domain_info->{tools}{tables};
2162 my $status;
2163 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2164 my $table_cmd = "$domain_cmd -t $table";
2166 # reset chain policies
2167 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2168 next unless $chain_info->{builtin} or
2169 (not $table_info->{has_builtin} and
2170 is_netfilter_builtin_chain($table, $chain));
2171 $status ||= execute_command("$table_cmd -P $chain ACCEPT")
2172 unless $option{noflush};
2175 # clear
2176 unless ($option{noflush}) {
2177 $status ||= execute_command("$table_cmd -F");
2178 $status ||= execute_command("$table_cmd -X");
2181 next if $option{flush};
2183 # create chains / set policy
2184 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2185 if (exists $chain_info->{policy}) {
2186 $status ||= execute_command("$table_cmd -P $chain $chain_info->{policy}")
2187 unless $chain_info->{policy} eq 'ACCEPT';
2188 } elsif (not is_netfilter_builtin_chain($table, $chain)) {
2189 $status ||= execute_command("$table_cmd -N $chain");
2193 # dump rules
2194 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2195 my $chain_cmd = "$table_cmd -A $chain";
2196 foreach my $rule (@{$chain_info->{rules}}) {
2197 $status ||= execute_command($chain_cmd . $rule->{rule});
2202 return $status;
2205 sub table_to_save($$) {
2206 my ($result_r, $table_info) = @_;
2208 foreach my $chain (sort keys %{$table_info->{chains}}) {
2209 my $chain_info = $table_info->{chains}{$chain};
2210 foreach my $rule (@{$chain_info->{rules}}) {
2211 $$result_r .= "-A $chain$rule->{rule}\n";
2216 sub rules_to_save($) {
2217 my ($domain_info) = @_;
2219 # convert this into an iptables-save text
2220 my $result = "# Generated by ferm $VERSION on " . localtime() . "\n";
2222 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2223 # select table
2224 $result .= '*' . $table . "\n";
2226 # create chains / set policy
2227 foreach my $chain (sort keys %{$table_info->{chains}}) {
2228 my $chain_info = $table_info->{chains}{$chain};
2229 my $policy = $option{flush} ? undef : $chain_info->{policy};
2230 unless (defined $policy) {
2231 if (is_netfilter_builtin_chain($table, $chain)) {
2232 $policy = 'ACCEPT';
2233 } else {
2234 next if $option{flush};
2235 $policy = '-';
2238 $result .= ":$chain $policy\ [0:0]\n";
2241 table_to_save(\$result, $table_info)
2242 unless $option{flush};
2244 # do it
2245 $result .= "COMMIT\n";
2248 return $result;
2251 sub restore_domain($$) {
2252 my ($domain_info, $save) = @_;
2254 my $path = $domain_info->{tools}{'tables-restore'};
2256 local *RESTORE;
2257 open RESTORE, "|$path"
2258 or die "Failed to run $path: $!\n";
2260 print RESTORE $save;
2262 close RESTORE
2263 or die "Failed to run $path\n";
2266 sub execute_fast($) {
2267 my $domain_info = shift;
2269 my $save = rules_to_save($domain_info);
2271 if ($option{lines}) {
2272 print LINES "$domain_info->{tools}{'tables-restore'} <<EOT\n"
2273 if $option{shell};
2274 print LINES $save;
2275 print LINES "EOT\n"
2276 if $option{shell};
2279 return if $option{noexec};
2281 eval {
2282 restore_domain($domain_info, $save);
2284 if ($@) {
2285 print STDERR $@;
2286 return 1;
2289 return;
2292 sub rollback() {
2293 my $error;
2294 while (my ($domain, $domain_info) = each %domains) {
2295 next unless $domain_info->{enabled};
2296 unless (defined $domain_info->{tools}{'tables-restore'}) {
2297 print STDERR "Cannot rollback domain '$domain' because there is no ${domain}tables-restore\n";
2298 next;
2301 my $reset = '';
2302 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2303 my $reset_chain = '';
2304 foreach my $chain (keys %{$table_info->{chains}}) {
2305 next unless is_netfilter_builtin_chain($table, $chain);
2306 $reset_chain .= ":${chain} ACCEPT [0:0]\n";
2308 $reset .= "*${table}\n${reset_chain}COMMIT\n"
2309 if length $reset_chain;
2312 $reset .= $domain_info->{previous}
2313 if defined $domain_info->{previous};
2315 restore_domain($domain_info, $reset);
2318 print STDERR "\nFirewall rules rolled back.\n" unless $error;
2319 exit 1;
2322 sub alrm_handler {
2323 # do nothing, just interrupt a system call
2326 sub confirm_rules() {
2327 $SIG{ALRM} = \&alrm_handler;
2329 alarm(5);
2331 print STDERR "\n"
2332 . "ferm has applied the new firewall rules.\n"
2333 . "Please type 'yes' to confirm:\n";
2334 STDERR->flush();
2336 alarm(30);
2338 my $line = '';
2339 STDIN->sysread($line, 3);
2341 eval {
2342 require POSIX;
2343 POSIX::tcflush(*STDIN, 2);
2345 print STDERR "$@" if $@;
2347 $SIG{ALRM} = 'DEFAULT';
2349 return $line eq 'yes';
2352 # end of ferm
2354 __END__
2356 =head1 NAME
2358 ferm - a firewall rule parser for linux
2360 =head1 SYNOPSIS
2362 B<ferm> I<options> I<inputfiles>
2364 =head1 OPTIONS
2366 -n, --noexec Do not execute the rules, just simulate
2367 -F, --flush Flush all netfilter tables managed by ferm
2368 -l, --lines Show all rules that were created
2369 -i, --interactive Interactive mode: revert if user does not confirm
2370 --remote Remote mode; ignore host specific configuration.
2371 This implies --noexec and --lines.
2372 -V, --version Show current version number
2373 -h, --help Look at this text
2374 --slow Slow mode, don't use iptables-restore
2375 --shell Generate a shell script which calls iptables-restore
2376 --domain {ip|ip6} Handle only the specified domain
2377 --def '$name=v' Override a variable
2379 =cut