@defined() support functions
[ferm.git] / src / ferm
blob3cb00ca6e5a2c858c4f4ffb7f1710ca579c37f83
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.2.1';
52 $VERSION .= '~git';
54 ## interface variables
55 # %option = command line and other options
56 use vars qw(%option);
58 ## hooks
59 use vars qw(@pre_hooks @post_hooks @flush_hooks);
61 ## parser variables
62 # $script: current script file
63 # @stack = ferm's parser stack containing local variables
64 # $auto_chain = index for the next auto-generated chain
65 use vars qw($script @stack $auto_chain);
67 ## netfilter variables
68 # %domains = state information about all domains ("ip" and "ip6")
69 # - initialized: domain initialization is done
70 # - tools: hash providing the paths of the domain's tools
71 # - previous: save file of the previous ruleset, for rollback
72 # - tables{$name}: ferm state information about tables
73 # - has_builtin: whether built-in chains have been determined in this table
74 # - chains{$chain}: ferm state information about the chains
75 # - builtin: whether this is a built-in chain
76 use vars qw(%domains);
78 ## constants
79 use vars qw(%deprecated_keywords);
81 # keywords from ferm 1.1 which are deprecated, and the new one; these
82 # are automatically replaced, and a warning is printed
83 %deprecated_keywords = ( goto => 'jump',
86 # these hashes provide the Netfilter module definitions
87 use vars qw(%proto_defs %match_defs %target_defs);
90 # This subsubsystem allows you to support (most) new netfilter modules
91 # in ferm. Add a call to one of the "add_XY_def()" functions below.
93 # Ok, now about the cryptic syntax: the function "add_XY_def()"
94 # registers a new module. There are three kinds of modules: protocol
95 # module (e.g. TCP, ICMP), match modules (e.g. state, physdev) and
96 # target modules (e.g. DNAT, MARK).
98 # The first parameter is always the module name which is passed to
99 # iptables with "-p", "-m" or "-j" (depending on which kind of module
100 # this is).
102 # After that, you add an encoded string for each option the module
103 # supports. This is where it becomes tricky.
105 # foo defaults to an option with one argument (which may be a ferm
106 # array)
108 # foo*0 option without any arguments
110 # foo=s one argument which must not be a ferm array ('s' stands for
111 # 'scalar')
113 # u32=m an array which renders into multiple iptables options in one
114 # rule
116 # ctstate=c one argument, if it's an array, pass it to iptables as a
117 # single comma separated value; example:
118 # ctstate (ESTABLISHED RELATED) translates to:
119 # --ctstate ESTABLISHED,RELATED
121 # foo=sac three arguments: scalar, array, comma separated; you may
122 # concatenate more than one letter code after the '='
124 # foo&bar one argument; call the perl function '&bar()' which parses
125 # the argument
127 # !foo negation is allowed and the '!' is written before the keyword
129 # foo! same as above, but '!' is after the keyword and before the
130 # parameters
132 # to:=to-destination makes "to" an alias for "to-destination"; you have
133 # to add a declaration for option "to-destination"
136 # prototype declarations
137 sub open_script($);
138 sub resolve($\@$);
139 sub enter($$);
140 sub rollback();
141 sub execute_fast($);
142 sub execute_slow($);
143 sub join_value($$);
144 sub ipfilter($@);
146 # add a module definition
147 sub add_def_x {
148 my $defs = shift;
149 my $domain_family = shift;
150 my $params_default = shift;
151 my $name = shift;
152 die if exists $defs->{$domain_family}{$name};
153 my $def = $defs->{$domain_family}{$name} = {};
154 foreach (@_) {
155 my $keyword = $_;
156 my $k;
158 if ($keyword =~ s,:=(\S+)$,,) {
159 $k = $def->{keywords}{$1} || die;
160 $k->{ferm_name} ||= $keyword;
161 } else {
162 my $params = $params_default;
163 $params = $1 if $keyword =~ s,\*(\d+)$,,;
164 $params = $1 if $keyword =~ s,=([acs]+|m)$,,;
165 if ($keyword =~ s,&(\S+)$,,) {
166 $params = eval "\\&$1";
167 die $@ if $@;
170 $k = {};
171 $k->{params} = $params if $params;
173 $k->{negation} = $k->{pre_negation} = 1 if $keyword =~ s,^!,,;
174 $k->{negation} = 1 if $keyword =~ s,!$,,;
175 $k->{name} = $keyword;
178 $def->{keywords}{$keyword} = $k;
181 return $def;
184 # add a protocol module definition
185 sub add_proto_def_x(@) {
186 my $domain_family = shift;
187 add_def_x(\%proto_defs, $domain_family, 1, @_);
190 # add a match module definition
191 sub add_match_def_x(@) {
192 my $domain_family = shift;
193 add_def_x(\%match_defs, $domain_family, 1, @_);
196 # add a target module definition
197 sub add_target_def_x(@) {
198 my $domain_family = shift;
199 add_def_x(\%target_defs, $domain_family, 's', @_);
202 sub add_def {
203 my $defs = shift;
204 add_def_x($defs, 'ip', @_);
207 # add a protocol module definition
208 sub add_proto_def(@) {
209 add_def(\%proto_defs, 1, @_);
212 # add a match module definition
213 sub add_match_def(@) {
214 add_def(\%match_defs, 1, @_);
217 # add a target module definition
218 sub add_target_def(@) {
219 add_def(\%target_defs, 's', @_);
222 add_proto_def 'dccp', qw(dccp-types!=c dccp-option!);
223 add_proto_def 'mh', qw(mh-type!);
224 add_proto_def 'icmp', qw(icmp-type! icmpv6-type:=icmp-type);
225 add_proto_def 'sctp', qw(chunk-types!=sc);
226 add_proto_def 'tcp', qw(tcp-flags!=cc !syn*0 tcp-option! mss);
227 add_proto_def 'udp', qw();
229 add_match_def '',
230 # --source, --destination
231 qw(source!&address_magic saddr:=source),
232 qw(destination!&address_magic daddr:=destination),
233 # --in-interface
234 qw(in-interface! interface:=in-interface if:=in-interface),
235 # --out-interface
236 qw(out-interface! outerface:=out-interface of:=out-interface),
237 # --fragment
238 qw(!fragment*0);
239 add_match_def 'account', qw(aaddr=s aname=s ashort*0);
240 add_match_def 'addrtype', qw(!src-type !dst-type),
241 qw(limit-iface-in*0 limit-iface-out*0);
242 add_match_def 'ah', qw(ahspi! ahlen! ahres*0);
243 add_match_def 'comment', qw(comment=s);
244 add_match_def 'condition', qw(condition!);
245 add_match_def 'connbytes', qw(!connbytes connbytes-dir connbytes-mode);
246 add_match_def 'connlimit', qw(!connlimit-above connlimit-mask);
247 add_match_def 'connmark', qw(!mark);
248 add_match_def 'conntrack', qw(!ctstate=c !ctproto ctorigsrc! ctorigdst! ctorigsrcport! ctorigdstport!),
249 qw(ctreplsrc! ctrepldst! !ctstatus !ctexpire=s ctdir=s);
250 add_match_def 'dscp', qw(dscp dscp-class);
251 add_match_def 'ecn', qw(ecn-tcp-cwr*0 ecn-tcp-ece*0 ecn-ip-ect);
252 add_match_def 'esp', qw(espspi!);
253 add_match_def 'eui64';
254 add_match_def 'fuzzy', qw(lower-limit=s upper-limit=s);
255 add_match_def 'hbh', qw(hbh-len! hbh-opts=c);
256 add_match_def 'helper', qw(helper);
257 add_match_def 'hl', qw(hl-eq! hl-lt=s hl-gt=s);
258 add_match_def 'hashlimit', qw(hashlimit=s hashlimit-burst=s hashlimit-mode=c hashlimit-name=s),
259 qw(hashlimit-htable-size=s hashlimit-htable-max=s),
260 qw(hashlimit-htable-expire=s hashlimit-htable-gcinterval=s);
261 add_match_def 'iprange', qw(!src-range !dst-range);
262 add_match_def 'ipv4options', qw(ssrr*0 lsrr*0 no-srr*0 !rr*0 !ts*0 !ra*0 !any-opt*0);
263 add_match_def 'ipv6header', qw(header!=c soft*0);
264 add_match_def 'length', qw(length!);
265 add_match_def 'limit', qw(limit=s limit-burst=s);
266 add_match_def 'mac', qw(mac-source!);
267 add_match_def 'mark', qw(!mark);
268 add_match_def 'multiport', qw(source-ports!&multiport_params),
269 qw(destination-ports!&multiport_params ports!&multiport_params);
270 add_match_def 'nth', qw(every counter start packet);
271 add_match_def 'osf', qw(!genre ttl=s log=s);
272 add_match_def 'owner', qw(!uid-owner !gid-owner pid-owner sid-owner),
273 qw(cmd-owner !socket-exists=0);
274 add_match_def 'physdev', qw(physdev-in! physdev-out!),
275 qw(!physdev-is-in*0 !physdev-is-out*0 !physdev-is-bridged*0);
276 add_match_def 'pkttype', qw(pkt-type!),
277 add_match_def 'policy',
278 qw(dir pol strict*0 !reqid !spi !proto !mode !tunnel-src !tunnel-dst next*0);
279 add_match_def 'psd', qw(psd-weight-threshold psd-delay-threshold),
280 qw(psd-lo-ports-weight psd-hi-ports-weight);
281 add_match_def 'quota', qw(quota=s);
282 add_match_def 'random', qw(average);
283 add_match_def 'realm', qw(realm!);
284 add_match_def 'recent', qw(name=s !set*0 !remove*0 !rcheck*0 !update*0 !seconds !hitcount rttl*0 rsource*0 rdest*0);
285 add_match_def 'rt', qw(rt-type! rt-segsleft! rt-len! rt-0-res*0 rt-0-addrs=c rt-0-not-strict*0);
286 add_match_def 'set', qw(!match-set=sc set:=match-set);
287 add_match_def 'state', qw(!state=c);
288 add_match_def 'statistic', qw(mode=s probability=s every=s packet=s);
289 add_match_def 'string', qw(algo=s from=s to=s string hex-string);
290 add_match_def 'tcpmss', qw(!mss);
291 add_match_def 'time', qw(timestart=s timestop=s days=c datestart=s datestop=s),
292 qw(!monthday=c !weekdays=c utc*0 localtz*0);
293 add_match_def 'tos', qw(!tos);
294 add_match_def 'ttl', qw(ttl-eq ttl-lt=s ttl-gt=s);
295 add_match_def 'u32', qw(!u32=m);
297 add_target_def 'BALANCE', qw(to-destination to:=to-destination);
298 add_target_def 'CHECKSUM', qw(checksum-fill*0);
299 add_target_def 'CLASSIFY', qw(set-class);
300 add_target_def 'CLUSTERIP', qw(new*0 hashmode clustermac total-nodes local-node hash-init);
301 add_target_def 'CONNMARK', qw(set-mark save-mark*0 restore-mark*0 mask);
302 add_target_def 'CONNSECMARK', qw(save*0 restore*0);
303 add_target_def 'CT', qw(notrack*0 helper ctevents=c expevents=c zone timeout);
304 add_target_def 'DNAT', qw(to-destination=m to:=to-destination persistent*0 random*0);
305 add_target_def 'DSCP', qw(set-dscp set-dscp-class);
306 add_target_def 'ECN', qw(ecn-tcp-remove*0);
307 add_target_def 'HL', qw(hl-set hl-dec hl-inc);
308 add_target_def 'IPV4OPTSSTRIP';
309 add_target_def 'LOG', qw(log-level log-prefix),
310 qw(log-tcp-sequence*0 log-tcp-options*0 log-ip-options*0 log-uid*0);
311 add_target_def 'MARK', qw(set-mark set-xmark and-mark or-mark xor-mark);
312 add_target_def 'MASQUERADE', qw(to-ports random*0);
313 add_target_def 'MIRROR';
314 add_target_def 'NETMAP', qw(to);
315 add_target_def 'NFLOG', qw(nflog-group nflog-prefix nflog-range nflog-threshold);
316 add_target_def 'NFQUEUE', qw(queue-num queue-balance queue-bypass*0 queue-cpu-fanout*0);
317 add_target_def 'NOTRACK';
318 add_target_def 'REDIRECT', qw(to-ports random*0);
319 add_target_def 'REJECT', qw(reject-with);
320 add_target_def 'ROUTE', qw(oif iif gw continue*0 tee*0);
321 add_target_def 'SAME', qw(to nodst*0 random*0);
322 add_target_def 'SECMARK', qw(selctx);
323 add_target_def 'SET', qw(add-set=sc del-set=sc);
324 add_target_def 'SNAT', qw(to-source=m to:=to-source persistent*0 random*0);
325 add_target_def 'TARPIT';
326 add_target_def 'TCPMSS', qw(set-mss clamp-mss-to-pmtu*0);
327 add_target_def 'TEE', qw(gateway);
328 add_target_def 'TOS', qw(set-tos and-tos or-tos xor-tos);
329 add_target_def 'TPROXY', qw(tproxy-mark on-port);
330 add_target_def 'TRACE';
331 add_target_def 'TTL', qw(ttl-set ttl-dec ttl-inc);
332 add_target_def 'ULOG', qw(ulog-nlgroup ulog-prefix ulog-cprange ulog-qthreshold);
334 add_match_def_x 'arp', '',
335 # ip
336 qw(source-ip! destination-ip! saddr:=source-ip daddr:=destination-ip),
337 # mac
338 qw(source-mac! destination-mac!),
339 # --in-interface
340 qw(in-interface! interface:=in-interface if:=in-interface),
341 # --out-interface
342 qw(out-interface! outerface:=out-interface of:=out-interface),
343 # misc
344 qw(h-length=s opcode=s h-type=s proto-type=s),
345 qw(mangle-ip-s=s mangle-ip-d=s mangle-mac-s=s mangle-mac-d=s mangle-target=s);
347 add_proto_def_x 'eb', 'IPv4',
348 qw(ip-source! ip-destination! ip-src:=ip-source ip-dst:=ip-destination),
349 qw(ip-tos!),
350 qw(ip-protocol! ip-proto:=ip-protocol),
351 qw(ip-source-port! ip-sport:=ip-source-port),
352 qw(ip-destination-port! ip-dport:=ip-destination-port);
354 add_proto_def_x 'eb', 'IPv6',
355 qw(ip6-source! ip6-destination! ip6-src:=ip6-source ip6-dst:=ip6-destination),
356 qw(ip6-tclass!),
357 qw(ip6-protocol! ip6-proto:=ip6-protocol),
358 qw(ip6-source-port! ip6-sport:=ip6-source-port),
359 qw(ip6-destination-port! ip6-dport:=ip6-destination-port);
361 add_proto_def_x 'eb', 'ARP',
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', 'RARP',
367 qw(!arp-gratuitous*0),
368 qw(arp-opcode! arp-htype!=ss arp-ptype!=ss),
369 qw(arp-ip-src! arp-ip-dst! arp-mac-src! arp-mac-dst!);
371 add_proto_def_x 'eb', '802_1Q',
372 qw(vlan-id! vlan-prio! vlan-encap!),
374 add_match_def_x 'eb', '',
375 # --in-interface
376 qw(in-interface! interface:=in-interface if:=in-interface),
377 # --out-interface
378 qw(out-interface! outerface:=out-interface of:=out-interface),
379 # logical interface
380 qw(logical-in! logical-out!),
381 # --source, --destination
382 qw(source! saddr:=source destination! daddr:=destination),
383 # 802.3
384 qw(802_3-sap! 802_3-type!),
385 # among
386 qw(!among-dst=c !among-src=c !among-dst-file !among-src-file),
387 # limit
388 qw(limit=s limit-burst=s),
389 # mark_m
390 qw(mark!),
391 # pkttype
392 qw(pkttype-type!),
393 # stp
394 qw(stp-type! stp-flags! stp-root-prio! stp-root-addr! stp-root-cost!),
395 qw(stp-sender-prio! stp-sender-addr! stp-port! stp-msg-age! stp-max-age!),
396 qw(stp-hello-time! stp-forward-delay!),
397 # log
398 qw(log*0 log-level=s log-prefix=s log-ip*0 log-arp*0);
400 add_target_def_x 'eb', 'arpreply', qw(arpreply-mac arpreply-target);
401 add_target_def_x 'eb', 'dnat', qw(to-destination dnat-target);
402 add_target_def_x 'eb', 'MARK', qw(set-mark mark-target);
403 add_target_def_x 'eb', 'redirect', qw(redirect-target);
404 add_target_def_x 'eb', 'snat', qw(to-source snat-target snat-arp*0);
406 # import-ferm uses the above tables
407 return 1 if $0 =~ /import-ferm$/;
409 # parameter parser for ipt_multiport
410 sub multiport_params {
411 my $rule = shift;
413 # multiport only allows 15 ports at a time. For this
414 # reason, we do a little magic here: split the ports
415 # into portions of 15, and handle these portions as
416 # array elements
418 my $proto = $rule->{protocol};
419 error('To use multiport, you have to specify "proto tcp" or "proto udp" first')
420 unless defined $proto and grep { /^(?:tcp|udp|udplite)$/ } to_array($proto);
422 my $value = getvalues(undef, allow_negation => 1,
423 allow_array_negation => 1);
424 if (ref $value and ref $value eq 'ARRAY') {
425 my @value = @$value;
426 my @params;
428 while (@value) {
429 push @params, join(',', splice(@value, 0, 15));
432 return @params == 1
433 ? $params[0]
434 : \@params;
435 } else {
436 return join_value(',', $value);
440 sub ipfilter($@) {
441 my $domain = shift;
442 my @ips;
443 # very crude IPv4/IPv6 address detection
444 if ($domain eq 'ip') {
445 @ips = grep { !/:[0-9a-f]*:/ } @_;
446 } elsif ($domain eq 'ip6') {
447 @ips = grep { !m,^[0-9./]+$,s } @_;
449 return @ips;
452 sub address_magic {
453 my $rule = shift;
454 my $domain = $rule->{domain};
455 my $value = getvalues(undef, allow_negation => 1);
457 my @ips;
458 my $negated = 0;
459 if (ref $value and ref $value eq 'ARRAY') {
460 @ips = @$value;
461 } elsif (ref $value and ref $value eq 'negated') {
462 @ips = @$value;
463 $negated = 1;
464 } elsif (ref $value) {
465 die;
466 } else {
467 @ips = ($value);
470 # only do magic on domain (ip ip6); do not process on a single-stack rule
471 # as to let admins spot their errors instead of silently ignoring them
472 @ips = ipfilter($domain, @ips) if defined $rule->{domain_both};
474 if ($negated && scalar @ips) {
475 return bless \@ips, 'negated';
476 } else {
477 return \@ips;
481 # initialize stack: command line definitions
482 unshift @stack, {};
484 # Get command line stuff
485 if ($has_getopt) {
486 my ($opt_noexec, $opt_flush, $opt_noflush, $opt_lines, $opt_interactive,
487 $opt_timeout, $opt_help,
488 $opt_version, $opt_test, $opt_fast, $opt_slow, $opt_shell,
489 $opt_domain);
491 Getopt::Long::Configure('bundling', 'auto_help', 'no_ignore_case',
492 'no_auto_abbrev');
494 sub opt_def {
495 my ($opt, $value) = @_;
496 die 'Invalid --def specification'
497 unless $value =~ /^\$?(\w+)=(.*)$/s;
498 my ($name, $unparsed_value) = ($1, $2);
499 my $tokens = tokenize_string($unparsed_value);
500 $value = getvalues(sub { shift @$tokens; });
501 die 'Extra tokens after --def'
502 if @$tokens > 0;
503 $stack[0]{vars}{$name} = $value;
506 local $SIG{__WARN__} = sub { die $_[0]; };
507 GetOptions('noexec|n' => \$opt_noexec,
508 'flush|F' => \$opt_flush,
509 'noflush' => \$opt_noflush,
510 'lines|l' => \$opt_lines,
511 'interactive|i' => \$opt_interactive,
512 'timeout|t=s' => \$opt_timeout,
513 'help|h' => \$opt_help,
514 'version|V' => \$opt_version,
515 test => \$opt_test,
516 remote => \$opt_test,
517 fast => \$opt_fast,
518 slow => \$opt_slow,
519 shell => \$opt_shell,
520 'domain=s' => \$opt_domain,
521 'def=s' => \&opt_def,
524 if (defined $opt_help) {
525 require Pod::Usage;
526 Pod::Usage::pod2usage(-exitstatus => 0);
529 if (defined $opt_version) {
530 printversion();
531 exit 0;
534 $option{noexec} = $opt_noexec || $opt_test;
535 $option{flush} = $opt_flush;
536 $option{noflush} = $opt_noflush;
537 $option{lines} = $opt_lines || $opt_test || $opt_shell;
538 $option{interactive} = $opt_interactive && !$opt_noexec;
539 $option{timeout} = defined $opt_timeout ? $opt_timeout : "30";
540 $option{test} = $opt_test;
541 $option{fast} = !$opt_slow;
542 $option{shell} = $opt_shell;
544 die("ferm interactive mode not possible: /dev/stdin is not a tty\n")
545 if $option{interactive} and not -t STDIN;
546 die("ferm interactive mode not possible: /dev/stderr is not a tty\n")
547 if $option{interactive} and not -t STDERR;
548 die("ferm timeout has no sense without interactive mode")
549 if not $opt_interactive and defined $opt_timeout;
550 die("invalid timeout. must be an integer")
551 if defined $opt_timeout and not $opt_timeout =~ /^[+-]?\d+$/;
553 $option{domain} = $opt_domain if defined $opt_domain;
554 } else {
555 # tiny getopt emulation for microperl
556 my $filename;
557 foreach (@ARGV) {
558 if ($_ eq '--noexec' or $_ eq '-n') {
559 $option{noexec} = 1;
560 } elsif ($_ eq '--lines' or $_ eq '-l') {
561 $option{lines} = 1;
562 } elsif ($_ eq '--fast') {
563 $option{fast} = 1;
564 } elsif ($_ eq '--test') {
565 $option{test} = 1;
566 $option{noexec} = 1;
567 $option{lines} = 1;
568 } elsif ($_ eq '--shell') {
569 $option{$_} = 1 foreach qw(shell fast lines);
570 } elsif (/^-/) {
571 printf STDERR "Usage: ferm [--noexec] [--lines] [--fast] [--shell] FILENAME\n";
572 exit 1;
573 } else {
574 $filename = $_;
577 undef @ARGV;
578 push @ARGV, $filename;
581 unless (@ARGV == 1) {
582 require Pod::Usage;
583 Pod::Usage::pod2usage(-exitstatus => 1);
586 if ($has_strict) {
587 open LINES, ">&STDOUT" if $option{lines};
588 open STDOUT, ">&STDERR" if $option{shell};
589 } else {
590 # microperl can't redirect file handles
591 *LINES = *STDOUT;
593 if ($option{fast} and not $option{noexec}) {
594 print STDERR "Sorry, ferm on microperl does not allow --fast without --noexec\n";
595 exit 1
599 unshift @stack, {};
600 open_script($ARGV[0]);
602 my( $volume,$dirs,$file ) = File::Spec->splitpath( $ARGV[0] );
603 $stack[0]{auto}{FILENAME} = $ARGV[0];
604 $stack[0]{auto}{FILEBNAME} = $file;
605 $stack[0]{auto}{DIRNAME} = $dirs;
609 # parse all input recursively
610 enter(0, undef);
611 die unless @stack == 2;
613 # enable/disable hooks depending on --flush
615 if ($option{flush}) {
616 undef @pre_hooks;
617 undef @post_hooks;
618 } else {
619 undef @flush_hooks;
622 # execute all generated rules
623 my $status;
625 foreach my $cmd (@pre_hooks) {
626 print LINES "$cmd\n" if $option{lines};
627 system($cmd) unless $option{noexec};
630 while (my ($domain, $domain_info) = each %domains) {
631 next unless $domain_info->{enabled};
632 my $s = $option{fast} &&
633 defined $domain_info->{tools}{'tables-restore'}
634 ? execute_fast($domain_info) : execute_slow($domain_info);
635 $status = $s if defined $s;
638 foreach my $cmd (@post_hooks, @flush_hooks) {
639 print LINES "$cmd\n" if $option{lines};
640 system($cmd) unless $option{noexec};
643 if (defined $status) {
644 rollback();
645 exit $status;
648 # ask user, and rollback if there is no confirmation
650 if ($option{interactive}) {
651 if ($option{shell}) {
652 print LINES "echo 'ferm has applied the new firewall rules.'\n";
653 print LINES "echo 'Please press Ctrl-C to confirm.'\n";
654 print LINES "sleep $option{timeout}\n";
655 while (my ($domain, $domain_info) = each %domains) {
656 my $restore = $domain_info->{tools}{'tables-restore'};
657 next unless defined $restore;
658 print LINES "$restore <\$${domain}_tmp\n";
662 confirm_rules() or rollback() unless $option{noexec};
665 exit 0;
667 # end of program execution!
670 # funcs
672 sub printversion {
673 print "ferm $VERSION\n";
674 print "Copyright (C) 2001-2012 Max Kellermann, Auke Kok\n";
675 print "This program is free software released under GPLv2.\n";
676 print "See the included COPYING file for license details.\n";
680 sub error {
681 # returns a nice formatted error message, showing the
682 # location of the error.
683 my $tabs = 0;
684 my @lines;
685 my $l = 0;
686 my @words = map { @$_ } @{$script->{past_tokens}};
688 for my $w ( 0 .. $#words ) {
689 if ($words[$w] eq "\x29")
690 { $l++ ; $lines[$l] = " " x ($tabs-- -1) ;};
691 if ($words[$w] eq "\x28")
692 { $l++ ; $lines[$l] = " " x $tabs++ ;};
693 if ($words[$w] eq "\x7d")
694 { $l++ ; $lines[$l] = " " x ($tabs-- -1) ;};
695 if ($words[$w] eq "\x7b")
696 { $l++ ; $lines[$l] = " " x $tabs++ ;};
697 if ( $l > $#lines ) { $lines[$l] = "" };
698 $lines[$l] .= $words[$w] . " ";
699 if ($words[$w] eq "\x28")
700 { $l++ ; $lines[$l] = " " x $tabs ;};
701 if (($words[$w] eq "\x29") && ($words[$w+1] ne "\x7b"))
702 { $l++ ; $lines[$l] = " " x $tabs ;};
703 if ($words[$w] eq "\x7b")
704 { $l++ ; $lines[$l] = " " x $tabs ;};
705 if (($words[$w] eq "\x7d") && ($words[$w+1] ne "\x7d"))
706 { $l++ ; $lines[$l] = " " x $tabs ;};
707 if (($words[$w] eq "\x3b") && ($words[$w+1] ne "\x7d"))
708 { $l++ ; $lines[$l] = " " x $tabs ;}
709 if ($words[$w-1] eq "option")
710 { $l++ ; $lines[$l] = " " x $tabs ;}
712 my $start = $#lines - 4;
713 if ($start < 0) { $start = 0 } ;
714 print STDERR "Error in $script->{filename} line $script->{line}:\n";
715 for $l ( $start .. $#lines)
716 { print STDERR $lines[$l]; if ($l != $#lines ) {print STDERR "\n"} ; };
717 print STDERR "<--\n";
718 die("@_\n");
721 # print a warning message about code from an input file
722 sub warning {
723 print STDERR "Warning in $script->{filename} line $script->{line}: "
724 . (shift) . "\n";
727 sub find_tool($) {
728 my $name = shift;
729 return $name if $option{test};
730 for my $path ('/sbin', split ':', $ENV{PATH}) {
731 my $ret = "$path/$name";
732 return $ret if -x $ret;
734 die "$name not found in PATH\n";
737 sub initialize_domain {
738 my $domain = shift;
739 my $domain_info = $domains{$domain} ||= {};
741 return if exists $domain_info->{initialized};
743 die "Invalid domain '$domain'\n" unless $domain =~ /^(?:ip6?|arp|eb)$/;
745 my @tools = qw(tables);
746 push @tools, qw(tables-save tables-restore)
747 if $domain =~ /^ip6?$/;
749 # determine the location of this domain's tools
750 my %tools = map { $_ => find_tool($domain . $_) } @tools;
751 $domain_info->{tools} = \%tools;
753 # make tables-save tell us about the state of this domain
754 # (which tables and chains do exist?), also remember the old
755 # save data which may be used later by the rollback function
756 local *SAVE;
757 if (!$option{test} &&
758 exists $tools{'tables-save'} &&
759 open(SAVE, "$tools{'tables-save'}|")) {
760 my $save = '';
762 my $table_info;
763 while (<SAVE>) {
764 $save .= $_;
766 if (/^\*(\w+)/) {
767 my $table = $1;
768 $table_info = $domain_info->{tables}{$table} ||= {};
769 } elsif (defined $table_info and /^:(\w+)\s+(\S+)/
770 and $2 ne '-') {
771 $table_info->{chains}{$1}{builtin} = 1;
772 $table_info->{has_builtin} = 1;
776 # for rollback
777 $domain_info->{previous} = $save;
780 if ($option{shell} && $option{interactive} &&
781 exists $tools{'tables-save'}) {
782 print LINES "${domain}_tmp=\$(mktemp ferm.XXXXXXXXXX)\n";
783 print LINES "$tools{'tables-save'} >\$${domain}_tmp\n";
786 $domain_info->{initialized} = 1;
789 sub check_domain($) {
790 my $domain = shift;
791 my @result;
793 return if exists $option{domain}
794 and $domain ne $option{domain};
796 eval {
797 initialize_domain($domain);
799 error($@) if $@;
801 return 1;
804 # split the input string into words and delete comments
805 sub tokenize_string($) {
806 my $string = shift;
808 my @ret;
810 foreach my $word ($string =~ m/(".*?"|'.*?'|`.*?`|[!,=&\$\%\(\){};]|[-+\w\/\.:]+|@\w+|#)/g) {
811 last if $word eq '#';
812 push @ret, $word;
815 return \@ret;
818 # generate a "line" special token, that marks the line number; these
819 # special tokens are inserted after each line break, so ferm keeps
820 # track of line numbers
821 sub make_line_token($) {
822 my $line = shift;
823 return bless(\$line, 'line');
826 # read some more tokens from the input file into a buffer
827 sub prepare_tokens() {
828 my $tokens = $script->{tokens};
829 while (@$tokens == 0) {
830 my $handle = $script->{handle};
831 return unless defined $handle;
832 my $line = <$handle>;
833 return unless defined $line;
835 push @$tokens, make_line_token($script->{line} + 1);
837 # the next parser stage eats this
838 push @$tokens, @{tokenize_string($line)};
841 return 1;
844 sub handle_special_token($) {
845 my $token = shift;
846 die unless ref $token;
847 if (ref $token eq 'line') {
848 $script->{line} = $$token;
849 } else {
850 die;
854 sub handle_special_tokens() {
855 my $tokens = $script->{tokens};
856 while (@$tokens > 0 and ref $tokens->[0]) {
857 handle_special_token(shift @$tokens);
861 # wrapper for prepare_tokens() which handles "special" tokens
862 sub prepare_normal_tokens() {
863 my $tokens = $script->{tokens};
864 while (1) {
865 handle_special_tokens();
866 return 1 if @$tokens > 0;
867 return unless prepare_tokens();
871 # open a ferm sub script
872 sub open_script($) {
873 my $filename = shift;
875 for (my $s = $script; defined $s; $s = $s->{parent}) {
876 die("Circular reference in $script->{filename} line $script->{line}: $filename\n")
877 if $s->{filename} eq $filename;
880 my $handle;
881 if ($filename eq '-') {
882 # Note that this only allowed in the command-line argument and not
883 # @includes, since those are filtered by collect_filenames()
884 $handle = *STDIN;
885 # also set a filename label so that error messages are more helpful
886 $filename = "<stdin>";
887 } else {
888 local *FILE;
889 open FILE, "$filename" or die("Failed to open $filename: $!\n");
890 $handle = *FILE;
893 $script = { filename => $filename,
894 handle => $handle,
895 line => 0,
896 past_tokens => [],
897 tokens => [],
898 parent => $script,
901 return $script;
904 # collect script filenames which are being included
905 sub collect_filenames(@) {
906 my @ret;
908 # determine the current script's parent directory for relative
909 # file names
910 die unless defined $script;
911 my $parent_dir = $script->{filename} =~ m,^(.*/),
912 ? $1 : './';
914 foreach my $pathname (@_) {
915 # non-absolute file names are relative to the parent script's
916 # file name
917 $pathname = $parent_dir . $pathname
918 unless $pathname =~ m,^/|\|$,;
920 if ($pathname =~ m,/$,) {
921 # include all regular files in a directory
923 error("'$pathname' is not a directory")
924 unless -d $pathname;
926 local *DIR;
927 opendir DIR, $pathname
928 or error("Failed to open directory '$pathname': $!");
929 my @names = readdir DIR;
930 closedir DIR;
932 # sort those names for a well-defined order
933 foreach my $name (sort { $a cmp $b } @names) {
934 # ignore dpkg's backup files
935 next if $name =~ /\.dpkg-(old|dist|new|tmp)$/;
936 # don't include hidden and backup files
937 next if $name =~ /^\.|~$/;
939 my $filename = $pathname . $name;
940 push @ret, $filename
941 if -f $filename;
943 } elsif ($pathname =~ m,\|$,) {
944 # run a program and use its output
945 push @ret, $pathname;
946 } elsif ($pathname =~ m,^\|,) {
947 error('This kind of pipe is not allowed');
948 } else {
949 # include a regular file
951 error("'$pathname' is a directory; maybe use trailing '/' to include a directory?")
952 if -d $pathname;
953 error("'$pathname' is not a file")
954 unless -f $pathname;
956 push @ret, $pathname;
960 return @ret;
963 # peek a token from the queue, but don't remove it
964 sub peek_token() {
965 return unless prepare_normal_tokens();
966 return $script->{tokens}[0];
969 # get a token from the queue, including "special" tokens
970 sub next_raw_token() {
971 return unless prepare_tokens();
972 return shift @{$script->{tokens}};
975 # get a token from the queue
976 sub next_token() {
977 return unless prepare_normal_tokens();
978 my $token = shift @{$script->{tokens}};
980 # update $script->{past_tokens}
981 my $past_tokens = $script->{past_tokens};
983 if (@$past_tokens > 0) {
984 my $prev_token = $past_tokens->[-1][-1];
985 $past_tokens->[-1] = @$past_tokens > 1 ? ['{'] : []
986 if $prev_token eq ';';
987 if ($prev_token eq '}') {
988 pop @$past_tokens;
989 $past_tokens->[-1] = $past_tokens->[-1][0] eq '{'
990 ? [ '{' ] : []
991 if @$past_tokens > 0;
995 push @$past_tokens, [] if $token eq '{' or @$past_tokens == 0;
996 push @{$past_tokens->[-1]}, $token;
998 # return
999 return $token;
1002 sub expect_token($;$) {
1003 my $expect = shift;
1004 my $msg = shift;
1005 my $token = next_token();
1006 error($msg || "'$expect' expected")
1007 unless defined $token and $token eq $expect;
1010 # require that another token exists, and that it's not a "special"
1011 # token, e.g. ";" and "{"
1012 sub require_next_token {
1013 my $code = shift || \&next_token;
1015 my $token = &$code(@_);
1017 error('unexpected end of file')
1018 unless defined $token;
1020 error("'$token' not allowed here")
1021 if $token =~ /^[;{}]$/;
1023 return $token;
1026 # return the value of a variable
1027 sub variable_value($) {
1028 my $name = shift;
1030 if ($name eq "LINE") {
1031 return $script->{line};
1034 foreach (@stack) {
1035 return $_->{vars}{$name}
1036 if exists $_->{vars}{$name};
1039 return $stack[0]{auto}{$name}
1040 if exists $stack[0]{auto}{$name};
1042 return;
1045 # determine the value of a variable, die if the value is an array
1046 sub string_variable_value($) {
1047 my $name = shift;
1048 my $value = variable_value($name);
1050 error("variable '$name' must be a string, but it is an array")
1051 if ref $value;
1053 return $value;
1056 # similar to the built-in "join" function, but also handle negated
1057 # values in a special way
1058 sub join_value($$) {
1059 my ($expr, $value) = @_;
1061 unless (ref $value) {
1062 return $value;
1063 } elsif (ref $value eq 'ARRAY') {
1064 return join($expr, @$value);
1065 } elsif (ref $value eq 'negated') {
1066 # bless'negated' is a special marker for negated values
1067 $value = join_value($expr, $value->[0]);
1068 return bless [ $value ], 'negated';
1069 } else {
1070 die;
1074 sub negate_value($$;$) {
1075 my ($value, $class, $allow_array) = @_;
1077 if (ref $value) {
1078 error('double negation is not allowed')
1079 if ref $value eq 'negated' or ref $value eq 'pre_negated';
1081 error('it is not possible to negate an array')
1082 if ref $value eq 'ARRAY' and not $allow_array;
1085 return bless [ $value ], $class || 'negated';
1088 sub format_bool($) {
1089 return $_[0] ? 1 : 0;
1092 sub resolve($\@$) {
1093 my ($resolver, $names, $type) = @_;
1095 my @result;
1096 foreach my $hostname (@$names) {
1097 my $query = $resolver->search($hostname, $type);
1098 error("DNS query for '$hostname' failed: " . $resolver->errorstring)
1099 unless $query;
1101 foreach my $rr ($query->answer) {
1102 next unless $rr->type eq $type;
1104 if ($type eq 'NS') {
1105 push @result, $rr->nsdname;
1106 } elsif ($type eq 'MX') {
1107 push @result, $rr->exchange;
1108 } else {
1109 push @result, $rr->address;
1114 # NS/MX records return host names; resolve these again in the
1115 # second pass (IPv4 only currently)
1116 @result = resolve($resolver, @result, 'A')
1117 if $type eq 'NS' or $type eq 'MX';
1119 return @result;
1122 sub lookup_function($) {
1123 my $name = shift;
1125 foreach (@stack) {
1126 return $_->{functions}{$name}
1127 if exists $_->{functions}{$name};
1130 return;
1133 # returns the next parameter, which may either be a scalar or an array
1134 sub getvalues {
1135 my $code = shift;
1136 my %options = @_;
1138 my $token = require_next_token($code);
1140 if ($token eq '(') {
1141 # read an array until ")"
1142 my @wordlist;
1144 for (;;) {
1145 $token = getvalues($code,
1146 parenthesis_allowed => 1,
1147 comma_allowed => 1);
1149 unless (ref $token) {
1150 last if $token eq ')';
1152 if ($token eq ',') {
1153 error('Comma is not allowed within arrays, please use only a space');
1154 next;
1157 push @wordlist, $token;
1158 } elsif (ref $token eq 'ARRAY') {
1159 push @wordlist, @$token;
1160 } else {
1161 error('unknown toke type');
1165 error('empty array not allowed here')
1166 unless @wordlist or not $options{non_empty};
1168 return @wordlist == 1
1169 ? $wordlist[0]
1170 : \@wordlist;
1171 } elsif ($token =~ /^\`(.*)\`$/s) {
1172 # execute a shell command, insert output
1173 my $command = $1;
1174 my $output = `$command`;
1175 unless ($? == 0) {
1176 if ($? == -1) {
1177 error("failed to execute: $!");
1178 } elsif ($? & 0x7f) {
1179 error("child died with signal " . ($? & 0x7f));
1180 } elsif ($? >> 8) {
1181 error("child exited with status " . ($? >> 8));
1185 # remove comments
1186 $output =~ s/#.*//mg;
1188 # tokenize
1189 my @tokens = grep { length } split /\s+/s, $output;
1191 my @values;
1192 while (@tokens) {
1193 my $value = getvalues(sub { shift @tokens });
1194 push @values, to_array($value);
1197 # and recurse
1198 return @values == 1
1199 ? $values[0]
1200 : \@values;
1201 } elsif ($token =~ /^\'(.*)\'$/s) {
1202 # single quotes: a string
1203 return $1;
1204 } elsif ($token =~ /^\"(.*)\"$/s) {
1205 # double quotes: a string with escapes
1206 $token = $1;
1207 $token =~ s,\$(\w+),string_variable_value($1),eg;
1208 return $token;
1209 } elsif ($token eq '!') {
1210 error('negation is not allowed here')
1211 unless $options{allow_negation};
1213 $token = getvalues($code);
1215 return negate_value($token, undef, $options{allow_array_negation});
1216 } elsif ($token eq ',') {
1217 return $token
1218 if $options{comma_allowed};
1220 error('comma is not allowed here');
1221 } elsif ($token eq '=') {
1222 error('equals operator ("=") is not allowed here');
1223 } elsif ($token eq '$') {
1224 my $name = require_next_token($code);
1225 error('variable name expected - if you want to concatenate strings, try using double quotes')
1226 unless $name =~ /^\w+$/;
1228 my $value = variable_value($name);
1230 error("no such variable: \$$name")
1231 unless defined $value;
1233 return $value;
1234 } elsif ($token eq '&') {
1235 error("function calls are not allowed as keyword parameter");
1236 } elsif ($token eq ')' and not $options{parenthesis_allowed}) {
1237 error('Syntax error');
1238 } elsif ($token =~ /^@/) {
1239 if ($token eq '@resolve') {
1240 my @params = get_function_params();
1241 error('Usage: @resolve((hostname ...), [type])')
1242 unless @params == 1 or @params == 2;
1243 eval { require Net::DNS; };
1244 error('For the @resolve() function, you need the Perl library Net::DNS')
1245 if $@;
1246 my $type = $params[1] || 'A';
1247 error('String expected') if ref $type;
1248 my $resolver = new Net::DNS::Resolver;
1249 @params = to_array($params[0]);
1250 my @result = resolve($resolver, @params, $type);
1251 return @result == 1 ? $result[0] : \@result;
1252 } elsif ($token eq '@defined') {
1253 expect_token('(', 'function name must be followed by "()"');
1254 my $type = require_next_token();
1255 if ($type eq '$') {
1256 my $name = require_next_token();
1257 error('variable name expected')
1258 unless $name =~ /^\w+$/;
1259 expect_token(')');
1260 return defined variable_value($name);
1261 } elsif ($type eq '&') {
1262 my $name = require_next_token();
1263 error('function name expected')
1264 unless $name =~ /^\w+$/;
1265 expect_token(')');
1266 return defined lookup_function($name);
1267 } else {
1268 error("'\$' or '&' expected")
1270 } elsif ($token eq '@eq') {
1271 my @params = get_function_params();
1272 error('Usage: @eq(a, b)') unless @params == 2;
1273 return format_bool($params[0] eq $params[1]);
1274 } elsif ($token eq '@ne') {
1275 my @params = get_function_params();
1276 error('Usage: @ne(a, b)') unless @params == 2;
1277 return format_bool($params[0] ne $params[1]);
1278 } elsif ($token eq '@not') {
1279 my @params = get_function_params();
1280 error('Usage: @not(a)') unless @params == 1;
1281 return format_bool(not $params[0]);
1282 } elsif ($token eq '@cat') {
1283 my $value = '';
1284 map {
1285 error('String expected') if ref $_;
1286 $value .= $_;
1287 } get_function_params();
1288 return $value;
1289 } elsif ($token eq '@substr') {
1290 my @params = get_function_params();
1291 error('Usage: @substr(string, num, num)') unless @params == 3;
1292 error('String expected') if ref $params[0] or ref $params[1] or ref $params[2];
1293 return substr($params[0],$params[1],$params[2]);
1294 } elsif ($token eq '@length') {
1295 my @params = get_function_params();
1296 error('Usage: @length(string)') unless @params == 1;
1297 error('String expected') if ref $params[0];
1298 return length($params[0]);
1299 } elsif ($token eq '@basename') {
1300 my @params = get_function_params();
1301 error('Usage: @basename(path)') unless @params == 1;
1302 error('String expected') if ref $params[0];
1303 my($volume,$path,$file) = File::Spec->splitpath( $params[0] );
1304 return $file;
1305 } elsif ($token eq '@dirname') {
1306 my @params = get_function_params();
1307 error('Usage: @dirname(path)') unless @params == 1;
1308 error('String expected') if ref $params[0];
1309 my($volume,$path,$file) = File::Spec->splitpath( $params[0] );
1310 return $path;
1311 } elsif ($token eq '@ipfilter') {
1312 my @params = get_function_params();
1313 error('Usage: @ipfilter((ip1 ip2 ...))') unless @params == 1;
1314 my $domain = $stack[0]{auto}{DOMAIN};
1315 error('No domain specified') unless defined $domain;
1316 my @ips = ipfilter($domain, to_array($params[0]));
1317 return \@ips;
1318 } else {
1319 error("unknown ferm built-in function");
1321 } else {
1322 return $token;
1326 # returns the next parameter, but only allow a scalar
1327 sub getvar() {
1328 my $token = getvalues();
1330 error('array not allowed here')
1331 if ref $token and ref $token eq 'ARRAY';
1333 return $token;
1336 sub get_function_params(%) {
1337 expect_token('(', 'function name must be followed by "()"');
1339 my $token = peek_token();
1340 if ($token eq ')') {
1341 require_next_token();
1342 return;
1345 my @params;
1347 while (1) {
1348 if (@params > 0) {
1349 $token = require_next_token();
1350 last
1351 if $token eq ')';
1353 error('"," expected')
1354 unless $token eq ',';
1357 push @params, getvalues(undef, @_);
1360 return @params;
1363 # collect all tokens in a flat array reference until the end of the
1364 # command is reached
1365 sub collect_tokens {
1366 my %options = @_;
1368 my @level;
1369 my @tokens;
1371 # re-insert a "line" token, because the starting token of the
1372 # current line has been consumed already
1373 push @tokens, make_line_token($script->{line});
1375 while (1) {
1376 my $keyword = next_raw_token();
1377 error('unexpected end of file within function/variable declaration')
1378 unless defined $keyword;
1380 if (ref $keyword) {
1381 handle_special_token($keyword);
1382 } elsif ($keyword =~ /^[\{\(]$/) {
1383 push @level, $keyword;
1384 } elsif ($keyword =~ /^[\}\)]$/) {
1385 my $expected = $keyword;
1386 $expected =~ tr/\}\)/\{\(/;
1387 my $opener = pop @level;
1388 error("unmatched '$keyword'")
1389 unless defined $opener and $opener eq $expected;
1390 } elsif ($keyword eq ';' and @level == 0) {
1391 push @tokens, $keyword
1392 if $options{include_semicolon};
1394 if ($options{include_else}) {
1395 my $token = peek_token;
1396 next if $token eq '@else';
1399 last;
1402 push @tokens, $keyword;
1404 last
1405 if $keyword eq '}' and @level == 0;
1408 return \@tokens;
1412 # returns the specified value as an array. dereference arrayrefs
1413 sub to_array($) {
1414 my $value = shift;
1415 die unless wantarray;
1416 die if @_;
1417 unless (ref $value) {
1418 return $value;
1419 } elsif (ref $value eq 'ARRAY') {
1420 return @$value;
1421 } else {
1422 die;
1426 # evaluate the specified value as bool
1427 sub eval_bool($) {
1428 my $value = shift;
1429 die if wantarray;
1430 die if @_;
1431 unless (ref $value) {
1432 return $value;
1433 } elsif (ref $value eq 'ARRAY') {
1434 return @$value > 0;
1435 } else {
1436 die;
1440 sub is_netfilter_core_target($) {
1441 my $target = shift;
1442 die unless defined $target and length $target;
1443 return grep { $_ eq $target } qw(ACCEPT DROP RETURN QUEUE);
1446 sub is_netfilter_module_target($$) {
1447 my ($domain_family, $target) = @_;
1448 die unless defined $target and length $target;
1450 return defined $domain_family &&
1451 exists $target_defs{$domain_family} &&
1452 $target_defs{$domain_family}{$target};
1455 sub is_netfilter_builtin_chain($$) {
1456 my ($table, $chain) = @_;
1458 return grep { $_ eq $chain }
1459 qw(PREROUTING INPUT FORWARD OUTPUT POSTROUTING);
1462 sub netfilter_canonical_protocol($) {
1463 my $proto = shift;
1464 return 'icmp'
1465 if $proto eq 'ipv6-icmp' or $proto eq 'icmpv6';
1466 return 'mh'
1467 if $proto eq 'ipv6-mh';
1468 return $proto;
1471 sub netfilter_protocol_module($) {
1472 my $proto = shift;
1473 return unless defined $proto;
1474 return 'icmp6'
1475 if $proto eq 'icmpv6';
1476 return $proto;
1479 # escape the string in a way safe for the shell
1480 sub shell_escape($) {
1481 my $token = shift;
1483 return $token if $token =~ /^[-_a-zA-Z0-9]+$/s;
1485 if ($option{fast}) {
1486 # iptables-save/iptables-restore are quite buggy concerning
1487 # escaping and special characters... we're trying our best
1488 # here
1490 $token =~ s,",\\",g;
1491 $token = '"' . $token . '"'
1492 if $token =~ /[\s\'\\;&]/s or length($token) == 0;
1493 } else {
1494 return $token
1495 if $token =~ /^\`.*\`$/;
1496 $token =~ s/'/'\\''/g;
1497 $token = '\'' . $token . '\''
1498 if $token =~ /[\s\"\\;<>&|]/s or length($token) == 0;
1501 return $token;
1504 # append an option to the shell command line, using information from
1505 # the module definition (see %match_defs etc.)
1506 sub shell_format_option($$) {
1507 my ($keyword, $value) = @_;
1509 my $cmd = '';
1510 if (ref $value) {
1511 if ((ref $value eq 'negated') || (ref $value eq 'pre_negated')) {
1512 $value = $value->[0];
1513 $cmd = ' !';
1517 unless (defined $value) {
1518 $cmd .= " --$keyword";
1519 } elsif (ref $value) {
1520 if (ref $value eq 'params') {
1521 $cmd .= " --$keyword ";
1522 $cmd .= join(' ', map { shell_escape($_) } @$value);
1523 } elsif (ref $value eq 'multi') {
1524 foreach (@$value) {
1525 $cmd .= " --$keyword " . shell_escape($_);
1527 } else {
1528 die;
1530 } else {
1531 $cmd .= " --$keyword " . shell_escape($value);
1534 return $cmd;
1537 sub format_option($$$) {
1538 my ($domain, $name, $value) = @_;
1540 $value = 'icmpv6' if $domain eq 'ip6' and $name eq 'protocol'
1541 and $value eq 'icmp';
1542 $name = 'icmpv6-type' if $domain eq 'ip6' and $name eq 'icmp-type';
1544 if ($domain eq 'ip6' and $name eq 'reject-with') {
1545 my %icmp_map = (
1546 'icmp-net-unreachable' => 'icmp6-no-route',
1547 'icmp-host-unreachable' => 'icmp6-addr-unreachable',
1548 'icmp-port-unreachable' => 'icmp6-port-unreachable',
1549 'icmp-net-prohibited' => 'icmp6-adm-prohibited',
1550 'icmp-host-prohibited' => 'icmp6-adm-prohibited',
1551 'icmp-admin-prohibited' => 'icmp6-adm-prohibited',
1553 $value = $icmp_map{$value} if exists $icmp_map{$value};
1556 return shell_format_option($name, $value);
1559 sub append_rule($$) {
1560 my ($chain_rules, $rule) = @_;
1562 my $cmd = join('', map { $_->[2] } @{$rule->{options}});
1563 push @$chain_rules, { rule => $cmd,
1564 script => $rule->{script},
1568 sub unfold_rule {
1569 my ($domain, $chain_rules, $rule) = (shift, shift, shift);
1570 return append_rule($chain_rules, $rule) unless @_;
1572 my $option = shift;
1573 my @values = @{$option->[1]};
1575 foreach my $value (@values) {
1576 $option->[2] = format_option($domain, $option->[0], $value);
1577 unfold_rule($domain, $chain_rules, $rule, @_);
1581 sub mkrules2($$$) {
1582 my ($domain, $chain_rules, $rule) = @_;
1584 my @unfold;
1585 foreach my $option (@{$rule->{options}}) {
1586 if (ref $option->[1] and ref $option->[1] eq 'ARRAY') {
1587 push @unfold, $option
1588 } else {
1589 $option->[2] = format_option($domain, $option->[0], $option->[1]);
1593 unfold_rule($domain, $chain_rules, $rule, @unfold);
1596 # convert a bunch of internal rule structures in iptables calls,
1597 # unfold arrays during that
1598 sub mkrules($) {
1599 my $rule = shift;
1601 my $domain = $rule->{domain};
1602 my $domain_info = $domains{$domain};
1603 $domain_info->{enabled} = 1;
1605 foreach my $table (to_array $rule->{table}) {
1606 my $table_info = $domain_info->{tables}{$table} ||= {};
1608 foreach my $chain (to_array $rule->{chain}) {
1609 my $chain_rules = $table_info->{chains}{$chain}{rules} ||= [];
1610 mkrules2($domain, $chain_rules, $rule)
1611 if $rule->{has_rule} and not $option{flush};
1616 # parse a keyword from a module definition
1617 sub parse_keyword(\%$$) {
1618 my ($rule, $def, $negated_ref) = @_;
1620 my $params = $def->{params};
1622 my $value;
1624 my $negated;
1625 if ($$negated_ref && exists $def->{pre_negation}) {
1626 $negated = 1;
1627 undef $$negated_ref;
1630 unless (defined $params) {
1631 undef $value;
1632 } elsif (ref $params && ref $params eq 'CODE') {
1633 $value = &$params($rule);
1634 } elsif ($params eq 'm') {
1635 $value = bless [ to_array getvalues() ], 'multi';
1636 } elsif ($params =~ /^[a-z]/) {
1637 if (exists $def->{negation} and not $negated) {
1638 my $token = peek_token();
1639 if ($token eq '!') {
1640 require_next_token();
1641 $negated = 1;
1645 my @params;
1646 foreach my $p (split(//, $params)) {
1647 if ($p eq 's') {
1648 push @params, getvar();
1649 } elsif ($p eq 'c') {
1650 my @v = to_array getvalues(undef, non_empty => 1);
1651 push @params, join(',', @v);
1652 } else {
1653 die;
1657 $value = @params == 1
1658 ? $params[0]
1659 : bless \@params, 'params';
1660 } elsif ($params == 1) {
1661 if (exists $def->{negation} and not $negated) {
1662 my $token = peek_token();
1663 if ($token eq '!') {
1664 require_next_token();
1665 $negated = 1;
1669 $value = getvalues();
1671 warning("log-prefix is too long; truncating to 29 characters: '$1'")
1672 if $def->{name} eq 'log-prefix' && $value =~ s,^(.{29}).+$,$1,;
1673 } else {
1674 if (exists $def->{negation} and not $negated) {
1675 my $token = peek_token();
1676 if ($token eq '!') {
1677 require_next_token();
1678 $negated = 1;
1682 $value = bless [ map {
1683 getvar()
1684 } (1..$params) ], 'params';
1687 $value = negate_value($value, exists $def->{pre_negation} && 'pre_negated')
1688 if $negated;
1690 return $value;
1693 sub append_option(\%$$) {
1694 my ($rule, $name, $value) = @_;
1695 push @{$rule->{options}}, [ $name, $value ];
1698 # parse options of a module
1699 sub parse_option($\%$) {
1700 my ($def, $rule, $negated_ref) = @_;
1702 append_option(%$rule, $def->{name},
1703 parse_keyword(%$rule, $def, $negated_ref));
1706 sub copy_on_write($$) {
1707 my ($rule, $key) = @_;
1708 return unless exists $rule->{cow}{$key};
1709 $rule->{$key} = {%{$rule->{$key}}};
1710 delete $rule->{cow}{$key};
1713 sub new_level(\%$) {
1714 my ($rule, $prev) = @_;
1716 %$rule = ();
1717 if (defined $prev) {
1718 # copy data from previous level
1719 $rule->{cow} = { keywords => 1, };
1720 $rule->{keywords} = $prev->{keywords};
1721 $rule->{match} = { %{$prev->{match}} };
1722 $rule->{options} = [@{$prev->{options}}];
1723 foreach my $key (qw(domain domain_family domain_both table chain protocol has_rule has_action)) {
1724 $rule->{$key} = $prev->{$key}
1725 if exists $prev->{$key};
1727 } else {
1728 $rule->{cow} = {};
1729 $rule->{keywords} = {};
1730 $rule->{match} = {};
1731 $rule->{options} = [];
1735 sub merge_keywords(\%$) {
1736 my ($rule, $keywords) = @_;
1737 copy_on_write($rule, 'keywords');
1738 while (my ($name, $def) = each %$keywords) {
1739 $rule->{keywords}{$name} = $def;
1743 sub set_domain(\%$) {
1744 my ($rule, $domain) = @_;
1746 return unless check_domain($domain);
1748 my $domain_family;
1749 unless (ref $domain) {
1750 $domain_family = $domain eq 'ip6' ? 'ip' : $domain;
1751 } elsif (@$domain == 0) {
1752 $domain_family = 'none';
1753 } elsif (grep { not /^ip6?$/s } @$domain) {
1754 error('Cannot combine non-IP domains');
1755 } else {
1756 $domain_family = 'ip';
1759 $rule->{domain_family} = $domain_family;
1760 $rule->{keywords} = $match_defs{$domain_family}{''}{keywords};
1761 $rule->{cow}{keywords} = 1;
1763 $rule->{domain} = $stack[0]{auto}{DOMAIN} = $domain;
1766 sub set_target(\%$$) {
1767 my ($rule, $name, $value) = @_;
1768 error('There can only one action per rule')
1769 if exists $rule->{has_action};
1770 $rule->{has_action} = 1;
1771 append_option(%$rule, $name, $value);
1774 sub set_module_target(\%$$) {
1775 my ($rule, $name, $defs) = @_;
1777 if ($name eq 'TCPMSS') {
1778 my $protos = $rule->{protocol};
1779 error('No protocol specified before TCPMSS')
1780 unless defined $protos;
1781 foreach my $proto (to_array $protos) {
1782 error('TCPMSS not available for protocol "$proto"')
1783 unless $proto eq 'tcp';
1787 # in ebtables, there is both "--mark" and "-j mark"... workaround:
1788 $name = 'mark' if $name eq 'MARK' and $rule->{domain_family} eq 'eb';
1790 set_target(%$rule, 'jump', $name);
1791 merge_keywords(%$rule, $defs->{keywords});
1794 # the main parser loop: read tokens, convert them into internal rule
1795 # structures
1796 sub enter($$) {
1797 my $lev = shift; # current recursion depth
1798 my $prev = shift; # previous rule hash
1800 # enter is the core of the firewall setup, it is a
1801 # simple parser program that recognizes keywords and
1802 # retreives parameters to set up the kernel routing
1803 # chains
1805 my $base_level = $script->{base_level} || 0;
1806 die if $base_level > $lev;
1808 my %rule;
1809 new_level(%rule, $prev);
1811 # read keywords 1 by 1 and dump into parser
1812 while (defined (my $keyword = next_token())) {
1813 # check if the current rule should be negated
1814 my $negated = $keyword eq '!';
1815 if ($negated) {
1816 # negation. get the next word which contains the 'real'
1817 # rule
1818 $keyword = getvar();
1820 error('unexpected end of file after negation')
1821 unless defined $keyword;
1824 # the core: parse all data
1825 for ($keyword)
1827 # deprecated keyword?
1828 if (exists $deprecated_keywords{$keyword}) {
1829 my $new_keyword = $deprecated_keywords{$keyword};
1830 warning("'$keyword' is deprecated, please use '$new_keyword' instead");
1831 $keyword = $new_keyword;
1834 # effectuation operator
1835 if ($keyword eq ';') {
1836 error('Empty rule before ";" not allowed')
1837 unless $rule{non_empty};
1839 if ($rule{has_rule} and not exists $rule{has_action}) {
1840 # something is wrong when a rule was specified,
1841 # but no action
1842 error('No action defined; did you mean "NOP"?');
1845 error('No chain defined') unless exists $rule{chain};
1847 $rule{script} = { filename => $script->{filename},
1848 line => $script->{line},
1851 mkrules(\%rule);
1853 # and clean up variables set in this level
1854 new_level(%rule, $prev);
1856 next;
1859 # conditional expression
1860 if ($keyword eq '@if') {
1861 unless (eval_bool(getvalues)) {
1862 collect_tokens;
1863 my $token = peek_token();
1864 if ($token and $token eq '@else') {
1865 require_next_token();
1866 } else {
1867 new_level(%rule, $prev);
1871 next;
1874 if ($keyword eq '@else') {
1875 # hack: if this "else" has not been eaten by the "if"
1876 # handler above, we believe it came from an if clause
1877 # which evaluated "true" - remove the "else" part now.
1878 collect_tokens;
1879 next;
1882 # hooks for custom shell commands
1883 if ($keyword eq 'hook') {
1884 warning("'hook' is deprecated, use '\@hook'");
1885 $keyword = '@hook';
1888 if ($keyword eq '@hook') {
1889 error('"hook" must be the first token in a command')
1890 if exists $rule{domain};
1892 my $position = getvar();
1893 my $hooks;
1894 if ($position eq 'pre') {
1895 $hooks = \@pre_hooks;
1896 } elsif ($position eq 'post') {
1897 $hooks = \@post_hooks;
1898 } elsif ($position eq 'flush') {
1899 $hooks = \@flush_hooks;
1900 } else {
1901 error("Invalid hook position: '$position'");
1904 push @$hooks, getvar();
1906 expect_token(';');
1907 next;
1910 # recursing operators
1911 if ($keyword eq '{') {
1912 # push stack
1913 my $old_stack_depth = @stack;
1915 unshift @stack, { auto => { %{$stack[0]{auto} || {}} } };
1917 # recurse
1918 enter($lev + 1, \%rule);
1920 # pop stack
1921 shift @stack;
1922 die unless @stack == $old_stack_depth;
1924 # after a block, the command is finished, clear this
1925 # level
1926 new_level(%rule, $prev);
1928 next;
1931 if ($keyword eq '}') {
1932 error('Unmatched "}"')
1933 if $lev <= $base_level;
1935 # consistency check: check if they havn't forgotten
1936 # the ';' after the last statement
1937 error('Missing semicolon before "}"')
1938 if $rule{non_empty};
1940 # and exit
1941 return;
1944 # include another file
1945 if ($keyword eq '@include' or $keyword eq 'include') {
1946 my @files = collect_filenames to_array getvalues;
1947 $keyword = next_token;
1948 error('Missing ";" - "include FILENAME" must be the last command in a rule')
1949 unless defined $keyword and $keyword eq ';';
1951 foreach my $filename (@files) {
1952 # save old script, open new script
1953 my $old_script = $script;
1954 open_script($filename);
1955 $script->{base_level} = $lev + 1;
1957 # push stack
1958 my $old_stack_depth = @stack;
1960 my $stack = {};
1962 if (@stack > 0) {
1963 # include files may set variables for their parent
1964 $stack->{vars} = ($stack[0]{vars} ||= {});
1965 $stack->{functions} = ($stack[0]{functions} ||= {});
1966 $stack->{auto} = { %{ $stack[0]{auto} || {} } };
1969 my( $volume,$dirs,$file ) = File::Spec->splitpath( $filename );
1970 $stack->{auto}{FILENAME} = $filename;
1971 $stack->{auto}{FILEBNAME} = $file;
1972 $stack->{auto}{DIRNAME} = $dirs;
1974 unshift @stack, $stack;
1976 # parse the script
1977 enter($lev + 1, \%rule);
1979 #check for exit status
1980 error("'$script->{filename}': exit status is not 0") if not close $script->{handle};
1982 # pop stack
1983 shift @stack;
1984 die unless @stack == $old_stack_depth;
1986 # restore old script
1987 $script = $old_script;
1990 next;
1993 # definition of a variable or function
1994 if ($keyword eq '@def' or $keyword eq 'def') {
1995 error('"def" must be the first token in a command')
1996 if $rule{non_empty};
1998 my $type = require_next_token();
1999 if ($type eq '$') {
2000 my $name = require_next_token();
2001 error('invalid variable name')
2002 unless $name =~ /^\w+$/;
2004 expect_token('=');
2006 my $value = getvalues(undef, allow_negation => 1);
2008 expect_token(';');
2010 $stack[0]{vars}{$name} = $value
2011 unless exists $stack[-1]{vars}{$name};
2012 } elsif ($type eq '&') {
2013 my $name = require_next_token();
2014 error('invalid function name')
2015 unless $name =~ /^\w+$/;
2017 expect_token('(', 'function parameter list or "()" expected');
2019 my @params;
2020 while (1) {
2021 my $token = require_next_token();
2022 last if $token eq ')';
2024 if (@params > 0) {
2025 error('"," expected')
2026 unless $token eq ',';
2028 $token = require_next_token();
2031 error('"$" and parameter name expected')
2032 unless $token eq '$';
2034 $token = require_next_token();
2035 error('invalid function parameter name')
2036 unless $token =~ /^\w+$/;
2038 push @params, $token;
2041 my %function;
2043 $function{params} = \@params;
2045 expect_token('=');
2047 my $tokens = collect_tokens();
2048 $function{block} = 1 if grep { $_ eq '{' } @$tokens;
2049 $function{tokens} = $tokens;
2051 $stack[0]{functions}{$name} = \%function
2052 unless exists $stack[-1]{functions}{$name};
2053 } else {
2054 error('"$" (variable) or "&" (function) expected');
2057 next;
2060 # this rule has something which isn't inherited by its
2061 # parent closure. This variable is used in a lot of
2062 # syntax checks.
2064 $rule{non_empty} = 1;
2066 # def references
2067 if ($keyword eq '$') {
2068 error('variable references are only allowed as keyword parameter');
2071 if ($keyword eq '&') {
2072 my $name = require_next_token();
2073 error('function name expected')
2074 unless $name =~ /^\w+$/;
2076 my $function = lookup_function($name);
2077 error("no such function: \&$name")
2078 unless defined $function;
2080 my $paramdef = $function->{params};
2081 die unless defined $paramdef;
2083 my @params = get_function_params(allow_negation => 1);
2085 error("Wrong number of parameters for function '\&$name': "
2086 . @$paramdef . " expected, " . @params . " given")
2087 unless @params == @$paramdef;
2089 my %vars;
2090 for (my $i = 0; $i < @params; $i++) {
2091 $vars{$paramdef->[$i]} = $params[$i];
2094 if ($function->{block}) {
2095 # block {} always ends the current rule, so if the
2096 # function contains a block, we have to require
2097 # the calling rule also ends here
2098 expect_token(';');
2101 my @tokens = @{$function->{tokens}};
2102 for (my $i = 0; $i < @tokens; $i++) {
2103 if ($tokens[$i] eq '$' and $i + 1 < @tokens and
2104 exists $vars{$tokens[$i + 1]}) {
2105 my @value = to_array($vars{$tokens[$i + 1]});
2106 @value = ('(', @value, ')')
2107 unless @tokens == 1;
2108 splice(@tokens, $i, 2, @value);
2109 $i += @value - 2;
2110 } elsif ($tokens[$i] =~ m,^"(.*)"$,) {
2111 $tokens[$i] =~ s,\$(\w+),exists $vars{$1} ? $vars{$1} : "\$$1",eg;
2115 unshift @{$script->{tokens}}, @tokens;
2117 next;
2120 # where to put the rule?
2121 if ($keyword eq 'domain') {
2122 error('Domain is already specified')
2123 if exists $rule{domain};
2125 my $domains = getvalues();
2126 if (ref $domains) {
2127 my $tokens = collect_tokens(include_semicolon => 1,
2128 include_else => 1);
2130 my $old_line = $script->{line};
2131 my $old_handle = $script->{handle};
2132 my $old_tokens = $script->{tokens};
2133 my $old_base_level = $script->{base_level};
2134 unshift @$old_tokens, make_line_token($script->{line});
2135 delete $script->{handle};
2137 for my $domain (@$domains) {
2138 my %inner;
2139 new_level(%inner, \%rule);
2140 set_domain(%inner, $domain) or next;
2141 $inner{domain_both} = 1;
2142 $script->{base_level} = 0;
2143 $script->{tokens} = [ @$tokens ];
2144 enter(0, \%inner);
2147 $script->{base_level} = $old_base_level;
2148 $script->{tokens} = $old_tokens;
2149 $script->{handle} = $old_handle;
2150 $script->{line} = $old_line;
2152 new_level(%rule, $prev);
2153 } else {
2154 unless (set_domain(%rule, $domains)) {
2155 collect_tokens();
2156 new_level(%rule, $prev);
2160 next;
2163 if ($keyword eq 'table') {
2164 warning('Table is already specified')
2165 if exists $rule{table};
2166 $rule{table} = $stack[0]{auto}{TABLE} = getvalues();
2168 set_domain(%rule, $option{domain} || 'ip')
2169 unless exists $rule{domain};
2171 next;
2174 if ($keyword eq 'chain') {
2175 warning('Chain is already specified')
2176 if exists $rule{chain};
2178 my $chain = $rule{chain} = $stack[0]{auto}{CHAIN} = getvalues();
2180 # ferm 1.1 allowed lower case built-in chain names
2181 foreach (ref $rule{chain} ? @{$rule{chain}} : $rule{chain}) {
2182 error('Please write built-in chain names in upper case')
2183 if /^(?:input|forward|output|prerouting|postrouting)$/;
2186 set_domain(%rule, $option{domain} || 'ip')
2187 unless exists $rule{domain};
2189 $rule{table} = 'filter'
2190 unless exists $rule{table};
2192 my $domain = $rule{domain};
2193 foreach my $table (to_array $rule{table}) {
2194 foreach my $c (to_array $chain) {
2195 $domains{$domain}{tables}{$table}{chains}{$c} ||= {};
2199 next;
2202 error('Chain must be specified')
2203 unless exists $rule{chain};
2205 # policy for built-in chain
2206 if ($keyword eq 'policy') {
2207 error('Cannot specify matches for policy')
2208 if $rule{has_rule};
2210 my $policy = getvar();
2211 error("Invalid policy target: $policy")
2212 unless is_netfilter_core_target($policy);
2214 expect_token(';');
2216 my $domain = $rule{domain};
2217 my $domain_info = $domains{$domain};
2218 $domain_info->{enabled} = 1;
2220 foreach my $table (to_array $rule{table}) {
2221 foreach my $chain (to_array $rule{chain}) {
2222 $domain_info->{tables}{$table}{chains}{$chain}{policy} = $policy;
2226 new_level(%rule, $prev);
2227 next;
2230 # create a subchain
2231 if ($keyword eq '@subchain' or $keyword eq 'subchain') {
2232 error('Chain must be specified')
2233 unless exists $rule{chain};
2235 error('No rule specified before "@subchain"')
2236 unless $rule{has_rule};
2238 my $subchain;
2239 my $token = peek_token();
2241 if ($token =~ /^(["'])(.*)\1$/s) {
2242 $subchain = $2;
2243 next_token();
2244 $keyword = next_token();
2245 } elsif ($token eq '{') {
2246 $keyword = next_token();
2247 $subchain = 'ferm_auto_' . ++$auto_chain;
2248 } else {
2249 $subchain = getvar();
2250 $keyword = next_token();
2253 my $domain = $rule{domain};
2254 foreach my $table (to_array $rule{table}) {
2255 $domains{$domain}{tables}{$table}{chains}{$subchain} ||= {};
2258 set_target(%rule, 'jump', $subchain);
2260 error('"{" or chain name expected after "@subchain"')
2261 unless $keyword eq '{';
2263 # create a deep copy of %rule, only containing values
2264 # which must be in the subchain
2265 my %inner = ( cow => { keywords => 1, },
2266 match => {},
2267 options => [],
2269 $inner{$_} = $rule{$_} foreach qw(domain domain_family domain_both table keywords);
2270 $inner{chain} = $inner{auto}{CHAIN} = $subchain;
2272 if (exists $rule{protocol}) {
2273 $inner{protocol} = $rule{protocol};
2274 append_option(%inner, 'protocol', $inner{protocol});
2277 # create a new stack frame
2278 my $old_stack_depth = @stack;
2279 my $stack = { auto => { %{$stack[0]{auto} || {}} } };
2280 $stack->{auto}{CHAIN} = $subchain;
2281 unshift @stack, $stack;
2283 # enter the block
2284 enter($lev + 1, \%inner);
2286 # pop stack frame
2287 shift @stack;
2288 die unless @stack == $old_stack_depth;
2290 # now handle the parent - it's a jump to the sub chain
2291 $rule{script} = {
2292 filename => $script->{filename},
2293 line => $script->{line},
2296 mkrules(\%rule);
2298 # and clean up variables set in this level
2299 new_level(%rule, $prev);
2300 delete $rule{has_rule};
2302 next;
2305 # everything else must be part of a "real" rule, not just
2306 # "policy only"
2307 $rule{has_rule} = 1;
2309 # extended parameters:
2310 if ($keyword =~ /^mod(?:ule)?$/) {
2311 foreach my $module (to_array getvalues) {
2312 next if exists $rule{match}{$module};
2314 my $domain_family = $rule{domain_family};
2315 my $defs = $match_defs{$domain_family}{$module};
2317 append_option(%rule, 'match', $module);
2318 $rule{match}{$module} = 1;
2320 merge_keywords(%rule, $defs->{keywords})
2321 if defined $defs;
2324 next;
2327 # keywords from $rule{keywords}
2329 if (exists $rule{keywords}{$keyword}) {
2330 my $def = $rule{keywords}{$keyword};
2331 parse_option($def, %rule, \$negated);
2332 next;
2336 # actions
2339 # jump action
2340 if ($keyword eq 'jump') {
2341 set_target(%rule, 'jump', getvar());
2342 next;
2345 # goto action
2346 if ($keyword eq 'realgoto') {
2347 set_target(%rule, 'goto', getvar());
2348 next;
2351 # action keywords
2352 if (is_netfilter_core_target($keyword)) {
2353 set_target(%rule, 'jump', $keyword);
2354 next;
2357 if ($keyword eq 'NOP') {
2358 error('There can only one action per rule')
2359 if exists $rule{has_action};
2360 $rule{has_action} = 1;
2361 next;
2364 if (my $defs = is_netfilter_module_target($rule{domain_family}, $keyword)) {
2365 set_module_target(%rule, $keyword, $defs);
2366 next;
2370 # protocol specific options
2373 if ($keyword eq 'proto' or $keyword eq 'protocol') {
2374 my $protocol = parse_keyword(%rule,
2375 { params => 1, negation => 1 },
2376 \$negated);
2377 $rule{protocol} = $protocol;
2378 append_option(%rule, 'protocol', $rule{protocol});
2380 unless (ref $protocol) {
2381 $protocol = netfilter_canonical_protocol($protocol);
2382 my $domain_family = $rule{domain_family};
2383 if (my $defs = $proto_defs{$domain_family}{$protocol}) {
2384 merge_keywords(%rule, $defs->{keywords});
2385 my $module = netfilter_protocol_module($protocol);
2386 $rule{match}{$module} = 1;
2389 next;
2392 # port switches
2393 if ($keyword =~ /^[sd]port$/) {
2394 my $proto = $rule{protocol};
2395 error('To use sport or dport, you have to specify "proto tcp" or "proto udp" first')
2396 unless defined $proto and grep { /^(?:tcp|udp|udplite|dccp|sctp)$/ } to_array $proto;
2398 append_option(%rule, $keyword,
2399 getvalues(undef, allow_negation => 1));
2400 next;
2403 # default
2404 error("Unrecognized keyword: $keyword");
2407 # if the rule didn't reset the negated flag, it's not
2408 # supported
2409 error("Doesn't support negation: $keyword")
2410 if $negated;
2413 error('Missing "}" at end of file')
2414 if $lev > $base_level;
2416 # consistency check: check if they havn't forgotten
2417 # the ';' before the last statement
2418 error("Missing semicolon before end of file")
2419 if $rule{non_empty};
2422 sub execute_command {
2423 my ($command, $script) = @_;
2425 print LINES "$command\n"
2426 if $option{lines};
2427 return if $option{noexec};
2429 my $ret = system($command);
2430 unless ($ret == 0) {
2431 if ($? == -1) {
2432 print STDERR "failed to execute: $!\n";
2433 exit 1;
2434 } elsif ($? & 0x7f) {
2435 printf STDERR "child died with signal %d\n", $? & 0x7f;
2436 return 1;
2437 } else {
2438 print STDERR "(rule declared in $script->{filename}:$script->{line})\n"
2439 if defined $script;
2440 return $? >> 8;
2444 return;
2447 sub execute_slow($) {
2448 my $domain_info = shift;
2450 my $domain_cmd = $domain_info->{tools}{tables};
2452 my $status;
2453 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2454 my $table_cmd = "$domain_cmd -t $table";
2456 # reset chain policies
2457 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2458 next unless $chain_info->{builtin} or
2459 (not $table_info->{has_builtin} and
2460 is_netfilter_builtin_chain($table, $chain));
2461 $status ||= execute_command("$table_cmd -P $chain ACCEPT")
2462 unless $option{noflush};
2465 # clear
2466 unless ($option{noflush}) {
2467 $status ||= execute_command("$table_cmd -F");
2468 $status ||= execute_command("$table_cmd -X");
2471 next if $option{flush};
2473 # create chains / set policy
2474 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2475 if (is_netfilter_builtin_chain($table, $chain)) {
2476 if (exists $chain_info->{policy}) {
2477 $status ||= execute_command("$table_cmd -P $chain $chain_info->{policy}")
2478 unless $chain_info->{policy} eq 'ACCEPT';
2480 } else {
2481 if (exists $chain_info->{policy}) {
2482 $status ||= execute_command("$table_cmd -N $chain -P $chain_info->{policy}");
2484 else {
2485 $status ||= execute_command("$table_cmd -N $chain");
2490 # dump rules
2491 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2492 my $chain_cmd = "$table_cmd -A $chain";
2493 foreach my $rule (@{$chain_info->{rules}}) {
2494 $status ||= execute_command($chain_cmd . $rule->{rule});
2499 return $status;
2502 sub table_to_save($$) {
2503 my ($result_r, $table_info) = @_;
2505 foreach my $chain (sort keys %{$table_info->{chains}}) {
2506 my $chain_info = $table_info->{chains}{$chain};
2507 foreach my $rule (@{$chain_info->{rules}}) {
2508 $$result_r .= "-A $chain$rule->{rule}\n";
2513 sub rules_to_save($) {
2514 my ($domain_info) = @_;
2516 # convert this into an iptables-save text
2517 my $result = "# Generated by ferm $VERSION on " . localtime() . "\n";
2519 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2520 # select table
2521 $result .= '*' . $table . "\n";
2523 # create chains / set policy
2524 foreach my $chain (sort keys %{$table_info->{chains}}) {
2525 my $chain_info = $table_info->{chains}{$chain};
2526 my $policy = $option{flush} ? undef : $chain_info->{policy};
2527 unless (defined $policy) {
2528 if (is_netfilter_builtin_chain($table, $chain)) {
2529 $policy = 'ACCEPT';
2530 } else {
2531 next if $option{flush};
2532 $policy = '-';
2535 $result .= ":$chain $policy\ [0:0]\n";
2538 table_to_save(\$result, $table_info)
2539 unless $option{flush};
2541 # do it
2542 $result .= "COMMIT\n";
2545 return $result;
2548 sub restore_domain($$) {
2549 my ($domain_info, $save) = @_;
2551 my $path = $domain_info->{tools}{'tables-restore'};
2552 $path .= " --noflush" if $option{noflush};
2554 local *RESTORE;
2555 open RESTORE, "|$path"
2556 or die "Failed to run $path: $!\n";
2558 print RESTORE $save;
2560 close RESTORE
2561 or die "Failed to run $path\n";
2564 sub execute_fast($) {
2565 my $domain_info = shift;
2567 my $save = rules_to_save($domain_info);
2569 if ($option{lines}) {
2570 my $path = $domain_info->{tools}{'tables-restore'};
2571 $path .= " --noflush" if $option{noflush};
2572 print LINES "$path <<EOT\n"
2573 if $option{shell};
2574 print LINES $save;
2575 print LINES "EOT\n"
2576 if $option{shell};
2579 return if $option{noexec};
2581 eval {
2582 restore_domain($domain_info, $save);
2584 if ($@) {
2585 print STDERR $@;
2586 return 1;
2589 return;
2592 sub rollback() {
2593 my $error;
2594 while (my ($domain, $domain_info) = each %domains) {
2595 next unless $domain_info->{enabled};
2596 unless (defined $domain_info->{tools}{'tables-restore'}) {
2597 print STDERR "Cannot rollback domain '$domain' because there is no ${domain}tables-restore\n";
2598 next;
2601 my $reset = '';
2602 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2603 my $reset_chain = '';
2604 foreach my $chain (keys %{$table_info->{chains}}) {
2605 next unless is_netfilter_builtin_chain($table, $chain);
2606 $reset_chain .= ":${chain} ACCEPT [0:0]\n";
2608 $reset .= "*${table}\n${reset_chain}COMMIT\n"
2609 if length $reset_chain;
2612 $reset .= $domain_info->{previous}
2613 if defined $domain_info->{previous};
2615 restore_domain($domain_info, $reset);
2618 print STDERR "\nFirewall rules rolled back.\n" unless $error;
2619 exit 1;
2622 sub alrm_handler {
2623 # do nothing, just interrupt a system call
2626 sub confirm_rules {
2627 $SIG{ALRM} = \&alrm_handler;
2629 alarm(5);
2631 print STDERR "\n"
2632 . "ferm has applied the new firewall rules.\n"
2633 . "Please type 'yes' to confirm:\n";
2634 STDERR->flush();
2636 alarm($option{timeout});
2638 my $line = '';
2639 STDIN->sysread($line, 3);
2641 eval {
2642 require POSIX;
2643 POSIX::tcflush(*STDIN, 2);
2645 print STDERR "$@" if $@;
2647 $SIG{ALRM} = 'DEFAULT';
2649 return $line eq 'yes';
2652 # end of ferm
2654 __END__
2656 =head1 NAME
2658 ferm - a firewall rule parser for linux
2660 =head1 SYNOPSIS
2662 B<ferm> I<options> I<inputfiles>
2664 =head1 OPTIONS
2666 -n, --noexec Do not execute the rules, just simulate
2667 -F, --flush Flush all netfilter tables managed by ferm
2668 -l, --lines Show all rules that were created
2669 -i, --interactive Interactive mode: revert if user does not confirm
2670 -t, --timeout s Define interactive mode timeout in seconds
2671 --remote Remote mode; ignore host specific configuration.
2672 This implies --noexec and --lines.
2673 -V, --version Show current version number
2674 -h, --help Look at this text
2675 --slow Slow mode, don't use iptables-restore
2676 --shell Generate a shell script which calls iptables-restore
2677 --domain {ip|ip6} Handle only the specified domain
2678 --def '$name=v' Override a variable
2680 =cut