implement confirmation/rollback for --shell --interactive
[ferm.git] / src / ferm
blob21440c0d3121295f31455b9dba76970c1eae87d3
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 # returns the next parameter, which may either be a scalar or an array
947 sub getvalues {
948 my $code = shift;
949 my %options = @_;
951 my $token = require_next_token($code);
953 if ($token eq '(') {
954 # read an array until ")"
955 my @wordlist;
957 for (;;) {
958 $token = getvalues($code,
959 parenthesis_allowed => 1,
960 comma_allowed => 1);
962 unless (ref $token) {
963 last if $token eq ')';
965 if ($token eq ',') {
966 error('Comma is not allowed within arrays, please use only a space');
967 next;
970 push @wordlist, $token;
971 } elsif (ref $token eq 'ARRAY') {
972 push @wordlist, @$token;
973 } else {
974 error('unknown toke type');
978 error('empty array not allowed here')
979 unless @wordlist or not $options{non_empty};
981 return @wordlist == 1
982 ? $wordlist[0]
983 : \@wordlist;
984 } elsif ($token =~ /^\`(.*)\`$/s) {
985 # execute a shell command, insert output
986 my $command = $1;
987 my $output = `$command`;
988 unless ($? == 0) {
989 if ($? == -1) {
990 error("failed to execute: $!");
991 } elsif ($? & 0x7f) {
992 error("child died with signal " . ($? & 0x7f));
993 } elsif ($? >> 8) {
994 error("child exited with status " . ($? >> 8));
998 # remove comments
999 $output =~ s/#.*//mg;
1001 # tokenize
1002 my @tokens = grep { length } split /\s+/s, $output;
1004 my @values;
1005 while (@tokens) {
1006 my $value = getvalues(sub { shift @tokens });
1007 push @values, to_array($value);
1010 # and recurse
1011 return @values == 1
1012 ? $values[0]
1013 : \@values;
1014 } elsif ($token =~ /^\'(.*)\'$/s) {
1015 # single quotes: a string
1016 return $1;
1017 } elsif ($token =~ /^\"(.*)\"$/s) {
1018 # double quotes: a string with escapes
1019 $token = $1;
1020 $token =~ s,\$(\w+),string_variable_value($1),eg;
1021 return $token;
1022 } elsif ($token eq '!') {
1023 error('negation is not allowed here')
1024 unless $options{allow_negation};
1026 $token = getvalues($code);
1028 return negate_value($token, undef, $options{allow_array_negation});
1029 } elsif ($token eq ',') {
1030 return $token
1031 if $options{comma_allowed};
1033 error('comma is not allowed here');
1034 } elsif ($token eq '=') {
1035 error('equals operator ("=") is not allowed here');
1036 } elsif ($token eq '$') {
1037 my $name = require_next_token($code);
1038 error('variable name expected - if you want to concatenate strings, try using double quotes')
1039 unless $name =~ /^\w+$/;
1041 my $value = variable_value($name);
1043 error("no such variable: \$$name")
1044 unless defined $value;
1046 return $value;
1047 } elsif ($token eq '&') {
1048 error("function calls are not allowed as keyword parameter");
1049 } elsif ($token eq ')' and not $options{parenthesis_allowed}) {
1050 error('Syntax error');
1051 } elsif ($token =~ /^@/) {
1052 if ($token eq '@resolve') {
1053 my @params = get_function_params();
1054 error('Usage: @resolve((hostname ...))')
1055 unless @params == 1;
1056 eval { require Net::DNS; };
1057 error('For the @resolve() function, you need the Perl library Net::DNS')
1058 if $@;
1059 my $type = 'A';
1060 my $resolver = new Net::DNS::Resolver;
1061 my @result;
1062 foreach my $hostname (to_array($params[0])) {
1063 my $query = $resolver->search($hostname, $type);
1064 error("DNS query for '$hostname' failed: " . $resolver->errorstring)
1065 unless $query;
1066 foreach my $rr ($query->answer) {
1067 next unless $rr->type eq $type;
1068 push @result, $rr->address;
1071 return \@result;
1072 } else {
1073 error("unknown ferm built-in function");
1075 } else {
1076 return $token;
1080 # returns the next parameter, but only allow a scalar
1081 sub getvar() {
1082 my $token = getvalues();
1084 error('array not allowed here')
1085 if ref $token and ref $token eq 'ARRAY';
1087 return $token;
1090 sub get_function_params(%) {
1091 expect_token('(', 'function name must be followed by "()"');
1093 my $token = peek_token();
1094 if ($token eq ')') {
1095 require_next_token();
1096 return;
1099 my @params;
1101 while (1) {
1102 if (@params > 0) {
1103 $token = require_next_token();
1104 last
1105 if $token eq ')';
1107 error('"," expected')
1108 unless $token eq ',';
1111 push @params, getvalues(undef, @_);
1114 return @params;
1117 # collect all tokens in a flat array reference until the end of the
1118 # command is reached
1119 sub collect_tokens() {
1120 my @level;
1121 my @tokens;
1123 while (1) {
1124 my $keyword = next_token();
1125 error('unexpected end of file within function/variable declaration')
1126 unless defined $keyword;
1128 if ($keyword =~ /^[\{\(]$/) {
1129 push @level, $keyword;
1130 } elsif ($keyword =~ /^[\}\)]$/) {
1131 my $expected = $keyword;
1132 $expected =~ tr/\}\)/\{\(/;
1133 my $opener = pop @level;
1134 error("unmatched '$keyword'")
1135 unless defined $opener and $opener eq $expected;
1136 } elsif ($keyword eq ';' and @level == 0) {
1137 last;
1140 push @tokens, $keyword;
1142 last
1143 if $keyword eq '}' and @level == 0;
1146 return \@tokens;
1150 # returns the specified value as an array. dereference arrayrefs
1151 sub to_array($) {
1152 my $value = shift;
1153 die unless wantarray;
1154 die if @_;
1155 unless (ref $value) {
1156 return $value;
1157 } elsif (ref $value eq 'ARRAY') {
1158 return @$value;
1159 } else {
1160 die;
1164 # evaluate the specified value as bool
1165 sub eval_bool($) {
1166 my $value = shift;
1167 die if wantarray;
1168 die if @_;
1169 unless (ref $value) {
1170 return $value;
1171 } elsif (ref $value eq 'ARRAY') {
1172 return @$value > 0;
1173 } else {
1174 die;
1178 sub is_netfilter_core_target($) {
1179 my $target = shift;
1180 die unless defined $target and length $target;
1181 return grep { $_ eq $target } qw(ACCEPT DROP RETURN QUEUE);
1184 sub is_netfilter_module_target($$) {
1185 my ($domain_family, $target) = @_;
1186 die unless defined $target and length $target;
1188 return defined $domain_family &&
1189 exists $target_defs{$domain_family} &&
1190 $target_defs{$domain_family}{$target};
1193 sub is_netfilter_builtin_chain($$) {
1194 my ($table, $chain) = @_;
1196 return grep { $_ eq $chain }
1197 qw(PREROUTING INPUT FORWARD OUTPUT POSTROUTING);
1200 sub netfilter_canonical_protocol($) {
1201 my $proto = shift;
1202 return 'icmpv6'
1203 if $proto eq 'ipv6-icmp';
1204 return 'mh'
1205 if $proto eq 'ipv6-mh';
1206 return $proto;
1209 sub netfilter_protocol_module($) {
1210 my $proto = shift;
1211 return unless defined $proto;
1212 return 'icmp6'
1213 if $proto eq 'icmpv6';
1214 return $proto;
1217 # escape the string in a way safe for the shell
1218 sub shell_escape($) {
1219 my $token = shift;
1221 return $token if $token =~ /^[-_a-zA-Z0-9]+$/s;
1223 if ($option{fast}) {
1224 # iptables-save/iptables-restore are quite buggy concerning
1225 # escaping and special characters... we're trying our best
1226 # here
1228 $token =~ s,",\\",g;
1229 $token = '"' . $token . '"'
1230 if $token =~ /[\s\'\\;&]/s or length($token) == 0;
1231 } else {
1232 return $token
1233 if $token =~ /^\`.*\`$/;
1234 $token =~ s/'/'\\''/g;
1235 $token = '\'' . $token . '\''
1236 if $token =~ /[\s\"\\;<>&|]/s or length($token) == 0;
1239 return $token;
1242 # append an option to the shell command line, using information from
1243 # the module definition (see %match_defs etc.)
1244 sub shell_format_option($$) {
1245 my ($keyword, $value) = @_;
1247 my $cmd = '';
1248 if (ref $value) {
1249 if ((ref $value eq 'negated') || (ref $value eq 'pre_negated')) {
1250 $value = $value->[0];
1251 $cmd = ' !';
1255 unless (defined $value) {
1256 $cmd .= " --$keyword";
1257 } elsif (ref $value) {
1258 if (ref $value eq 'params') {
1259 $cmd .= " --$keyword ";
1260 $cmd .= join(' ', map { shell_escape($_) } @$value);
1261 } elsif (ref $value eq 'multi') {
1262 foreach (@$value) {
1263 $cmd .= " --$keyword " . shell_escape($_);
1265 } else {
1266 die;
1268 } else {
1269 $cmd .= " --$keyword " . shell_escape($value);
1272 return $cmd;
1275 sub format_option($$$) {
1276 my ($domain, $name, $value) = @_;
1277 $value = 'icmpv6' if $domain eq 'ip6' and $name eq 'protocol'
1278 and $value eq 'icmp';
1279 return shell_format_option($name, $value);
1282 sub append_rule($$) {
1283 my ($chain_rules, $rule) = @_;
1285 my $cmd = join('', map { $_->[2] } @{$rule->{options}});
1286 push @$chain_rules, { rule => $cmd,
1287 script => $rule->{script},
1291 sub format_option($$$) {
1292 my ($domain, $name, $value) = @_;
1293 $value = 'icmpv6' if $domain eq 'ip6' and $name eq 'protocol'
1294 and $value eq 'icmp';
1295 return shell_format_option($name, $value);
1298 sub unfold_rule {
1299 my ($domain, $chain_rules, $rule) = (shift, shift, shift);
1300 return append_rule($chain_rules, $rule) unless @_;
1302 my $option = shift;
1303 my @values = @{$option->[1]};
1305 foreach my $value (@values) {
1306 $option->[2] = format_option($domain, $option->[0], $value);
1307 unfold_rule($domain, $chain_rules, $rule, @_);
1311 sub mkrules2($$$) {
1312 my ($domain, $chain_rules, $rule) = @_;
1314 my @unfold;
1315 foreach my $option (@{$rule->{options}}) {
1316 if (ref $option->[1] and ref $option->[1] eq 'ARRAY') {
1317 push @unfold, $option
1318 } else {
1319 $option->[2] = format_option($domain, $option->[0], $option->[1]);
1323 unfold_rule($domain, $chain_rules, $rule, @unfold);
1326 # convert a bunch of internal rule structures in iptables calls,
1327 # unfold arrays during that
1328 sub mkrules($) {
1329 my $rule = shift;
1331 foreach my $domain (to_array $rule->{domain}) {
1332 my $domain_info = $domains{$domain};
1333 $domain_info->{enabled} = 1;
1335 foreach my $table (to_array $rule->{table}) {
1336 my $table_info = $domain_info->{tables}{$table} ||= {};
1338 foreach my $chain (to_array $rule->{chain}) {
1339 my $chain_rules = $table_info->{chains}{$chain}{rules} ||= [];
1340 mkrules2($domain, $chain_rules, $rule)
1341 if $rule->{has_rule} and not $option{flush};
1347 # parse a keyword from a module definition
1348 sub parse_keyword(\%$$) {
1349 my ($rule, $def, $negated_ref) = @_;
1351 my $params = $def->{params};
1353 my $value;
1355 my $negated;
1356 if ($$negated_ref && exists $def->{pre_negation}) {
1357 $negated = 1;
1358 undef $$negated_ref;
1361 unless (defined $params) {
1362 undef $value;
1363 } elsif (ref $params && ref $params eq 'CODE') {
1364 $value = &$params($rule);
1365 } elsif ($params eq 'm') {
1366 $value = bless [ to_array getvalues() ], 'multi';
1367 } elsif ($params =~ /^[a-z]/) {
1368 if (exists $def->{negation} and not $negated) {
1369 my $token = peek_token();
1370 if ($token eq '!') {
1371 require_next_token();
1372 $negated = 1;
1376 my @params;
1377 foreach my $p (split(//, $params)) {
1378 if ($p eq 's') {
1379 push @params, getvar();
1380 } elsif ($p eq 'c') {
1381 my @v = to_array getvalues(undef, non_empty => 1);
1382 push @params, join(',', @v);
1383 } else {
1384 die;
1388 $value = @params == 1
1389 ? $params[0]
1390 : bless \@params, 'params';
1391 } elsif ($params == 1) {
1392 if (exists $def->{negation} and not $negated) {
1393 my $token = peek_token();
1394 if ($token eq '!') {
1395 require_next_token();
1396 $negated = 1;
1400 $value = getvalues();
1402 warning("log-prefix is too long; truncating to 29 characters: '$1'")
1403 if $def->{name} eq 'log-prefix' && $value =~ s,^(.{29}).+$,$1,;
1404 } else {
1405 if (exists $def->{negation} and not $negated) {
1406 my $token = peek_token();
1407 if ($token eq '!') {
1408 require_next_token();
1409 $negated = 1;
1413 $value = bless [ map {
1414 getvar()
1415 } (1..$params) ], 'params';
1418 $value = negate_value($value, exists $def->{pre_negation} && 'pre_negated')
1419 if $negated;
1421 return $value;
1424 sub append_option(\%$$) {
1425 my ($rule, $name, $value) = @_;
1426 push @{$rule->{options}}, [ $name, $value ];
1429 # parse options of a module
1430 sub parse_option($\%$) {
1431 my ($def, $rule, $negated_ref) = @_;
1433 append_option(%$rule, $def->{name},
1434 parse_keyword(%$rule, $def, $negated_ref));
1437 sub copy_on_write($$) {
1438 my ($rule, $key) = @_;
1439 return unless exists $rule->{cow}{$key};
1440 $rule->{$key} = {%{$rule->{$key}}};
1441 delete $rule->{cow}{$key};
1444 sub new_level(\%$) {
1445 my ($rule, $prev) = @_;
1447 %$rule = ();
1448 if (defined $prev) {
1449 # copy data from previous level
1450 $rule->{cow} = { keywords => 1, };
1451 $rule->{keywords} = $prev->{keywords};
1452 $rule->{match} = { %{$prev->{match}} };
1453 $rule->{options} = [@{$prev->{options}}];
1454 foreach my $key (qw(domain domain_family table chain protocol has_rule has_action)) {
1455 $rule->{$key} = $prev->{$key}
1456 if exists $prev->{$key};
1458 } else {
1459 $rule->{cow} = {};
1460 $rule->{keywords} = {};
1461 $rule->{match} = {};
1462 $rule->{options} = [];
1466 sub merge_keywords(\%$) {
1467 my ($rule, $keywords) = @_;
1468 copy_on_write($rule, 'keywords');
1469 while (my ($name, $def) = each %$keywords) {
1470 $rule->{keywords}{$name} = $def;
1474 sub set_domain(\%$) {
1475 my ($rule, $domain) = @_;
1477 my $filtered_domain = filter_domains($domain);
1478 my $domain_family;
1479 unless (ref $domain) {
1480 $domain_family = $domain eq 'ip6' ? 'ip' : $domain;
1481 } elsif (@$domain == 0) {
1482 $domain_family = 'none';
1483 } elsif (grep { not /^ip6?$/s } @$domain) {
1484 error('Cannot combine non-IP domains');
1485 } else {
1486 $domain_family = 'ip';
1489 $rule->{domain_family} = $domain_family;
1490 $rule->{keywords} = $match_defs{$domain_family}{''}{keywords};
1491 $rule->{cow}{keywords} = 1;
1493 $rule->{domain} = $stack[0]{auto}{DOMAIN} = $filtered_domain;
1496 sub set_target(\%$$) {
1497 my ($rule, $name, $value) = @_;
1498 error('There can only one action per rule')
1499 if exists $rule->{has_action};
1500 $rule->{has_action} = 1;
1501 append_option(%$rule, $name, $value);
1504 sub set_module_target(\%$$) {
1505 my ($rule, $name, $defs) = @_;
1507 if ($name eq 'TCPMSS') {
1508 my $protos = $rule->{protocol};
1509 error('No protocol specified before TCPMSS')
1510 unless defined $protos;
1511 foreach my $proto (to_array $protos) {
1512 error('TCPMSS not available for protocol "$proto"')
1513 unless $proto eq 'tcp';
1517 # in ebtables, there is both "--mark" and "-j mark"... workaround:
1518 $name = 'mark' if $name eq 'MARK' and $rule->{domain_family} eq 'eb';
1520 set_target(%$rule, 'jump', $name);
1521 merge_keywords(%$rule, $defs->{keywords});
1524 # the main parser loop: read tokens, convert them into internal rule
1525 # structures
1526 sub enter($$) {
1527 my $lev = shift; # current recursion depth
1528 my $prev = shift; # previous rule hash
1530 # enter is the core of the firewall setup, it is a
1531 # simple parser program that recognizes keywords and
1532 # retreives parameters to set up the kernel routing
1533 # chains
1535 my $base_level = $script->{base_level} || 0;
1536 die if $base_level > $lev;
1538 my %rule;
1539 new_level(%rule, $prev);
1541 # read keywords 1 by 1 and dump into parser
1542 while (defined (my $keyword = next_token())) {
1543 # check if the current rule should be negated
1544 my $negated = $keyword eq '!';
1545 if ($negated) {
1546 # negation. get the next word which contains the 'real'
1547 # rule
1548 $keyword = getvar();
1550 error('unexpected end of file after negation')
1551 unless defined $keyword;
1554 # the core: parse all data
1555 for ($keyword)
1557 # deprecated keyword?
1558 if (exists $deprecated_keywords{$keyword}) {
1559 my $new_keyword = $deprecated_keywords{$keyword};
1560 warning("'$keyword' is deprecated, please use '$new_keyword' instead");
1561 $keyword = $new_keyword;
1564 # effectuation operator
1565 if ($keyword eq ';') {
1566 error('Empty rule before ";" not allowed')
1567 unless $rule{non_empty};
1569 if ($rule{has_rule} and not exists $rule{has_action}) {
1570 # something is wrong when a rule was specified,
1571 # but no action
1572 error('No action defined; did you mean "NOP"?');
1575 error('No chain defined') unless exists $rule{chain};
1577 $rule{script} = { filename => $script->{filename},
1578 line => $script->{line},
1581 mkrules(\%rule);
1583 # and clean up variables set in this level
1584 new_level(%rule, $prev);
1586 next;
1589 # conditional expression
1590 if ($keyword eq '@if') {
1591 unless (eval_bool(getvalues)) {
1592 collect_tokens;
1593 my $token = peek_token();
1594 require_next_token() if $token and $token eq '@else';
1597 next;
1600 if ($keyword eq '@else') {
1601 # hack: if this "else" has not been eaten by the "if"
1602 # handler above, we believe it came from an if clause
1603 # which evaluated "true" - remove the "else" part now.
1604 collect_tokens;
1605 next;
1608 # hooks for custom shell commands
1609 if ($keyword eq 'hook') {
1610 warning("'hook' is deprecated, use '\@hook'");
1611 $keyword = '@hook';
1614 if ($keyword eq '@hook') {
1615 error('"hook" must be the first token in a command')
1616 if exists $rule{domain};
1618 my $position = getvar();
1619 my $hooks;
1620 if ($position eq 'pre') {
1621 $hooks = \@pre_hooks;
1622 } elsif ($position eq 'post') {
1623 $hooks = \@post_hooks;
1624 } elsif ($position eq 'flush') {
1625 $hooks = \@flush_hooks;
1626 } else {
1627 error("Invalid hook position: '$position'");
1630 push @$hooks, getvar();
1632 expect_token(';');
1633 next;
1636 # recursing operators
1637 if ($keyword eq '{') {
1638 # push stack
1639 my $old_stack_depth = @stack;
1641 unshift @stack, { auto => { %{$stack[0]{auto} || {}} } };
1643 # recurse
1644 enter($lev + 1, \%rule);
1646 # pop stack
1647 shift @stack;
1648 die unless @stack == $old_stack_depth;
1650 # after a block, the command is finished, clear this
1651 # level
1652 new_level(%rule, $prev);
1654 next;
1657 if ($keyword eq '}') {
1658 error('Unmatched "}"')
1659 if $lev <= $base_level;
1661 # consistency check: check if they havn't forgotten
1662 # the ';' after the last statement
1663 error('Missing semicolon before "}"')
1664 if $rule{non_empty};
1666 # and exit
1667 return;
1670 # include another file
1671 if ($keyword eq '@include' or $keyword eq 'include') {
1672 my @files = collect_filenames to_array getvalues;
1673 $keyword = next_token;
1674 error('Missing ";" - "include FILENAME" must be the last command in a rule')
1675 unless defined $keyword and $keyword eq ';';
1677 foreach my $filename (@files) {
1678 # save old script, open new script
1679 my $old_script = $script;
1680 open_script($filename);
1681 $script->{base_level} = $lev + 1;
1683 # push stack
1684 my $old_stack_depth = @stack;
1686 my $stack = {};
1688 if (@stack > 0) {
1689 # include files may set variables for their parent
1690 $stack->{vars} = ($stack[0]{vars} ||= {});
1691 $stack->{functions} = ($stack[0]{functions} ||= {});
1692 $stack->{auto} = { %{ $stack[0]{auto} || {} } };
1695 $stack->{auto}{FILENAME} = $filename;
1696 $stack->{auto}{DIRNAME} = $filename =~ m,^(.*)/,s ? $1 : '.';
1698 unshift @stack, $stack;
1700 # parse the script
1701 enter($lev + 1, \%rule);
1703 # pop stack
1704 shift @stack;
1705 die unless @stack == $old_stack_depth;
1707 # restore old script
1708 $script = $old_script;
1711 next;
1714 # definition of a variable or function
1715 if ($keyword eq '@def' or $keyword eq 'def') {
1716 error('"def" must be the first token in a command')
1717 if $rule{non_empty};
1719 my $type = require_next_token();
1720 if ($type eq '$') {
1721 my $name = require_next_token();
1722 error('invalid variable name')
1723 unless $name =~ /^\w+$/;
1725 expect_token('=');
1727 my $value = getvalues(undef, allow_negation => 1);
1729 expect_token(';');
1731 $stack[0]{vars}{$name} = $value
1732 unless exists $stack[-1]{vars}{$name};
1733 } elsif ($type eq '&') {
1734 my $name = require_next_token();
1735 error('invalid function name')
1736 unless $name =~ /^\w+$/;
1738 expect_token('(', 'function parameter list or "()" expected');
1740 my @params;
1741 while (1) {
1742 my $token = require_next_token();
1743 last if $token eq ')';
1745 if (@params > 0) {
1746 error('"," expected')
1747 unless $token eq ',';
1749 $token = require_next_token();
1752 error('"$" and parameter name expected')
1753 unless $token eq '$';
1755 $token = require_next_token();
1756 error('invalid function parameter name')
1757 unless $token =~ /^\w+$/;
1759 push @params, $token;
1762 my %function;
1764 $function{params} = \@params;
1766 expect_token('=');
1768 my $tokens = collect_tokens();
1769 $function{block} = 1 if grep { $_ eq '{' } @$tokens;
1770 $function{tokens} = $tokens;
1772 $stack[0]{functions}{$name} = \%function
1773 unless exists $stack[-1]{functions}{$name};
1774 } else {
1775 error('"$" (variable) or "&" (function) expected');
1778 next;
1781 # this rule has something which isn't inherited by its
1782 # parent closure. This variable is used in a lot of
1783 # syntax checks.
1785 $rule{non_empty} = 1;
1787 # def references
1788 if ($keyword eq '$') {
1789 error('variable references are only allowed as keyword parameter');
1792 if ($keyword eq '&') {
1793 my $name = require_next_token();
1794 error('function name expected')
1795 unless $name =~ /^\w+$/;
1797 my $function;
1798 foreach (@stack) {
1799 $function = $_->{functions}{$name};
1800 last if defined $function;
1802 error("no such function: \&$name")
1803 unless defined $function;
1805 my $paramdef = $function->{params};
1806 die unless defined $paramdef;
1808 my @params = get_function_params(allow_negation => 1);
1810 error("Wrong number of parameters for function '\&$name': "
1811 . @$paramdef . " expected, " . @params . " given")
1812 unless @params == @$paramdef;
1814 my %vars;
1815 for (my $i = 0; $i < @params; $i++) {
1816 $vars{$paramdef->[$i]} = $params[$i];
1819 if ($function->{block}) {
1820 # block {} always ends the current rule, so if the
1821 # function contains a block, we have to require
1822 # the calling rule also ends here
1823 expect_token(';');
1826 my @tokens = @{$function->{tokens}};
1827 for (my $i = 0; $i < @tokens; $i++) {
1828 if ($tokens[$i] eq '$' and $i + 1 < @tokens and
1829 exists $vars{$tokens[$i + 1]}) {
1830 my @value = to_array($vars{$tokens[$i + 1]});
1831 @value = ('(', @value, ')')
1832 unless @tokens == 1;
1833 splice(@tokens, $i, 2, @value);
1834 $i += @value - 2;
1835 } elsif ($tokens[$i] =~ m,^"(.*)"$,) {
1836 $tokens[$i] =~ s,\$(\w+),exists $vars{$1} ? $vars{$1} : "\$$1",eg;
1840 unshift @{$script->{tokens}}, @tokens;
1842 next;
1845 # where to put the rule?
1846 if ($keyword eq 'domain') {
1847 error('Domain is already specified')
1848 if exists $rule{domain};
1850 set_domain(%rule, getvalues());
1851 next;
1854 if ($keyword eq 'table') {
1855 warning('Table is already specified')
1856 if exists $rule{table};
1857 $rule{table} = $stack[0]{auto}{TABLE} = getvalues();
1859 set_domain(%rule, 'ip')
1860 unless exists $rule{domain};
1862 next;
1865 if ($keyword eq 'chain') {
1866 warning('Chain is already specified')
1867 if exists $rule{chain};
1869 my $chain = $rule{chain} = $stack[0]{auto}{CHAIN} = getvalues();
1871 # ferm 1.1 allowed lower case built-in chain names
1872 foreach (ref $rule{chain} ? @{$rule{chain}} : $rule{chain}) {
1873 error('Please write built-in chain names in upper case')
1874 if /^(?:input|forward|output|prerouting|postrouting)$/;
1877 set_domain(%rule, 'ip')
1878 unless exists $rule{domain};
1880 $rule{table} = 'filter'
1881 unless exists $rule{table};
1883 foreach my $domain (to_array $rule{domain}) {
1884 foreach my $table (to_array $rule{table}) {
1885 foreach my $c (to_array $chain) {
1886 $domains{$domain}{tables}{$table}{chains}{$c} ||= {};
1891 next;
1894 error('Chain must be specified')
1895 unless exists $rule{chain};
1897 # policy for built-in chain
1898 if ($keyword eq 'policy') {
1899 error('Cannot specify matches for policy')
1900 if $rule{has_rule};
1902 my $policy = getvar();
1903 error("Invalid policy target: $policy")
1904 unless $policy =~ /^(?:ACCEPT|DROP)$/;
1906 expect_token(';');
1908 foreach my $domain (to_array $rule{domain}) {
1909 my $domain_info = $domains{$domain};
1910 $domain_info->{enabled} = 1;
1912 foreach my $table (to_array $rule{table}) {
1913 foreach my $chain (to_array $rule{chain}) {
1914 $domain_info->{tables}{$table}{chains}{$chain}{policy} = $policy;
1919 new_level(%rule, $prev);
1920 next;
1923 # create a subchain
1924 if ($keyword eq '@subchain' or $keyword eq 'subchain') {
1925 error('Chain must be specified')
1926 unless exists $rule{chain};
1928 error('No rule specified before "@subchain"')
1929 unless $rule{has_rule};
1931 my $subchain;
1932 $keyword = next_token();
1934 if ($keyword =~ /^(["'])(.*)\1$/s) {
1935 $subchain = $2;
1936 $keyword = next_token();
1937 } else {
1938 $subchain = 'ferm_auto_' . ++$auto_chain;
1941 foreach my $domain (to_array $rule{domain}) {
1942 foreach my $table (to_array $rule{table}) {
1943 $domains{$domain}{tables}{$table}{chains}{$subchain} ||= {};
1947 set_target(%rule, 'jump', $subchain);
1949 error('"{" or chain name expected after "@subchain"')
1950 unless $keyword eq '{';
1952 # create a deep copy of %rule, only containing values
1953 # which must be in the subchain
1954 my %inner = ( cow => { keywords => 1, },
1955 match => {},
1956 options => [],
1958 $inner{$_} = $rule{$_} foreach qw(domain domain_family table keywords);
1959 $inner{chain} = $inner{auto}{CHAIN} = $subchain;
1961 if (exists $rule{protocol}) {
1962 $inner{protocol} = $rule{protocol};
1963 append_option(%inner, 'protocol', $inner{protocol});
1966 # create a new stack frame
1967 my $old_stack_depth = @stack;
1968 my $stack = { auto => { %{$stack[0]{auto} || {}} } };
1969 $stack->{auto}{CHAIN} = $subchain;
1970 unshift @stack, $stack;
1972 # enter the block
1973 enter($lev + 1, \%inner);
1975 # pop stack frame
1976 shift @stack;
1977 die unless @stack == $old_stack_depth;
1979 # now handle the parent - it's a jump to the sub chain
1980 $rule{script} = {
1981 filename => $script->{filename},
1982 line => $script->{line},
1985 mkrules(\%rule);
1987 # and clean up variables set in this level
1988 new_level(%rule, $prev);
1989 delete $rule{has_rule};
1991 next;
1994 # everything else must be part of a "real" rule, not just
1995 # "policy only"
1996 $rule{has_rule} = 1;
1998 # extended parameters:
1999 if ($keyword =~ /^mod(?:ule)?$/) {
2000 foreach my $module (to_array getvalues) {
2001 next if exists $rule{match}{$module};
2003 my $domain_family = $rule{domain_family};
2004 my $defs = $match_defs{$domain_family}{$module};
2006 append_option(%rule, 'match', $module);
2007 $rule{match}{$module} = 1;
2009 merge_keywords(%rule, $defs->{keywords})
2010 if defined $defs;
2013 next;
2016 # keywords from $rule{keywords}
2018 if (exists $rule{keywords}{$keyword}) {
2019 my $def = $rule{keywords}{$keyword};
2020 parse_option($def, %rule, \$negated);
2021 next;
2025 # actions
2028 # jump action
2029 if ($keyword eq 'jump') {
2030 set_target(%rule, 'jump', getvar());
2031 next;
2034 # goto action
2035 if ($keyword eq 'realgoto') {
2036 set_target(%rule, 'goto', getvar());
2037 next;
2040 # action keywords
2041 if (is_netfilter_core_target($keyword)) {
2042 set_target(%rule, 'jump', $keyword);
2043 next;
2046 if ($keyword eq 'NOP') {
2047 error('There can only one action per rule')
2048 if exists $rule{has_action};
2049 $rule{has_action} = 1;
2050 next;
2053 if (my $defs = is_netfilter_module_target($rule{domain_family}, $keyword)) {
2054 set_module_target(%rule, $keyword, $defs);
2055 next;
2059 # protocol specific options
2062 if ($keyword eq 'proto' or $keyword eq 'protocol') {
2063 my $protocol = parse_keyword(%rule,
2064 { params => 1, negation => 1 },
2065 \$negated);
2066 $rule{protocol} = $protocol;
2067 append_option(%rule, 'protocol', $rule{protocol});
2069 unless (ref $protocol) {
2070 $protocol = netfilter_canonical_protocol($protocol);
2071 my $domain_family = $rule{domain_family};
2072 if (my $defs = $proto_defs{$domain_family}{$protocol}) {
2073 merge_keywords(%rule, $defs->{keywords});
2074 my $module = netfilter_protocol_module($protocol);
2075 $rule{match}{$module} = 1;
2078 next;
2081 # port switches
2082 if ($keyword =~ /^[sd]port$/) {
2083 my $proto = $rule{protocol};
2084 error('To use sport or dport, you have to specify "proto tcp" or "proto udp" first')
2085 unless defined $proto and grep { /^(?:tcp|udp|udplite|dccp|sctp)$/ } to_array $proto;
2087 append_option(%rule, $keyword,
2088 getvalues(undef, allow_negation => 1));
2089 next;
2092 # default
2093 error("Unrecognized keyword: $keyword");
2096 # if the rule didn't reset the negated flag, it's not
2097 # supported
2098 error("Doesn't support negation: $keyword")
2099 if $negated;
2102 error('Missing "}" at end of file')
2103 if $lev > $base_level;
2105 # consistency check: check if they havn't forgotten
2106 # the ';' before the last statement
2107 error("Missing semicolon before end of file")
2108 if $rule{non_empty};
2111 sub execute_command {
2112 my ($command, $script) = @_;
2114 print LINES "$command\n"
2115 if $option{lines};
2116 return if $option{noexec};
2118 my $ret = system($command);
2119 unless ($ret == 0) {
2120 if ($? == -1) {
2121 print STDERR "failed to execute: $!\n";
2122 exit 1;
2123 } elsif ($? & 0x7f) {
2124 printf STDERR "child died with signal %d\n", $? & 0x7f;
2125 return 1;
2126 } else {
2127 print STDERR "(rule declared in $script->{filename}:$script->{line})\n"
2128 if defined $script;
2129 return $? >> 8;
2133 return;
2136 sub execute_slow($) {
2137 my $domain_info = shift;
2139 my $domain_cmd = $domain_info->{tools}{tables};
2141 my $status;
2142 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2143 my $table_cmd = "$domain_cmd -t $table";
2145 # reset chain policies
2146 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2147 next unless $chain_info->{builtin} or
2148 (not $table_info->{has_builtin} and
2149 is_netfilter_builtin_chain($table, $chain));
2150 $status ||= execute_command("$table_cmd -P $chain ACCEPT")
2151 unless $option{noflush};
2154 # clear
2155 unless ($option{noflush}) {
2156 $status ||= execute_command("$table_cmd -F");
2157 $status ||= execute_command("$table_cmd -X");
2160 next if $option{flush};
2162 # create chains / set policy
2163 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2164 if (exists $chain_info->{policy}) {
2165 $status ||= execute_command("$table_cmd -P $chain $chain_info->{policy}")
2166 unless $chain_info->{policy} eq 'ACCEPT';
2167 } elsif (not is_netfilter_builtin_chain($table, $chain)) {
2168 $status ||= execute_command("$table_cmd -N $chain");
2172 # dump rules
2173 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2174 my $chain_cmd = "$table_cmd -A $chain";
2175 foreach my $rule (@{$chain_info->{rules}}) {
2176 $status ||= execute_command($chain_cmd . $rule->{rule});
2181 return $status;
2184 sub table_to_save($$) {
2185 my ($result_r, $table_info) = @_;
2187 foreach my $chain (sort keys %{$table_info->{chains}}) {
2188 my $chain_info = $table_info->{chains}{$chain};
2189 foreach my $rule (@{$chain_info->{rules}}) {
2190 $$result_r .= "-A $chain$rule->{rule}\n";
2195 sub rules_to_save($) {
2196 my ($domain_info) = @_;
2198 # convert this into an iptables-save text
2199 my $result = "# Generated by ferm $VERSION on " . localtime() . "\n";
2201 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2202 # select table
2203 $result .= '*' . $table . "\n";
2205 # create chains / set policy
2206 foreach my $chain (sort keys %{$table_info->{chains}}) {
2207 my $chain_info = $table_info->{chains}{$chain};
2208 my $policy = $option{flush} ? undef : $chain_info->{policy};
2209 unless (defined $policy) {
2210 if (is_netfilter_builtin_chain($table, $chain)) {
2211 $policy = 'ACCEPT';
2212 } else {
2213 next if $option{flush};
2214 $policy = '-';
2217 $result .= ":$chain $policy\ [0:0]\n";
2220 table_to_save(\$result, $table_info)
2221 unless $option{flush};
2223 # do it
2224 $result .= "COMMIT\n";
2227 return $result;
2230 sub restore_domain($$) {
2231 my ($domain_info, $save) = @_;
2233 my $path = $domain_info->{tools}{'tables-restore'};
2235 local *RESTORE;
2236 open RESTORE, "|$path"
2237 or die "Failed to run $path: $!\n";
2239 print RESTORE $save;
2241 close RESTORE
2242 or die "Failed to run $path\n";
2245 sub execute_fast($) {
2246 my $domain_info = shift;
2248 my $save = rules_to_save($domain_info);
2250 if ($option{lines}) {
2251 print LINES "$domain_info->{tools}{'tables-restore'} <<EOT\n"
2252 if $option{shell};
2253 print LINES $save;
2254 print LINES "EOT\n"
2255 if $option{shell};
2258 return if $option{noexec};
2260 eval {
2261 restore_domain($domain_info, $save);
2263 if ($@) {
2264 print STDERR $@;
2265 return 1;
2268 return;
2271 sub rollback() {
2272 my $error;
2273 while (my ($domain, $domain_info) = each %domains) {
2274 next unless $domain_info->{enabled};
2275 unless (defined $domain_info->{tools}{'tables-restore'}) {
2276 print STDERR "Cannot rollback domain '$domain' because there is no ${domain}tables-restore\n";
2277 next;
2280 my $reset = '';
2281 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2282 my $reset_chain = '';
2283 foreach my $chain (keys %{$table_info->{chains}}) {
2284 next unless is_netfilter_builtin_chain($table, $chain);
2285 $reset_chain .= ":${chain} ACCEPT [0:0]\n";
2287 $reset .= "*${table}\n${reset_chain}COMMIT\n"
2288 if length $reset_chain;
2291 $reset .= $domain_info->{previous}
2292 if defined $domain_info->{previous};
2294 restore_domain($domain_info, $reset);
2297 print STDERR "\nFirewall rules rolled back.\n" unless $error;
2298 exit 1;
2301 sub alrm_handler {
2302 # do nothing, just interrupt a system call
2305 sub confirm_rules() {
2306 $SIG{ALRM} = \&alrm_handler;
2308 alarm(5);
2310 print STDERR "\n"
2311 . "ferm has applied the new firewall rules.\n"
2312 . "Please type 'yes' to confirm:\n";
2313 STDERR->flush();
2315 alarm(30);
2317 my $line = '';
2318 STDIN->sysread($line, 3);
2320 eval {
2321 require POSIX;
2322 POSIX::tcflush(*STDIN, 2);
2324 print STDERR "$@" if $@;
2326 $SIG{ALRM} = 'DEFAULT';
2328 return $line eq 'yes';
2331 # end of ferm
2333 __END__
2335 =head1 NAME
2337 ferm - a firewall rule parser for linux
2339 =head1 SYNOPSIS
2341 B<ferm> I<options> I<inputfiles>
2343 =head1 OPTIONS
2345 -n, --noexec Do not execute the rules, just simulate
2346 -F, --flush Flush all netfilter tables managed by ferm
2347 -l, --lines Show all rules that were created
2348 -i, --interactive Interactive mode: revert if user does not confirm
2349 --remote Remote mode; ignore host specific configuration.
2350 This implies --noexec and --lines.
2351 -V, --version Show current version number
2352 -h, --help Look at this text
2353 --slow Slow mode, don't use iptables-restore
2354 --shell Generate a shell script which calls iptables-restore
2355 --domain {ip|ip6} Handle only the specified domain
2356 --def '$name=v' Override a variable
2358 =cut