Add support for TEE target
[ferm.git] / src / ferm
blob92a4d88ab894cc544296054cc78c7a261a5f9106
1 #!/usr/bin/perl
4 # ferm, a firewall setup program that makes firewall rules easy!
6 # Copyright (C) 2001-2012 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.3';
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=c 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 'osf', qw(!genre ttl=s log=s);
270 add_match_def 'owner', qw(!uid-owner !gid-owner pid-owner sid-owner),
271 qw(cmd-owner !socket-exists=0);
272 add_match_def 'physdev', qw(physdev-in! physdev-out!),
273 qw(!physdev-is-in*0 !physdev-is-out*0 !physdev-is-bridged*0);
274 add_match_def 'pkttype', qw(pkt-type!),
275 add_match_def 'policy',
276 qw(dir pol strict*0 !reqid !spi !proto !mode !tunnel-src !tunnel-dst next*0);
277 add_match_def 'psd', qw(psd-weight-threshold psd-delay-threshold),
278 qw(psd-lo-ports-weight psd-hi-ports-weight);
279 add_match_def 'quota', qw(quota=s);
280 add_match_def 'random', qw(average);
281 add_match_def 'realm', qw(realm!);
282 add_match_def 'recent', qw(name=s !set*0 !remove*0 !rcheck*0 !update*0 !seconds !hitcount rttl*0 rsource*0 rdest*0);
283 add_match_def 'rt', qw(rt-type! rt-segsleft! rt-len! rt-0-res*0 rt-0-addrs=c rt-0-not-strict*0);
284 add_match_def 'set', qw(!match-set=sc set:=match-set);
285 add_match_def 'state', qw(!state=c);
286 add_match_def 'statistic', qw(mode=s probability=s every=s packet=s);
287 add_match_def 'string', qw(algo=s from=s to=s string hex-string);
288 add_match_def 'tcpmss', qw(!mss);
289 add_match_def 'time', qw(timestart=s timestop=s days=c datestart=s datestop=s),
290 qw(!monthday=c !weekdays=c utc*0 localtz*0);
291 add_match_def 'tos', qw(!tos);
292 add_match_def 'ttl', qw(ttl-eq ttl-lt=s ttl-gt=s);
293 add_match_def 'u32', qw(!u32=m);
295 add_target_def 'BALANCE', qw(to-destination to:=to-destination);
296 add_target_def 'CLASSIFY', qw(set-class);
297 add_target_def 'CLUSTERIP', qw(new*0 hashmode clustermac total-nodes local-node hash-init);
298 add_target_def 'CONNMARK', qw(set-mark save-mark*0 restore-mark*0 mask);
299 add_target_def 'CONNSECMARK', qw(save*0 restore*0);
300 add_target_def 'DNAT', qw(to-destination=m to:=to-destination persistent*0 random*0);
301 add_target_def 'DSCP', qw(set-dscp set-dscp-class);
302 add_target_def 'ECN', qw(ecn-tcp-remove*0);
303 add_target_def 'HL', qw(hl-set hl-dec hl-inc);
304 add_target_def 'IPV4OPTSSTRIP';
305 add_target_def 'LOG', qw(log-level log-prefix),
306 qw(log-tcp-sequence*0 log-tcp-options*0 log-ip-options*0 log-uid*0);
307 add_target_def 'MARK', qw(set-mark set-xmark and-mark or-mark xor-mark);
308 add_target_def 'MASQUERADE', qw(to-ports random*0);
309 add_target_def 'MIRROR';
310 add_target_def 'NETMAP', qw(to);
311 add_target_def 'NFLOG', qw(nflog-group nflog-prefix nflog-range nflog-threshold);
312 add_target_def 'NFQUEUE', qw(queue-num);
313 add_target_def 'NOTRACK';
314 add_target_def 'REDIRECT', qw(to-ports random*0);
315 add_target_def 'REJECT', qw(reject-with);
316 add_target_def 'ROUTE', qw(oif iif gw continue*0 tee*0);
317 add_target_def 'SAME', qw(to nodst*0 random*0);
318 add_target_def 'SECMARK', qw(selctx);
319 add_target_def 'SET', qw(add-set=sc del-set=sc);
320 add_target_def 'SNAT', qw(to-source=m to:=to-source persistent*0 random*0);
321 add_target_def 'TARPIT';
322 add_target_def 'TCPMSS', qw(set-mss clamp-mss-to-pmtu*0);
323 add_target_def 'TEE', qw(gateway);
324 add_target_def 'TOS', qw(set-tos and-tos or-tos xor-tos);
325 add_target_def 'TPROXY', qw(tproxy-mark on-port);
326 add_target_def 'TRACE';
327 add_target_def 'TTL', qw(ttl-set ttl-dec ttl-inc);
328 add_target_def 'ULOG', qw(ulog-nlgroup ulog-prefix ulog-cprange ulog-qthreshold);
330 add_match_def_x 'arp', '',
331 # ip
332 qw(source-ip! destination-ip! saddr:=source-ip daddr:=destination-ip),
333 # mac
334 qw(source-mac! destination-mac!),
335 # --in-interface
336 qw(in-interface! interface:=in-interface if:=in-interface),
337 # --out-interface
338 qw(out-interface! outerface:=out-interface of:=out-interface),
339 # misc
340 qw(h-length=s opcode=s h-type=s proto-type=s),
341 qw(mangle-ip-s=s mangle-ip-d=s mangle-mac-s=s mangle-mac-d=s mangle-target=s);
343 add_proto_def_x 'eb', 'IPv4',
344 qw(ip-source! ip-destination! ip-src:=ip-source ip-dst:=ip-destination),
345 qw(ip-tos!),
346 qw(ip-protocol! ip-proto:=ip-protocol),
347 qw(ip-source-port! ip-sport:=ip-source-port),
348 qw(ip-destination-port! ip-dport:=ip-destination-port);
350 add_proto_def_x 'eb', 'IPv6',
351 qw(ip6-source! ip6-destination! ip6-src:=ip6-source ip6-dst:=ip6-destination),
352 qw(ip6-tclass!),
353 qw(ip6-protocol! ip6-proto:=ip6-protocol),
354 qw(ip6-source-port! ip6-sport:=ip6-source-port),
355 qw(ip6-destination-port! ip6-dport:=ip6-destination-port);
357 add_proto_def_x 'eb', 'ARP',
358 qw(!arp-gratuitous*0),
359 qw(arp-opcode! arp-htype!=ss arp-ptype!=ss),
360 qw(arp-ip-src! arp-ip-dst! arp-mac-src! arp-mac-dst!);
362 add_proto_def_x 'eb', 'RARP',
363 qw(!arp-gratuitous*0),
364 qw(arp-opcode! arp-htype!=ss arp-ptype!=ss),
365 qw(arp-ip-src! arp-ip-dst! arp-mac-src! arp-mac-dst!);
367 add_proto_def_x 'eb', '802_1Q',
368 qw(vlan-id! vlan-prio! vlan-encap!),
370 add_match_def_x 'eb', '',
371 # --in-interface
372 qw(in-interface! interface:=in-interface if:=in-interface),
373 # --out-interface
374 qw(out-interface! outerface:=out-interface of:=out-interface),
375 # logical interface
376 qw(logical-in! logical-out!),
377 # --source, --destination
378 qw(source! saddr:=source destination! daddr:=destination),
379 # 802.3
380 qw(802_3-sap! 802_3-type!),
381 # among
382 qw(!among-dst=c !among-src=c !among-dst-file !among-src-file),
383 # limit
384 qw(limit=s limit-burst=s),
385 # mark_m
386 qw(mark!),
387 # pkttype
388 qw(pkttype-type!),
389 # stp
390 qw(stp-type! stp-flags! stp-root-prio! stp-root-addr! stp-root-cost!),
391 qw(stp-sender-prio! stp-sender-addr! stp-port! stp-msg-age! stp-max-age!),
392 qw(stp-hello-time! stp-forward-delay!),
393 # log
394 qw(log*0 log-level=s log-prefix=s log-ip*0 log-arp*0);
396 add_target_def_x 'eb', 'arpreply', qw(arpreply-mac arpreply-target);
397 add_target_def_x 'eb', 'dnat', qw(to-destination dnat-target);
398 add_target_def_x 'eb', 'MARK', qw(set-mark mark-target);
399 add_target_def_x 'eb', 'redirect', qw(redirect-target);
400 add_target_def_x 'eb', 'snat', qw(to-source snat-target snat-arp*0);
402 # import-ferm uses the above tables
403 return 1 if $0 =~ /import-ferm$/;
405 # parameter parser for ipt_multiport
406 sub multiport_params {
407 my $rule = shift;
409 # multiport only allows 15 ports at a time. For this
410 # reason, we do a little magic here: split the ports
411 # into portions of 15, and handle these portions as
412 # array elements
414 my $proto = $rule->{protocol};
415 error('To use multiport, you have to specify "proto tcp" or "proto udp" first')
416 unless defined $proto and grep { /^(?:tcp|udp|udplite)$/ } to_array($proto);
418 my $value = getvalues(undef, allow_negation => 1,
419 allow_array_negation => 1);
420 if (ref $value and ref $value eq 'ARRAY') {
421 my @value = @$value;
422 my @params;
424 while (@value) {
425 push @params, join(',', splice(@value, 0, 15));
428 return @params == 1
429 ? $params[0]
430 : \@params;
431 } else {
432 return join_value(',', $value);
436 # initialize stack: command line definitions
437 unshift @stack, {};
439 # Get command line stuff
440 if ($has_getopt) {
441 my ($opt_noexec, $opt_flush, $opt_noflush, $opt_lines, $opt_interactive,
442 $opt_timeout, $opt_help,
443 $opt_version, $opt_test, $opt_fast, $opt_slow, $opt_shell,
444 $opt_domain);
446 Getopt::Long::Configure('bundling', 'auto_help', 'no_ignore_case',
447 'no_auto_abbrev');
449 sub opt_def {
450 my ($opt, $value) = @_;
451 die 'Invalid --def specification'
452 unless $value =~ /^\$?(\w+)=(.*)$/s;
453 my ($name, $unparsed_value) = ($1, $2);
454 my $tokens = tokenize_string($unparsed_value);
455 $value = getvalues(sub { shift @$tokens; });
456 die 'Extra tokens after --def'
457 if @$tokens > 0;
458 $stack[0]{vars}{$name} = $value;
461 local $SIG{__WARN__} = sub { die $_[0]; };
462 GetOptions('noexec|n' => \$opt_noexec,
463 'flush|F' => \$opt_flush,
464 'noflush' => \$opt_noflush,
465 'lines|l' => \$opt_lines,
466 'interactive|i' => \$opt_interactive,
467 'timeout|t=s' => \$opt_timeout,
468 'help|h' => \$opt_help,
469 'version|V' => \$opt_version,
470 test => \$opt_test,
471 remote => \$opt_test,
472 fast => \$opt_fast,
473 slow => \$opt_slow,
474 shell => \$opt_shell,
475 'domain=s' => \$opt_domain,
476 'def=s' => \&opt_def,
479 if (defined $opt_help) {
480 require Pod::Usage;
481 Pod::Usage::pod2usage(-exitstatus => 0);
484 if (defined $opt_version) {
485 printversion();
486 exit 0;
489 $option{noexec} = $opt_noexec || $opt_test;
490 $option{flush} = $opt_flush;
491 $option{noflush} = $opt_noflush;
492 $option{lines} = $opt_lines || $opt_test || $opt_shell;
493 $option{interactive} = $opt_interactive && !$opt_noexec;
494 $option{timeout} = defined $opt_timeout ? $opt_timeout : "30";
495 $option{test} = $opt_test;
496 $option{fast} = !$opt_slow;
497 $option{shell} = $opt_shell;
499 die("ferm interactive mode not possible: /dev/stdin is not a tty\n")
500 if $option{interactive} and not -t STDIN;
501 die("ferm interactive mode not possible: /dev/stderr is not a tty\n")
502 if $option{interactive} and not -t STDERR;
503 die("ferm timeout has no sense without interactive mode")
504 if not $opt_interactive and defined $opt_timeout;
505 die("invalid timeout. must be an integer")
506 if defined $opt_timeout and not $opt_timeout =~ /^[+-]?\d+$/;
508 $option{domain} = $opt_domain if defined $opt_domain;
509 } else {
510 # tiny getopt emulation for microperl
511 my $filename;
512 foreach (@ARGV) {
513 if ($_ eq '--noexec' or $_ eq '-n') {
514 $option{noexec} = 1;
515 } elsif ($_ eq '--lines' or $_ eq '-l') {
516 $option{lines} = 1;
517 } elsif ($_ eq '--fast') {
518 $option{fast} = 1;
519 } elsif ($_ eq '--test') {
520 $option{test} = 1;
521 $option{noexec} = 1;
522 $option{lines} = 1;
523 } elsif ($_ eq '--shell') {
524 $option{$_} = 1 foreach qw(shell fast lines);
525 } elsif (/^-/) {
526 printf STDERR "Usage: ferm [--noexec] [--lines] [--fast] [--shell] FILENAME\n";
527 exit 1;
528 } else {
529 $filename = $_;
532 undef @ARGV;
533 push @ARGV, $filename;
536 unless (@ARGV == 1) {
537 require Pod::Usage;
538 Pod::Usage::pod2usage(-exitstatus => 1);
541 if ($has_strict) {
542 open LINES, ">&STDOUT" if $option{lines};
543 open STDOUT, ">&STDERR" if $option{shell};
544 } else {
545 # microperl can't redirect file handles
546 *LINES = *STDOUT;
548 if ($option{fast} and not $option{noexec}) {
549 print STDERR "Sorry, ferm on microperl does not allow --fast without --noexec\n";
550 exit 1
554 unshift @stack, {};
555 open_script($ARGV[0]);
557 my( $volume,$dirs,$file ) = File::Spec->splitpath( $ARGV[0] );
558 $stack[0]{auto}{FILENAME} = $ARGV[0];
559 $stack[0]{auto}{FILEBNAME} = $file;
560 $stack[0]{auto}{DIRNAME} = $dirs;
564 # parse all input recursively
565 enter(0, undef);
566 die unless @stack == 2;
568 # enable/disable hooks depending on --flush
570 if ($option{flush}) {
571 undef @pre_hooks;
572 undef @post_hooks;
573 } else {
574 undef @flush_hooks;
577 # execute all generated rules
578 my $status;
580 foreach my $cmd (@pre_hooks) {
581 print LINES "$cmd\n" if $option{lines};
582 system($cmd) unless $option{noexec};
585 while (my ($domain, $domain_info) = each %domains) {
586 next unless $domain_info->{enabled};
587 my $s = $option{fast} &&
588 defined $domain_info->{tools}{'tables-restore'}
589 ? execute_fast($domain_info) : execute_slow($domain_info);
590 $status = $s if defined $s;
593 foreach my $cmd (@post_hooks, @flush_hooks) {
594 print LINES "$cmd\n" if $option{lines};
595 system($cmd) unless $option{noexec};
598 if (defined $status) {
599 rollback();
600 exit $status;
603 # ask user, and rollback if there is no confirmation
605 if ($option{interactive}) {
606 if ($option{shell}) {
607 print LINES "echo 'ferm has applied the new firewall rules.'\n";
608 print LINES "echo 'Please press Ctrl-C to confirm.'\n";
609 print LINES "sleep $option{timeout}\n";
610 while (my ($domain, $domain_info) = each %domains) {
611 my $restore = $domain_info->{tools}{'tables-restore'};
612 next unless defined $restore;
613 print LINES "$restore <\$${domain}_tmp\n";
617 confirm_rules() or rollback() unless $option{noexec};
620 exit 0;
622 # end of program execution!
625 # funcs
627 sub printversion {
628 print "ferm $VERSION\n";
629 print "Copyright (C) 2001-2012 Max Kellermann, Auke Kok\n";
630 print "This program is free software released under GPLv2.\n";
631 print "See the included COPYING file for license details.\n";
635 sub error {
636 # returns a nice formatted error message, showing the
637 # location of the error.
638 my $tabs = 0;
639 my @lines;
640 my $l = 0;
641 my @words = map { @$_ } @{$script->{past_tokens}};
643 for my $w ( 0 .. $#words ) {
644 if ($words[$w] eq "\x29")
645 { $l++ ; $lines[$l] = " " x ($tabs-- -1) ;};
646 if ($words[$w] eq "\x28")
647 { $l++ ; $lines[$l] = " " x $tabs++ ;};
648 if ($words[$w] eq "\x7d")
649 { $l++ ; $lines[$l] = " " x ($tabs-- -1) ;};
650 if ($words[$w] eq "\x7b")
651 { $l++ ; $lines[$l] = " " x $tabs++ ;};
652 if ( $l > $#lines ) { $lines[$l] = "" };
653 $lines[$l] .= $words[$w] . " ";
654 if ($words[$w] eq "\x28")
655 { $l++ ; $lines[$l] = " " x $tabs ;};
656 if (($words[$w] eq "\x29") && ($words[$w+1] ne "\x7b"))
657 { $l++ ; $lines[$l] = " " x $tabs ;};
658 if ($words[$w] eq "\x7b")
659 { $l++ ; $lines[$l] = " " x $tabs ;};
660 if (($words[$w] eq "\x7d") && ($words[$w+1] ne "\x7d"))
661 { $l++ ; $lines[$l] = " " x $tabs ;};
662 if (($words[$w] eq "\x3b") && ($words[$w+1] ne "\x7d"))
663 { $l++ ; $lines[$l] = " " x $tabs ;}
664 if ($words[$w-1] eq "option")
665 { $l++ ; $lines[$l] = " " x $tabs ;}
667 my $start = $#lines - 4;
668 if ($start < 0) { $start = 0 } ;
669 print STDERR "Error in $script->{filename} line $script->{line}:\n";
670 for $l ( $start .. $#lines)
671 { print STDERR $lines[$l]; if ($l != $#lines ) {print STDERR "\n"} ; };
672 print STDERR "<--\n";
673 die("@_\n");
676 # print a warning message about code from an input file
677 sub warning {
678 print STDERR "Warning in $script->{filename} line $script->{line}: "
679 . (shift) . "\n";
682 sub find_tool($) {
683 my $name = shift;
684 return $name if $option{test};
685 for my $path ('/sbin', split ':', $ENV{PATH}) {
686 my $ret = "$path/$name";
687 return $ret if -x $ret;
689 die "$name not found in PATH\n";
692 sub initialize_domain {
693 my $domain = shift;
694 my $domain_info = $domains{$domain} ||= {};
696 return if exists $domain_info->{initialized};
698 die "Invalid domain '$domain'\n" unless $domain =~ /^(?:ip6?|arp|eb)$/;
700 my @tools = qw(tables);
701 push @tools, qw(tables-save tables-restore)
702 if $domain =~ /^ip6?$/;
704 # determine the location of this domain's tools
705 my %tools = map { $_ => find_tool($domain . $_) } @tools;
706 $domain_info->{tools} = \%tools;
708 # make tables-save tell us about the state of this domain
709 # (which tables and chains do exist?), also remember the old
710 # save data which may be used later by the rollback function
711 local *SAVE;
712 if (!$option{test} &&
713 exists $tools{'tables-save'} &&
714 open(SAVE, "$tools{'tables-save'}|")) {
715 my $save = '';
717 my $table_info;
718 while (<SAVE>) {
719 $save .= $_;
721 if (/^\*(\w+)/) {
722 my $table = $1;
723 $table_info = $domain_info->{tables}{$table} ||= {};
724 } elsif (defined $table_info and /^:(\w+)\s+(\S+)/
725 and $2 ne '-') {
726 $table_info->{chains}{$1}{builtin} = 1;
727 $table_info->{has_builtin} = 1;
731 # for rollback
732 $domain_info->{previous} = $save;
735 if ($option{shell} && $option{interactive} &&
736 exists $tools{'tables-save'}) {
737 print LINES "${domain}_tmp=\$(mktemp ferm.XXXXXXXXXX)\n";
738 print LINES "$tools{'tables-save'} >\$${domain}_tmp\n";
741 $domain_info->{initialized} = 1;
744 sub check_domain($) {
745 my $domain = shift;
746 my @result;
748 return if exists $option{domain}
749 and $domain ne $option{domain};
751 eval {
752 initialize_domain($domain);
754 error($@) if $@;
756 return 1;
759 # split the input string into words and delete comments
760 sub tokenize_string($) {
761 my $string = shift;
763 my @ret;
765 foreach my $word ($string =~ m/(".*?"|'.*?'|`.*?`|[!,=&\$\%\(\){};]|[-+\w\/\.:]+|@\w+|#)/g) {
766 last if $word eq '#';
767 push @ret, $word;
770 return \@ret;
773 # generate a "line" special token, that marks the line number; these
774 # special tokens are inserted after each line break, so ferm keeps
775 # track of line numbers
776 sub make_line_token($) {
777 my $line = shift;
778 return bless(\$line, 'line');
781 # read some more tokens from the input file into a buffer
782 sub prepare_tokens() {
783 my $tokens = $script->{tokens};
784 while (@$tokens == 0) {
785 my $handle = $script->{handle};
786 return unless defined $handle;
787 my $line = <$handle>;
788 return unless defined $line;
790 push @$tokens, make_line_token($script->{line} + 1);
792 # the next parser stage eats this
793 push @$tokens, @{tokenize_string($line)};
796 return 1;
799 sub handle_special_token($) {
800 my $token = shift;
801 die unless ref $token;
802 if (ref $token eq 'line') {
803 $script->{line} = $$token;
804 } else {
805 die;
809 sub handle_special_tokens() {
810 my $tokens = $script->{tokens};
811 while (@$tokens > 0 and ref $tokens->[0]) {
812 handle_special_token(shift @$tokens);
816 # wrapper for prepare_tokens() which handles "special" tokens
817 sub prepare_normal_tokens() {
818 my $tokens = $script->{tokens};
819 while (1) {
820 handle_special_tokens();
821 return 1 if @$tokens > 0;
822 return unless prepare_tokens();
826 # open a ferm sub script
827 sub open_script($) {
828 my $filename = shift;
830 for (my $s = $script; defined $s; $s = $s->{parent}) {
831 die("Circular reference in $script->{filename} line $script->{line}: $filename\n")
832 if $s->{filename} eq $filename;
835 my $handle;
836 if ($filename eq '-') {
837 # Note that this only allowed in the command-line argument and not
838 # @includes, since those are filtered by collect_filenames()
839 $handle = *STDIN;
840 # also set a filename label so that error messages are more helpful
841 $filename = "<stdin>";
842 } else {
843 local *FILE;
844 open FILE, "$filename" or die("Failed to open $filename: $!\n");
845 $handle = *FILE;
848 $script = { filename => $filename,
849 handle => $handle,
850 line => 0,
851 past_tokens => [],
852 tokens => [],
853 parent => $script,
856 return $script;
859 # collect script filenames which are being included
860 sub collect_filenames(@) {
861 my @ret;
863 # determine the current script's parent directory for relative
864 # file names
865 die unless defined $script;
866 my $parent_dir = $script->{filename} =~ m,^(.*/),
867 ? $1 : './';
869 foreach my $pathname (@_) {
870 # non-absolute file names are relative to the parent script's
871 # file name
872 $pathname = $parent_dir . $pathname
873 unless $pathname =~ m,^/|\|$,;
875 if ($pathname =~ m,/$,) {
876 # include all regular files in a directory
878 error("'$pathname' is not a directory")
879 unless -d $pathname;
881 local *DIR;
882 opendir DIR, $pathname
883 or error("Failed to open directory '$pathname': $!");
884 my @names = readdir DIR;
885 closedir DIR;
887 # sort those names for a well-defined order
888 foreach my $name (sort { $a cmp $b } @names) {
889 # ignore dpkg's backup files
890 next if $name =~ /\.dpkg-(old|dist|new|tmp)$/;
891 # don't include hidden and backup files
892 next if $name =~ /^\.|~$/;
894 my $filename = $pathname . $name;
895 push @ret, $filename
896 if -f $filename;
898 } elsif ($pathname =~ m,\|$,) {
899 # run a program and use its output
900 push @ret, $pathname;
901 } elsif ($pathname =~ m,^\|,) {
902 error('This kind of pipe is not allowed');
903 } else {
904 # include a regular file
906 error("'$pathname' is a directory; maybe use trailing '/' to include a directory?")
907 if -d $pathname;
908 error("'$pathname' is not a file")
909 unless -f $pathname;
911 push @ret, $pathname;
915 return @ret;
918 # peek a token from the queue, but don't remove it
919 sub peek_token() {
920 return unless prepare_normal_tokens();
921 return $script->{tokens}[0];
924 # get a token from the queue, including "special" tokens
925 sub next_raw_token() {
926 return unless prepare_tokens();
927 return shift @{$script->{tokens}};
930 # get a token from the queue
931 sub next_token() {
932 return unless prepare_normal_tokens();
933 my $token = shift @{$script->{tokens}};
935 # update $script->{past_tokens}
936 my $past_tokens = $script->{past_tokens};
938 if (@$past_tokens > 0) {
939 my $prev_token = $past_tokens->[-1][-1];
940 $past_tokens->[-1] = @$past_tokens > 1 ? ['{'] : []
941 if $prev_token eq ';';
942 if ($prev_token eq '}') {
943 pop @$past_tokens;
944 $past_tokens->[-1] = $past_tokens->[-1][0] eq '{'
945 ? [ '{' ] : []
946 if @$past_tokens > 0;
950 push @$past_tokens, [] if $token eq '{' or @$past_tokens == 0;
951 push @{$past_tokens->[-1]}, $token;
953 # return
954 return $token;
957 sub expect_token($;$) {
958 my $expect = shift;
959 my $msg = shift;
960 my $token = next_token();
961 error($msg || "'$expect' expected")
962 unless defined $token and $token eq $expect;
965 # require that another token exists, and that it's not a "special"
966 # token, e.g. ";" and "{"
967 sub require_next_token {
968 my $code = shift || \&next_token;
970 my $token = &$code(@_);
972 error('unexpected end of file')
973 unless defined $token;
975 error("'$token' not allowed here")
976 if $token =~ /^[;{}]$/;
978 return $token;
981 # return the value of a variable
982 sub variable_value($) {
983 my $name = shift;
985 if ($name eq "LINE") {
986 return $script->{line};
989 foreach (@stack) {
990 return $_->{vars}{$name}
991 if exists $_->{vars}{$name};
994 return $stack[0]{auto}{$name}
995 if exists $stack[0]{auto}{$name};
997 return;
1000 # determine the value of a variable, die if the value is an array
1001 sub string_variable_value($) {
1002 my $name = shift;
1003 my $value = variable_value($name);
1005 error("variable '$name' must be a string, but it is an array")
1006 if ref $value;
1008 return $value;
1011 # similar to the built-in "join" function, but also handle negated
1012 # values in a special way
1013 sub join_value($$) {
1014 my ($expr, $value) = @_;
1016 unless (ref $value) {
1017 return $value;
1018 } elsif (ref $value eq 'ARRAY') {
1019 return join($expr, @$value);
1020 } elsif (ref $value eq 'negated') {
1021 # bless'negated' is a special marker for negated values
1022 $value = join_value($expr, $value->[0]);
1023 return bless [ $value ], 'negated';
1024 } else {
1025 die;
1029 sub negate_value($$;$) {
1030 my ($value, $class, $allow_array) = @_;
1032 if (ref $value) {
1033 error('double negation is not allowed')
1034 if ref $value eq 'negated' or ref $value eq 'pre_negated';
1036 error('it is not possible to negate an array')
1037 if ref $value eq 'ARRAY' and not $allow_array;
1040 return bless [ $value ], $class || 'negated';
1043 sub format_bool($) {
1044 return $_[0] ? 1 : 0;
1047 sub resolve($\@$) {
1048 my ($resolver, $names, $type) = @_;
1050 my @result;
1051 foreach my $hostname (@$names) {
1052 my $query = $resolver->search($hostname, $type);
1053 error("DNS query for '$hostname' failed: " . $resolver->errorstring)
1054 unless $query;
1056 foreach my $rr ($query->answer) {
1057 next unless $rr->type eq $type;
1059 if ($type eq 'NS') {
1060 push @result, $rr->nsdname;
1061 } elsif ($type eq 'MX') {
1062 push @result, $rr->exchange;
1063 } else {
1064 push @result, $rr->address;
1069 # NS/MX records return host names; resolve these again in the
1070 # second pass (IPv4 only currently)
1071 @result = resolve($resolver, @result, 'A')
1072 if $type eq 'NS' or $type eq 'MX';
1074 return @result;
1077 # returns the next parameter, which may either be a scalar or an array
1078 sub getvalues {
1079 my $code = shift;
1080 my %options = @_;
1082 my $token = require_next_token($code);
1084 if ($token eq '(') {
1085 # read an array until ")"
1086 my @wordlist;
1088 for (;;) {
1089 $token = getvalues($code,
1090 parenthesis_allowed => 1,
1091 comma_allowed => 1);
1093 unless (ref $token) {
1094 last if $token eq ')';
1096 if ($token eq ',') {
1097 error('Comma is not allowed within arrays, please use only a space');
1098 next;
1101 push @wordlist, $token;
1102 } elsif (ref $token eq 'ARRAY') {
1103 push @wordlist, @$token;
1104 } else {
1105 error('unknown toke type');
1109 error('empty array not allowed here')
1110 unless @wordlist or not $options{non_empty};
1112 return @wordlist == 1
1113 ? $wordlist[0]
1114 : \@wordlist;
1115 } elsif ($token =~ /^\`(.*)\`$/s) {
1116 # execute a shell command, insert output
1117 my $command = $1;
1118 my $output = `$command`;
1119 unless ($? == 0) {
1120 if ($? == -1) {
1121 error("failed to execute: $!");
1122 } elsif ($? & 0x7f) {
1123 error("child died with signal " . ($? & 0x7f));
1124 } elsif ($? >> 8) {
1125 error("child exited with status " . ($? >> 8));
1129 # remove comments
1130 $output =~ s/#.*//mg;
1132 # tokenize
1133 my @tokens = grep { length } split /\s+/s, $output;
1135 my @values;
1136 while (@tokens) {
1137 my $value = getvalues(sub { shift @tokens });
1138 push @values, to_array($value);
1141 # and recurse
1142 return @values == 1
1143 ? $values[0]
1144 : \@values;
1145 } elsif ($token =~ /^\'(.*)\'$/s) {
1146 # single quotes: a string
1147 return $1;
1148 } elsif ($token =~ /^\"(.*)\"$/s) {
1149 # double quotes: a string with escapes
1150 $token = $1;
1151 $token =~ s,\$(\w+),string_variable_value($1),eg;
1152 return $token;
1153 } elsif ($token eq '!') {
1154 error('negation is not allowed here')
1155 unless $options{allow_negation};
1157 $token = getvalues($code);
1159 return negate_value($token, undef, $options{allow_array_negation});
1160 } elsif ($token eq ',') {
1161 return $token
1162 if $options{comma_allowed};
1164 error('comma is not allowed here');
1165 } elsif ($token eq '=') {
1166 error('equals operator ("=") is not allowed here');
1167 } elsif ($token eq '$') {
1168 my $name = require_next_token($code);
1169 error('variable name expected - if you want to concatenate strings, try using double quotes')
1170 unless $name =~ /^\w+$/;
1172 my $value = variable_value($name);
1174 error("no such variable: \$$name")
1175 unless defined $value;
1177 return $value;
1178 } elsif ($token eq '&') {
1179 error("function calls are not allowed as keyword parameter");
1180 } elsif ($token eq ')' and not $options{parenthesis_allowed}) {
1181 error('Syntax error');
1182 } elsif ($token =~ /^@/) {
1183 if ($token eq '@resolve') {
1184 my @params = get_function_params();
1185 error('Usage: @resolve((hostname ...), [type])')
1186 unless @params == 1 or @params == 2;
1187 eval { require Net::DNS; };
1188 error('For the @resolve() function, you need the Perl library Net::DNS')
1189 if $@;
1190 my $type = $params[1] || 'A';
1191 error('String expected') if ref $type;
1192 my $resolver = new Net::DNS::Resolver;
1193 @params = to_array($params[0]);
1194 my @result = resolve($resolver, @params, $type);
1195 return @result == 1 ? $result[0] : \@result;
1196 } elsif ($token eq '@eq') {
1197 my @params = get_function_params();
1198 error('Usage: @eq(a, b)') unless @params == 2;
1199 return format_bool($params[0] eq $params[1]);
1200 } elsif ($token eq '@ne') {
1201 my @params = get_function_params();
1202 error('Usage: @ne(a, b)') unless @params == 2;
1203 return format_bool($params[0] ne $params[1]);
1204 } elsif ($token eq '@not') {
1205 my @params = get_function_params();
1206 error('Usage: @not(a)') unless @params == 1;
1207 return format_bool(not $params[0]);
1208 } elsif ($token eq '@cat') {
1209 my $value = '';
1210 map {
1211 error('String expected') if ref $_;
1212 $value .= $_;
1213 } get_function_params();
1214 return $value;
1215 } elsif ($token eq '@substr') {
1216 my @params = get_function_params();
1217 error('Usage: @substr(string, num, num)') unless @params == 3;
1218 error('String expected') if ref $params[0] or ref $params[1] or ref $params[2];
1219 return substr($params[0],$params[1],$params[2]);
1220 } elsif ($token eq '@length') {
1221 my @params = get_function_params();
1222 error('Usage: @length(string)') unless @params == 1;
1223 error('String expected') if ref $params[0];
1224 return length($params[0]);
1225 } elsif ($token eq '@basename') {
1226 my @params = get_function_params();
1227 error('Usage: @basename(path)') unless @params == 1;
1228 error('String expected') if ref $params[0];
1229 my($volume,$path,$file) = File::Spec->splitpath( $params[0] );
1230 return $file;
1231 } elsif ($token eq '@dirname') {
1232 my @params = get_function_params();
1233 error('Usage: @dirname(path)') unless @params == 1;
1234 error('String expected') if ref $params[0];
1235 my($volume,$path,$file) = File::Spec->splitpath( $params[0] );
1236 return $path;
1237 } elsif ($token eq '@ipfilter') {
1238 my @params = get_function_params();
1239 error('Usage: @ipfilter((ip1 ip2 ...))') unless @params == 1;
1240 my $domain = $stack[0]{auto}{DOMAIN};
1241 error('No domain specified') unless defined $domain;
1242 my @ips = to_array($params[0]);
1244 # very crude IPv4/IPv6 address detection
1245 if ($domain eq 'ip') {
1246 @ips = grep { !/:[0-9a-f]*:/ } @ips;
1247 } elsif ($domain eq 'ip6') {
1248 @ips = grep { !m,^[0-9./]+$,s } @ips;
1251 return \@ips;
1252 } else {
1253 error("unknown ferm built-in function");
1255 } else {
1256 return $token;
1260 # returns the next parameter, but only allow a scalar
1261 sub getvar() {
1262 my $token = getvalues();
1264 error('array not allowed here')
1265 if ref $token and ref $token eq 'ARRAY';
1267 return $token;
1270 sub get_function_params(%) {
1271 expect_token('(', 'function name must be followed by "()"');
1273 my $token = peek_token();
1274 if ($token eq ')') {
1275 require_next_token();
1276 return;
1279 my @params;
1281 while (1) {
1282 if (@params > 0) {
1283 $token = require_next_token();
1284 last
1285 if $token eq ')';
1287 error('"," expected')
1288 unless $token eq ',';
1291 push @params, getvalues(undef, @_);
1294 return @params;
1297 # collect all tokens in a flat array reference until the end of the
1298 # command is reached
1299 sub collect_tokens {
1300 my %options = @_;
1302 my @level;
1303 my @tokens;
1305 # re-insert a "line" token, because the starting token of the
1306 # current line has been consumed already
1307 push @tokens, make_line_token($script->{line});
1309 while (1) {
1310 my $keyword = next_raw_token();
1311 error('unexpected end of file within function/variable declaration')
1312 unless defined $keyword;
1314 if (ref $keyword) {
1315 handle_special_token($keyword);
1316 } elsif ($keyword =~ /^[\{\(]$/) {
1317 push @level, $keyword;
1318 } elsif ($keyword =~ /^[\}\)]$/) {
1319 my $expected = $keyword;
1320 $expected =~ tr/\}\)/\{\(/;
1321 my $opener = pop @level;
1322 error("unmatched '$keyword'")
1323 unless defined $opener and $opener eq $expected;
1324 } elsif ($keyword eq ';' and @level == 0) {
1325 push @tokens, $keyword
1326 if $options{include_semicolon};
1328 if ($options{include_else}) {
1329 my $token = peek_token;
1330 next if $token eq '@else';
1333 last;
1336 push @tokens, $keyword;
1338 last
1339 if $keyword eq '}' and @level == 0;
1342 return \@tokens;
1346 # returns the specified value as an array. dereference arrayrefs
1347 sub to_array($) {
1348 my $value = shift;
1349 die unless wantarray;
1350 die if @_;
1351 unless (ref $value) {
1352 return $value;
1353 } elsif (ref $value eq 'ARRAY') {
1354 return @$value;
1355 } else {
1356 die;
1360 # evaluate the specified value as bool
1361 sub eval_bool($) {
1362 my $value = shift;
1363 die if wantarray;
1364 die if @_;
1365 unless (ref $value) {
1366 return $value;
1367 } elsif (ref $value eq 'ARRAY') {
1368 return @$value > 0;
1369 } else {
1370 die;
1374 sub is_netfilter_core_target($) {
1375 my $target = shift;
1376 die unless defined $target and length $target;
1377 return grep { $_ eq $target } qw(ACCEPT DROP RETURN QUEUE);
1380 sub is_netfilter_module_target($$) {
1381 my ($domain_family, $target) = @_;
1382 die unless defined $target and length $target;
1384 return defined $domain_family &&
1385 exists $target_defs{$domain_family} &&
1386 $target_defs{$domain_family}{$target};
1389 sub is_netfilter_builtin_chain($$) {
1390 my ($table, $chain) = @_;
1392 return grep { $_ eq $chain }
1393 qw(PREROUTING INPUT FORWARD OUTPUT POSTROUTING);
1396 sub netfilter_canonical_protocol($) {
1397 my $proto = shift;
1398 return 'icmp'
1399 if $proto eq 'ipv6-icmp' or $proto eq 'icmpv6';
1400 return 'mh'
1401 if $proto eq 'ipv6-mh';
1402 return $proto;
1405 sub netfilter_protocol_module($) {
1406 my $proto = shift;
1407 return unless defined $proto;
1408 return 'icmp6'
1409 if $proto eq 'icmpv6';
1410 return $proto;
1413 # escape the string in a way safe for the shell
1414 sub shell_escape($) {
1415 my $token = shift;
1417 return $token if $token =~ /^[-_a-zA-Z0-9]+$/s;
1419 if ($option{fast}) {
1420 # iptables-save/iptables-restore are quite buggy concerning
1421 # escaping and special characters... we're trying our best
1422 # here
1424 $token =~ s,",\\",g;
1425 $token = '"' . $token . '"'
1426 if $token =~ /[\s\'\\;&]/s or length($token) == 0;
1427 } else {
1428 return $token
1429 if $token =~ /^\`.*\`$/;
1430 $token =~ s/'/'\\''/g;
1431 $token = '\'' . $token . '\''
1432 if $token =~ /[\s\"\\;<>&|]/s or length($token) == 0;
1435 return $token;
1438 # append an option to the shell command line, using information from
1439 # the module definition (see %match_defs etc.)
1440 sub shell_format_option($$) {
1441 my ($keyword, $value) = @_;
1443 my $cmd = '';
1444 if (ref $value) {
1445 if ((ref $value eq 'negated') || (ref $value eq 'pre_negated')) {
1446 $value = $value->[0];
1447 $cmd = ' !';
1451 unless (defined $value) {
1452 $cmd .= " --$keyword";
1453 } elsif (ref $value) {
1454 if (ref $value eq 'params') {
1455 $cmd .= " --$keyword ";
1456 $cmd .= join(' ', map { shell_escape($_) } @$value);
1457 } elsif (ref $value eq 'multi') {
1458 foreach (@$value) {
1459 $cmd .= " --$keyword " . shell_escape($_);
1461 } else {
1462 die;
1464 } else {
1465 $cmd .= " --$keyword " . shell_escape($value);
1468 return $cmd;
1471 sub format_option($$$) {
1472 my ($domain, $name, $value) = @_;
1474 $value = 'icmpv6' if $domain eq 'ip6' and $name eq 'protocol'
1475 and $value eq 'icmp';
1476 $name = 'icmpv6-type' if $domain eq 'ip6' and $name eq 'icmp-type';
1478 if ($domain eq 'ip6' and $name eq 'reject-with') {
1479 my %icmp_map = (
1480 'icmp-net-unreachable' => 'icmp6-no-route',
1481 'icmp-host-unreachable' => 'icmp6-addr-unreachable',
1482 'icmp-port-unreachable' => 'icmp6-port-unreachable',
1483 'icmp-net-prohibited' => 'icmp6-adm-prohibited',
1484 'icmp-host-prohibited' => 'icmp6-adm-prohibited',
1485 'icmp-admin-prohibited' => 'icmp6-adm-prohibited',
1487 $value = $icmp_map{$value} if exists $icmp_map{$value};
1490 return shell_format_option($name, $value);
1493 sub append_rule($$) {
1494 my ($chain_rules, $rule) = @_;
1496 my $cmd = join('', map { $_->[2] } @{$rule->{options}});
1497 push @$chain_rules, { rule => $cmd,
1498 script => $rule->{script},
1502 sub unfold_rule {
1503 my ($domain, $chain_rules, $rule) = (shift, shift, shift);
1504 return append_rule($chain_rules, $rule) unless @_;
1506 my $option = shift;
1507 my @values = @{$option->[1]};
1509 foreach my $value (@values) {
1510 $option->[2] = format_option($domain, $option->[0], $value);
1511 unfold_rule($domain, $chain_rules, $rule, @_);
1515 sub mkrules2($$$) {
1516 my ($domain, $chain_rules, $rule) = @_;
1518 my @unfold;
1519 foreach my $option (@{$rule->{options}}) {
1520 if (ref $option->[1] and ref $option->[1] eq 'ARRAY') {
1521 push @unfold, $option
1522 } else {
1523 $option->[2] = format_option($domain, $option->[0], $option->[1]);
1527 unfold_rule($domain, $chain_rules, $rule, @unfold);
1530 # convert a bunch of internal rule structures in iptables calls,
1531 # unfold arrays during that
1532 sub mkrules($) {
1533 my $rule = shift;
1535 my $domain = $rule->{domain};
1536 my $domain_info = $domains{$domain};
1537 $domain_info->{enabled} = 1;
1539 foreach my $table (to_array $rule->{table}) {
1540 my $table_info = $domain_info->{tables}{$table} ||= {};
1542 foreach my $chain (to_array $rule->{chain}) {
1543 my $chain_rules = $table_info->{chains}{$chain}{rules} ||= [];
1544 mkrules2($domain, $chain_rules, $rule)
1545 if $rule->{has_rule} and not $option{flush};
1550 # parse a keyword from a module definition
1551 sub parse_keyword(\%$$) {
1552 my ($rule, $def, $negated_ref) = @_;
1554 my $params = $def->{params};
1556 my $value;
1558 my $negated;
1559 if ($$negated_ref && exists $def->{pre_negation}) {
1560 $negated = 1;
1561 undef $$negated_ref;
1564 unless (defined $params) {
1565 undef $value;
1566 } elsif (ref $params && ref $params eq 'CODE') {
1567 $value = &$params($rule);
1568 } elsif ($params eq 'm') {
1569 $value = bless [ to_array getvalues() ], 'multi';
1570 } elsif ($params =~ /^[a-z]/) {
1571 if (exists $def->{negation} and not $negated) {
1572 my $token = peek_token();
1573 if ($token eq '!') {
1574 require_next_token();
1575 $negated = 1;
1579 my @params;
1580 foreach my $p (split(//, $params)) {
1581 if ($p eq 's') {
1582 push @params, getvar();
1583 } elsif ($p eq 'c') {
1584 my @v = to_array getvalues(undef, non_empty => 1);
1585 push @params, join(',', @v);
1586 } else {
1587 die;
1591 $value = @params == 1
1592 ? $params[0]
1593 : bless \@params, 'params';
1594 } elsif ($params == 1) {
1595 if (exists $def->{negation} and not $negated) {
1596 my $token = peek_token();
1597 if ($token eq '!') {
1598 require_next_token();
1599 $negated = 1;
1603 $value = getvalues();
1605 warning("log-prefix is too long; truncating to 29 characters: '$1'")
1606 if $def->{name} eq 'log-prefix' && $value =~ s,^(.{29}).+$,$1,;
1607 } else {
1608 if (exists $def->{negation} and not $negated) {
1609 my $token = peek_token();
1610 if ($token eq '!') {
1611 require_next_token();
1612 $negated = 1;
1616 $value = bless [ map {
1617 getvar()
1618 } (1..$params) ], 'params';
1621 $value = negate_value($value, exists $def->{pre_negation} && 'pre_negated')
1622 if $negated;
1624 return $value;
1627 sub append_option(\%$$) {
1628 my ($rule, $name, $value) = @_;
1629 push @{$rule->{options}}, [ $name, $value ];
1632 # parse options of a module
1633 sub parse_option($\%$) {
1634 my ($def, $rule, $negated_ref) = @_;
1636 append_option(%$rule, $def->{name},
1637 parse_keyword(%$rule, $def, $negated_ref));
1640 sub copy_on_write($$) {
1641 my ($rule, $key) = @_;
1642 return unless exists $rule->{cow}{$key};
1643 $rule->{$key} = {%{$rule->{$key}}};
1644 delete $rule->{cow}{$key};
1647 sub new_level(\%$) {
1648 my ($rule, $prev) = @_;
1650 %$rule = ();
1651 if (defined $prev) {
1652 # copy data from previous level
1653 $rule->{cow} = { keywords => 1, };
1654 $rule->{keywords} = $prev->{keywords};
1655 $rule->{match} = { %{$prev->{match}} };
1656 $rule->{options} = [@{$prev->{options}}];
1657 foreach my $key (qw(domain domain_family table chain protocol has_rule has_action)) {
1658 $rule->{$key} = $prev->{$key}
1659 if exists $prev->{$key};
1661 } else {
1662 $rule->{cow} = {};
1663 $rule->{keywords} = {};
1664 $rule->{match} = {};
1665 $rule->{options} = [];
1669 sub merge_keywords(\%$) {
1670 my ($rule, $keywords) = @_;
1671 copy_on_write($rule, 'keywords');
1672 while (my ($name, $def) = each %$keywords) {
1673 $rule->{keywords}{$name} = $def;
1677 sub set_domain(\%$) {
1678 my ($rule, $domain) = @_;
1680 return unless check_domain($domain);
1682 my $domain_family;
1683 unless (ref $domain) {
1684 $domain_family = $domain eq 'ip6' ? 'ip' : $domain;
1685 } elsif (@$domain == 0) {
1686 $domain_family = 'none';
1687 } elsif (grep { not /^ip6?$/s } @$domain) {
1688 error('Cannot combine non-IP domains');
1689 } else {
1690 $domain_family = 'ip';
1693 $rule->{domain_family} = $domain_family;
1694 $rule->{keywords} = $match_defs{$domain_family}{''}{keywords};
1695 $rule->{cow}{keywords} = 1;
1697 $rule->{domain} = $stack[0]{auto}{DOMAIN} = $domain;
1700 sub set_target(\%$$) {
1701 my ($rule, $name, $value) = @_;
1702 error('There can only one action per rule')
1703 if exists $rule->{has_action};
1704 $rule->{has_action} = 1;
1705 append_option(%$rule, $name, $value);
1708 sub set_module_target(\%$$) {
1709 my ($rule, $name, $defs) = @_;
1711 if ($name eq 'TCPMSS') {
1712 my $protos = $rule->{protocol};
1713 error('No protocol specified before TCPMSS')
1714 unless defined $protos;
1715 foreach my $proto (to_array $protos) {
1716 error('TCPMSS not available for protocol "$proto"')
1717 unless $proto eq 'tcp';
1721 # in ebtables, there is both "--mark" and "-j mark"... workaround:
1722 $name = 'mark' if $name eq 'MARK' and $rule->{domain_family} eq 'eb';
1724 set_target(%$rule, 'jump', $name);
1725 merge_keywords(%$rule, $defs->{keywords});
1728 # the main parser loop: read tokens, convert them into internal rule
1729 # structures
1730 sub enter($$) {
1731 my $lev = shift; # current recursion depth
1732 my $prev = shift; # previous rule hash
1734 # enter is the core of the firewall setup, it is a
1735 # simple parser program that recognizes keywords and
1736 # retreives parameters to set up the kernel routing
1737 # chains
1739 my $base_level = $script->{base_level} || 0;
1740 die if $base_level > $lev;
1742 my %rule;
1743 new_level(%rule, $prev);
1745 # read keywords 1 by 1 and dump into parser
1746 while (defined (my $keyword = next_token())) {
1747 # check if the current rule should be negated
1748 my $negated = $keyword eq '!';
1749 if ($negated) {
1750 # negation. get the next word which contains the 'real'
1751 # rule
1752 $keyword = getvar();
1754 error('unexpected end of file after negation')
1755 unless defined $keyword;
1758 # the core: parse all data
1759 for ($keyword)
1761 # deprecated keyword?
1762 if (exists $deprecated_keywords{$keyword}) {
1763 my $new_keyword = $deprecated_keywords{$keyword};
1764 warning("'$keyword' is deprecated, please use '$new_keyword' instead");
1765 $keyword = $new_keyword;
1768 # effectuation operator
1769 if ($keyword eq ';') {
1770 error('Empty rule before ";" not allowed')
1771 unless $rule{non_empty};
1773 if ($rule{has_rule} and not exists $rule{has_action}) {
1774 # something is wrong when a rule was specified,
1775 # but no action
1776 error('No action defined; did you mean "NOP"?');
1779 error('No chain defined') unless exists $rule{chain};
1781 $rule{script} = { filename => $script->{filename},
1782 line => $script->{line},
1785 mkrules(\%rule);
1787 # and clean up variables set in this level
1788 new_level(%rule, $prev);
1790 next;
1793 # conditional expression
1794 if ($keyword eq '@if') {
1795 unless (eval_bool(getvalues)) {
1796 collect_tokens;
1797 my $token = peek_token();
1798 if ($token and $token eq '@else') {
1799 require_next_token();
1800 } else {
1801 new_level(%rule, $prev);
1805 next;
1808 if ($keyword eq '@else') {
1809 # hack: if this "else" has not been eaten by the "if"
1810 # handler above, we believe it came from an if clause
1811 # which evaluated "true" - remove the "else" part now.
1812 collect_tokens;
1813 next;
1816 # hooks for custom shell commands
1817 if ($keyword eq 'hook') {
1818 warning("'hook' is deprecated, use '\@hook'");
1819 $keyword = '@hook';
1822 if ($keyword eq '@hook') {
1823 error('"hook" must be the first token in a command')
1824 if exists $rule{domain};
1826 my $position = getvar();
1827 my $hooks;
1828 if ($position eq 'pre') {
1829 $hooks = \@pre_hooks;
1830 } elsif ($position eq 'post') {
1831 $hooks = \@post_hooks;
1832 } elsif ($position eq 'flush') {
1833 $hooks = \@flush_hooks;
1834 } else {
1835 error("Invalid hook position: '$position'");
1838 push @$hooks, getvar();
1840 expect_token(';');
1841 next;
1844 # recursing operators
1845 if ($keyword eq '{') {
1846 # push stack
1847 my $old_stack_depth = @stack;
1849 unshift @stack, { auto => { %{$stack[0]{auto} || {}} } };
1851 # recurse
1852 enter($lev + 1, \%rule);
1854 # pop stack
1855 shift @stack;
1856 die unless @stack == $old_stack_depth;
1858 # after a block, the command is finished, clear this
1859 # level
1860 new_level(%rule, $prev);
1862 next;
1865 if ($keyword eq '}') {
1866 error('Unmatched "}"')
1867 if $lev <= $base_level;
1869 # consistency check: check if they havn't forgotten
1870 # the ';' after the last statement
1871 error('Missing semicolon before "}"')
1872 if $rule{non_empty};
1874 # and exit
1875 return;
1878 # include another file
1879 if ($keyword eq '@include' or $keyword eq 'include') {
1880 my @files = collect_filenames to_array getvalues;
1881 $keyword = next_token;
1882 error('Missing ";" - "include FILENAME" must be the last command in a rule')
1883 unless defined $keyword and $keyword eq ';';
1885 foreach my $filename (@files) {
1886 # save old script, open new script
1887 my $old_script = $script;
1888 open_script($filename);
1889 $script->{base_level} = $lev + 1;
1891 # push stack
1892 my $old_stack_depth = @stack;
1894 my $stack = {};
1896 if (@stack > 0) {
1897 # include files may set variables for their parent
1898 $stack->{vars} = ($stack[0]{vars} ||= {});
1899 $stack->{functions} = ($stack[0]{functions} ||= {});
1900 $stack->{auto} = { %{ $stack[0]{auto} || {} } };
1903 my( $volume,$dirs,$file ) = File::Spec->splitpath( $filename );
1904 $stack->{auto}{FILENAME} = $filename;
1905 $stack->{auto}{FILEBNAME} = $file;
1906 $stack->{auto}{DIRNAME} = $dirs;
1908 unshift @stack, $stack;
1910 # parse the script
1911 enter($lev + 1, \%rule);
1913 # pop stack
1914 shift @stack;
1915 die unless @stack == $old_stack_depth;
1917 # restore old script
1918 $script = $old_script;
1921 next;
1924 # definition of a variable or function
1925 if ($keyword eq '@def' or $keyword eq 'def') {
1926 error('"def" must be the first token in a command')
1927 if $rule{non_empty};
1929 my $type = require_next_token();
1930 if ($type eq '$') {
1931 my $name = require_next_token();
1932 error('invalid variable name')
1933 unless $name =~ /^\w+$/;
1935 expect_token('=');
1937 my $value = getvalues(undef, allow_negation => 1);
1939 expect_token(';');
1941 $stack[0]{vars}{$name} = $value
1942 unless exists $stack[-1]{vars}{$name};
1943 } elsif ($type eq '&') {
1944 my $name = require_next_token();
1945 error('invalid function name')
1946 unless $name =~ /^\w+$/;
1948 expect_token('(', 'function parameter list or "()" expected');
1950 my @params;
1951 while (1) {
1952 my $token = require_next_token();
1953 last if $token eq ')';
1955 if (@params > 0) {
1956 error('"," expected')
1957 unless $token eq ',';
1959 $token = require_next_token();
1962 error('"$" and parameter name expected')
1963 unless $token eq '$';
1965 $token = require_next_token();
1966 error('invalid function parameter name')
1967 unless $token =~ /^\w+$/;
1969 push @params, $token;
1972 my %function;
1974 $function{params} = \@params;
1976 expect_token('=');
1978 my $tokens = collect_tokens();
1979 $function{block} = 1 if grep { $_ eq '{' } @$tokens;
1980 $function{tokens} = $tokens;
1982 $stack[0]{functions}{$name} = \%function
1983 unless exists $stack[-1]{functions}{$name};
1984 } else {
1985 error('"$" (variable) or "&" (function) expected');
1988 next;
1991 # this rule has something which isn't inherited by its
1992 # parent closure. This variable is used in a lot of
1993 # syntax checks.
1995 $rule{non_empty} = 1;
1997 # def references
1998 if ($keyword eq '$') {
1999 error('variable references are only allowed as keyword parameter');
2002 if ($keyword eq '&') {
2003 my $name = require_next_token();
2004 error('function name expected')
2005 unless $name =~ /^\w+$/;
2007 my $function;
2008 foreach (@stack) {
2009 $function = $_->{functions}{$name};
2010 last if defined $function;
2012 error("no such function: \&$name")
2013 unless defined $function;
2015 my $paramdef = $function->{params};
2016 die unless defined $paramdef;
2018 my @params = get_function_params(allow_negation => 1);
2020 error("Wrong number of parameters for function '\&$name': "
2021 . @$paramdef . " expected, " . @params . " given")
2022 unless @params == @$paramdef;
2024 my %vars;
2025 for (my $i = 0; $i < @params; $i++) {
2026 $vars{$paramdef->[$i]} = $params[$i];
2029 if ($function->{block}) {
2030 # block {} always ends the current rule, so if the
2031 # function contains a block, we have to require
2032 # the calling rule also ends here
2033 expect_token(';');
2036 my @tokens = @{$function->{tokens}};
2037 for (my $i = 0; $i < @tokens; $i++) {
2038 if ($tokens[$i] eq '$' and $i + 1 < @tokens and
2039 exists $vars{$tokens[$i + 1]}) {
2040 my @value = to_array($vars{$tokens[$i + 1]});
2041 @value = ('(', @value, ')')
2042 unless @tokens == 1;
2043 splice(@tokens, $i, 2, @value);
2044 $i += @value - 2;
2045 } elsif ($tokens[$i] =~ m,^"(.*)"$,) {
2046 $tokens[$i] =~ s,\$(\w+),exists $vars{$1} ? $vars{$1} : "\$$1",eg;
2050 unshift @{$script->{tokens}}, @tokens;
2052 next;
2055 # where to put the rule?
2056 if ($keyword eq 'domain') {
2057 error('Domain is already specified')
2058 if exists $rule{domain};
2060 my $domains = getvalues();
2061 if (ref $domains) {
2062 my $tokens = collect_tokens(include_semicolon => 1,
2063 include_else => 1);
2065 my $old_line = $script->{line};
2066 my $old_handle = $script->{handle};
2067 my $old_tokens = $script->{tokens};
2068 my $old_base_level = $script->{base_level};
2069 unshift @$old_tokens, make_line_token($script->{line});
2070 delete $script->{handle};
2072 for my $domain (@$domains) {
2073 my %inner;
2074 new_level(%inner, \%rule);
2075 set_domain(%inner, $domain) or next;
2076 $script->{base_level} = 0;
2077 $script->{tokens} = [ @$tokens ];
2078 enter(0, \%inner);
2081 $script->{base_level} = $old_base_level;
2082 $script->{tokens} = $old_tokens;
2083 $script->{handle} = $old_handle;
2084 $script->{line} = $old_line;
2086 new_level(%rule, $prev);
2087 } else {
2088 unless (set_domain(%rule, $domains)) {
2089 collect_tokens();
2090 new_level(%rule, $prev);
2094 next;
2097 if ($keyword eq 'table') {
2098 warning('Table is already specified')
2099 if exists $rule{table};
2100 $rule{table} = $stack[0]{auto}{TABLE} = getvalues();
2102 set_domain(%rule, $option{domain} || 'ip')
2103 unless exists $rule{domain};
2105 next;
2108 if ($keyword eq 'chain') {
2109 warning('Chain is already specified')
2110 if exists $rule{chain};
2112 my $chain = $rule{chain} = $stack[0]{auto}{CHAIN} = getvalues();
2114 # ferm 1.1 allowed lower case built-in chain names
2115 foreach (ref $rule{chain} ? @{$rule{chain}} : $rule{chain}) {
2116 error('Please write built-in chain names in upper case')
2117 if /^(?:input|forward|output|prerouting|postrouting)$/;
2120 set_domain(%rule, $option{domain} || 'ip')
2121 unless exists $rule{domain};
2123 $rule{table} = 'filter'
2124 unless exists $rule{table};
2126 my $domain = $rule{domain};
2127 foreach my $table (to_array $rule{table}) {
2128 foreach my $c (to_array $chain) {
2129 $domains{$domain}{tables}{$table}{chains}{$c} ||= {};
2133 next;
2136 error('Chain must be specified')
2137 unless exists $rule{chain};
2139 # policy for built-in chain
2140 if ($keyword eq 'policy') {
2141 error('Cannot specify matches for policy')
2142 if $rule{has_rule};
2144 my $policy = getvar();
2145 error("Invalid policy target: $policy")
2146 unless is_netfilter_core_target($policy);
2148 expect_token(';');
2150 my $domain = $rule{domain};
2151 my $domain_info = $domains{$domain};
2152 $domain_info->{enabled} = 1;
2154 foreach my $table (to_array $rule{table}) {
2155 foreach my $chain (to_array $rule{chain}) {
2156 $domain_info->{tables}{$table}{chains}{$chain}{policy} = $policy;
2160 new_level(%rule, $prev);
2161 next;
2164 # create a subchain
2165 if ($keyword eq '@subchain' or $keyword eq 'subchain') {
2166 error('Chain must be specified')
2167 unless exists $rule{chain};
2169 error('No rule specified before "@subchain"')
2170 unless $rule{has_rule};
2172 my $subchain;
2173 my $token = peek_token();
2175 if ($token =~ /^(["'])(.*)\1$/s) {
2176 $subchain = $2;
2177 next_token();
2178 $keyword = next_token();
2179 } elsif ($token eq '{') {
2180 $keyword = next_token();
2181 $subchain = 'ferm_auto_' . ++$auto_chain;
2182 } else {
2183 $subchain = getvar();
2184 $keyword = next_token();
2187 my $domain = $rule{domain};
2188 foreach my $table (to_array $rule{table}) {
2189 $domains{$domain}{tables}{$table}{chains}{$subchain} ||= {};
2192 set_target(%rule, 'jump', $subchain);
2194 error('"{" or chain name expected after "@subchain"')
2195 unless $keyword eq '{';
2197 # create a deep copy of %rule, only containing values
2198 # which must be in the subchain
2199 my %inner = ( cow => { keywords => 1, },
2200 match => {},
2201 options => [],
2203 $inner{$_} = $rule{$_} foreach qw(domain domain_family table keywords);
2204 $inner{chain} = $inner{auto}{CHAIN} = $subchain;
2206 if (exists $rule{protocol}) {
2207 $inner{protocol} = $rule{protocol};
2208 append_option(%inner, 'protocol', $inner{protocol});
2211 # create a new stack frame
2212 my $old_stack_depth = @stack;
2213 my $stack = { auto => { %{$stack[0]{auto} || {}} } };
2214 $stack->{auto}{CHAIN} = $subchain;
2215 unshift @stack, $stack;
2217 # enter the block
2218 enter($lev + 1, \%inner);
2220 # pop stack frame
2221 shift @stack;
2222 die unless @stack == $old_stack_depth;
2224 # now handle the parent - it's a jump to the sub chain
2225 $rule{script} = {
2226 filename => $script->{filename},
2227 line => $script->{line},
2230 mkrules(\%rule);
2232 # and clean up variables set in this level
2233 new_level(%rule, $prev);
2234 delete $rule{has_rule};
2236 next;
2239 # everything else must be part of a "real" rule, not just
2240 # "policy only"
2241 $rule{has_rule} = 1;
2243 # extended parameters:
2244 if ($keyword =~ /^mod(?:ule)?$/) {
2245 foreach my $module (to_array getvalues) {
2246 next if exists $rule{match}{$module};
2248 my $domain_family = $rule{domain_family};
2249 my $defs = $match_defs{$domain_family}{$module};
2251 append_option(%rule, 'match', $module);
2252 $rule{match}{$module} = 1;
2254 merge_keywords(%rule, $defs->{keywords})
2255 if defined $defs;
2258 next;
2261 # keywords from $rule{keywords}
2263 if (exists $rule{keywords}{$keyword}) {
2264 my $def = $rule{keywords}{$keyword};
2265 parse_option($def, %rule, \$negated);
2266 next;
2270 # actions
2273 # jump action
2274 if ($keyword eq 'jump') {
2275 set_target(%rule, 'jump', getvar());
2276 next;
2279 # goto action
2280 if ($keyword eq 'realgoto') {
2281 set_target(%rule, 'goto', getvar());
2282 next;
2285 # action keywords
2286 if (is_netfilter_core_target($keyword)) {
2287 set_target(%rule, 'jump', $keyword);
2288 next;
2291 if ($keyword eq 'NOP') {
2292 error('There can only one action per rule')
2293 if exists $rule{has_action};
2294 $rule{has_action} = 1;
2295 next;
2298 if (my $defs = is_netfilter_module_target($rule{domain_family}, $keyword)) {
2299 set_module_target(%rule, $keyword, $defs);
2300 next;
2304 # protocol specific options
2307 if ($keyword eq 'proto' or $keyword eq 'protocol') {
2308 my $protocol = parse_keyword(%rule,
2309 { params => 1, negation => 1 },
2310 \$negated);
2311 $rule{protocol} = $protocol;
2312 append_option(%rule, 'protocol', $rule{protocol});
2314 unless (ref $protocol) {
2315 $protocol = netfilter_canonical_protocol($protocol);
2316 my $domain_family = $rule{domain_family};
2317 if (my $defs = $proto_defs{$domain_family}{$protocol}) {
2318 merge_keywords(%rule, $defs->{keywords});
2319 my $module = netfilter_protocol_module($protocol);
2320 $rule{match}{$module} = 1;
2323 next;
2326 # port switches
2327 if ($keyword =~ /^[sd]port$/) {
2328 my $proto = $rule{protocol};
2329 error('To use sport or dport, you have to specify "proto tcp" or "proto udp" first')
2330 unless defined $proto and grep { /^(?:tcp|udp|udplite|dccp|sctp)$/ } to_array $proto;
2332 append_option(%rule, $keyword,
2333 getvalues(undef, allow_negation => 1));
2334 next;
2337 # default
2338 error("Unrecognized keyword: $keyword");
2341 # if the rule didn't reset the negated flag, it's not
2342 # supported
2343 error("Doesn't support negation: $keyword")
2344 if $negated;
2347 error('Missing "}" at end of file')
2348 if $lev > $base_level;
2350 # consistency check: check if they havn't forgotten
2351 # the ';' before the last statement
2352 error("Missing semicolon before end of file")
2353 if $rule{non_empty};
2356 sub execute_command {
2357 my ($command, $script) = @_;
2359 print LINES "$command\n"
2360 if $option{lines};
2361 return if $option{noexec};
2363 my $ret = system($command);
2364 unless ($ret == 0) {
2365 if ($? == -1) {
2366 print STDERR "failed to execute: $!\n";
2367 exit 1;
2368 } elsif ($? & 0x7f) {
2369 printf STDERR "child died with signal %d\n", $? & 0x7f;
2370 return 1;
2371 } else {
2372 print STDERR "(rule declared in $script->{filename}:$script->{line})\n"
2373 if defined $script;
2374 return $? >> 8;
2378 return;
2381 sub execute_slow($) {
2382 my $domain_info = shift;
2384 my $domain_cmd = $domain_info->{tools}{tables};
2386 my $status;
2387 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2388 my $table_cmd = "$domain_cmd -t $table";
2390 # reset chain policies
2391 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2392 next unless $chain_info->{builtin} or
2393 (not $table_info->{has_builtin} and
2394 is_netfilter_builtin_chain($table, $chain));
2395 $status ||= execute_command("$table_cmd -P $chain ACCEPT")
2396 unless $option{noflush};
2399 # clear
2400 unless ($option{noflush}) {
2401 $status ||= execute_command("$table_cmd -F");
2402 $status ||= execute_command("$table_cmd -X");
2405 next if $option{flush};
2407 # create chains / set policy
2408 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2409 if (is_netfilter_builtin_chain($table, $chain)) {
2410 if (exists $chain_info->{policy}) {
2411 $status ||= execute_command("$table_cmd -P $chain $chain_info->{policy}")
2412 unless $chain_info->{policy} eq 'ACCEPT';
2414 } else {
2415 if (exists $chain_info->{policy}) {
2416 $status ||= execute_command("$table_cmd -N $chain -P $chain_info->{policy}");
2418 else {
2419 $status ||= execute_command("$table_cmd -N $chain");
2424 # dump rules
2425 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2426 my $chain_cmd = "$table_cmd -A $chain";
2427 foreach my $rule (@{$chain_info->{rules}}) {
2428 $status ||= execute_command($chain_cmd . $rule->{rule});
2433 return $status;
2436 sub table_to_save($$) {
2437 my ($result_r, $table_info) = @_;
2439 foreach my $chain (sort keys %{$table_info->{chains}}) {
2440 my $chain_info = $table_info->{chains}{$chain};
2441 foreach my $rule (@{$chain_info->{rules}}) {
2442 $$result_r .= "-A $chain$rule->{rule}\n";
2447 sub rules_to_save($) {
2448 my ($domain_info) = @_;
2450 # convert this into an iptables-save text
2451 my $result = "# Generated by ferm $VERSION on " . localtime() . "\n";
2453 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2454 # select table
2455 $result .= '*' . $table . "\n";
2457 # create chains / set policy
2458 foreach my $chain (sort keys %{$table_info->{chains}}) {
2459 my $chain_info = $table_info->{chains}{$chain};
2460 my $policy = $option{flush} ? undef : $chain_info->{policy};
2461 unless (defined $policy) {
2462 if (is_netfilter_builtin_chain($table, $chain)) {
2463 $policy = 'ACCEPT';
2464 } else {
2465 next if $option{flush};
2466 $policy = '-';
2469 $result .= ":$chain $policy\ [0:0]\n";
2472 table_to_save(\$result, $table_info)
2473 unless $option{flush};
2475 # do it
2476 $result .= "COMMIT\n";
2479 return $result;
2482 sub restore_domain($$) {
2483 my ($domain_info, $save) = @_;
2485 my $path = $domain_info->{tools}{'tables-restore'};
2486 $path .= " --noflush" if $option{noflush};
2488 local *RESTORE;
2489 open RESTORE, "|$path"
2490 or die "Failed to run $path: $!\n";
2492 print RESTORE $save;
2494 close RESTORE
2495 or die "Failed to run $path\n";
2498 sub execute_fast($) {
2499 my $domain_info = shift;
2501 my $save = rules_to_save($domain_info);
2503 if ($option{lines}) {
2504 my $path = $domain_info->{tools}{'tables-restore'};
2505 $path .= " --noflush" if $option{noflush};
2506 print LINES "$path <<EOT\n"
2507 if $option{shell};
2508 print LINES $save;
2509 print LINES "EOT\n"
2510 if $option{shell};
2513 return if $option{noexec};
2515 eval {
2516 restore_domain($domain_info, $save);
2518 if ($@) {
2519 print STDERR $@;
2520 return 1;
2523 return;
2526 sub rollback() {
2527 my $error;
2528 while (my ($domain, $domain_info) = each %domains) {
2529 next unless $domain_info->{enabled};
2530 unless (defined $domain_info->{tools}{'tables-restore'}) {
2531 print STDERR "Cannot rollback domain '$domain' because there is no ${domain}tables-restore\n";
2532 next;
2535 my $reset = '';
2536 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2537 my $reset_chain = '';
2538 foreach my $chain (keys %{$table_info->{chains}}) {
2539 next unless is_netfilter_builtin_chain($table, $chain);
2540 $reset_chain .= ":${chain} ACCEPT [0:0]\n";
2542 $reset .= "*${table}\n${reset_chain}COMMIT\n"
2543 if length $reset_chain;
2546 $reset .= $domain_info->{previous}
2547 if defined $domain_info->{previous};
2549 restore_domain($domain_info, $reset);
2552 print STDERR "\nFirewall rules rolled back.\n" unless $error;
2553 exit 1;
2556 sub alrm_handler {
2557 # do nothing, just interrupt a system call
2560 sub confirm_rules {
2561 $SIG{ALRM} = \&alrm_handler;
2563 alarm(5);
2565 print STDERR "\n"
2566 . "ferm has applied the new firewall rules.\n"
2567 . "Please type 'yes' to confirm:\n";
2568 STDERR->flush();
2570 alarm($option{timeout});
2572 my $line = '';
2573 STDIN->sysread($line, 3);
2575 eval {
2576 require POSIX;
2577 POSIX::tcflush(*STDIN, 2);
2579 print STDERR "$@" if $@;
2581 $SIG{ALRM} = 'DEFAULT';
2583 return $line eq 'yes';
2586 # end of ferm
2588 __END__
2590 =head1 NAME
2592 ferm - a firewall rule parser for linux
2594 =head1 SYNOPSIS
2596 B<ferm> I<options> I<inputfiles>
2598 =head1 OPTIONS
2600 -n, --noexec Do not execute the rules, just simulate
2601 -F, --flush Flush all netfilter tables managed by ferm
2602 -l, --lines Show all rules that were created
2603 -i, --interactive Interactive mode: revert if user does not confirm
2604 -t, --timeout s Define interactive mode timeout in seconds
2605 --remote Remote mode; ignore host specific configuration.
2606 This implies --noexec and --lines.
2607 -V, --version Show current version number
2608 -h, --help Look at this text
2609 --slow Slow mode, don't use iptables-restore
2610 --shell Generate a shell script which calls iptables-restore
2611 --domain {ip|ip6} Handle only the specified domain
2612 --def '$name=v' Override a variable
2614 =cut