support the TPROXY target
[ferm.git] / src / ferm
blobc0ac8c3e1ad647eb446ad6f785e8921401e7c4fc
1 #!/usr/bin/perl
4 # ferm, a firewall setup program that makes firewall rules easy!
6 # Copyright (C) 2001-2011 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 use File::Spec;
32 BEGIN {
33 eval { require strict; import strict; };
34 $has_strict = not $@;
35 if ($@) {
36 # we need no vars.pm if there is not even strict.pm
37 $INC{'vars.pm'} = 1;
38 *vars::import = sub {};
39 } else {
40 require IO::Handle;
43 eval { require Getopt::Long; import Getopt::Long; };
44 $has_getopt = not $@;
47 use vars qw($has_strict $has_getopt);
49 use vars qw($VERSION);
51 $VERSION = '2.1.1';
52 $VERSION .= '~git';
54 ## interface variables
55 # %option = command line and other options
56 use vars qw(%option);
58 ## hooks
59 use vars qw(@pre_hooks @post_hooks @flush_hooks);
61 ## parser variables
62 # $script: current script file
63 # @stack = ferm's parser stack containing local variables
64 # $auto_chain = index for the next auto-generated chain
65 use vars qw($script @stack $auto_chain);
67 ## netfilter variables
68 # %domains = state information about all domains ("ip" and "ip6")
69 # - initialized: domain initialization is done
70 # - tools: hash providing the paths of the domain's tools
71 # - previous: save file of the previous ruleset, for rollback
72 # - tables{$name}: ferm state information about tables
73 # - has_builtin: whether built-in chains have been determined in this table
74 # - chains{$chain}: ferm state information about the chains
75 # - builtin: whether this is a built-in chain
76 use vars qw(%domains);
78 ## constants
79 use vars qw(%deprecated_keywords);
81 # keywords from ferm 1.1 which are deprecated, and the new one; these
82 # are automatically replaced, and a warning is printed
83 %deprecated_keywords = ( goto => 'jump',
86 # these hashes provide the Netfilter module definitions
87 use vars qw(%proto_defs %match_defs %target_defs);
90 # This subsubsystem allows you to support (most) new netfilter modules
91 # in ferm. Add a call to one of the "add_XY_def()" functions below.
93 # Ok, now about the cryptic syntax: the function "add_XY_def()"
94 # registers a new module. There are three kinds of modules: protocol
95 # module (e.g. TCP, ICMP), match modules (e.g. state, physdev) and
96 # target modules (e.g. DNAT, MARK).
98 # The first parameter is always the module name which is passed to
99 # iptables with "-p", "-m" or "-j" (depending on which kind of module
100 # this is).
102 # After that, you add an encoded string for each option the module
103 # supports. This is where it becomes tricky.
105 # foo defaults to an option with one argument (which may be a ferm
106 # array)
108 # foo*0 option without any arguments
110 # foo=s one argument which must not be a ferm array ('s' stands for
111 # 'scalar')
113 # u32=m an array which renders into multiple iptables options in one
114 # rule
116 # ctstate=c one argument, if it's an array, pass it to iptables as a
117 # single comma separated value; example:
118 # ctstate (ESTABLISHED RELATED) translates to:
119 # --ctstate ESTABLISHED,RELATED
121 # foo=sac three arguments: scalar, array, comma separated; you may
122 # concatenate more than one letter code after the '='
124 # foo&bar one argument; call the perl function '&bar()' which parses
125 # the argument
127 # !foo negation is allowed and the '!' is written before the keyword
129 # foo! same as above, but '!' is after the keyword and before the
130 # parameters
132 # to:=to-destination makes "to" an alias for "to-destination"; you have
133 # to add a declaration for option "to-destination"
136 # prototype declarations
137 sub open_script($);
138 sub resolve($\@$);
139 sub enter($$);
140 sub rollback();
141 sub execute_fast($);
142 sub execute_slow($);
143 sub join_value($$);
145 # add a module definition
146 sub add_def_x {
147 my $defs = shift;
148 my $domain_family = shift;
149 my $params_default = shift;
150 my $name = shift;
151 die if exists $defs->{$domain_family}{$name};
152 my $def = $defs->{$domain_family}{$name} = {};
153 foreach (@_) {
154 my $keyword = $_;
155 my $k;
157 if ($keyword =~ s,:=(\S+)$,,) {
158 $k = $def->{keywords}{$1} || die;
159 $k->{ferm_name} ||= $keyword;
160 } else {
161 my $params = $params_default;
162 $params = $1 if $keyword =~ s,\*(\d+)$,,;
163 $params = $1 if $keyword =~ s,=([acs]+|m)$,,;
164 if ($keyword =~ s,&(\S+)$,,) {
165 $params = eval "\\&$1";
166 die $@ if $@;
169 $k = {};
170 $k->{params} = $params if $params;
172 $k->{negation} = $k->{pre_negation} = 1 if $keyword =~ s,^!,,;
173 $k->{negation} = 1 if $keyword =~ s,!$,,;
174 $k->{name} = $keyword;
177 $def->{keywords}{$keyword} = $k;
180 return $def;
183 # add a protocol module definition
184 sub add_proto_def_x(@) {
185 my $domain_family = shift;
186 add_def_x(\%proto_defs, $domain_family, 1, @_);
189 # add a match module definition
190 sub add_match_def_x(@) {
191 my $domain_family = shift;
192 add_def_x(\%match_defs, $domain_family, 1, @_);
195 # add a target module definition
196 sub add_target_def_x(@) {
197 my $domain_family = shift;
198 add_def_x(\%target_defs, $domain_family, 's', @_);
201 sub add_def {
202 my $defs = shift;
203 add_def_x($defs, 'ip', @_);
206 # add a protocol module definition
207 sub add_proto_def(@) {
208 add_def(\%proto_defs, 1, @_);
211 # add a match module definition
212 sub add_match_def(@) {
213 add_def(\%match_defs, 1, @_);
216 # add a target module definition
217 sub add_target_def(@) {
218 add_def(\%target_defs, 's', @_);
221 add_proto_def 'dccp', qw(dccp-types!=c dccp-option!);
222 add_proto_def 'mh', qw(mh-type!);
223 add_proto_def 'icmp', qw(icmp-type! icmpv6-type:=icmp-type);
224 add_proto_def 'sctp', qw(chunk-types!=sc);
225 add_proto_def 'tcp', qw(tcp-flags!=cc !syn*0 tcp-option! mss);
226 add_proto_def 'udp', qw();
228 add_match_def '',
229 # --source, --destination
230 qw(source! saddr:=source destination! daddr:=destination),
231 # --in-interface
232 qw(in-interface! interface:=in-interface if:=in-interface),
233 # --out-interface
234 qw(out-interface! outerface:=out-interface of:=out-interface),
235 # --fragment
236 qw(!fragment*0);
237 add_match_def 'account', qw(aaddr=s aname=s ashort*0);
238 add_match_def 'addrtype', qw(!src-type !dst-type),
239 qw(limit-iface-in*0 limit-iface-out*0);
240 add_match_def 'ah', qw(ahspi! ahlen! ahres*0);
241 add_match_def 'comment', qw(comment=s);
242 add_match_def 'condition', qw(condition!);
243 add_match_def 'connbytes', qw(!connbytes connbytes-dir connbytes-mode);
244 add_match_def 'connlimit', qw(!connlimit-above connlimit-mask);
245 add_match_def 'connmark', qw(!mark);
246 add_match_def 'conntrack', qw(!ctstate=c !ctproto ctorigsrc! ctorigdst! ctorigsrcport! ctorigdstport!),
247 qw(ctreplsrc! ctrepldst! !ctstatus !ctexpire=s ctdir=s);
248 add_match_def 'dscp', qw(dscp dscp-class);
249 add_match_def 'ecn', qw(ecn-tcp-cwr*0 ecn-tcp-ece*0 ecn-ip-ect);
250 add_match_def 'esp', qw(espspi!);
251 add_match_def 'eui64';
252 add_match_def 'fuzzy', qw(lower-limit=s upper-limit=s);
253 add_match_def 'hbh', qw(hbh-len! hbh-opts=c);
254 add_match_def 'helper', qw(helper);
255 add_match_def 'hl', qw(hl-eq! hl-lt=s hl-gt=s);
256 add_match_def 'hashlimit', qw(hashlimit=s hashlimit-burst=s hashlimit-mode=s hashlimit-name=s),
257 qw(hashlimit-htable-size=s hashlimit-htable-max=s),
258 qw(hashlimit-htable-expire=s hashlimit-htable-gcinterval=s);
259 add_match_def 'iprange', qw(!src-range !dst-range);
260 add_match_def 'ipv4options', qw(ssrr*0 lsrr*0 no-srr*0 !rr*0 !ts*0 !ra*0 !any-opt*0);
261 add_match_def 'ipv6header', qw(header!=c soft*0);
262 add_match_def 'length', qw(length!);
263 add_match_def 'limit', qw(limit=s limit-burst=s);
264 add_match_def 'mac', qw(mac-source!);
265 add_match_def 'mark', qw(!mark);
266 add_match_def 'multiport', qw(source-ports!&multiport_params),
267 qw(destination-ports!&multiport_params ports!&multiport_params);
268 add_match_def 'nth', qw(every counter start packet);
269 add_match_def 'owner', qw(!uid-owner !gid-owner pid-owner sid-owner),
270 qw(cmd-owner !socket-exists=0);
271 add_match_def 'physdev', qw(physdev-in! physdev-out!),
272 qw(!physdev-is-in*0 !physdev-is-out*0 !physdev-is-bridged*0);
273 add_match_def 'pkttype', qw(pkt-type!),
274 add_match_def 'policy',
275 qw(dir pol strict*0 !reqid !spi !proto !mode !tunnel-src !tunnel-dst next*0);
276 add_match_def 'psd', qw(psd-weight-threshold psd-delay-threshold),
277 qw(psd-lo-ports-weight psd-hi-ports-weight);
278 add_match_def 'quota', qw(quota=s);
279 add_match_def 'random', qw(average);
280 add_match_def 'realm', qw(realm!);
281 add_match_def 'recent', qw(name=s !set*0 !remove*0 !rcheck*0 !update*0 !seconds !hitcount rttl*0 rsource*0 rdest*0);
282 add_match_def 'rt', qw(rt-type! rt-segsleft! rt-len! rt-0-res*0 rt-0-addrs=c rt-0-not-strict*0);
283 add_match_def 'set', qw(!match-set=sc set:=match-set);
284 add_match_def 'state', qw(!state=c);
285 add_match_def 'statistic', qw(mode=s probability=s every=s packet=s);
286 add_match_def 'string', qw(algo=s from=s to=s string hex-string);
287 add_match_def 'tcpmss', qw(!mss);
288 add_match_def 'time', qw(timestart=s timestop=s days=c datestart=s datestop=s),
289 qw(!monthday=c !weekdays=c utc*0 localtz*0);
290 add_match_def 'tos', qw(!tos);
291 add_match_def 'ttl', qw(ttl-eq ttl-lt=s ttl-gt=s);
292 add_match_def 'u32', qw(!u32=m);
294 add_target_def 'BALANCE', qw(to-destination to:=to-destination);
295 add_target_def 'CLASSIFY', qw(set-class);
296 add_target_def 'CLUSTERIP', qw(new*0 hashmode clustermac total-nodes local-node hash-init);
297 add_target_def 'CONNMARK', qw(set-mark save-mark*0 restore-mark*0 mask);
298 add_target_def 'CONNSECMARK', qw(save*0 restore*0);
299 add_target_def 'DNAT', qw(to-destination=m to:=to-destination random*0);
300 add_target_def 'DSCP', qw(set-dscp set-dscp-class);
301 add_target_def 'ECN', qw(ecn-tcp-remove*0);
302 add_target_def 'HL', qw(hl-set hl-dec hl-inc);
303 add_target_def 'IPV4OPTSSTRIP';
304 add_target_def 'LOG', qw(log-level log-prefix),
305 qw(log-tcp-sequence*0 log-tcp-options*0 log-ip-options*0 log-uid*0);
306 add_target_def 'MARK', qw(set-mark set-xmark and-mark or-mark xor-mark);
307 add_target_def 'MASQUERADE', qw(to-ports random*0);
308 add_target_def 'MIRROR';
309 add_target_def 'NETMAP', qw(to);
310 add_target_def 'NFLOG', qw(nflog-group nflog-prefix nflog-range nflog-threshold);
311 add_target_def 'NFQUEUE', qw(queue-num);
312 add_target_def 'NOTRACK';
313 add_target_def 'REDIRECT', qw(to-ports random*0);
314 add_target_def 'REJECT', qw(reject-with);
315 add_target_def 'ROUTE', qw(oif iif gw continue*0 tee*0);
316 add_target_def 'SAME', qw(to nodst*0 random*0);
317 add_target_def 'SECMARK', qw(selctx);
318 add_target_def 'SET', qw(add-set=sc del-set=sc);
319 add_target_def 'SNAT', qw(to-source=m to:=to-source random*0);
320 add_target_def 'TARPIT';
321 add_target_def 'TCPMSS', qw(set-mss clamp-mss-to-pmtu*0);
322 add_target_def 'TOS', qw(set-tos and-tos or-tos xor-tos);
323 add_target_def 'TPROXY', qw(tproxy-mark on-port);
324 add_target_def 'TRACE';
325 add_target_def 'TTL', qw(ttl-set ttl-dec ttl-inc);
326 add_target_def 'ULOG', qw(ulog-nlgroup ulog-prefix ulog-cprange ulog-qthreshold);
328 add_match_def_x 'arp', '',
329 # ip
330 qw(source-ip! destination-ip! saddr:=source-ip daddr:=destination-ip),
331 # mac
332 qw(source-mac! destination-mac!),
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 # misc
338 qw(h-length=s opcode=s h-type=s proto-type=s),
339 qw(mangle-ip-s=s mangle-ip-d=s mangle-mac-s=s mangle-mac-d=s mangle-target=s);
341 add_proto_def_x 'eb', 'IPv4',
342 qw(ip-source! ip-destination! ip-src:=ip-source ip-dst:=ip-destination),
343 qw(ip-tos!),
344 qw(ip-protocol! ip-proto:=ip-protocol),
345 qw(ip-source-port! ip-sport:=ip-source-port),
346 qw(ip-destination-port! ip-dport:=ip-destination-port);
348 add_proto_def_x 'eb', 'IPv6',
349 qw(ip6-source! ip6-destination! ip6-src:=ip6-source ip6-dst:=ip6-destination),
350 qw(ip6-tclass!),
351 qw(ip6-protocol! ip6-proto:=ip6-protocol),
352 qw(ip6-source-port! ip6-sport:=ip6-source-port),
353 qw(ip6-destination-port! ip6-dport:=ip6-destination-port);
355 add_proto_def_x 'eb', 'ARP',
356 qw(!arp-gratuitous*0),
357 qw(arp-opcode! arp-htype!=ss arp-ptype!=ss),
358 qw(arp-ip-src! arp-ip-dst! arp-mac-src! arp-mac-dst!);
360 add_proto_def_x 'eb', 'RARP',
361 qw(!arp-gratuitous*0),
362 qw(arp-opcode! arp-htype!=ss arp-ptype!=ss),
363 qw(arp-ip-src! arp-ip-dst! arp-mac-src! arp-mac-dst!);
365 add_proto_def_x 'eb', '802_1Q',
366 qw(vlan-id! vlan-prio! vlan-encap!),
368 add_match_def_x 'eb', '',
369 # --in-interface
370 qw(in-interface! interface:=in-interface if:=in-interface),
371 # --out-interface
372 qw(out-interface! outerface:=out-interface of:=out-interface),
373 # logical interface
374 qw(logical-in! logical-out!),
375 # --source, --destination
376 qw(source! saddr:=source destination! daddr:=destination),
377 # 802.3
378 qw(802_3-sap! 802_3-type!),
379 # among
380 qw(!among-dst=c !among-src=c !among-dst-file !among-src-file),
381 # limit
382 qw(limit=s limit-burst=s),
383 # mark_m
384 qw(mark!),
385 # pkttype
386 qw(pkttype-type!),
387 # stp
388 qw(stp-type! stp-flags! stp-root-prio! stp-root-addr! stp-root-cost!),
389 qw(stp-sender-prio! stp-sender-addr! stp-port! stp-msg-age! stp-max-age!),
390 qw(stp-hello-time! stp-forward-delay!),
391 # log
392 qw(log*0 log-level=s log-prefix=s log-ip*0 log-arp*0);
394 add_target_def_x 'eb', 'arpreply', qw(arpreply-mac arpreply-target);
395 add_target_def_x 'eb', 'dnat', qw(to-destination dnat-target);
396 add_target_def_x 'eb', 'MARK', qw(set-mark mark-target);
397 add_target_def_x 'eb', 'redirect', qw(redirect-target);
398 add_target_def_x 'eb', 'snat', qw(to-source snat-target snat-arp*0);
400 # import-ferm uses the above tables
401 return 1 if $0 =~ /import-ferm$/;
403 # parameter parser for ipt_multiport
404 sub multiport_params {
405 my $rule = shift;
407 # multiport only allows 15 ports at a time. For this
408 # reason, we do a little magic here: split the ports
409 # into portions of 15, and handle these portions as
410 # array elements
412 my $proto = $rule->{protocol};
413 error('To use multiport, you have to specify "proto tcp" or "proto udp" first')
414 unless defined $proto and grep { /^(?:tcp|udp|udplite)$/ } to_array($proto);
416 my $value = getvalues(undef, allow_negation => 1,
417 allow_array_negation => 1);
418 if (ref $value and ref $value eq 'ARRAY') {
419 my @value = @$value;
420 my @params;
422 while (@value) {
423 push @params, join(',', splice(@value, 0, 15));
426 return @params == 1
427 ? $params[0]
428 : \@params;
429 } else {
430 return join_value(',', $value);
434 # initialize stack: command line definitions
435 unshift @stack, {};
437 # Get command line stuff
438 if ($has_getopt) {
439 my ($opt_noexec, $opt_flush, $opt_noflush, $opt_lines, $opt_interactive,
440 $opt_timeout, $opt_help,
441 $opt_version, $opt_test, $opt_fast, $opt_slow, $opt_shell,
442 $opt_domain);
444 Getopt::Long::Configure('bundling', 'auto_help', 'no_ignore_case',
445 'no_auto_abbrev');
447 sub opt_def {
448 my ($opt, $value) = @_;
449 die 'Invalid --def specification'
450 unless $value =~ /^\$?(\w+)=(.*)$/s;
451 my ($name, $unparsed_value) = ($1, $2);
452 my $tokens = tokenize_string($unparsed_value);
453 $value = getvalues(sub { shift @$tokens; });
454 die 'Extra tokens after --def'
455 if @$tokens > 0;
456 $stack[0]{vars}{$name} = $value;
459 local $SIG{__WARN__} = sub { die $_[0]; };
460 GetOptions('noexec|n' => \$opt_noexec,
461 'flush|F' => \$opt_flush,
462 'noflush' => \$opt_noflush,
463 'lines|l' => \$opt_lines,
464 'interactive|i' => \$opt_interactive,
465 'timeout|t=s' => \$opt_timeout,
466 'help|h' => \$opt_help,
467 'version|V' => \$opt_version,
468 test => \$opt_test,
469 remote => \$opt_test,
470 fast => \$opt_fast,
471 slow => \$opt_slow,
472 shell => \$opt_shell,
473 'domain=s' => \$opt_domain,
474 'def=s' => \&opt_def,
477 if (defined $opt_help) {
478 require Pod::Usage;
479 Pod::Usage::pod2usage(-exitstatus => 0);
482 if (defined $opt_version) {
483 printversion();
484 exit 0;
487 $option{noexec} = $opt_noexec || $opt_test;
488 $option{flush} = $opt_flush;
489 $option{noflush} = $opt_noflush;
490 $option{lines} = $opt_lines || $opt_test || $opt_shell;
491 $option{interactive} = $opt_interactive && !$opt_noexec;
492 $option{timeout} = defined $opt_timeout ? $opt_timeout : "30";
493 $option{test} = $opt_test;
494 $option{fast} = !$opt_slow;
495 $option{shell} = $opt_shell;
497 die("ferm interactive mode not possible: /dev/stdin is not a tty\n")
498 if $option{interactive} and not -t STDIN;
499 die("ferm interactive mode not possible: /dev/stderr is not a tty\n")
500 if $option{interactive} and not -t STDERR;
501 die("ferm timeout has no sense without interactive mode")
502 if not $opt_interactive and defined $opt_timeout;
503 die("invalid timeout. must be an integer")
504 if defined $opt_timeout and not $opt_timeout =~ /^[+-]?\d+$/;
506 $option{domain} = $opt_domain if defined $opt_domain;
507 } else {
508 # tiny getopt emulation for microperl
509 my $filename;
510 foreach (@ARGV) {
511 if ($_ eq '--noexec' or $_ eq '-n') {
512 $option{noexec} = 1;
513 } elsif ($_ eq '--lines' or $_ eq '-l') {
514 $option{lines} = 1;
515 } elsif ($_ eq '--fast') {
516 $option{fast} = 1;
517 } elsif ($_ eq '--test') {
518 $option{test} = 1;
519 $option{noexec} = 1;
520 $option{lines} = 1;
521 } elsif ($_ eq '--shell') {
522 $option{$_} = 1 foreach qw(shell fast lines);
523 } elsif (/^-/) {
524 printf STDERR "Usage: ferm [--noexec] [--lines] [--fast] [--shell] FILENAME\n";
525 exit 1;
526 } else {
527 $filename = $_;
530 undef @ARGV;
531 push @ARGV, $filename;
534 unless (@ARGV == 1) {
535 require Pod::Usage;
536 Pod::Usage::pod2usage(-exitstatus => 1);
539 if ($has_strict) {
540 open LINES, ">&STDOUT" if $option{lines};
541 open STDOUT, ">&STDERR" if $option{shell};
542 } else {
543 # microperl can't redirect file handles
544 *LINES = *STDOUT;
546 if ($option{fast} and not $option{noexec}) {
547 print STDERR "Sorry, ferm on microperl does not allow --fast without --noexec\n";
548 exit 1
552 unshift @stack, {};
553 open_script($ARGV[0]);
555 my( $volume,$dirs,$file ) = File::Spec->splitpath( $ARGV[0] );
556 $stack[0]{auto}{FILENAME} = $ARGV[0];
557 $stack[0]{auto}{FILEBNAME} = $file;
558 $stack[0]{auto}{DIRNAME} = $dirs;
562 # parse all input recursively
563 enter(0, undef);
564 die unless @stack == 2;
566 # enable/disable hooks depending on --flush
568 if ($option{flush}) {
569 undef @pre_hooks;
570 undef @post_hooks;
571 } else {
572 undef @flush_hooks;
575 # execute all generated rules
576 my $status;
578 foreach my $cmd (@pre_hooks) {
579 print LINES "$cmd\n" if $option{lines};
580 system($cmd) unless $option{noexec};
583 while (my ($domain, $domain_info) = each %domains) {
584 next unless $domain_info->{enabled};
585 my $s = $option{fast} &&
586 defined $domain_info->{tools}{'tables-restore'}
587 ? execute_fast($domain_info) : execute_slow($domain_info);
588 $status = $s if defined $s;
591 foreach my $cmd (@post_hooks, @flush_hooks) {
592 print LINES "$cmd\n" if $option{lines};
593 system($cmd) unless $option{noexec};
596 if (defined $status) {
597 rollback();
598 exit $status;
601 # ask user, and rollback if there is no confirmation
603 if ($option{interactive}) {
604 if ($option{shell}) {
605 print LINES "echo 'ferm has applied the new firewall rules.'\n";
606 print LINES "echo 'Please press Ctrl-C to confirm.'\n";
607 print LINES "sleep $option{timeout}\n";
608 while (my ($domain, $domain_info) = each %domains) {
609 my $restore = $domain_info->{tools}{'tables-restore'};
610 next unless defined $restore;
611 print LINES "$restore <\$${domain}_tmp\n";
615 confirm_rules() or rollback() unless $option{noexec};
618 exit 0;
620 # end of program execution!
623 # funcs
625 sub printversion {
626 print "ferm $VERSION\n";
627 print "Copyright (C) 2001-2011 Max Kellermann, Auke Kok\n";
628 print "This program is free software released under GPLv2.\n";
629 print "See the included COPYING file for license details.\n";
633 sub error {
634 # returns a nice formatted error message, showing the
635 # location of the error.
636 my $tabs = 0;
637 my @lines;
638 my $l = 0;
639 my @words = map { @$_ } @{$script->{past_tokens}};
641 for my $w ( 0 .. $#words ) {
642 if ($words[$w] eq "\x29")
643 { $l++ ; $lines[$l] = " " x ($tabs-- -1) ;};
644 if ($words[$w] eq "\x28")
645 { $l++ ; $lines[$l] = " " x $tabs++ ;};
646 if ($words[$w] eq "\x7d")
647 { $l++ ; $lines[$l] = " " x ($tabs-- -1) ;};
648 if ($words[$w] eq "\x7b")
649 { $l++ ; $lines[$l] = " " x $tabs++ ;};
650 if ( $l > $#lines ) { $lines[$l] = "" };
651 $lines[$l] .= $words[$w] . " ";
652 if ($words[$w] eq "\x28")
653 { $l++ ; $lines[$l] = " " x $tabs ;};
654 if (($words[$w] eq "\x29") && ($words[$w+1] ne "\x7b"))
655 { $l++ ; $lines[$l] = " " x $tabs ;};
656 if ($words[$w] eq "\x7b")
657 { $l++ ; $lines[$l] = " " x $tabs ;};
658 if (($words[$w] eq "\x7d") && ($words[$w+1] ne "\x7d"))
659 { $l++ ; $lines[$l] = " " x $tabs ;};
660 if (($words[$w] eq "\x3b") && ($words[$w+1] ne "\x7d"))
661 { $l++ ; $lines[$l] = " " x $tabs ;}
662 if ($words[$w-1] eq "option")
663 { $l++ ; $lines[$l] = " " x $tabs ;}
665 my $start = $#lines - 4;
666 if ($start < 0) { $start = 0 } ;
667 print STDERR "Error in $script->{filename} line $script->{line}:\n";
668 for $l ( $start .. $#lines)
669 { print STDERR $lines[$l]; if ($l != $#lines ) {print STDERR "\n"} ; };
670 print STDERR "<--\n";
671 die("@_\n");
674 # print a warning message about code from an input file
675 sub warning {
676 print STDERR "Warning in $script->{filename} line $script->{line}: "
677 . (shift) . "\n";
680 sub find_tool($) {
681 my $name = shift;
682 return $name if $option{test};
683 for my $path ('/sbin', split ':', $ENV{PATH}) {
684 my $ret = "$path/$name";
685 return $ret if -x $ret;
687 die "$name not found in PATH\n";
690 sub initialize_domain {
691 my $domain = shift;
692 my $domain_info = $domains{$domain} ||= {};
694 return if exists $domain_info->{initialized};
696 die "Invalid domain '$domain'\n" unless $domain =~ /^(?:ip6?|arp|eb)$/;
698 my @tools = qw(tables);
699 push @tools, qw(tables-save tables-restore)
700 if $domain =~ /^ip6?$/;
702 # determine the location of this domain's tools
703 my %tools = map { $_ => find_tool($domain . $_) } @tools;
704 $domain_info->{tools} = \%tools;
706 # make tables-save tell us about the state of this domain
707 # (which tables and chains do exist?), also remember the old
708 # save data which may be used later by the rollback function
709 local *SAVE;
710 if (!$option{test} &&
711 exists $tools{'tables-save'} &&
712 open(SAVE, "$tools{'tables-save'}|")) {
713 my $save = '';
715 my $table_info;
716 while (<SAVE>) {
717 $save .= $_;
719 if (/^\*(\w+)/) {
720 my $table = $1;
721 $table_info = $domain_info->{tables}{$table} ||= {};
722 } elsif (defined $table_info and /^:(\w+)\s+(\S+)/
723 and $2 ne '-') {
724 $table_info->{chains}{$1}{builtin} = 1;
725 $table_info->{has_builtin} = 1;
729 # for rollback
730 $domain_info->{previous} = $save;
733 if ($option{shell} && $option{interactive} &&
734 exists $tools{'tables-save'}) {
735 print LINES "${domain}_tmp=\$(mktemp ferm.XXXXXXXXXX)\n";
736 print LINES "$tools{'tables-save'} >\$${domain}_tmp\n";
739 $domain_info->{initialized} = 1;
742 sub check_domain($) {
743 my $domain = shift;
744 my @result;
746 return if exists $option{domain}
747 and $domain ne $option{domain};
749 eval {
750 initialize_domain($domain);
752 error($@) if $@;
754 return 1;
757 # split the input string into words and delete comments
758 sub tokenize_string($) {
759 my $string = shift;
761 my @ret;
763 foreach my $word ($string =~ m/(".*?"|'.*?'|`.*?`|[!,=&\$\%\(\){};]|[-+\w\/\.:]+|@\w+|#)/g) {
764 last if $word eq '#';
765 push @ret, $word;
768 return \@ret;
771 # generate a "line" special token, that marks the line number; these
772 # special tokens are inserted after each line break, so ferm keeps
773 # track of line numbers
774 sub make_line_token($) {
775 my $line = shift;
776 return bless(\$line, 'line');
779 # read some more tokens from the input file into a buffer
780 sub prepare_tokens() {
781 my $tokens = $script->{tokens};
782 while (@$tokens == 0) {
783 my $handle = $script->{handle};
784 return unless defined $handle;
785 my $line = <$handle>;
786 return unless defined $line;
788 push @$tokens, make_line_token($script->{line} + 1);
790 # the next parser stage eats this
791 push @$tokens, @{tokenize_string($line)};
794 return 1;
797 sub handle_special_token($) {
798 my $token = shift;
799 die unless ref $token;
800 if (ref $token eq 'line') {
801 $script->{line} = $$token;
802 } else {
803 die;
807 sub handle_special_tokens() {
808 my $tokens = $script->{tokens};
809 while (@$tokens > 0 and ref $tokens->[0]) {
810 handle_special_token(shift @$tokens);
814 # wrapper for prepare_tokens() which handles "special" tokens
815 sub prepare_normal_tokens() {
816 my $tokens = $script->{tokens};
817 while (1) {
818 handle_special_tokens();
819 return 1 if @$tokens > 0;
820 return unless prepare_tokens();
824 # open a ferm sub script
825 sub open_script($) {
826 my $filename = shift;
828 for (my $s = $script; defined $s; $s = $s->{parent}) {
829 die("Circular reference in $script->{filename} line $script->{line}: $filename\n")
830 if $s->{filename} eq $filename;
833 my $handle;
834 if ($filename eq '-') {
835 # Note that this only allowed in the command-line argument and not
836 # @includes, since those are filtered by collect_filenames()
837 $handle = *STDIN;
838 # also set a filename label so that error messages are more helpful
839 $filename = "<stdin>";
840 } else {
841 local *FILE;
842 open FILE, "$filename" or die("Failed to open $filename: $!\n");
843 $handle = *FILE;
846 $script = { filename => $filename,
847 handle => $handle,
848 line => 0,
849 past_tokens => [],
850 tokens => [],
851 parent => $script,
854 return $script;
857 # collect script filenames which are being included
858 sub collect_filenames(@) {
859 my @ret;
861 # determine the current script's parent directory for relative
862 # file names
863 die unless defined $script;
864 my $parent_dir = $script->{filename} =~ m,^(.*/),
865 ? $1 : './';
867 foreach my $pathname (@_) {
868 # non-absolute file names are relative to the parent script's
869 # file name
870 $pathname = $parent_dir . $pathname
871 unless $pathname =~ m,^/|\|$,;
873 if ($pathname =~ m,/$,) {
874 # include all regular files in a directory
876 error("'$pathname' is not a directory")
877 unless -d $pathname;
879 local *DIR;
880 opendir DIR, $pathname
881 or error("Failed to open directory '$pathname': $!");
882 my @names = readdir DIR;
883 closedir DIR;
885 # sort those names for a well-defined order
886 foreach my $name (sort { $a cmp $b } @names) {
887 # ignore dpkg's backup files
888 next if $name =~ /\.dpkg-(old|dist|new|tmp)$/;
889 # don't include hidden and backup files
890 next if $name =~ /^\.|~$/;
892 my $filename = $pathname . $name;
893 push @ret, $filename
894 if -f $filename;
896 } elsif ($pathname =~ m,\|$,) {
897 # run a program and use its output
898 push @ret, $pathname;
899 } elsif ($pathname =~ m,^\|,) {
900 error('This kind of pipe is not allowed');
901 } else {
902 # include a regular file
904 error("'$pathname' is a directory; maybe use trailing '/' to include a directory?")
905 if -d $pathname;
906 error("'$pathname' is not a file")
907 unless -f $pathname;
909 push @ret, $pathname;
913 return @ret;
916 # peek a token from the queue, but don't remove it
917 sub peek_token() {
918 return unless prepare_normal_tokens();
919 return $script->{tokens}[0];
922 # get a token from the queue, including "special" tokens
923 sub next_raw_token() {
924 return unless prepare_tokens();
925 return shift @{$script->{tokens}};
928 # get a token from the queue
929 sub next_token() {
930 return unless prepare_normal_tokens();
931 my $token = shift @{$script->{tokens}};
933 # update $script->{past_tokens}
934 my $past_tokens = $script->{past_tokens};
936 if (@$past_tokens > 0) {
937 my $prev_token = $past_tokens->[-1][-1];
938 $past_tokens->[-1] = @$past_tokens > 1 ? ['{'] : []
939 if $prev_token eq ';';
940 if ($prev_token eq '}') {
941 pop @$past_tokens;
942 $past_tokens->[-1] = $past_tokens->[-1][0] eq '{'
943 ? [ '{' ] : []
944 if @$past_tokens > 0;
948 push @$past_tokens, [] if $token eq '{' or @$past_tokens == 0;
949 push @{$past_tokens->[-1]}, $token;
951 # return
952 return $token;
955 sub expect_token($;$) {
956 my $expect = shift;
957 my $msg = shift;
958 my $token = next_token();
959 error($msg || "'$expect' expected")
960 unless defined $token and $token eq $expect;
963 # require that another token exists, and that it's not a "special"
964 # token, e.g. ";" and "{"
965 sub require_next_token {
966 my $code = shift || \&next_token;
968 my $token = &$code(@_);
970 error('unexpected end of file')
971 unless defined $token;
973 error("'$token' not allowed here")
974 if $token =~ /^[;{}]$/;
976 return $token;
979 # return the value of a variable
980 sub variable_value($) {
981 my $name = shift;
983 if ($name eq "LINE") {
984 return $script->{line};
987 foreach (@stack) {
988 return $_->{vars}{$name}
989 if exists $_->{vars}{$name};
992 return $stack[0]{auto}{$name}
993 if exists $stack[0]{auto}{$name};
995 return;
998 # determine the value of a variable, die if the value is an array
999 sub string_variable_value($) {
1000 my $name = shift;
1001 my $value = variable_value($name);
1003 error("variable '$name' must be a string, but it is an array")
1004 if ref $value;
1006 return $value;
1009 # similar to the built-in "join" function, but also handle negated
1010 # values in a special way
1011 sub join_value($$) {
1012 my ($expr, $value) = @_;
1014 unless (ref $value) {
1015 return $value;
1016 } elsif (ref $value eq 'ARRAY') {
1017 return join($expr, @$value);
1018 } elsif (ref $value eq 'negated') {
1019 # bless'negated' is a special marker for negated values
1020 $value = join_value($expr, $value->[0]);
1021 return bless [ $value ], 'negated';
1022 } else {
1023 die;
1027 sub negate_value($$;$) {
1028 my ($value, $class, $allow_array) = @_;
1030 if (ref $value) {
1031 error('double negation is not allowed')
1032 if ref $value eq 'negated' or ref $value eq 'pre_negated';
1034 error('it is not possible to negate an array')
1035 if ref $value eq 'ARRAY' and not $allow_array;
1038 return bless [ $value ], $class || 'negated';
1041 sub format_bool($) {
1042 return $_[0] ? 1 : 0;
1045 sub resolve($\@$) {
1046 my ($resolver, $names, $type) = @_;
1048 my @result;
1049 foreach my $hostname (@$names) {
1050 my $query = $resolver->search($hostname, $type);
1051 error("DNS query for '$hostname' failed: " . $resolver->errorstring)
1052 unless $query;
1054 foreach my $rr ($query->answer) {
1055 next unless $rr->type eq $type;
1057 if ($type eq 'NS') {
1058 push @result, $rr->nsdname;
1059 } elsif ($type eq 'MX') {
1060 push @result, $rr->exchange;
1061 } else {
1062 push @result, $rr->address;
1067 # NS/MX records return host names; resolve these again in the
1068 # second pass (IPv4 only currently)
1069 @result = resolve($resolver, @result, 'A')
1070 if $type eq 'NS' or $type eq 'MX';
1072 return @result;
1075 # returns the next parameter, which may either be a scalar or an array
1076 sub getvalues {
1077 my $code = shift;
1078 my %options = @_;
1080 my $token = require_next_token($code);
1082 if ($token eq '(') {
1083 # read an array until ")"
1084 my @wordlist;
1086 for (;;) {
1087 $token = getvalues($code,
1088 parenthesis_allowed => 1,
1089 comma_allowed => 1);
1091 unless (ref $token) {
1092 last if $token eq ')';
1094 if ($token eq ',') {
1095 error('Comma is not allowed within arrays, please use only a space');
1096 next;
1099 push @wordlist, $token;
1100 } elsif (ref $token eq 'ARRAY') {
1101 push @wordlist, @$token;
1102 } else {
1103 error('unknown toke type');
1107 error('empty array not allowed here')
1108 unless @wordlist or not $options{non_empty};
1110 return @wordlist == 1
1111 ? $wordlist[0]
1112 : \@wordlist;
1113 } elsif ($token =~ /^\`(.*)\`$/s) {
1114 # execute a shell command, insert output
1115 my $command = $1;
1116 my $output = `$command`;
1117 unless ($? == 0) {
1118 if ($? == -1) {
1119 error("failed to execute: $!");
1120 } elsif ($? & 0x7f) {
1121 error("child died with signal " . ($? & 0x7f));
1122 } elsif ($? >> 8) {
1123 error("child exited with status " . ($? >> 8));
1127 # remove comments
1128 $output =~ s/#.*//mg;
1130 # tokenize
1131 my @tokens = grep { length } split /\s+/s, $output;
1133 my @values;
1134 while (@tokens) {
1135 my $value = getvalues(sub { shift @tokens });
1136 push @values, to_array($value);
1139 # and recurse
1140 return @values == 1
1141 ? $values[0]
1142 : \@values;
1143 } elsif ($token =~ /^\'(.*)\'$/s) {
1144 # single quotes: a string
1145 return $1;
1146 } elsif ($token =~ /^\"(.*)\"$/s) {
1147 # double quotes: a string with escapes
1148 $token = $1;
1149 $token =~ s,\$(\w+),string_variable_value($1),eg;
1150 return $token;
1151 } elsif ($token eq '!') {
1152 error('negation is not allowed here')
1153 unless $options{allow_negation};
1155 $token = getvalues($code);
1157 return negate_value($token, undef, $options{allow_array_negation});
1158 } elsif ($token eq ',') {
1159 return $token
1160 if $options{comma_allowed};
1162 error('comma is not allowed here');
1163 } elsif ($token eq '=') {
1164 error('equals operator ("=") is not allowed here');
1165 } elsif ($token eq '$') {
1166 my $name = require_next_token($code);
1167 error('variable name expected - if you want to concatenate strings, try using double quotes')
1168 unless $name =~ /^\w+$/;
1170 my $value = variable_value($name);
1172 error("no such variable: \$$name")
1173 unless defined $value;
1175 return $value;
1176 } elsif ($token eq '&') {
1177 error("function calls are not allowed as keyword parameter");
1178 } elsif ($token eq ')' and not $options{parenthesis_allowed}) {
1179 error('Syntax error');
1180 } elsif ($token =~ /^@/) {
1181 if ($token eq '@resolve') {
1182 my @params = get_function_params();
1183 error('Usage: @resolve((hostname ...), [type])')
1184 unless @params == 1 or @params == 2;
1185 eval { require Net::DNS; };
1186 error('For the @resolve() function, you need the Perl library Net::DNS')
1187 if $@;
1188 my $type = $params[1] || 'A';
1189 my $resolver = new Net::DNS::Resolver;
1190 @params = to_array($params[0]);
1191 my @result = resolve($resolver, @params, $type);
1192 return @result == 1 ? $result[0] : \@result;
1193 } elsif ($token eq '@eq') {
1194 my @params = get_function_params();
1195 error('Usage: @eq(a, b)') unless @params == 2;
1196 return format_bool($params[0] eq $params[1]);
1197 } elsif ($token eq '@ne') {
1198 my @params = get_function_params();
1199 error('Usage: @ne(a, b)') unless @params == 2;
1200 return format_bool($params[0] ne $params[1]);
1201 } elsif ($token eq '@not') {
1202 my @params = get_function_params();
1203 error('Usage: @not(a)') unless @params == 1;
1204 return format_bool(not $params[0]);
1205 } elsif ($token eq '@cat') {
1206 my $value = '';
1207 map { $value .= $_ } get_function_params();
1208 return $value;
1209 } elsif ($token eq '@substr') {
1210 my @params = get_function_params();
1211 error('Usage: @substr(string, num, num)') unless @params == 3;
1212 return substr($params[0],$params[1],$params[2]);
1213 } elsif ($token eq '@length') {
1214 my @params = get_function_params();
1215 error('Usage: @length(string)') unless @params == 1;
1216 return length($params[0]);
1217 } elsif ($token eq '@basename') {
1218 my @params = get_function_params();
1219 error('Usage: @basename(path)') unless @params == 1;
1220 my($volume,$path,$file) = File::Spec->splitpath( $params[0] );
1221 return $file;
1222 } elsif ($token eq '@dirname') {
1223 my @params = get_function_params();
1224 error('Usage: @dirname(path)') unless @params == 1;
1225 my($volume,$path,$file) = File::Spec->splitpath( $params[0] );
1226 return $path;
1227 } elsif ($token eq '@ipfilter') {
1228 my @params = get_function_params();
1229 error('Usage: @ipfilter((ip1 ip2 ...))') unless @params == 1;
1230 my $domain = $stack[0]{auto}{DOMAIN};
1231 error('No domain specified') unless defined $domain;
1232 my @ips = to_array($params[0]);
1234 # very crude IPv4/IPv6 address detection
1235 if ($domain eq 'ip') {
1236 @ips = grep { !/:[0-9a-f]*:/ } @ips;
1237 } elsif ($domain eq 'ip6') {
1238 @ips = grep { !m,^[0-9./]+$,s } @ips;
1241 return \@ips;
1242 } else {
1243 error("unknown ferm built-in function");
1245 } else {
1246 return $token;
1250 # returns the next parameter, but only allow a scalar
1251 sub getvar() {
1252 my $token = getvalues();
1254 error('array not allowed here')
1255 if ref $token and ref $token eq 'ARRAY';
1257 return $token;
1260 sub get_function_params(%) {
1261 expect_token('(', 'function name must be followed by "()"');
1263 my $token = peek_token();
1264 if ($token eq ')') {
1265 require_next_token();
1266 return;
1269 my @params;
1271 while (1) {
1272 if (@params > 0) {
1273 $token = require_next_token();
1274 last
1275 if $token eq ')';
1277 error('"," expected')
1278 unless $token eq ',';
1281 push @params, getvalues(undef, @_);
1284 return @params;
1287 # collect all tokens in a flat array reference until the end of the
1288 # command is reached
1289 sub collect_tokens {
1290 my %options = @_;
1292 my @level;
1293 my @tokens;
1295 # re-insert a "line" token, because the starting token of the
1296 # current line has been consumed already
1297 push @tokens, make_line_token($script->{line});
1299 while (1) {
1300 my $keyword = next_raw_token();
1301 error('unexpected end of file within function/variable declaration')
1302 unless defined $keyword;
1304 if (ref $keyword) {
1305 handle_special_token($keyword);
1306 } elsif ($keyword =~ /^[\{\(]$/) {
1307 push @level, $keyword;
1308 } elsif ($keyword =~ /^[\}\)]$/) {
1309 my $expected = $keyword;
1310 $expected =~ tr/\}\)/\{\(/;
1311 my $opener = pop @level;
1312 error("unmatched '$keyword'")
1313 unless defined $opener and $opener eq $expected;
1314 } elsif ($keyword eq ';' and @level == 0) {
1315 push @tokens, $keyword
1316 if $options{include_semicolon};
1318 if ($options{include_else}) {
1319 my $token = peek_token;
1320 next if $token eq '@else';
1323 last;
1326 push @tokens, $keyword;
1328 last
1329 if $keyword eq '}' and @level == 0;
1332 return \@tokens;
1336 # returns the specified value as an array. dereference arrayrefs
1337 sub to_array($) {
1338 my $value = shift;
1339 die unless wantarray;
1340 die if @_;
1341 unless (ref $value) {
1342 return $value;
1343 } elsif (ref $value eq 'ARRAY') {
1344 return @$value;
1345 } else {
1346 die;
1350 # evaluate the specified value as bool
1351 sub eval_bool($) {
1352 my $value = shift;
1353 die if wantarray;
1354 die if @_;
1355 unless (ref $value) {
1356 return $value;
1357 } elsif (ref $value eq 'ARRAY') {
1358 return @$value > 0;
1359 } else {
1360 die;
1364 sub is_netfilter_core_target($) {
1365 my $target = shift;
1366 die unless defined $target and length $target;
1367 return grep { $_ eq $target } qw(ACCEPT DROP RETURN QUEUE);
1370 sub is_netfilter_module_target($$) {
1371 my ($domain_family, $target) = @_;
1372 die unless defined $target and length $target;
1374 return defined $domain_family &&
1375 exists $target_defs{$domain_family} &&
1376 $target_defs{$domain_family}{$target};
1379 sub is_netfilter_builtin_chain($$) {
1380 my ($table, $chain) = @_;
1382 return grep { $_ eq $chain }
1383 qw(PREROUTING INPUT FORWARD OUTPUT POSTROUTING);
1386 sub netfilter_canonical_protocol($) {
1387 my $proto = shift;
1388 return 'icmp'
1389 if $proto eq 'ipv6-icmp' or $proto eq 'icmpv6';
1390 return 'mh'
1391 if $proto eq 'ipv6-mh';
1392 return $proto;
1395 sub netfilter_protocol_module($) {
1396 my $proto = shift;
1397 return unless defined $proto;
1398 return 'icmp6'
1399 if $proto eq 'icmpv6';
1400 return $proto;
1403 # escape the string in a way safe for the shell
1404 sub shell_escape($) {
1405 my $token = shift;
1407 return $token if $token =~ /^[-_a-zA-Z0-9]+$/s;
1409 if ($option{fast}) {
1410 # iptables-save/iptables-restore are quite buggy concerning
1411 # escaping and special characters... we're trying our best
1412 # here
1414 $token =~ s,",\\",g;
1415 $token = '"' . $token . '"'
1416 if $token =~ /[\s\'\\;&]/s or length($token) == 0;
1417 } else {
1418 return $token
1419 if $token =~ /^\`.*\`$/;
1420 $token =~ s/'/'\\''/g;
1421 $token = '\'' . $token . '\''
1422 if $token =~ /[\s\"\\;<>&|]/s or length($token) == 0;
1425 return $token;
1428 # append an option to the shell command line, using information from
1429 # the module definition (see %match_defs etc.)
1430 sub shell_format_option($$) {
1431 my ($keyword, $value) = @_;
1433 my $cmd = '';
1434 if (ref $value) {
1435 if ((ref $value eq 'negated') || (ref $value eq 'pre_negated')) {
1436 $value = $value->[0];
1437 $cmd = ' !';
1441 unless (defined $value) {
1442 $cmd .= " --$keyword";
1443 } elsif (ref $value) {
1444 if (ref $value eq 'params') {
1445 $cmd .= " --$keyword ";
1446 $cmd .= join(' ', map { shell_escape($_) } @$value);
1447 } elsif (ref $value eq 'multi') {
1448 foreach (@$value) {
1449 $cmd .= " --$keyword " . shell_escape($_);
1451 } else {
1452 die;
1454 } else {
1455 $cmd .= " --$keyword " . shell_escape($value);
1458 return $cmd;
1461 sub format_option($$$) {
1462 my ($domain, $name, $value) = @_;
1464 $value = 'icmpv6' if $domain eq 'ip6' and $name eq 'protocol'
1465 and $value eq 'icmp';
1466 $name = 'icmpv6-type' if $domain eq 'ip6' and $name eq 'icmp-type';
1468 if ($domain eq 'ip6' and $name eq 'reject-with') {
1469 my %icmp_map = (
1470 'icmp-net-unreachable' => 'icmp6-no-route',
1471 'icmp-host-unreachable' => 'icmp6-addr-unreachable',
1472 'icmp-port-unreachable' => 'icmp6-port-unreachable',
1473 'icmp-net-prohibited' => 'icmp6-adm-prohibited',
1474 'icmp-host-prohibited' => 'icmp6-adm-prohibited',
1475 'icmp-admin-prohibited' => 'icmp6-adm-prohibited',
1477 $value = $icmp_map{$value} if exists $icmp_map{$value};
1480 return shell_format_option($name, $value);
1483 sub append_rule($$) {
1484 my ($chain_rules, $rule) = @_;
1486 my $cmd = join('', map { $_->[2] } @{$rule->{options}});
1487 push @$chain_rules, { rule => $cmd,
1488 script => $rule->{script},
1492 sub unfold_rule {
1493 my ($domain, $chain_rules, $rule) = (shift, shift, shift);
1494 return append_rule($chain_rules, $rule) unless @_;
1496 my $option = shift;
1497 my @values = @{$option->[1]};
1499 foreach my $value (@values) {
1500 $option->[2] = format_option($domain, $option->[0], $value);
1501 unfold_rule($domain, $chain_rules, $rule, @_);
1505 sub mkrules2($$$) {
1506 my ($domain, $chain_rules, $rule) = @_;
1508 my @unfold;
1509 foreach my $option (@{$rule->{options}}) {
1510 if (ref $option->[1] and ref $option->[1] eq 'ARRAY') {
1511 push @unfold, $option
1512 } else {
1513 $option->[2] = format_option($domain, $option->[0], $option->[1]);
1517 unfold_rule($domain, $chain_rules, $rule, @unfold);
1520 # convert a bunch of internal rule structures in iptables calls,
1521 # unfold arrays during that
1522 sub mkrules($) {
1523 my $rule = shift;
1525 my $domain = $rule->{domain};
1526 my $domain_info = $domains{$domain};
1527 $domain_info->{enabled} = 1;
1529 foreach my $table (to_array $rule->{table}) {
1530 my $table_info = $domain_info->{tables}{$table} ||= {};
1532 foreach my $chain (to_array $rule->{chain}) {
1533 my $chain_rules = $table_info->{chains}{$chain}{rules} ||= [];
1534 mkrules2($domain, $chain_rules, $rule)
1535 if $rule->{has_rule} and not $option{flush};
1540 # parse a keyword from a module definition
1541 sub parse_keyword(\%$$) {
1542 my ($rule, $def, $negated_ref) = @_;
1544 my $params = $def->{params};
1546 my $value;
1548 my $negated;
1549 if ($$negated_ref && exists $def->{pre_negation}) {
1550 $negated = 1;
1551 undef $$negated_ref;
1554 unless (defined $params) {
1555 undef $value;
1556 } elsif (ref $params && ref $params eq 'CODE') {
1557 $value = &$params($rule);
1558 } elsif ($params eq 'm') {
1559 $value = bless [ to_array getvalues() ], 'multi';
1560 } elsif ($params =~ /^[a-z]/) {
1561 if (exists $def->{negation} and not $negated) {
1562 my $token = peek_token();
1563 if ($token eq '!') {
1564 require_next_token();
1565 $negated = 1;
1569 my @params;
1570 foreach my $p (split(//, $params)) {
1571 if ($p eq 's') {
1572 push @params, getvar();
1573 } elsif ($p eq 'c') {
1574 my @v = to_array getvalues(undef, non_empty => 1);
1575 push @params, join(',', @v);
1576 } else {
1577 die;
1581 $value = @params == 1
1582 ? $params[0]
1583 : bless \@params, 'params';
1584 } elsif ($params == 1) {
1585 if (exists $def->{negation} and not $negated) {
1586 my $token = peek_token();
1587 if ($token eq '!') {
1588 require_next_token();
1589 $negated = 1;
1593 $value = getvalues();
1595 warning("log-prefix is too long; truncating to 29 characters: '$1'")
1596 if $def->{name} eq 'log-prefix' && $value =~ s,^(.{29}).+$,$1,;
1597 } else {
1598 if (exists $def->{negation} and not $negated) {
1599 my $token = peek_token();
1600 if ($token eq '!') {
1601 require_next_token();
1602 $negated = 1;
1606 $value = bless [ map {
1607 getvar()
1608 } (1..$params) ], 'params';
1611 $value = negate_value($value, exists $def->{pre_negation} && 'pre_negated')
1612 if $negated;
1614 return $value;
1617 sub append_option(\%$$) {
1618 my ($rule, $name, $value) = @_;
1619 push @{$rule->{options}}, [ $name, $value ];
1622 # parse options of a module
1623 sub parse_option($\%$) {
1624 my ($def, $rule, $negated_ref) = @_;
1626 append_option(%$rule, $def->{name},
1627 parse_keyword(%$rule, $def, $negated_ref));
1630 sub copy_on_write($$) {
1631 my ($rule, $key) = @_;
1632 return unless exists $rule->{cow}{$key};
1633 $rule->{$key} = {%{$rule->{$key}}};
1634 delete $rule->{cow}{$key};
1637 sub new_level(\%$) {
1638 my ($rule, $prev) = @_;
1640 %$rule = ();
1641 if (defined $prev) {
1642 # copy data from previous level
1643 $rule->{cow} = { keywords => 1, };
1644 $rule->{keywords} = $prev->{keywords};
1645 $rule->{match} = { %{$prev->{match}} };
1646 $rule->{options} = [@{$prev->{options}}];
1647 foreach my $key (qw(domain domain_family table chain protocol has_rule has_action)) {
1648 $rule->{$key} = $prev->{$key}
1649 if exists $prev->{$key};
1651 } else {
1652 $rule->{cow} = {};
1653 $rule->{keywords} = {};
1654 $rule->{match} = {};
1655 $rule->{options} = [];
1659 sub merge_keywords(\%$) {
1660 my ($rule, $keywords) = @_;
1661 copy_on_write($rule, 'keywords');
1662 while (my ($name, $def) = each %$keywords) {
1663 $rule->{keywords}{$name} = $def;
1667 sub set_domain(\%$) {
1668 my ($rule, $domain) = @_;
1670 return unless check_domain($domain);
1672 my $domain_family;
1673 unless (ref $domain) {
1674 $domain_family = $domain eq 'ip6' ? 'ip' : $domain;
1675 } elsif (@$domain == 0) {
1676 $domain_family = 'none';
1677 } elsif (grep { not /^ip6?$/s } @$domain) {
1678 error('Cannot combine non-IP domains');
1679 } else {
1680 $domain_family = 'ip';
1683 $rule->{domain_family} = $domain_family;
1684 $rule->{keywords} = $match_defs{$domain_family}{''}{keywords};
1685 $rule->{cow}{keywords} = 1;
1687 $rule->{domain} = $stack[0]{auto}{DOMAIN} = $domain;
1690 sub set_target(\%$$) {
1691 my ($rule, $name, $value) = @_;
1692 error('There can only one action per rule')
1693 if exists $rule->{has_action};
1694 $rule->{has_action} = 1;
1695 append_option(%$rule, $name, $value);
1698 sub set_module_target(\%$$) {
1699 my ($rule, $name, $defs) = @_;
1701 if ($name eq 'TCPMSS') {
1702 my $protos = $rule->{protocol};
1703 error('No protocol specified before TCPMSS')
1704 unless defined $protos;
1705 foreach my $proto (to_array $protos) {
1706 error('TCPMSS not available for protocol "$proto"')
1707 unless $proto eq 'tcp';
1711 # in ebtables, there is both "--mark" and "-j mark"... workaround:
1712 $name = 'mark' if $name eq 'MARK' and $rule->{domain_family} eq 'eb';
1714 set_target(%$rule, 'jump', $name);
1715 merge_keywords(%$rule, $defs->{keywords});
1718 # the main parser loop: read tokens, convert them into internal rule
1719 # structures
1720 sub enter($$) {
1721 my $lev = shift; # current recursion depth
1722 my $prev = shift; # previous rule hash
1724 # enter is the core of the firewall setup, it is a
1725 # simple parser program that recognizes keywords and
1726 # retreives parameters to set up the kernel routing
1727 # chains
1729 my $base_level = $script->{base_level} || 0;
1730 die if $base_level > $lev;
1732 my %rule;
1733 new_level(%rule, $prev);
1735 # read keywords 1 by 1 and dump into parser
1736 while (defined (my $keyword = next_token())) {
1737 # check if the current rule should be negated
1738 my $negated = $keyword eq '!';
1739 if ($negated) {
1740 # negation. get the next word which contains the 'real'
1741 # rule
1742 $keyword = getvar();
1744 error('unexpected end of file after negation')
1745 unless defined $keyword;
1748 # the core: parse all data
1749 for ($keyword)
1751 # deprecated keyword?
1752 if (exists $deprecated_keywords{$keyword}) {
1753 my $new_keyword = $deprecated_keywords{$keyword};
1754 warning("'$keyword' is deprecated, please use '$new_keyword' instead");
1755 $keyword = $new_keyword;
1758 # effectuation operator
1759 if ($keyword eq ';') {
1760 error('Empty rule before ";" not allowed')
1761 unless $rule{non_empty};
1763 if ($rule{has_rule} and not exists $rule{has_action}) {
1764 # something is wrong when a rule was specified,
1765 # but no action
1766 error('No action defined; did you mean "NOP"?');
1769 error('No chain defined') unless exists $rule{chain};
1771 $rule{script} = { filename => $script->{filename},
1772 line => $script->{line},
1775 mkrules(\%rule);
1777 # and clean up variables set in this level
1778 new_level(%rule, $prev);
1780 next;
1783 # conditional expression
1784 if ($keyword eq '@if') {
1785 unless (eval_bool(getvalues)) {
1786 collect_tokens;
1787 my $token = peek_token();
1788 if ($token and $token eq '@else') {
1789 require_next_token();
1790 } else {
1791 new_level(%rule, $prev);
1795 next;
1798 if ($keyword eq '@else') {
1799 # hack: if this "else" has not been eaten by the "if"
1800 # handler above, we believe it came from an if clause
1801 # which evaluated "true" - remove the "else" part now.
1802 collect_tokens;
1803 next;
1806 # hooks for custom shell commands
1807 if ($keyword eq 'hook') {
1808 warning("'hook' is deprecated, use '\@hook'");
1809 $keyword = '@hook';
1812 if ($keyword eq '@hook') {
1813 error('"hook" must be the first token in a command')
1814 if exists $rule{domain};
1816 my $position = getvar();
1817 my $hooks;
1818 if ($position eq 'pre') {
1819 $hooks = \@pre_hooks;
1820 } elsif ($position eq 'post') {
1821 $hooks = \@post_hooks;
1822 } elsif ($position eq 'flush') {
1823 $hooks = \@flush_hooks;
1824 } else {
1825 error("Invalid hook position: '$position'");
1828 push @$hooks, getvar();
1830 expect_token(';');
1831 next;
1834 # recursing operators
1835 if ($keyword eq '{') {
1836 # push stack
1837 my $old_stack_depth = @stack;
1839 unshift @stack, { auto => { %{$stack[0]{auto} || {}} } };
1841 # recurse
1842 enter($lev + 1, \%rule);
1844 # pop stack
1845 shift @stack;
1846 die unless @stack == $old_stack_depth;
1848 # after a block, the command is finished, clear this
1849 # level
1850 new_level(%rule, $prev);
1852 next;
1855 if ($keyword eq '}') {
1856 error('Unmatched "}"')
1857 if $lev <= $base_level;
1859 # consistency check: check if they havn't forgotten
1860 # the ';' after the last statement
1861 error('Missing semicolon before "}"')
1862 if $rule{non_empty};
1864 # and exit
1865 return;
1868 # include another file
1869 if ($keyword eq '@include' or $keyword eq 'include') {
1870 my @files = collect_filenames to_array getvalues;
1871 $keyword = next_token;
1872 error('Missing ";" - "include FILENAME" must be the last command in a rule')
1873 unless defined $keyword and $keyword eq ';';
1875 foreach my $filename (@files) {
1876 # save old script, open new script
1877 my $old_script = $script;
1878 open_script($filename);
1879 $script->{base_level} = $lev + 1;
1881 # push stack
1882 my $old_stack_depth = @stack;
1884 my $stack = {};
1886 if (@stack > 0) {
1887 # include files may set variables for their parent
1888 $stack->{vars} = ($stack[0]{vars} ||= {});
1889 $stack->{functions} = ($stack[0]{functions} ||= {});
1890 $stack->{auto} = { %{ $stack[0]{auto} || {} } };
1893 my( $volume,$dirs,$file ) = File::Spec->splitpath( $filename );
1894 $stack->{auto}{FILENAME} = $filename;
1895 $stack->{auto}{FILEBNAME} = $file;
1896 $stack->{auto}{DIRNAME} = $dirs;
1898 unshift @stack, $stack;
1900 # parse the script
1901 enter($lev + 1, \%rule);
1903 # pop stack
1904 shift @stack;
1905 die unless @stack == $old_stack_depth;
1907 # restore old script
1908 $script = $old_script;
1911 next;
1914 # definition of a variable or function
1915 if ($keyword eq '@def' or $keyword eq 'def') {
1916 error('"def" must be the first token in a command')
1917 if $rule{non_empty};
1919 my $type = require_next_token();
1920 if ($type eq '$') {
1921 my $name = require_next_token();
1922 error('invalid variable name')
1923 unless $name =~ /^\w+$/;
1925 expect_token('=');
1927 my $value = getvalues(undef, allow_negation => 1);
1929 expect_token(';');
1931 $stack[0]{vars}{$name} = $value
1932 unless exists $stack[-1]{vars}{$name};
1933 } elsif ($type eq '&') {
1934 my $name = require_next_token();
1935 error('invalid function name')
1936 unless $name =~ /^\w+$/;
1938 expect_token('(', 'function parameter list or "()" expected');
1940 my @params;
1941 while (1) {
1942 my $token = require_next_token();
1943 last if $token eq ')';
1945 if (@params > 0) {
1946 error('"," expected')
1947 unless $token eq ',';
1949 $token = require_next_token();
1952 error('"$" and parameter name expected')
1953 unless $token eq '$';
1955 $token = require_next_token();
1956 error('invalid function parameter name')
1957 unless $token =~ /^\w+$/;
1959 push @params, $token;
1962 my %function;
1964 $function{params} = \@params;
1966 expect_token('=');
1968 my $tokens = collect_tokens();
1969 $function{block} = 1 if grep { $_ eq '{' } @$tokens;
1970 $function{tokens} = $tokens;
1972 $stack[0]{functions}{$name} = \%function
1973 unless exists $stack[-1]{functions}{$name};
1974 } else {
1975 error('"$" (variable) or "&" (function) expected');
1978 next;
1981 # this rule has something which isn't inherited by its
1982 # parent closure. This variable is used in a lot of
1983 # syntax checks.
1985 $rule{non_empty} = 1;
1987 # def references
1988 if ($keyword eq '$') {
1989 error('variable references are only allowed as keyword parameter');
1992 if ($keyword eq '&') {
1993 my $name = require_next_token();
1994 error('function name expected')
1995 unless $name =~ /^\w+$/;
1997 my $function;
1998 foreach (@stack) {
1999 $function = $_->{functions}{$name};
2000 last if defined $function;
2002 error("no such function: \&$name")
2003 unless defined $function;
2005 my $paramdef = $function->{params};
2006 die unless defined $paramdef;
2008 my @params = get_function_params(allow_negation => 1);
2010 error("Wrong number of parameters for function '\&$name': "
2011 . @$paramdef . " expected, " . @params . " given")
2012 unless @params == @$paramdef;
2014 my %vars;
2015 for (my $i = 0; $i < @params; $i++) {
2016 $vars{$paramdef->[$i]} = $params[$i];
2019 if ($function->{block}) {
2020 # block {} always ends the current rule, so if the
2021 # function contains a block, we have to require
2022 # the calling rule also ends here
2023 expect_token(';');
2026 my @tokens = @{$function->{tokens}};
2027 for (my $i = 0; $i < @tokens; $i++) {
2028 if ($tokens[$i] eq '$' and $i + 1 < @tokens and
2029 exists $vars{$tokens[$i + 1]}) {
2030 my @value = to_array($vars{$tokens[$i + 1]});
2031 @value = ('(', @value, ')')
2032 unless @tokens == 1;
2033 splice(@tokens, $i, 2, @value);
2034 $i += @value - 2;
2035 } elsif ($tokens[$i] =~ m,^"(.*)"$,) {
2036 $tokens[$i] =~ s,\$(\w+),exists $vars{$1} ? $vars{$1} : "\$$1",eg;
2040 unshift @{$script->{tokens}}, @tokens;
2042 next;
2045 # where to put the rule?
2046 if ($keyword eq 'domain') {
2047 error('Domain is already specified')
2048 if exists $rule{domain};
2050 my $domains = getvalues();
2051 if (ref $domains) {
2052 my $tokens = collect_tokens(include_semicolon => 1,
2053 include_else => 1);
2055 my $old_line = $script->{line};
2056 my $old_handle = $script->{handle};
2057 my $old_tokens = $script->{tokens};
2058 unshift @$old_tokens, make_line_token($script->{line});
2059 delete $script->{handle};
2061 for my $domain (@$domains) {
2062 my %inner;
2063 new_level(%inner, \%rule);
2064 set_domain(%inner, $domain) or next;
2065 $script->{tokens} = [ @$tokens ];
2066 enter($lev, \%inner);
2069 $script->{tokens} = $old_tokens;
2070 $script->{handle} = $old_handle;
2071 $script->{line} = $old_line;
2073 new_level(%rule, $prev);
2074 } else {
2075 unless (set_domain(%rule, $domains)) {
2076 collect_tokens();
2077 new_level(%rule, $prev);
2081 next;
2084 if ($keyword eq 'table') {
2085 warning('Table is already specified')
2086 if exists $rule{table};
2087 $rule{table} = $stack[0]{auto}{TABLE} = getvalues();
2089 set_domain(%rule, $option{domain} || 'ip')
2090 unless exists $rule{domain};
2092 next;
2095 if ($keyword eq 'chain') {
2096 warning('Chain is already specified')
2097 if exists $rule{chain};
2099 my $chain = $rule{chain} = $stack[0]{auto}{CHAIN} = getvalues();
2101 # ferm 1.1 allowed lower case built-in chain names
2102 foreach (ref $rule{chain} ? @{$rule{chain}} : $rule{chain}) {
2103 error('Please write built-in chain names in upper case')
2104 if /^(?:input|forward|output|prerouting|postrouting)$/;
2107 set_domain(%rule, $option{domain} || 'ip')
2108 unless exists $rule{domain};
2110 $rule{table} = 'filter'
2111 unless exists $rule{table};
2113 my $domain = $rule{domain};
2114 foreach my $table (to_array $rule{table}) {
2115 foreach my $c (to_array $chain) {
2116 $domains{$domain}{tables}{$table}{chains}{$c} ||= {};
2120 next;
2123 error('Chain must be specified')
2124 unless exists $rule{chain};
2126 # policy for built-in chain
2127 if ($keyword eq 'policy') {
2128 error('Cannot specify matches for policy')
2129 if $rule{has_rule};
2131 my $policy = getvar();
2132 error("Invalid policy target: $policy")
2133 unless $policy =~ /^(?:ACCEPT|DROP)$/;
2135 expect_token(';');
2137 my $domain = $rule{domain};
2138 my $domain_info = $domains{$domain};
2139 $domain_info->{enabled} = 1;
2141 foreach my $table (to_array $rule{table}) {
2142 foreach my $chain (to_array $rule{chain}) {
2143 $domain_info->{tables}{$table}{chains}{$chain}{policy} = $policy;
2147 new_level(%rule, $prev);
2148 next;
2151 # create a subchain
2152 if ($keyword eq '@subchain' or $keyword eq 'subchain') {
2153 error('Chain must be specified')
2154 unless exists $rule{chain};
2156 error('No rule specified before "@subchain"')
2157 unless $rule{has_rule};
2159 my $subchain;
2160 my $token = peek_token();
2162 if ($token =~ /^(["'])(.*)\1$/s) {
2163 $subchain = $2;
2164 next_token();
2165 $keyword = next_token();
2166 } elsif ($token eq '{') {
2167 $keyword = next_token();
2168 $subchain = 'ferm_auto_' . ++$auto_chain;
2169 } else {
2170 $subchain = getvar();
2171 $keyword = next_token();
2174 my $domain = $rule{domain};
2175 foreach my $table (to_array $rule{table}) {
2176 $domains{$domain}{tables}{$table}{chains}{$subchain} ||= {};
2179 set_target(%rule, 'jump', $subchain);
2181 error('"{" or chain name expected after "@subchain"')
2182 unless $keyword eq '{';
2184 # create a deep copy of %rule, only containing values
2185 # which must be in the subchain
2186 my %inner = ( cow => { keywords => 1, },
2187 match => {},
2188 options => [],
2190 $inner{$_} = $rule{$_} foreach qw(domain domain_family table keywords);
2191 $inner{chain} = $inner{auto}{CHAIN} = $subchain;
2193 if (exists $rule{protocol}) {
2194 $inner{protocol} = $rule{protocol};
2195 append_option(%inner, 'protocol', $inner{protocol});
2198 # create a new stack frame
2199 my $old_stack_depth = @stack;
2200 my $stack = { auto => { %{$stack[0]{auto} || {}} } };
2201 $stack->{auto}{CHAIN} = $subchain;
2202 unshift @stack, $stack;
2204 # enter the block
2205 enter($lev + 1, \%inner);
2207 # pop stack frame
2208 shift @stack;
2209 die unless @stack == $old_stack_depth;
2211 # now handle the parent - it's a jump to the sub chain
2212 $rule{script} = {
2213 filename => $script->{filename},
2214 line => $script->{line},
2217 mkrules(\%rule);
2219 # and clean up variables set in this level
2220 new_level(%rule, $prev);
2221 delete $rule{has_rule};
2223 next;
2226 # everything else must be part of a "real" rule, not just
2227 # "policy only"
2228 $rule{has_rule} = 1;
2230 # extended parameters:
2231 if ($keyword =~ /^mod(?:ule)?$/) {
2232 foreach my $module (to_array getvalues) {
2233 next if exists $rule{match}{$module};
2235 my $domain_family = $rule{domain_family};
2236 my $defs = $match_defs{$domain_family}{$module};
2238 append_option(%rule, 'match', $module);
2239 $rule{match}{$module} = 1;
2241 merge_keywords(%rule, $defs->{keywords})
2242 if defined $defs;
2245 next;
2248 # keywords from $rule{keywords}
2250 if (exists $rule{keywords}{$keyword}) {
2251 my $def = $rule{keywords}{$keyword};
2252 parse_option($def, %rule, \$negated);
2253 next;
2257 # actions
2260 # jump action
2261 if ($keyword eq 'jump') {
2262 set_target(%rule, 'jump', getvar());
2263 next;
2266 # goto action
2267 if ($keyword eq 'realgoto') {
2268 set_target(%rule, 'goto', getvar());
2269 next;
2272 # action keywords
2273 if (is_netfilter_core_target($keyword)) {
2274 set_target(%rule, 'jump', $keyword);
2275 next;
2278 if ($keyword eq 'NOP') {
2279 error('There can only one action per rule')
2280 if exists $rule{has_action};
2281 $rule{has_action} = 1;
2282 next;
2285 if (my $defs = is_netfilter_module_target($rule{domain_family}, $keyword)) {
2286 set_module_target(%rule, $keyword, $defs);
2287 next;
2291 # protocol specific options
2294 if ($keyword eq 'proto' or $keyword eq 'protocol') {
2295 my $protocol = parse_keyword(%rule,
2296 { params => 1, negation => 1 },
2297 \$negated);
2298 $rule{protocol} = $protocol;
2299 append_option(%rule, 'protocol', $rule{protocol});
2301 unless (ref $protocol) {
2302 $protocol = netfilter_canonical_protocol($protocol);
2303 my $domain_family = $rule{domain_family};
2304 if (my $defs = $proto_defs{$domain_family}{$protocol}) {
2305 merge_keywords(%rule, $defs->{keywords});
2306 my $module = netfilter_protocol_module($protocol);
2307 $rule{match}{$module} = 1;
2310 next;
2313 # port switches
2314 if ($keyword =~ /^[sd]port$/) {
2315 my $proto = $rule{protocol};
2316 error('To use sport or dport, you have to specify "proto tcp" or "proto udp" first')
2317 unless defined $proto and grep { /^(?:tcp|udp|udplite|dccp|sctp)$/ } to_array $proto;
2319 append_option(%rule, $keyword,
2320 getvalues(undef, allow_negation => 1));
2321 next;
2324 # default
2325 error("Unrecognized keyword: $keyword");
2328 # if the rule didn't reset the negated flag, it's not
2329 # supported
2330 error("Doesn't support negation: $keyword")
2331 if $negated;
2334 error('Missing "}" at end of file')
2335 if $lev > $base_level;
2337 # consistency check: check if they havn't forgotten
2338 # the ';' before the last statement
2339 error("Missing semicolon before end of file")
2340 if $rule{non_empty};
2343 sub execute_command {
2344 my ($command, $script) = @_;
2346 print LINES "$command\n"
2347 if $option{lines};
2348 return if $option{noexec};
2350 my $ret = system($command);
2351 unless ($ret == 0) {
2352 if ($? == -1) {
2353 print STDERR "failed to execute: $!\n";
2354 exit 1;
2355 } elsif ($? & 0x7f) {
2356 printf STDERR "child died with signal %d\n", $? & 0x7f;
2357 return 1;
2358 } else {
2359 print STDERR "(rule declared in $script->{filename}:$script->{line})\n"
2360 if defined $script;
2361 return $? >> 8;
2365 return;
2368 sub execute_slow($) {
2369 my $domain_info = shift;
2371 my $domain_cmd = $domain_info->{tools}{tables};
2373 my $status;
2374 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2375 my $table_cmd = "$domain_cmd -t $table";
2377 # reset chain policies
2378 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2379 next unless $chain_info->{builtin} or
2380 (not $table_info->{has_builtin} and
2381 is_netfilter_builtin_chain($table, $chain));
2382 $status ||= execute_command("$table_cmd -P $chain ACCEPT")
2383 unless $option{noflush};
2386 # clear
2387 unless ($option{noflush}) {
2388 $status ||= execute_command("$table_cmd -F");
2389 $status ||= execute_command("$table_cmd -X");
2392 next if $option{flush};
2394 # create chains / set policy
2395 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2396 if (exists $chain_info->{policy}) {
2397 $status ||= execute_command("$table_cmd -P $chain $chain_info->{policy}")
2398 unless $chain_info->{policy} eq 'ACCEPT';
2399 } elsif (not is_netfilter_builtin_chain($table, $chain)) {
2400 $status ||= execute_command("$table_cmd -N $chain");
2404 # dump rules
2405 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2406 my $chain_cmd = "$table_cmd -A $chain";
2407 foreach my $rule (@{$chain_info->{rules}}) {
2408 $status ||= execute_command($chain_cmd . $rule->{rule});
2413 return $status;
2416 sub table_to_save($$) {
2417 my ($result_r, $table_info) = @_;
2419 foreach my $chain (sort keys %{$table_info->{chains}}) {
2420 my $chain_info = $table_info->{chains}{$chain};
2421 foreach my $rule (@{$chain_info->{rules}}) {
2422 $$result_r .= "-A $chain$rule->{rule}\n";
2427 sub rules_to_save($) {
2428 my ($domain_info) = @_;
2430 # convert this into an iptables-save text
2431 my $result = "# Generated by ferm $VERSION on " . localtime() . "\n";
2433 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2434 # select table
2435 $result .= '*' . $table . "\n";
2437 # create chains / set policy
2438 foreach my $chain (sort keys %{$table_info->{chains}}) {
2439 my $chain_info = $table_info->{chains}{$chain};
2440 my $policy = $option{flush} ? undef : $chain_info->{policy};
2441 unless (defined $policy) {
2442 if (is_netfilter_builtin_chain($table, $chain)) {
2443 $policy = 'ACCEPT';
2444 } else {
2445 next if $option{flush};
2446 $policy = '-';
2449 $result .= ":$chain $policy\ [0:0]\n";
2452 table_to_save(\$result, $table_info)
2453 unless $option{flush};
2455 # do it
2456 $result .= "COMMIT\n";
2459 return $result;
2462 sub restore_domain($$) {
2463 my ($domain_info, $save) = @_;
2465 my $path = $domain_info->{tools}{'tables-restore'};
2466 $path .= " --noflush" if $option{noflush};
2468 local *RESTORE;
2469 open RESTORE, "|$path"
2470 or die "Failed to run $path: $!\n";
2472 print RESTORE $save;
2474 close RESTORE
2475 or die "Failed to run $path\n";
2478 sub execute_fast($) {
2479 my $domain_info = shift;
2481 my $save = rules_to_save($domain_info);
2483 if ($option{lines}) {
2484 my $path = $domain_info->{tools}{'tables-restore'};
2485 $path .= " --noflush" if $option{noflush};
2486 print LINES "$path <<EOT\n"
2487 if $option{shell};
2488 print LINES $save;
2489 print LINES "EOT\n"
2490 if $option{shell};
2493 return if $option{noexec};
2495 eval {
2496 restore_domain($domain_info, $save);
2498 if ($@) {
2499 print STDERR $@;
2500 return 1;
2503 return;
2506 sub rollback() {
2507 my $error;
2508 while (my ($domain, $domain_info) = each %domains) {
2509 next unless $domain_info->{enabled};
2510 unless (defined $domain_info->{tools}{'tables-restore'}) {
2511 print STDERR "Cannot rollback domain '$domain' because there is no ${domain}tables-restore\n";
2512 next;
2515 my $reset = '';
2516 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2517 my $reset_chain = '';
2518 foreach my $chain (keys %{$table_info->{chains}}) {
2519 next unless is_netfilter_builtin_chain($table, $chain);
2520 $reset_chain .= ":${chain} ACCEPT [0:0]\n";
2522 $reset .= "*${table}\n${reset_chain}COMMIT\n"
2523 if length $reset_chain;
2526 $reset .= $domain_info->{previous}
2527 if defined $domain_info->{previous};
2529 restore_domain($domain_info, $reset);
2532 print STDERR "\nFirewall rules rolled back.\n" unless $error;
2533 exit 1;
2536 sub alrm_handler {
2537 # do nothing, just interrupt a system call
2540 sub confirm_rules {
2541 $SIG{ALRM} = \&alrm_handler;
2543 alarm(5);
2545 print STDERR "\n"
2546 . "ferm has applied the new firewall rules.\n"
2547 . "Please type 'yes' to confirm:\n";
2548 STDERR->flush();
2550 alarm($option{timeout});
2552 my $line = '';
2553 STDIN->sysread($line, 3);
2555 eval {
2556 require POSIX;
2557 POSIX::tcflush(*STDIN, 2);
2559 print STDERR "$@" if $@;
2561 $SIG{ALRM} = 'DEFAULT';
2563 return $line eq 'yes';
2566 # end of ferm
2568 __END__
2570 =head1 NAME
2572 ferm - a firewall rule parser for linux
2574 =head1 SYNOPSIS
2576 B<ferm> I<options> I<inputfiles>
2578 =head1 OPTIONS
2580 -n, --noexec Do not execute the rules, just simulate
2581 -F, --flush Flush all netfilter tables managed by ferm
2582 -l, --lines Show all rules that were created
2583 -i, --interactive Interactive mode: revert if user does not confirm
2584 -t, --timeout s Define interactive mode timeout in seconds
2585 --remote Remote mode; ignore host specific configuration.
2586 This implies --noexec and --lines.
2587 -V, --version Show current version number
2588 -h, --help Look at this text
2589 --slow Slow mode, don't use iptables-restore
2590 --shell Generate a shell script which calls iptables-restore
2591 --domain {ip|ip6} Handle only the specified domain
2592 --def '$name=v' Override a variable
2594 =cut