support netfilter module "osf"
[ferm.git] / src / ferm
blob0c21a37ff0d8a05157e864331d9fa7c163c3c854
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.2';
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 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 random*0);
321 add_target_def 'TARPIT';
322 add_target_def 'TCPMSS', qw(set-mss clamp-mss-to-pmtu*0);
323 add_target_def 'TOS', qw(set-tos and-tos or-tos xor-tos);
324 add_target_def 'TPROXY', qw(tproxy-mark on-port);
325 add_target_def 'TRACE';
326 add_target_def 'TTL', qw(ttl-set ttl-dec ttl-inc);
327 add_target_def 'ULOG', qw(ulog-nlgroup ulog-prefix ulog-cprange ulog-qthreshold);
329 add_match_def_x 'arp', '',
330 # ip
331 qw(source-ip! destination-ip! saddr:=source-ip daddr:=destination-ip),
332 # mac
333 qw(source-mac! destination-mac!),
334 # --in-interface
335 qw(in-interface! interface:=in-interface if:=in-interface),
336 # --out-interface
337 qw(out-interface! outerface:=out-interface of:=out-interface),
338 # misc
339 qw(h-length=s opcode=s h-type=s proto-type=s),
340 qw(mangle-ip-s=s mangle-ip-d=s mangle-mac-s=s mangle-mac-d=s mangle-target=s);
342 add_proto_def_x 'eb', 'IPv4',
343 qw(ip-source! ip-destination! ip-src:=ip-source ip-dst:=ip-destination),
344 qw(ip-tos!),
345 qw(ip-protocol! ip-proto:=ip-protocol),
346 qw(ip-source-port! ip-sport:=ip-source-port),
347 qw(ip-destination-port! ip-dport:=ip-destination-port);
349 add_proto_def_x 'eb', 'IPv6',
350 qw(ip6-source! ip6-destination! ip6-src:=ip6-source ip6-dst:=ip6-destination),
351 qw(ip6-tclass!),
352 qw(ip6-protocol! ip6-proto:=ip6-protocol),
353 qw(ip6-source-port! ip6-sport:=ip6-source-port),
354 qw(ip6-destination-port! ip6-dport:=ip6-destination-port);
356 add_proto_def_x 'eb', 'ARP',
357 qw(!arp-gratuitous*0),
358 qw(arp-opcode! arp-htype!=ss arp-ptype!=ss),
359 qw(arp-ip-src! arp-ip-dst! arp-mac-src! arp-mac-dst!);
361 add_proto_def_x 'eb', 'RARP',
362 qw(!arp-gratuitous*0),
363 qw(arp-opcode! arp-htype!=ss arp-ptype!=ss),
364 qw(arp-ip-src! arp-ip-dst! arp-mac-src! arp-mac-dst!);
366 add_proto_def_x 'eb', '802_1Q',
367 qw(vlan-id! vlan-prio! vlan-encap!),
369 add_match_def_x 'eb', '',
370 # --in-interface
371 qw(in-interface! interface:=in-interface if:=in-interface),
372 # --out-interface
373 qw(out-interface! outerface:=out-interface of:=out-interface),
374 # logical interface
375 qw(logical-in! logical-out!),
376 # --source, --destination
377 qw(source! saddr:=source destination! daddr:=destination),
378 # 802.3
379 qw(802_3-sap! 802_3-type!),
380 # among
381 qw(!among-dst=c !among-src=c !among-dst-file !among-src-file),
382 # limit
383 qw(limit=s limit-burst=s),
384 # mark_m
385 qw(mark!),
386 # pkttype
387 qw(pkttype-type!),
388 # stp
389 qw(stp-type! stp-flags! stp-root-prio! stp-root-addr! stp-root-cost!),
390 qw(stp-sender-prio! stp-sender-addr! stp-port! stp-msg-age! stp-max-age!),
391 qw(stp-hello-time! stp-forward-delay!),
392 # log
393 qw(log*0 log-level=s log-prefix=s log-ip*0 log-arp*0);
395 add_target_def_x 'eb', 'arpreply', qw(arpreply-mac arpreply-target);
396 add_target_def_x 'eb', 'dnat', qw(to-destination dnat-target);
397 add_target_def_x 'eb', 'MARK', qw(set-mark mark-target);
398 add_target_def_x 'eb', 'redirect', qw(redirect-target);
399 add_target_def_x 'eb', 'snat', qw(to-source snat-target snat-arp*0);
401 # import-ferm uses the above tables
402 return 1 if $0 =~ /import-ferm$/;
404 # parameter parser for ipt_multiport
405 sub multiport_params {
406 my $rule = shift;
408 # multiport only allows 15 ports at a time. For this
409 # reason, we do a little magic here: split the ports
410 # into portions of 15, and handle these portions as
411 # array elements
413 my $proto = $rule->{protocol};
414 error('To use multiport, you have to specify "proto tcp" or "proto udp" first')
415 unless defined $proto and grep { /^(?:tcp|udp|udplite)$/ } to_array($proto);
417 my $value = getvalues(undef, allow_negation => 1,
418 allow_array_negation => 1);
419 if (ref $value and ref $value eq 'ARRAY') {
420 my @value = @$value;
421 my @params;
423 while (@value) {
424 push @params, join(',', splice(@value, 0, 15));
427 return @params == 1
428 ? $params[0]
429 : \@params;
430 } else {
431 return join_value(',', $value);
435 # initialize stack: command line definitions
436 unshift @stack, {};
438 # Get command line stuff
439 if ($has_getopt) {
440 my ($opt_noexec, $opt_flush, $opt_noflush, $opt_lines, $opt_interactive,
441 $opt_timeout, $opt_help,
442 $opt_version, $opt_test, $opt_fast, $opt_slow, $opt_shell,
443 $opt_domain);
445 Getopt::Long::Configure('bundling', 'auto_help', 'no_ignore_case',
446 'no_auto_abbrev');
448 sub opt_def {
449 my ($opt, $value) = @_;
450 die 'Invalid --def specification'
451 unless $value =~ /^\$?(\w+)=(.*)$/s;
452 my ($name, $unparsed_value) = ($1, $2);
453 my $tokens = tokenize_string($unparsed_value);
454 $value = getvalues(sub { shift @$tokens; });
455 die 'Extra tokens after --def'
456 if @$tokens > 0;
457 $stack[0]{vars}{$name} = $value;
460 local $SIG{__WARN__} = sub { die $_[0]; };
461 GetOptions('noexec|n' => \$opt_noexec,
462 'flush|F' => \$opt_flush,
463 'noflush' => \$opt_noflush,
464 'lines|l' => \$opt_lines,
465 'interactive|i' => \$opt_interactive,
466 'timeout|t=s' => \$opt_timeout,
467 'help|h' => \$opt_help,
468 'version|V' => \$opt_version,
469 test => \$opt_test,
470 remote => \$opt_test,
471 fast => \$opt_fast,
472 slow => \$opt_slow,
473 shell => \$opt_shell,
474 'domain=s' => \$opt_domain,
475 'def=s' => \&opt_def,
478 if (defined $opt_help) {
479 require Pod::Usage;
480 Pod::Usage::pod2usage(-exitstatus => 0);
483 if (defined $opt_version) {
484 printversion();
485 exit 0;
488 $option{noexec} = $opt_noexec || $opt_test;
489 $option{flush} = $opt_flush;
490 $option{noflush} = $opt_noflush;
491 $option{lines} = $opt_lines || $opt_test || $opt_shell;
492 $option{interactive} = $opt_interactive && !$opt_noexec;
493 $option{timeout} = defined $opt_timeout ? $opt_timeout : "30";
494 $option{test} = $opt_test;
495 $option{fast} = !$opt_slow;
496 $option{shell} = $opt_shell;
498 die("ferm interactive mode not possible: /dev/stdin is not a tty\n")
499 if $option{interactive} and not -t STDIN;
500 die("ferm interactive mode not possible: /dev/stderr is not a tty\n")
501 if $option{interactive} and not -t STDERR;
502 die("ferm timeout has no sense without interactive mode")
503 if not $opt_interactive and defined $opt_timeout;
504 die("invalid timeout. must be an integer")
505 if defined $opt_timeout and not $opt_timeout =~ /^[+-]?\d+$/;
507 $option{domain} = $opt_domain if defined $opt_domain;
508 } else {
509 # tiny getopt emulation for microperl
510 my $filename;
511 foreach (@ARGV) {
512 if ($_ eq '--noexec' or $_ eq '-n') {
513 $option{noexec} = 1;
514 } elsif ($_ eq '--lines' or $_ eq '-l') {
515 $option{lines} = 1;
516 } elsif ($_ eq '--fast') {
517 $option{fast} = 1;
518 } elsif ($_ eq '--test') {
519 $option{test} = 1;
520 $option{noexec} = 1;
521 $option{lines} = 1;
522 } elsif ($_ eq '--shell') {
523 $option{$_} = 1 foreach qw(shell fast lines);
524 } elsif (/^-/) {
525 printf STDERR "Usage: ferm [--noexec] [--lines] [--fast] [--shell] FILENAME\n";
526 exit 1;
527 } else {
528 $filename = $_;
531 undef @ARGV;
532 push @ARGV, $filename;
535 unless (@ARGV == 1) {
536 require Pod::Usage;
537 Pod::Usage::pod2usage(-exitstatus => 1);
540 if ($has_strict) {
541 open LINES, ">&STDOUT" if $option{lines};
542 open STDOUT, ">&STDERR" if $option{shell};
543 } else {
544 # microperl can't redirect file handles
545 *LINES = *STDOUT;
547 if ($option{fast} and not $option{noexec}) {
548 print STDERR "Sorry, ferm on microperl does not allow --fast without --noexec\n";
549 exit 1
553 unshift @stack, {};
554 open_script($ARGV[0]);
556 my( $volume,$dirs,$file ) = File::Spec->splitpath( $ARGV[0] );
557 $stack[0]{auto}{FILENAME} = $ARGV[0];
558 $stack[0]{auto}{FILEBNAME} = $file;
559 $stack[0]{auto}{DIRNAME} = $dirs;
563 # parse all input recursively
564 enter(0, undef);
565 die unless @stack == 2;
567 # enable/disable hooks depending on --flush
569 if ($option{flush}) {
570 undef @pre_hooks;
571 undef @post_hooks;
572 } else {
573 undef @flush_hooks;
576 # execute all generated rules
577 my $status;
579 foreach my $cmd (@pre_hooks) {
580 print LINES "$cmd\n" if $option{lines};
581 system($cmd) unless $option{noexec};
584 while (my ($domain, $domain_info) = each %domains) {
585 next unless $domain_info->{enabled};
586 my $s = $option{fast} &&
587 defined $domain_info->{tools}{'tables-restore'}
588 ? execute_fast($domain_info) : execute_slow($domain_info);
589 $status = $s if defined $s;
592 foreach my $cmd (@post_hooks, @flush_hooks) {
593 print LINES "$cmd\n" if $option{lines};
594 system($cmd) unless $option{noexec};
597 if (defined $status) {
598 rollback();
599 exit $status;
602 # ask user, and rollback if there is no confirmation
604 if ($option{interactive}) {
605 if ($option{shell}) {
606 print LINES "echo 'ferm has applied the new firewall rules.'\n";
607 print LINES "echo 'Please press Ctrl-C to confirm.'\n";
608 print LINES "sleep $option{timeout}\n";
609 while (my ($domain, $domain_info) = each %domains) {
610 my $restore = $domain_info->{tools}{'tables-restore'};
611 next unless defined $restore;
612 print LINES "$restore <\$${domain}_tmp\n";
616 confirm_rules() or rollback() unless $option{noexec};
619 exit 0;
621 # end of program execution!
624 # funcs
626 sub printversion {
627 print "ferm $VERSION\n";
628 print "Copyright (C) 2001-2012 Max Kellermann, Auke Kok\n";
629 print "This program is free software released under GPLv2.\n";
630 print "See the included COPYING file for license details.\n";
634 sub error {
635 # returns a nice formatted error message, showing the
636 # location of the error.
637 my $tabs = 0;
638 my @lines;
639 my $l = 0;
640 my @words = map { @$_ } @{$script->{past_tokens}};
642 for my $w ( 0 .. $#words ) {
643 if ($words[$w] eq "\x29")
644 { $l++ ; $lines[$l] = " " x ($tabs-- -1) ;};
645 if ($words[$w] eq "\x28")
646 { $l++ ; $lines[$l] = " " x $tabs++ ;};
647 if ($words[$w] eq "\x7d")
648 { $l++ ; $lines[$l] = " " x ($tabs-- -1) ;};
649 if ($words[$w] eq "\x7b")
650 { $l++ ; $lines[$l] = " " x $tabs++ ;};
651 if ( $l > $#lines ) { $lines[$l] = "" };
652 $lines[$l] .= $words[$w] . " ";
653 if ($words[$w] eq "\x28")
654 { $l++ ; $lines[$l] = " " x $tabs ;};
655 if (($words[$w] eq "\x29") && ($words[$w+1] ne "\x7b"))
656 { $l++ ; $lines[$l] = " " x $tabs ;};
657 if ($words[$w] eq "\x7b")
658 { $l++ ; $lines[$l] = " " x $tabs ;};
659 if (($words[$w] eq "\x7d") && ($words[$w+1] ne "\x7d"))
660 { $l++ ; $lines[$l] = " " x $tabs ;};
661 if (($words[$w] eq "\x3b") && ($words[$w+1] ne "\x7d"))
662 { $l++ ; $lines[$l] = " " x $tabs ;}
663 if ($words[$w-1] eq "option")
664 { $l++ ; $lines[$l] = " " x $tabs ;}
666 my $start = $#lines - 4;
667 if ($start < 0) { $start = 0 } ;
668 print STDERR "Error in $script->{filename} line $script->{line}:\n";
669 for $l ( $start .. $#lines)
670 { print STDERR $lines[$l]; if ($l != $#lines ) {print STDERR "\n"} ; };
671 print STDERR "<--\n";
672 die("@_\n");
675 # print a warning message about code from an input file
676 sub warning {
677 print STDERR "Warning in $script->{filename} line $script->{line}: "
678 . (shift) . "\n";
681 sub find_tool($) {
682 my $name = shift;
683 return $name if $option{test};
684 for my $path ('/sbin', split ':', $ENV{PATH}) {
685 my $ret = "$path/$name";
686 return $ret if -x $ret;
688 die "$name not found in PATH\n";
691 sub initialize_domain {
692 my $domain = shift;
693 my $domain_info = $domains{$domain} ||= {};
695 return if exists $domain_info->{initialized};
697 die "Invalid domain '$domain'\n" unless $domain =~ /^(?:ip6?|arp|eb)$/;
699 my @tools = qw(tables);
700 push @tools, qw(tables-save tables-restore)
701 if $domain =~ /^ip6?$/;
703 # determine the location of this domain's tools
704 my %tools = map { $_ => find_tool($domain . $_) } @tools;
705 $domain_info->{tools} = \%tools;
707 # make tables-save tell us about the state of this domain
708 # (which tables and chains do exist?), also remember the old
709 # save data which may be used later by the rollback function
710 local *SAVE;
711 if (!$option{test} &&
712 exists $tools{'tables-save'} &&
713 open(SAVE, "$tools{'tables-save'}|")) {
714 my $save = '';
716 my $table_info;
717 while (<SAVE>) {
718 $save .= $_;
720 if (/^\*(\w+)/) {
721 my $table = $1;
722 $table_info = $domain_info->{tables}{$table} ||= {};
723 } elsif (defined $table_info and /^:(\w+)\s+(\S+)/
724 and $2 ne '-') {
725 $table_info->{chains}{$1}{builtin} = 1;
726 $table_info->{has_builtin} = 1;
730 # for rollback
731 $domain_info->{previous} = $save;
734 if ($option{shell} && $option{interactive} &&
735 exists $tools{'tables-save'}) {
736 print LINES "${domain}_tmp=\$(mktemp ferm.XXXXXXXXXX)\n";
737 print LINES "$tools{'tables-save'} >\$${domain}_tmp\n";
740 $domain_info->{initialized} = 1;
743 sub check_domain($) {
744 my $domain = shift;
745 my @result;
747 return if exists $option{domain}
748 and $domain ne $option{domain};
750 eval {
751 initialize_domain($domain);
753 error($@) if $@;
755 return 1;
758 # split the input string into words and delete comments
759 sub tokenize_string($) {
760 my $string = shift;
762 my @ret;
764 foreach my $word ($string =~ m/(".*?"|'.*?'|`.*?`|[!,=&\$\%\(\){};]|[-+\w\/\.:]+|@\w+|#)/g) {
765 last if $word eq '#';
766 push @ret, $word;
769 return \@ret;
772 # generate a "line" special token, that marks the line number; these
773 # special tokens are inserted after each line break, so ferm keeps
774 # track of line numbers
775 sub make_line_token($) {
776 my $line = shift;
777 return bless(\$line, 'line');
780 # read some more tokens from the input file into a buffer
781 sub prepare_tokens() {
782 my $tokens = $script->{tokens};
783 while (@$tokens == 0) {
784 my $handle = $script->{handle};
785 return unless defined $handle;
786 my $line = <$handle>;
787 return unless defined $line;
789 push @$tokens, make_line_token($script->{line} + 1);
791 # the next parser stage eats this
792 push @$tokens, @{tokenize_string($line)};
795 return 1;
798 sub handle_special_token($) {
799 my $token = shift;
800 die unless ref $token;
801 if (ref $token eq 'line') {
802 $script->{line} = $$token;
803 } else {
804 die;
808 sub handle_special_tokens() {
809 my $tokens = $script->{tokens};
810 while (@$tokens > 0 and ref $tokens->[0]) {
811 handle_special_token(shift @$tokens);
815 # wrapper for prepare_tokens() which handles "special" tokens
816 sub prepare_normal_tokens() {
817 my $tokens = $script->{tokens};
818 while (1) {
819 handle_special_tokens();
820 return 1 if @$tokens > 0;
821 return unless prepare_tokens();
825 # open a ferm sub script
826 sub open_script($) {
827 my $filename = shift;
829 for (my $s = $script; defined $s; $s = $s->{parent}) {
830 die("Circular reference in $script->{filename} line $script->{line}: $filename\n")
831 if $s->{filename} eq $filename;
834 my $handle;
835 if ($filename eq '-') {
836 # Note that this only allowed in the command-line argument and not
837 # @includes, since those are filtered by collect_filenames()
838 $handle = *STDIN;
839 # also set a filename label so that error messages are more helpful
840 $filename = "<stdin>";
841 } else {
842 local *FILE;
843 open FILE, "$filename" or die("Failed to open $filename: $!\n");
844 $handle = *FILE;
847 $script = { filename => $filename,
848 handle => $handle,
849 line => 0,
850 past_tokens => [],
851 tokens => [],
852 parent => $script,
855 return $script;
858 # collect script filenames which are being included
859 sub collect_filenames(@) {
860 my @ret;
862 # determine the current script's parent directory for relative
863 # file names
864 die unless defined $script;
865 my $parent_dir = $script->{filename} =~ m,^(.*/),
866 ? $1 : './';
868 foreach my $pathname (@_) {
869 # non-absolute file names are relative to the parent script's
870 # file name
871 $pathname = $parent_dir . $pathname
872 unless $pathname =~ m,^/|\|$,;
874 if ($pathname =~ m,/$,) {
875 # include all regular files in a directory
877 error("'$pathname' is not a directory")
878 unless -d $pathname;
880 local *DIR;
881 opendir DIR, $pathname
882 or error("Failed to open directory '$pathname': $!");
883 my @names = readdir DIR;
884 closedir DIR;
886 # sort those names for a well-defined order
887 foreach my $name (sort { $a cmp $b } @names) {
888 # ignore dpkg's backup files
889 next if $name =~ /\.dpkg-(old|dist|new|tmp)$/;
890 # don't include hidden and backup files
891 next if $name =~ /^\.|~$/;
893 my $filename = $pathname . $name;
894 push @ret, $filename
895 if -f $filename;
897 } elsif ($pathname =~ m,\|$,) {
898 # run a program and use its output
899 push @ret, $pathname;
900 } elsif ($pathname =~ m,^\|,) {
901 error('This kind of pipe is not allowed');
902 } else {
903 # include a regular file
905 error("'$pathname' is a directory; maybe use trailing '/' to include a directory?")
906 if -d $pathname;
907 error("'$pathname' is not a file")
908 unless -f $pathname;
910 push @ret, $pathname;
914 return @ret;
917 # peek a token from the queue, but don't remove it
918 sub peek_token() {
919 return unless prepare_normal_tokens();
920 return $script->{tokens}[0];
923 # get a token from the queue, including "special" tokens
924 sub next_raw_token() {
925 return unless prepare_tokens();
926 return shift @{$script->{tokens}};
929 # get a token from the queue
930 sub next_token() {
931 return unless prepare_normal_tokens();
932 my $token = shift @{$script->{tokens}};
934 # update $script->{past_tokens}
935 my $past_tokens = $script->{past_tokens};
937 if (@$past_tokens > 0) {
938 my $prev_token = $past_tokens->[-1][-1];
939 $past_tokens->[-1] = @$past_tokens > 1 ? ['{'] : []
940 if $prev_token eq ';';
941 if ($prev_token eq '}') {
942 pop @$past_tokens;
943 $past_tokens->[-1] = $past_tokens->[-1][0] eq '{'
944 ? [ '{' ] : []
945 if @$past_tokens > 0;
949 push @$past_tokens, [] if $token eq '{' or @$past_tokens == 0;
950 push @{$past_tokens->[-1]}, $token;
952 # return
953 return $token;
956 sub expect_token($;$) {
957 my $expect = shift;
958 my $msg = shift;
959 my $token = next_token();
960 error($msg || "'$expect' expected")
961 unless defined $token and $token eq $expect;
964 # require that another token exists, and that it's not a "special"
965 # token, e.g. ";" and "{"
966 sub require_next_token {
967 my $code = shift || \&next_token;
969 my $token = &$code(@_);
971 error('unexpected end of file')
972 unless defined $token;
974 error("'$token' not allowed here")
975 if $token =~ /^[;{}]$/;
977 return $token;
980 # return the value of a variable
981 sub variable_value($) {
982 my $name = shift;
984 if ($name eq "LINE") {
985 return $script->{line};
988 foreach (@stack) {
989 return $_->{vars}{$name}
990 if exists $_->{vars}{$name};
993 return $stack[0]{auto}{$name}
994 if exists $stack[0]{auto}{$name};
996 return;
999 # determine the value of a variable, die if the value is an array
1000 sub string_variable_value($) {
1001 my $name = shift;
1002 my $value = variable_value($name);
1004 error("variable '$name' must be a string, but it is an array")
1005 if ref $value;
1007 return $value;
1010 # similar to the built-in "join" function, but also handle negated
1011 # values in a special way
1012 sub join_value($$) {
1013 my ($expr, $value) = @_;
1015 unless (ref $value) {
1016 return $value;
1017 } elsif (ref $value eq 'ARRAY') {
1018 return join($expr, @$value);
1019 } elsif (ref $value eq 'negated') {
1020 # bless'negated' is a special marker for negated values
1021 $value = join_value($expr, $value->[0]);
1022 return bless [ $value ], 'negated';
1023 } else {
1024 die;
1028 sub negate_value($$;$) {
1029 my ($value, $class, $allow_array) = @_;
1031 if (ref $value) {
1032 error('double negation is not allowed')
1033 if ref $value eq 'negated' or ref $value eq 'pre_negated';
1035 error('it is not possible to negate an array')
1036 if ref $value eq 'ARRAY' and not $allow_array;
1039 return bless [ $value ], $class || 'negated';
1042 sub format_bool($) {
1043 return $_[0] ? 1 : 0;
1046 sub resolve($\@$) {
1047 my ($resolver, $names, $type) = @_;
1049 my @result;
1050 foreach my $hostname (@$names) {
1051 my $query = $resolver->search($hostname, $type);
1052 error("DNS query for '$hostname' failed: " . $resolver->errorstring)
1053 unless $query;
1055 foreach my $rr ($query->answer) {
1056 next unless $rr->type eq $type;
1058 if ($type eq 'NS') {
1059 push @result, $rr->nsdname;
1060 } elsif ($type eq 'MX') {
1061 push @result, $rr->exchange;
1062 } else {
1063 push @result, $rr->address;
1068 # NS/MX records return host names; resolve these again in the
1069 # second pass (IPv4 only currently)
1070 @result = resolve($resolver, @result, 'A')
1071 if $type eq 'NS' or $type eq 'MX';
1073 return @result;
1076 # returns the next parameter, which may either be a scalar or an array
1077 sub getvalues {
1078 my $code = shift;
1079 my %options = @_;
1081 my $token = require_next_token($code);
1083 if ($token eq '(') {
1084 # read an array until ")"
1085 my @wordlist;
1087 for (;;) {
1088 $token = getvalues($code,
1089 parenthesis_allowed => 1,
1090 comma_allowed => 1);
1092 unless (ref $token) {
1093 last if $token eq ')';
1095 if ($token eq ',') {
1096 error('Comma is not allowed within arrays, please use only a space');
1097 next;
1100 push @wordlist, $token;
1101 } elsif (ref $token eq 'ARRAY') {
1102 push @wordlist, @$token;
1103 } else {
1104 error('unknown toke type');
1108 error('empty array not allowed here')
1109 unless @wordlist or not $options{non_empty};
1111 return @wordlist == 1
1112 ? $wordlist[0]
1113 : \@wordlist;
1114 } elsif ($token =~ /^\`(.*)\`$/s) {
1115 # execute a shell command, insert output
1116 my $command = $1;
1117 my $output = `$command`;
1118 unless ($? == 0) {
1119 if ($? == -1) {
1120 error("failed to execute: $!");
1121 } elsif ($? & 0x7f) {
1122 error("child died with signal " . ($? & 0x7f));
1123 } elsif ($? >> 8) {
1124 error("child exited with status " . ($? >> 8));
1128 # remove comments
1129 $output =~ s/#.*//mg;
1131 # tokenize
1132 my @tokens = grep { length } split /\s+/s, $output;
1134 my @values;
1135 while (@tokens) {
1136 my $value = getvalues(sub { shift @tokens });
1137 push @values, to_array($value);
1140 # and recurse
1141 return @values == 1
1142 ? $values[0]
1143 : \@values;
1144 } elsif ($token =~ /^\'(.*)\'$/s) {
1145 # single quotes: a string
1146 return $1;
1147 } elsif ($token =~ /^\"(.*)\"$/s) {
1148 # double quotes: a string with escapes
1149 $token = $1;
1150 $token =~ s,\$(\w+),string_variable_value($1),eg;
1151 return $token;
1152 } elsif ($token eq '!') {
1153 error('negation is not allowed here')
1154 unless $options{allow_negation};
1156 $token = getvalues($code);
1158 return negate_value($token, undef, $options{allow_array_negation});
1159 } elsif ($token eq ',') {
1160 return $token
1161 if $options{comma_allowed};
1163 error('comma is not allowed here');
1164 } elsif ($token eq '=') {
1165 error('equals operator ("=") is not allowed here');
1166 } elsif ($token eq '$') {
1167 my $name = require_next_token($code);
1168 error('variable name expected - if you want to concatenate strings, try using double quotes')
1169 unless $name =~ /^\w+$/;
1171 my $value = variable_value($name);
1173 error("no such variable: \$$name")
1174 unless defined $value;
1176 return $value;
1177 } elsif ($token eq '&') {
1178 error("function calls are not allowed as keyword parameter");
1179 } elsif ($token eq ')' and not $options{parenthesis_allowed}) {
1180 error('Syntax error');
1181 } elsif ($token =~ /^@/) {
1182 if ($token eq '@resolve') {
1183 my @params = get_function_params();
1184 error('Usage: @resolve((hostname ...), [type])')
1185 unless @params == 1 or @params == 2;
1186 eval { require Net::DNS; };
1187 error('For the @resolve() function, you need the Perl library Net::DNS')
1188 if $@;
1189 my $type = $params[1] || 'A';
1190 error('String expected') if ref $type;
1191 my $resolver = new Net::DNS::Resolver;
1192 @params = to_array($params[0]);
1193 my @result = resolve($resolver, @params, $type);
1194 return @result == 1 ? $result[0] : \@result;
1195 } elsif ($token eq '@eq') {
1196 my @params = get_function_params();
1197 error('Usage: @eq(a, b)') unless @params == 2;
1198 return format_bool($params[0] eq $params[1]);
1199 } elsif ($token eq '@ne') {
1200 my @params = get_function_params();
1201 error('Usage: @ne(a, b)') unless @params == 2;
1202 return format_bool($params[0] ne $params[1]);
1203 } elsif ($token eq '@not') {
1204 my @params = get_function_params();
1205 error('Usage: @not(a)') unless @params == 1;
1206 return format_bool(not $params[0]);
1207 } elsif ($token eq '@cat') {
1208 my $value = '';
1209 map {
1210 error('String expected') if ref $_;
1211 $value .= $_;
1212 } get_function_params();
1213 return $value;
1214 } elsif ($token eq '@substr') {
1215 my @params = get_function_params();
1216 error('Usage: @substr(string, num, num)') unless @params == 3;
1217 error('String expected') if ref $params[0] or ref $params[1] or ref $params[2];
1218 return substr($params[0],$params[1],$params[2]);
1219 } elsif ($token eq '@length') {
1220 my @params = get_function_params();
1221 error('Usage: @length(string)') unless @params == 1;
1222 error('String expected') if ref $params[0];
1223 return length($params[0]);
1224 } elsif ($token eq '@basename') {
1225 my @params = get_function_params();
1226 error('Usage: @basename(path)') unless @params == 1;
1227 error('String expected') if ref $params[0];
1228 my($volume,$path,$file) = File::Spec->splitpath( $params[0] );
1229 return $file;
1230 } elsif ($token eq '@dirname') {
1231 my @params = get_function_params();
1232 error('Usage: @dirname(path)') unless @params == 1;
1233 error('String expected') if ref $params[0];
1234 my($volume,$path,$file) = File::Spec->splitpath( $params[0] );
1235 return $path;
1236 } elsif ($token eq '@ipfilter') {
1237 my @params = get_function_params();
1238 error('Usage: @ipfilter((ip1 ip2 ...))') unless @params == 1;
1239 my $domain = $stack[0]{auto}{DOMAIN};
1240 error('No domain specified') unless defined $domain;
1241 my @ips = to_array($params[0]);
1243 # very crude IPv4/IPv6 address detection
1244 if ($domain eq 'ip') {
1245 @ips = grep { !/:[0-9a-f]*:/ } @ips;
1246 } elsif ($domain eq 'ip6') {
1247 @ips = grep { !m,^[0-9./]+$,s } @ips;
1250 return \@ips;
1251 } else {
1252 error("unknown ferm built-in function");
1254 } else {
1255 return $token;
1259 # returns the next parameter, but only allow a scalar
1260 sub getvar() {
1261 my $token = getvalues();
1263 error('array not allowed here')
1264 if ref $token and ref $token eq 'ARRAY';
1266 return $token;
1269 sub get_function_params(%) {
1270 expect_token('(', 'function name must be followed by "()"');
1272 my $token = peek_token();
1273 if ($token eq ')') {
1274 require_next_token();
1275 return;
1278 my @params;
1280 while (1) {
1281 if (@params > 0) {
1282 $token = require_next_token();
1283 last
1284 if $token eq ')';
1286 error('"," expected')
1287 unless $token eq ',';
1290 push @params, getvalues(undef, @_);
1293 return @params;
1296 # collect all tokens in a flat array reference until the end of the
1297 # command is reached
1298 sub collect_tokens {
1299 my %options = @_;
1301 my @level;
1302 my @tokens;
1304 # re-insert a "line" token, because the starting token of the
1305 # current line has been consumed already
1306 push @tokens, make_line_token($script->{line});
1308 while (1) {
1309 my $keyword = next_raw_token();
1310 error('unexpected end of file within function/variable declaration')
1311 unless defined $keyword;
1313 if (ref $keyword) {
1314 handle_special_token($keyword);
1315 } elsif ($keyword =~ /^[\{\(]$/) {
1316 push @level, $keyword;
1317 } elsif ($keyword =~ /^[\}\)]$/) {
1318 my $expected = $keyword;
1319 $expected =~ tr/\}\)/\{\(/;
1320 my $opener = pop @level;
1321 error("unmatched '$keyword'")
1322 unless defined $opener and $opener eq $expected;
1323 } elsif ($keyword eq ';' and @level == 0) {
1324 push @tokens, $keyword
1325 if $options{include_semicolon};
1327 if ($options{include_else}) {
1328 my $token = peek_token;
1329 next if $token eq '@else';
1332 last;
1335 push @tokens, $keyword;
1337 last
1338 if $keyword eq '}' and @level == 0;
1341 return \@tokens;
1345 # returns the specified value as an array. dereference arrayrefs
1346 sub to_array($) {
1347 my $value = shift;
1348 die unless wantarray;
1349 die if @_;
1350 unless (ref $value) {
1351 return $value;
1352 } elsif (ref $value eq 'ARRAY') {
1353 return @$value;
1354 } else {
1355 die;
1359 # evaluate the specified value as bool
1360 sub eval_bool($) {
1361 my $value = shift;
1362 die if wantarray;
1363 die if @_;
1364 unless (ref $value) {
1365 return $value;
1366 } elsif (ref $value eq 'ARRAY') {
1367 return @$value > 0;
1368 } else {
1369 die;
1373 sub is_netfilter_core_target($) {
1374 my $target = shift;
1375 die unless defined $target and length $target;
1376 return grep { $_ eq $target } qw(ACCEPT DROP RETURN QUEUE);
1379 sub is_netfilter_module_target($$) {
1380 my ($domain_family, $target) = @_;
1381 die unless defined $target and length $target;
1383 return defined $domain_family &&
1384 exists $target_defs{$domain_family} &&
1385 $target_defs{$domain_family}{$target};
1388 sub is_netfilter_builtin_chain($$) {
1389 my ($table, $chain) = @_;
1391 return grep { $_ eq $chain }
1392 qw(PREROUTING INPUT FORWARD OUTPUT POSTROUTING);
1395 sub netfilter_canonical_protocol($) {
1396 my $proto = shift;
1397 return 'icmp'
1398 if $proto eq 'ipv6-icmp' or $proto eq 'icmpv6';
1399 return 'mh'
1400 if $proto eq 'ipv6-mh';
1401 return $proto;
1404 sub netfilter_protocol_module($) {
1405 my $proto = shift;
1406 return unless defined $proto;
1407 return 'icmp6'
1408 if $proto eq 'icmpv6';
1409 return $proto;
1412 # escape the string in a way safe for the shell
1413 sub shell_escape($) {
1414 my $token = shift;
1416 return $token if $token =~ /^[-_a-zA-Z0-9]+$/s;
1418 if ($option{fast}) {
1419 # iptables-save/iptables-restore are quite buggy concerning
1420 # escaping and special characters... we're trying our best
1421 # here
1423 $token =~ s,",\\",g;
1424 $token = '"' . $token . '"'
1425 if $token =~ /[\s\'\\;&]/s or length($token) == 0;
1426 } else {
1427 return $token
1428 if $token =~ /^\`.*\`$/;
1429 $token =~ s/'/'\\''/g;
1430 $token = '\'' . $token . '\''
1431 if $token =~ /[\s\"\\;<>&|]/s or length($token) == 0;
1434 return $token;
1437 # append an option to the shell command line, using information from
1438 # the module definition (see %match_defs etc.)
1439 sub shell_format_option($$) {
1440 my ($keyword, $value) = @_;
1442 my $cmd = '';
1443 if (ref $value) {
1444 if ((ref $value eq 'negated') || (ref $value eq 'pre_negated')) {
1445 $value = $value->[0];
1446 $cmd = ' !';
1450 unless (defined $value) {
1451 $cmd .= " --$keyword";
1452 } elsif (ref $value) {
1453 if (ref $value eq 'params') {
1454 $cmd .= " --$keyword ";
1455 $cmd .= join(' ', map { shell_escape($_) } @$value);
1456 } elsif (ref $value eq 'multi') {
1457 foreach (@$value) {
1458 $cmd .= " --$keyword " . shell_escape($_);
1460 } else {
1461 die;
1463 } else {
1464 $cmd .= " --$keyword " . shell_escape($value);
1467 return $cmd;
1470 sub format_option($$$) {
1471 my ($domain, $name, $value) = @_;
1473 $value = 'icmpv6' if $domain eq 'ip6' and $name eq 'protocol'
1474 and $value eq 'icmp';
1475 $name = 'icmpv6-type' if $domain eq 'ip6' and $name eq 'icmp-type';
1477 if ($domain eq 'ip6' and $name eq 'reject-with') {
1478 my %icmp_map = (
1479 'icmp-net-unreachable' => 'icmp6-no-route',
1480 'icmp-host-unreachable' => 'icmp6-addr-unreachable',
1481 'icmp-port-unreachable' => 'icmp6-port-unreachable',
1482 'icmp-net-prohibited' => 'icmp6-adm-prohibited',
1483 'icmp-host-prohibited' => 'icmp6-adm-prohibited',
1484 'icmp-admin-prohibited' => 'icmp6-adm-prohibited',
1486 $value = $icmp_map{$value} if exists $icmp_map{$value};
1489 return shell_format_option($name, $value);
1492 sub append_rule($$) {
1493 my ($chain_rules, $rule) = @_;
1495 my $cmd = join('', map { $_->[2] } @{$rule->{options}});
1496 push @$chain_rules, { rule => $cmd,
1497 script => $rule->{script},
1501 sub unfold_rule {
1502 my ($domain, $chain_rules, $rule) = (shift, shift, shift);
1503 return append_rule($chain_rules, $rule) unless @_;
1505 my $option = shift;
1506 my @values = @{$option->[1]};
1508 foreach my $value (@values) {
1509 $option->[2] = format_option($domain, $option->[0], $value);
1510 unfold_rule($domain, $chain_rules, $rule, @_);
1514 sub mkrules2($$$) {
1515 my ($domain, $chain_rules, $rule) = @_;
1517 my @unfold;
1518 foreach my $option (@{$rule->{options}}) {
1519 if (ref $option->[1] and ref $option->[1] eq 'ARRAY') {
1520 push @unfold, $option
1521 } else {
1522 $option->[2] = format_option($domain, $option->[0], $option->[1]);
1526 unfold_rule($domain, $chain_rules, $rule, @unfold);
1529 # convert a bunch of internal rule structures in iptables calls,
1530 # unfold arrays during that
1531 sub mkrules($) {
1532 my $rule = shift;
1534 my $domain = $rule->{domain};
1535 my $domain_info = $domains{$domain};
1536 $domain_info->{enabled} = 1;
1538 foreach my $table (to_array $rule->{table}) {
1539 my $table_info = $domain_info->{tables}{$table} ||= {};
1541 foreach my $chain (to_array $rule->{chain}) {
1542 my $chain_rules = $table_info->{chains}{$chain}{rules} ||= [];
1543 mkrules2($domain, $chain_rules, $rule)
1544 if $rule->{has_rule} and not $option{flush};
1549 # parse a keyword from a module definition
1550 sub parse_keyword(\%$$) {
1551 my ($rule, $def, $negated_ref) = @_;
1553 my $params = $def->{params};
1555 my $value;
1557 my $negated;
1558 if ($$negated_ref && exists $def->{pre_negation}) {
1559 $negated = 1;
1560 undef $$negated_ref;
1563 unless (defined $params) {
1564 undef $value;
1565 } elsif (ref $params && ref $params eq 'CODE') {
1566 $value = &$params($rule);
1567 } elsif ($params eq 'm') {
1568 $value = bless [ to_array getvalues() ], 'multi';
1569 } elsif ($params =~ /^[a-z]/) {
1570 if (exists $def->{negation} and not $negated) {
1571 my $token = peek_token();
1572 if ($token eq '!') {
1573 require_next_token();
1574 $negated = 1;
1578 my @params;
1579 foreach my $p (split(//, $params)) {
1580 if ($p eq 's') {
1581 push @params, getvar();
1582 } elsif ($p eq 'c') {
1583 my @v = to_array getvalues(undef, non_empty => 1);
1584 push @params, join(',', @v);
1585 } else {
1586 die;
1590 $value = @params == 1
1591 ? $params[0]
1592 : bless \@params, 'params';
1593 } elsif ($params == 1) {
1594 if (exists $def->{negation} and not $negated) {
1595 my $token = peek_token();
1596 if ($token eq '!') {
1597 require_next_token();
1598 $negated = 1;
1602 $value = getvalues();
1604 warning("log-prefix is too long; truncating to 29 characters: '$1'")
1605 if $def->{name} eq 'log-prefix' && $value =~ s,^(.{29}).+$,$1,;
1606 } else {
1607 if (exists $def->{negation} and not $negated) {
1608 my $token = peek_token();
1609 if ($token eq '!') {
1610 require_next_token();
1611 $negated = 1;
1615 $value = bless [ map {
1616 getvar()
1617 } (1..$params) ], 'params';
1620 $value = negate_value($value, exists $def->{pre_negation} && 'pre_negated')
1621 if $negated;
1623 return $value;
1626 sub append_option(\%$$) {
1627 my ($rule, $name, $value) = @_;
1628 push @{$rule->{options}}, [ $name, $value ];
1631 # parse options of a module
1632 sub parse_option($\%$) {
1633 my ($def, $rule, $negated_ref) = @_;
1635 append_option(%$rule, $def->{name},
1636 parse_keyword(%$rule, $def, $negated_ref));
1639 sub copy_on_write($$) {
1640 my ($rule, $key) = @_;
1641 return unless exists $rule->{cow}{$key};
1642 $rule->{$key} = {%{$rule->{$key}}};
1643 delete $rule->{cow}{$key};
1646 sub new_level(\%$) {
1647 my ($rule, $prev) = @_;
1649 %$rule = ();
1650 if (defined $prev) {
1651 # copy data from previous level
1652 $rule->{cow} = { keywords => 1, };
1653 $rule->{keywords} = $prev->{keywords};
1654 $rule->{match} = { %{$prev->{match}} };
1655 $rule->{options} = [@{$prev->{options}}];
1656 foreach my $key (qw(domain domain_family table chain protocol has_rule has_action)) {
1657 $rule->{$key} = $prev->{$key}
1658 if exists $prev->{$key};
1660 } else {
1661 $rule->{cow} = {};
1662 $rule->{keywords} = {};
1663 $rule->{match} = {};
1664 $rule->{options} = [];
1668 sub merge_keywords(\%$) {
1669 my ($rule, $keywords) = @_;
1670 copy_on_write($rule, 'keywords');
1671 while (my ($name, $def) = each %$keywords) {
1672 $rule->{keywords}{$name} = $def;
1676 sub set_domain(\%$) {
1677 my ($rule, $domain) = @_;
1679 return unless check_domain($domain);
1681 my $domain_family;
1682 unless (ref $domain) {
1683 $domain_family = $domain eq 'ip6' ? 'ip' : $domain;
1684 } elsif (@$domain == 0) {
1685 $domain_family = 'none';
1686 } elsif (grep { not /^ip6?$/s } @$domain) {
1687 error('Cannot combine non-IP domains');
1688 } else {
1689 $domain_family = 'ip';
1692 $rule->{domain_family} = $domain_family;
1693 $rule->{keywords} = $match_defs{$domain_family}{''}{keywords};
1694 $rule->{cow}{keywords} = 1;
1696 $rule->{domain} = $stack[0]{auto}{DOMAIN} = $domain;
1699 sub set_target(\%$$) {
1700 my ($rule, $name, $value) = @_;
1701 error('There can only one action per rule')
1702 if exists $rule->{has_action};
1703 $rule->{has_action} = 1;
1704 append_option(%$rule, $name, $value);
1707 sub set_module_target(\%$$) {
1708 my ($rule, $name, $defs) = @_;
1710 if ($name eq 'TCPMSS') {
1711 my $protos = $rule->{protocol};
1712 error('No protocol specified before TCPMSS')
1713 unless defined $protos;
1714 foreach my $proto (to_array $protos) {
1715 error('TCPMSS not available for protocol "$proto"')
1716 unless $proto eq 'tcp';
1720 # in ebtables, there is both "--mark" and "-j mark"... workaround:
1721 $name = 'mark' if $name eq 'MARK' and $rule->{domain_family} eq 'eb';
1723 set_target(%$rule, 'jump', $name);
1724 merge_keywords(%$rule, $defs->{keywords});
1727 # the main parser loop: read tokens, convert them into internal rule
1728 # structures
1729 sub enter($$) {
1730 my $lev = shift; # current recursion depth
1731 my $prev = shift; # previous rule hash
1733 # enter is the core of the firewall setup, it is a
1734 # simple parser program that recognizes keywords and
1735 # retreives parameters to set up the kernel routing
1736 # chains
1738 my $base_level = $script->{base_level} || 0;
1739 die if $base_level > $lev;
1741 my %rule;
1742 new_level(%rule, $prev);
1744 # read keywords 1 by 1 and dump into parser
1745 while (defined (my $keyword = next_token())) {
1746 # check if the current rule should be negated
1747 my $negated = $keyword eq '!';
1748 if ($negated) {
1749 # negation. get the next word which contains the 'real'
1750 # rule
1751 $keyword = getvar();
1753 error('unexpected end of file after negation')
1754 unless defined $keyword;
1757 # the core: parse all data
1758 for ($keyword)
1760 # deprecated keyword?
1761 if (exists $deprecated_keywords{$keyword}) {
1762 my $new_keyword = $deprecated_keywords{$keyword};
1763 warning("'$keyword' is deprecated, please use '$new_keyword' instead");
1764 $keyword = $new_keyword;
1767 # effectuation operator
1768 if ($keyword eq ';') {
1769 error('Empty rule before ";" not allowed')
1770 unless $rule{non_empty};
1772 if ($rule{has_rule} and not exists $rule{has_action}) {
1773 # something is wrong when a rule was specified,
1774 # but no action
1775 error('No action defined; did you mean "NOP"?');
1778 error('No chain defined') unless exists $rule{chain};
1780 $rule{script} = { filename => $script->{filename},
1781 line => $script->{line},
1784 mkrules(\%rule);
1786 # and clean up variables set in this level
1787 new_level(%rule, $prev);
1789 next;
1792 # conditional expression
1793 if ($keyword eq '@if') {
1794 unless (eval_bool(getvalues)) {
1795 collect_tokens;
1796 my $token = peek_token();
1797 if ($token and $token eq '@else') {
1798 require_next_token();
1799 } else {
1800 new_level(%rule, $prev);
1804 next;
1807 if ($keyword eq '@else') {
1808 # hack: if this "else" has not been eaten by the "if"
1809 # handler above, we believe it came from an if clause
1810 # which evaluated "true" - remove the "else" part now.
1811 collect_tokens;
1812 next;
1815 # hooks for custom shell commands
1816 if ($keyword eq 'hook') {
1817 warning("'hook' is deprecated, use '\@hook'");
1818 $keyword = '@hook';
1821 if ($keyword eq '@hook') {
1822 error('"hook" must be the first token in a command')
1823 if exists $rule{domain};
1825 my $position = getvar();
1826 my $hooks;
1827 if ($position eq 'pre') {
1828 $hooks = \@pre_hooks;
1829 } elsif ($position eq 'post') {
1830 $hooks = \@post_hooks;
1831 } elsif ($position eq 'flush') {
1832 $hooks = \@flush_hooks;
1833 } else {
1834 error("Invalid hook position: '$position'");
1837 push @$hooks, getvar();
1839 expect_token(';');
1840 next;
1843 # recursing operators
1844 if ($keyword eq '{') {
1845 # push stack
1846 my $old_stack_depth = @stack;
1848 unshift @stack, { auto => { %{$stack[0]{auto} || {}} } };
1850 # recurse
1851 enter($lev + 1, \%rule);
1853 # pop stack
1854 shift @stack;
1855 die unless @stack == $old_stack_depth;
1857 # after a block, the command is finished, clear this
1858 # level
1859 new_level(%rule, $prev);
1861 next;
1864 if ($keyword eq '}') {
1865 error('Unmatched "}"')
1866 if $lev <= $base_level;
1868 # consistency check: check if they havn't forgotten
1869 # the ';' after the last statement
1870 error('Missing semicolon before "}"')
1871 if $rule{non_empty};
1873 # and exit
1874 return;
1877 # include another file
1878 if ($keyword eq '@include' or $keyword eq 'include') {
1879 my @files = collect_filenames to_array getvalues;
1880 $keyword = next_token;
1881 error('Missing ";" - "include FILENAME" must be the last command in a rule')
1882 unless defined $keyword and $keyword eq ';';
1884 foreach my $filename (@files) {
1885 # save old script, open new script
1886 my $old_script = $script;
1887 open_script($filename);
1888 $script->{base_level} = $lev + 1;
1890 # push stack
1891 my $old_stack_depth = @stack;
1893 my $stack = {};
1895 if (@stack > 0) {
1896 # include files may set variables for their parent
1897 $stack->{vars} = ($stack[0]{vars} ||= {});
1898 $stack->{functions} = ($stack[0]{functions} ||= {});
1899 $stack->{auto} = { %{ $stack[0]{auto} || {} } };
1902 my( $volume,$dirs,$file ) = File::Spec->splitpath( $filename );
1903 $stack->{auto}{FILENAME} = $filename;
1904 $stack->{auto}{FILEBNAME} = $file;
1905 $stack->{auto}{DIRNAME} = $dirs;
1907 unshift @stack, $stack;
1909 # parse the script
1910 enter($lev + 1, \%rule);
1912 # pop stack
1913 shift @stack;
1914 die unless @stack == $old_stack_depth;
1916 # restore old script
1917 $script = $old_script;
1920 next;
1923 # definition of a variable or function
1924 if ($keyword eq '@def' or $keyword eq 'def') {
1925 error('"def" must be the first token in a command')
1926 if $rule{non_empty};
1928 my $type = require_next_token();
1929 if ($type eq '$') {
1930 my $name = require_next_token();
1931 error('invalid variable name')
1932 unless $name =~ /^\w+$/;
1934 expect_token('=');
1936 my $value = getvalues(undef, allow_negation => 1);
1938 expect_token(';');
1940 $stack[0]{vars}{$name} = $value
1941 unless exists $stack[-1]{vars}{$name};
1942 } elsif ($type eq '&') {
1943 my $name = require_next_token();
1944 error('invalid function name')
1945 unless $name =~ /^\w+$/;
1947 expect_token('(', 'function parameter list or "()" expected');
1949 my @params;
1950 while (1) {
1951 my $token = require_next_token();
1952 last if $token eq ')';
1954 if (@params > 0) {
1955 error('"," expected')
1956 unless $token eq ',';
1958 $token = require_next_token();
1961 error('"$" and parameter name expected')
1962 unless $token eq '$';
1964 $token = require_next_token();
1965 error('invalid function parameter name')
1966 unless $token =~ /^\w+$/;
1968 push @params, $token;
1971 my %function;
1973 $function{params} = \@params;
1975 expect_token('=');
1977 my $tokens = collect_tokens();
1978 $function{block} = 1 if grep { $_ eq '{' } @$tokens;
1979 $function{tokens} = $tokens;
1981 $stack[0]{functions}{$name} = \%function
1982 unless exists $stack[-1]{functions}{$name};
1983 } else {
1984 error('"$" (variable) or "&" (function) expected');
1987 next;
1990 # this rule has something which isn't inherited by its
1991 # parent closure. This variable is used in a lot of
1992 # syntax checks.
1994 $rule{non_empty} = 1;
1996 # def references
1997 if ($keyword eq '$') {
1998 error('variable references are only allowed as keyword parameter');
2001 if ($keyword eq '&') {
2002 my $name = require_next_token();
2003 error('function name expected')
2004 unless $name =~ /^\w+$/;
2006 my $function;
2007 foreach (@stack) {
2008 $function = $_->{functions}{$name};
2009 last if defined $function;
2011 error("no such function: \&$name")
2012 unless defined $function;
2014 my $paramdef = $function->{params};
2015 die unless defined $paramdef;
2017 my @params = get_function_params(allow_negation => 1);
2019 error("Wrong number of parameters for function '\&$name': "
2020 . @$paramdef . " expected, " . @params . " given")
2021 unless @params == @$paramdef;
2023 my %vars;
2024 for (my $i = 0; $i < @params; $i++) {
2025 $vars{$paramdef->[$i]} = $params[$i];
2028 if ($function->{block}) {
2029 # block {} always ends the current rule, so if the
2030 # function contains a block, we have to require
2031 # the calling rule also ends here
2032 expect_token(';');
2035 my @tokens = @{$function->{tokens}};
2036 for (my $i = 0; $i < @tokens; $i++) {
2037 if ($tokens[$i] eq '$' and $i + 1 < @tokens and
2038 exists $vars{$tokens[$i + 1]}) {
2039 my @value = to_array($vars{$tokens[$i + 1]});
2040 @value = ('(', @value, ')')
2041 unless @tokens == 1;
2042 splice(@tokens, $i, 2, @value);
2043 $i += @value - 2;
2044 } elsif ($tokens[$i] =~ m,^"(.*)"$,) {
2045 $tokens[$i] =~ s,\$(\w+),exists $vars{$1} ? $vars{$1} : "\$$1",eg;
2049 unshift @{$script->{tokens}}, @tokens;
2051 next;
2054 # where to put the rule?
2055 if ($keyword eq 'domain') {
2056 error('Domain is already specified')
2057 if exists $rule{domain};
2059 my $domains = getvalues();
2060 if (ref $domains) {
2061 my $tokens = collect_tokens(include_semicolon => 1,
2062 include_else => 1);
2064 my $old_line = $script->{line};
2065 my $old_handle = $script->{handle};
2066 my $old_tokens = $script->{tokens};
2067 my $old_base_level = $script->{base_level};
2068 unshift @$old_tokens, make_line_token($script->{line});
2069 delete $script->{handle};
2071 for my $domain (@$domains) {
2072 my %inner;
2073 new_level(%inner, \%rule);
2074 set_domain(%inner, $domain) or next;
2075 $script->{base_level} = 0;
2076 $script->{tokens} = [ @$tokens ];
2077 enter(0, \%inner);
2080 $script->{base_level} = $old_base_level;
2081 $script->{tokens} = $old_tokens;
2082 $script->{handle} = $old_handle;
2083 $script->{line} = $old_line;
2085 new_level(%rule, $prev);
2086 } else {
2087 unless (set_domain(%rule, $domains)) {
2088 collect_tokens();
2089 new_level(%rule, $prev);
2093 next;
2096 if ($keyword eq 'table') {
2097 warning('Table is already specified')
2098 if exists $rule{table};
2099 $rule{table} = $stack[0]{auto}{TABLE} = getvalues();
2101 set_domain(%rule, $option{domain} || 'ip')
2102 unless exists $rule{domain};
2104 next;
2107 if ($keyword eq 'chain') {
2108 warning('Chain is already specified')
2109 if exists $rule{chain};
2111 my $chain = $rule{chain} = $stack[0]{auto}{CHAIN} = getvalues();
2113 # ferm 1.1 allowed lower case built-in chain names
2114 foreach (ref $rule{chain} ? @{$rule{chain}} : $rule{chain}) {
2115 error('Please write built-in chain names in upper case')
2116 if /^(?:input|forward|output|prerouting|postrouting)$/;
2119 set_domain(%rule, $option{domain} || 'ip')
2120 unless exists $rule{domain};
2122 $rule{table} = 'filter'
2123 unless exists $rule{table};
2125 my $domain = $rule{domain};
2126 foreach my $table (to_array $rule{table}) {
2127 foreach my $c (to_array $chain) {
2128 $domains{$domain}{tables}{$table}{chains}{$c} ||= {};
2132 next;
2135 error('Chain must be specified')
2136 unless exists $rule{chain};
2138 # policy for built-in chain
2139 if ($keyword eq 'policy') {
2140 error('Cannot specify matches for policy')
2141 if $rule{has_rule};
2143 my $policy = getvar();
2144 error("Invalid policy target: $policy")
2145 unless is_netfilter_core_target($policy);
2147 expect_token(';');
2149 my $domain = $rule{domain};
2150 my $domain_info = $domains{$domain};
2151 $domain_info->{enabled} = 1;
2153 foreach my $table (to_array $rule{table}) {
2154 foreach my $chain (to_array $rule{chain}) {
2155 $domain_info->{tables}{$table}{chains}{$chain}{policy} = $policy;
2159 new_level(%rule, $prev);
2160 next;
2163 # create a subchain
2164 if ($keyword eq '@subchain' or $keyword eq 'subchain') {
2165 error('Chain must be specified')
2166 unless exists $rule{chain};
2168 error('No rule specified before "@subchain"')
2169 unless $rule{has_rule};
2171 my $subchain;
2172 my $token = peek_token();
2174 if ($token =~ /^(["'])(.*)\1$/s) {
2175 $subchain = $2;
2176 next_token();
2177 $keyword = next_token();
2178 } elsif ($token eq '{') {
2179 $keyword = next_token();
2180 $subchain = 'ferm_auto_' . ++$auto_chain;
2181 } else {
2182 $subchain = getvar();
2183 $keyword = next_token();
2186 my $domain = $rule{domain};
2187 foreach my $table (to_array $rule{table}) {
2188 $domains{$domain}{tables}{$table}{chains}{$subchain} ||= {};
2191 set_target(%rule, 'jump', $subchain);
2193 error('"{" or chain name expected after "@subchain"')
2194 unless $keyword eq '{';
2196 # create a deep copy of %rule, only containing values
2197 # which must be in the subchain
2198 my %inner = ( cow => { keywords => 1, },
2199 match => {},
2200 options => [],
2202 $inner{$_} = $rule{$_} foreach qw(domain domain_family table keywords);
2203 $inner{chain} = $inner{auto}{CHAIN} = $subchain;
2205 if (exists $rule{protocol}) {
2206 $inner{protocol} = $rule{protocol};
2207 append_option(%inner, 'protocol', $inner{protocol});
2210 # create a new stack frame
2211 my $old_stack_depth = @stack;
2212 my $stack = { auto => { %{$stack[0]{auto} || {}} } };
2213 $stack->{auto}{CHAIN} = $subchain;
2214 unshift @stack, $stack;
2216 # enter the block
2217 enter($lev + 1, \%inner);
2219 # pop stack frame
2220 shift @stack;
2221 die unless @stack == $old_stack_depth;
2223 # now handle the parent - it's a jump to the sub chain
2224 $rule{script} = {
2225 filename => $script->{filename},
2226 line => $script->{line},
2229 mkrules(\%rule);
2231 # and clean up variables set in this level
2232 new_level(%rule, $prev);
2233 delete $rule{has_rule};
2235 next;
2238 # everything else must be part of a "real" rule, not just
2239 # "policy only"
2240 $rule{has_rule} = 1;
2242 # extended parameters:
2243 if ($keyword =~ /^mod(?:ule)?$/) {
2244 foreach my $module (to_array getvalues) {
2245 next if exists $rule{match}{$module};
2247 my $domain_family = $rule{domain_family};
2248 my $defs = $match_defs{$domain_family}{$module};
2250 append_option(%rule, 'match', $module);
2251 $rule{match}{$module} = 1;
2253 merge_keywords(%rule, $defs->{keywords})
2254 if defined $defs;
2257 next;
2260 # keywords from $rule{keywords}
2262 if (exists $rule{keywords}{$keyword}) {
2263 my $def = $rule{keywords}{$keyword};
2264 parse_option($def, %rule, \$negated);
2265 next;
2269 # actions
2272 # jump action
2273 if ($keyword eq 'jump') {
2274 set_target(%rule, 'jump', getvar());
2275 next;
2278 # goto action
2279 if ($keyword eq 'realgoto') {
2280 set_target(%rule, 'goto', getvar());
2281 next;
2284 # action keywords
2285 if (is_netfilter_core_target($keyword)) {
2286 set_target(%rule, 'jump', $keyword);
2287 next;
2290 if ($keyword eq 'NOP') {
2291 error('There can only one action per rule')
2292 if exists $rule{has_action};
2293 $rule{has_action} = 1;
2294 next;
2297 if (my $defs = is_netfilter_module_target($rule{domain_family}, $keyword)) {
2298 set_module_target(%rule, $keyword, $defs);
2299 next;
2303 # protocol specific options
2306 if ($keyword eq 'proto' or $keyword eq 'protocol') {
2307 my $protocol = parse_keyword(%rule,
2308 { params => 1, negation => 1 },
2309 \$negated);
2310 $rule{protocol} = $protocol;
2311 append_option(%rule, 'protocol', $rule{protocol});
2313 unless (ref $protocol) {
2314 $protocol = netfilter_canonical_protocol($protocol);
2315 my $domain_family = $rule{domain_family};
2316 if (my $defs = $proto_defs{$domain_family}{$protocol}) {
2317 merge_keywords(%rule, $defs->{keywords});
2318 my $module = netfilter_protocol_module($protocol);
2319 $rule{match}{$module} = 1;
2322 next;
2325 # port switches
2326 if ($keyword =~ /^[sd]port$/) {
2327 my $proto = $rule{protocol};
2328 error('To use sport or dport, you have to specify "proto tcp" or "proto udp" first')
2329 unless defined $proto and grep { /^(?:tcp|udp|udplite|dccp|sctp)$/ } to_array $proto;
2331 append_option(%rule, $keyword,
2332 getvalues(undef, allow_negation => 1));
2333 next;
2336 # default
2337 error("Unrecognized keyword: $keyword");
2340 # if the rule didn't reset the negated flag, it's not
2341 # supported
2342 error("Doesn't support negation: $keyword")
2343 if $negated;
2346 error('Missing "}" at end of file')
2347 if $lev > $base_level;
2349 # consistency check: check if they havn't forgotten
2350 # the ';' before the last statement
2351 error("Missing semicolon before end of file")
2352 if $rule{non_empty};
2355 sub execute_command {
2356 my ($command, $script) = @_;
2358 print LINES "$command\n"
2359 if $option{lines};
2360 return if $option{noexec};
2362 my $ret = system($command);
2363 unless ($ret == 0) {
2364 if ($? == -1) {
2365 print STDERR "failed to execute: $!\n";
2366 exit 1;
2367 } elsif ($? & 0x7f) {
2368 printf STDERR "child died with signal %d\n", $? & 0x7f;
2369 return 1;
2370 } else {
2371 print STDERR "(rule declared in $script->{filename}:$script->{line})\n"
2372 if defined $script;
2373 return $? >> 8;
2377 return;
2380 sub execute_slow($) {
2381 my $domain_info = shift;
2383 my $domain_cmd = $domain_info->{tools}{tables};
2385 my $status;
2386 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2387 my $table_cmd = "$domain_cmd -t $table";
2389 # reset chain policies
2390 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2391 next unless $chain_info->{builtin} or
2392 (not $table_info->{has_builtin} and
2393 is_netfilter_builtin_chain($table, $chain));
2394 $status ||= execute_command("$table_cmd -P $chain ACCEPT")
2395 unless $option{noflush};
2398 # clear
2399 unless ($option{noflush}) {
2400 $status ||= execute_command("$table_cmd -F");
2401 $status ||= execute_command("$table_cmd -X");
2404 next if $option{flush};
2406 # create chains / set policy
2407 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2408 if (is_netfilter_builtin_chain($table, $chain)) {
2409 if (exists $chain_info->{policy}) {
2410 $status ||= execute_command("$table_cmd -P $chain $chain_info->{policy}")
2411 unless $chain_info->{policy} eq 'ACCEPT';
2413 } else {
2414 if (exists $chain_info->{policy}) {
2415 $status ||= execute_command("$table_cmd -N $chain -P $chain_info->{policy}");
2417 else {
2418 $status ||= execute_command("$table_cmd -N $chain");
2423 # dump rules
2424 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2425 my $chain_cmd = "$table_cmd -A $chain";
2426 foreach my $rule (@{$chain_info->{rules}}) {
2427 $status ||= execute_command($chain_cmd . $rule->{rule});
2432 return $status;
2435 sub table_to_save($$) {
2436 my ($result_r, $table_info) = @_;
2438 foreach my $chain (sort keys %{$table_info->{chains}}) {
2439 my $chain_info = $table_info->{chains}{$chain};
2440 foreach my $rule (@{$chain_info->{rules}}) {
2441 $$result_r .= "-A $chain$rule->{rule}\n";
2446 sub rules_to_save($) {
2447 my ($domain_info) = @_;
2449 # convert this into an iptables-save text
2450 my $result = "# Generated by ferm $VERSION on " . localtime() . "\n";
2452 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2453 # select table
2454 $result .= '*' . $table . "\n";
2456 # create chains / set policy
2457 foreach my $chain (sort keys %{$table_info->{chains}}) {
2458 my $chain_info = $table_info->{chains}{$chain};
2459 my $policy = $option{flush} ? undef : $chain_info->{policy};
2460 unless (defined $policy) {
2461 if (is_netfilter_builtin_chain($table, $chain)) {
2462 $policy = 'ACCEPT';
2463 } else {
2464 next if $option{flush};
2465 $policy = '-';
2468 $result .= ":$chain $policy\ [0:0]\n";
2471 table_to_save(\$result, $table_info)
2472 unless $option{flush};
2474 # do it
2475 $result .= "COMMIT\n";
2478 return $result;
2481 sub restore_domain($$) {
2482 my ($domain_info, $save) = @_;
2484 my $path = $domain_info->{tools}{'tables-restore'};
2485 $path .= " --noflush" if $option{noflush};
2487 local *RESTORE;
2488 open RESTORE, "|$path"
2489 or die "Failed to run $path: $!\n";
2491 print RESTORE $save;
2493 close RESTORE
2494 or die "Failed to run $path\n";
2497 sub execute_fast($) {
2498 my $domain_info = shift;
2500 my $save = rules_to_save($domain_info);
2502 if ($option{lines}) {
2503 my $path = $domain_info->{tools}{'tables-restore'};
2504 $path .= " --noflush" if $option{noflush};
2505 print LINES "$path <<EOT\n"
2506 if $option{shell};
2507 print LINES $save;
2508 print LINES "EOT\n"
2509 if $option{shell};
2512 return if $option{noexec};
2514 eval {
2515 restore_domain($domain_info, $save);
2517 if ($@) {
2518 print STDERR $@;
2519 return 1;
2522 return;
2525 sub rollback() {
2526 my $error;
2527 while (my ($domain, $domain_info) = each %domains) {
2528 next unless $domain_info->{enabled};
2529 unless (defined $domain_info->{tools}{'tables-restore'}) {
2530 print STDERR "Cannot rollback domain '$domain' because there is no ${domain}tables-restore\n";
2531 next;
2534 my $reset = '';
2535 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2536 my $reset_chain = '';
2537 foreach my $chain (keys %{$table_info->{chains}}) {
2538 next unless is_netfilter_builtin_chain($table, $chain);
2539 $reset_chain .= ":${chain} ACCEPT [0:0]\n";
2541 $reset .= "*${table}\n${reset_chain}COMMIT\n"
2542 if length $reset_chain;
2545 $reset .= $domain_info->{previous}
2546 if defined $domain_info->{previous};
2548 restore_domain($domain_info, $reset);
2551 print STDERR "\nFirewall rules rolled back.\n" unless $error;
2552 exit 1;
2555 sub alrm_handler {
2556 # do nothing, just interrupt a system call
2559 sub confirm_rules {
2560 $SIG{ALRM} = \&alrm_handler;
2562 alarm(5);
2564 print STDERR "\n"
2565 . "ferm has applied the new firewall rules.\n"
2566 . "Please type 'yes' to confirm:\n";
2567 STDERR->flush();
2569 alarm($option{timeout});
2571 my $line = '';
2572 STDIN->sysread($line, 3);
2574 eval {
2575 require POSIX;
2576 POSIX::tcflush(*STDIN, 2);
2578 print STDERR "$@" if $@;
2580 $SIG{ALRM} = 'DEFAULT';
2582 return $line eq 'yes';
2585 # end of ferm
2587 __END__
2589 =head1 NAME
2591 ferm - a firewall rule parser for linux
2593 =head1 SYNOPSIS
2595 B<ferm> I<options> I<inputfiles>
2597 =head1 OPTIONS
2599 -n, --noexec Do not execute the rules, just simulate
2600 -F, --flush Flush all netfilter tables managed by ferm
2601 -l, --lines Show all rules that were created
2602 -i, --interactive Interactive mode: revert if user does not confirm
2603 -t, --timeout s Define interactive mode timeout in seconds
2604 --remote Remote mode; ignore host specific configuration.
2605 This implies --noexec and --lines.
2606 -V, --version Show current version number
2607 -h, --help Look at this text
2608 --slow Slow mode, don't use iptables-restore
2609 --shell Generate a shell script which calls iptables-restore
2610 --domain {ip|ip6} Handle only the specified domain
2611 --def '$name=v' Override a variable
2613 =cut