Automatically apply @ipfilter on dual-stack config
[ferm.git] / src / ferm
blob4230e13b06f29bc098d340efd3962a7e2b32fab3
1 #!/usr/bin/perl
4 # ferm, a firewall setup program that makes firewall rules easy!
6 # Copyright (C) 2001-2012 Max Kellermann, Auke Kok
8 # Comments, questions, greetings and additions to this program
9 # may be sent to <ferm@foo-projects.org>
13 # This program is free software; you can redistribute it and/or modify
14 # it under the terms of the GNU General Public License as published by
15 # the Free Software Foundation; either version 2 of the License, or
16 # (at your option) any later version.
18 # This program is distributed in the hope that it will be useful,
19 # but WITHOUT ANY WARRANTY; without even the implied warranty of
20 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 # GNU General Public License for more details.
23 # You should have received a copy of the GNU General Public License
24 # along with this program; if not, write to the Free Software
25 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
28 # $Id$
30 use File::Spec;
32 BEGIN {
33 eval { require strict; import strict; };
34 $has_strict = not $@;
35 if ($@) {
36 # we need no vars.pm if there is not even strict.pm
37 $INC{'vars.pm'} = 1;
38 *vars::import = sub {};
39 } else {
40 require IO::Handle;
43 eval { require Getopt::Long; import Getopt::Long; };
44 $has_getopt = not $@;
47 use vars qw($has_strict $has_getopt);
49 use vars qw($VERSION);
51 $VERSION = '2.1.3';
52 $VERSION .= '~git';
54 ## interface variables
55 # %option = command line and other options
56 use vars qw(%option);
58 ## hooks
59 use vars qw(@pre_hooks @post_hooks @flush_hooks);
61 ## parser variables
62 # $script: current script file
63 # @stack = ferm's parser stack containing local variables
64 # $auto_chain = index for the next auto-generated chain
65 use vars qw($script @stack $auto_chain);
67 ## netfilter variables
68 # %domains = state information about all domains ("ip" and "ip6")
69 # - initialized: domain initialization is done
70 # - tools: hash providing the paths of the domain's tools
71 # - previous: save file of the previous ruleset, for rollback
72 # - tables{$name}: ferm state information about tables
73 # - has_builtin: whether built-in chains have been determined in this table
74 # - chains{$chain}: ferm state information about the chains
75 # - builtin: whether this is a built-in chain
76 use vars qw(%domains);
78 ## constants
79 use vars qw(%deprecated_keywords);
81 # keywords from ferm 1.1 which are deprecated, and the new one; these
82 # are automatically replaced, and a warning is printed
83 %deprecated_keywords = ( goto => 'jump',
86 # these hashes provide the Netfilter module definitions
87 use vars qw(%proto_defs %match_defs %target_defs);
90 # This subsubsystem allows you to support (most) new netfilter modules
91 # in ferm. Add a call to one of the "add_XY_def()" functions below.
93 # Ok, now about the cryptic syntax: the function "add_XY_def()"
94 # registers a new module. There are three kinds of modules: protocol
95 # module (e.g. TCP, ICMP), match modules (e.g. state, physdev) and
96 # target modules (e.g. DNAT, MARK).
98 # The first parameter is always the module name which is passed to
99 # iptables with "-p", "-m" or "-j" (depending on which kind of module
100 # this is).
102 # After that, you add an encoded string for each option the module
103 # supports. This is where it becomes tricky.
105 # foo defaults to an option with one argument (which may be a ferm
106 # array)
108 # foo*0 option without any arguments
110 # foo=s one argument which must not be a ferm array ('s' stands for
111 # 'scalar')
113 # u32=m an array which renders into multiple iptables options in one
114 # rule
116 # ctstate=c one argument, if it's an array, pass it to iptables as a
117 # single comma separated value; example:
118 # ctstate (ESTABLISHED RELATED) translates to:
119 # --ctstate ESTABLISHED,RELATED
121 # foo=sac three arguments: scalar, array, comma separated; you may
122 # concatenate more than one letter code after the '='
124 # foo&bar one argument; call the perl function '&bar()' which parses
125 # the argument
127 # !foo negation is allowed and the '!' is written before the keyword
129 # foo! same as above, but '!' is after the keyword and before the
130 # parameters
132 # to:=to-destination makes "to" an alias for "to-destination"; you have
133 # to add a declaration for option "to-destination"
136 # prototype declarations
137 sub open_script($);
138 sub resolve($\@$);
139 sub enter($$);
140 sub rollback();
141 sub execute_fast($);
142 sub execute_slow($);
143 sub join_value($$);
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 'CLASSIFY', qw(set-class);
299 add_target_def 'CLUSTERIP', qw(new*0 hashmode clustermac total-nodes local-node hash-init);
300 add_target_def 'CONNMARK', qw(set-mark save-mark*0 restore-mark*0 mask);
301 add_target_def 'CONNSECMARK', qw(save*0 restore*0);
302 add_target_def 'CT', qw(notrack*0 helper ctevents=c expevents=c zone timeout);
303 add_target_def 'DNAT', qw(to-destination=m to:=to-destination persistent*0 random*0);
304 add_target_def 'DSCP', qw(set-dscp set-dscp-class);
305 add_target_def 'ECN', qw(ecn-tcp-remove*0);
306 add_target_def 'HL', qw(hl-set hl-dec hl-inc);
307 add_target_def 'IPV4OPTSSTRIP';
308 add_target_def 'LOG', qw(log-level log-prefix),
309 qw(log-tcp-sequence*0 log-tcp-options*0 log-ip-options*0 log-uid*0);
310 add_target_def 'MARK', qw(set-mark set-xmark and-mark or-mark xor-mark);
311 add_target_def 'MASQUERADE', qw(to-ports random*0);
312 add_target_def 'MIRROR';
313 add_target_def 'NETMAP', qw(to);
314 add_target_def 'NFLOG', qw(nflog-group nflog-prefix nflog-range nflog-threshold);
315 add_target_def 'NFQUEUE', qw(queue-num);
316 add_target_def 'NOTRACK';
317 add_target_def 'REDIRECT', qw(to-ports random*0);
318 add_target_def 'REJECT', qw(reject-with);
319 add_target_def 'ROUTE', qw(oif iif gw continue*0 tee*0);
320 add_target_def 'SAME', qw(to nodst*0 random*0);
321 add_target_def 'SECMARK', qw(selctx);
322 add_target_def 'SET', qw(add-set=sc del-set=sc);
323 add_target_def 'SNAT', qw(to-source=m to:=to-source persistent*0 random*0);
324 add_target_def 'TARPIT';
325 add_target_def 'TCPMSS', qw(set-mss clamp-mss-to-pmtu*0);
326 add_target_def 'TEE', qw(gateway);
327 add_target_def 'TOS', qw(set-tos and-tos or-tos xor-tos);
328 add_target_def 'TPROXY', qw(tproxy-mark on-port);
329 add_target_def 'TRACE';
330 add_target_def 'TTL', qw(ttl-set ttl-dec ttl-inc);
331 add_target_def 'ULOG', qw(ulog-nlgroup ulog-prefix ulog-cprange ulog-qthreshold);
333 add_match_def_x 'arp', '',
334 # ip
335 qw(source-ip! destination-ip! saddr:=source-ip daddr:=destination-ip),
336 # mac
337 qw(source-mac! destination-mac!),
338 # --in-interface
339 qw(in-interface! interface:=in-interface if:=in-interface),
340 # --out-interface
341 qw(out-interface! outerface:=out-interface of:=out-interface),
342 # misc
343 qw(h-length=s opcode=s h-type=s proto-type=s),
344 qw(mangle-ip-s=s mangle-ip-d=s mangle-mac-s=s mangle-mac-d=s mangle-target=s);
346 add_proto_def_x 'eb', 'IPv4',
347 qw(ip-source! ip-destination! ip-src:=ip-source ip-dst:=ip-destination),
348 qw(ip-tos!),
349 qw(ip-protocol! ip-proto:=ip-protocol),
350 qw(ip-source-port! ip-sport:=ip-source-port),
351 qw(ip-destination-port! ip-dport:=ip-destination-port);
353 add_proto_def_x 'eb', 'IPv6',
354 qw(ip6-source! ip6-destination! ip6-src:=ip6-source ip6-dst:=ip6-destination),
355 qw(ip6-tclass!),
356 qw(ip6-protocol! ip6-proto:=ip6-protocol),
357 qw(ip6-source-port! ip6-sport:=ip6-source-port),
358 qw(ip6-destination-port! ip6-dport:=ip6-destination-port);
360 add_proto_def_x 'eb', 'ARP',
361 qw(!arp-gratuitous*0),
362 qw(arp-opcode! arp-htype!=ss arp-ptype!=ss),
363 qw(arp-ip-src! arp-ip-dst! arp-mac-src! arp-mac-dst!);
365 add_proto_def_x 'eb', 'RARP',
366 qw(!arp-gratuitous*0),
367 qw(arp-opcode! arp-htype!=ss arp-ptype!=ss),
368 qw(arp-ip-src! arp-ip-dst! arp-mac-src! arp-mac-dst!);
370 add_proto_def_x 'eb', '802_1Q',
371 qw(vlan-id! vlan-prio! vlan-encap!),
373 add_match_def_x 'eb', '',
374 # --in-interface
375 qw(in-interface! interface:=in-interface if:=in-interface),
376 # --out-interface
377 qw(out-interface! outerface:=out-interface of:=out-interface),
378 # logical interface
379 qw(logical-in! logical-out!),
380 # --source, --destination
381 qw(source! saddr:=source destination! daddr:=destination),
382 # 802.3
383 qw(802_3-sap! 802_3-type!),
384 # among
385 qw(!among-dst=c !among-src=c !among-dst-file !among-src-file),
386 # limit
387 qw(limit=s limit-burst=s),
388 # mark_m
389 qw(mark!),
390 # pkttype
391 qw(pkttype-type!),
392 # stp
393 qw(stp-type! stp-flags! stp-root-prio! stp-root-addr! stp-root-cost!),
394 qw(stp-sender-prio! stp-sender-addr! stp-port! stp-msg-age! stp-max-age!),
395 qw(stp-hello-time! stp-forward-delay!),
396 # log
397 qw(log*0 log-level=s log-prefix=s log-ip*0 log-arp*0);
399 add_target_def_x 'eb', 'arpreply', qw(arpreply-mac arpreply-target);
400 add_target_def_x 'eb', 'dnat', qw(to-destination dnat-target);
401 add_target_def_x 'eb', 'MARK', qw(set-mark mark-target);
402 add_target_def_x 'eb', 'redirect', qw(redirect-target);
403 add_target_def_x 'eb', 'snat', qw(to-source snat-target snat-arp*0);
405 # import-ferm uses the above tables
406 return 1 if $0 =~ /import-ferm$/;
408 # parameter parser for ipt_multiport
409 sub multiport_params {
410 my $rule = shift;
412 # multiport only allows 15 ports at a time. For this
413 # reason, we do a little magic here: split the ports
414 # into portions of 15, and handle these portions as
415 # array elements
417 my $proto = $rule->{protocol};
418 error('To use multiport, you have to specify "proto tcp" or "proto udp" first')
419 unless defined $proto and grep { /^(?:tcp|udp|udplite)$/ } to_array($proto);
421 my $value = getvalues(undef, allow_negation => 1,
422 allow_array_negation => 1);
423 if (ref $value and ref $value eq 'ARRAY') {
424 my @value = @$value;
425 my @params;
427 while (@value) {
428 push @params, join(',', splice(@value, 0, 15));
431 return @params == 1
432 ? $params[0]
433 : \@params;
434 } else {
435 return join_value(',', $value);
439 sub ipfilter($@) {
440 my $domain = shift;
441 my @ips;
442 # very crude IPv4/IPv6 address detection
443 if ($domain eq 'ip') {
444 @ips = grep { !/:[0-9a-f]*:/ } @_;
445 } elsif ($domain eq 'ip6') {
446 @ips = grep { !m,^[0-9./]+$,s } @_;
448 return @ips;
451 sub address_magic {
452 my $rule = shift;
453 my $domain = $rule->{domain};
454 my $value = getvalues(undef, allow_negation => 1);
456 my @ips;
457 my $negated = 0;
458 if (ref $value and ref $value eq 'ARRAY') {
459 @ips = @$value;
460 } elsif (ref $value and ref $value eq 'negated') {
461 @ips = @$value;
462 $negated = 1;
463 } elsif (ref $value) {
464 die;
465 } else {
466 @ips = ($value);
469 # only do magic on domain (ip ip6); do not process on a single-stack rule
470 # as to let admins spot their errors instead of silently ignoring them
471 @ips = ipfilter($domain, @ips) if defined $rule->{domain_both};
473 if ($negated && scalar @ips) {
474 return bless \@ips, 'negated';
475 } else {
476 return \@ips;
480 # initialize stack: command line definitions
481 unshift @stack, {};
483 # Get command line stuff
484 if ($has_getopt) {
485 my ($opt_noexec, $opt_flush, $opt_noflush, $opt_lines, $opt_interactive,
486 $opt_timeout, $opt_help,
487 $opt_version, $opt_test, $opt_fast, $opt_slow, $opt_shell,
488 $opt_domain);
490 Getopt::Long::Configure('bundling', 'auto_help', 'no_ignore_case',
491 'no_auto_abbrev');
493 sub opt_def {
494 my ($opt, $value) = @_;
495 die 'Invalid --def specification'
496 unless $value =~ /^\$?(\w+)=(.*)$/s;
497 my ($name, $unparsed_value) = ($1, $2);
498 my $tokens = tokenize_string($unparsed_value);
499 $value = getvalues(sub { shift @$tokens; });
500 die 'Extra tokens after --def'
501 if @$tokens > 0;
502 $stack[0]{vars}{$name} = $value;
505 local $SIG{__WARN__} = sub { die $_[0]; };
506 GetOptions('noexec|n' => \$opt_noexec,
507 'flush|F' => \$opt_flush,
508 'noflush' => \$opt_noflush,
509 'lines|l' => \$opt_lines,
510 'interactive|i' => \$opt_interactive,
511 'timeout|t=s' => \$opt_timeout,
512 'help|h' => \$opt_help,
513 'version|V' => \$opt_version,
514 test => \$opt_test,
515 remote => \$opt_test,
516 fast => \$opt_fast,
517 slow => \$opt_slow,
518 shell => \$opt_shell,
519 'domain=s' => \$opt_domain,
520 'def=s' => \&opt_def,
523 if (defined $opt_help) {
524 require Pod::Usage;
525 Pod::Usage::pod2usage(-exitstatus => 0);
528 if (defined $opt_version) {
529 printversion();
530 exit 0;
533 $option{noexec} = $opt_noexec || $opt_test;
534 $option{flush} = $opt_flush;
535 $option{noflush} = $opt_noflush;
536 $option{lines} = $opt_lines || $opt_test || $opt_shell;
537 $option{interactive} = $opt_interactive && !$opt_noexec;
538 $option{timeout} = defined $opt_timeout ? $opt_timeout : "30";
539 $option{test} = $opt_test;
540 $option{fast} = !$opt_slow;
541 $option{shell} = $opt_shell;
543 die("ferm interactive mode not possible: /dev/stdin is not a tty\n")
544 if $option{interactive} and not -t STDIN;
545 die("ferm interactive mode not possible: /dev/stderr is not a tty\n")
546 if $option{interactive} and not -t STDERR;
547 die("ferm timeout has no sense without interactive mode")
548 if not $opt_interactive and defined $opt_timeout;
549 die("invalid timeout. must be an integer")
550 if defined $opt_timeout and not $opt_timeout =~ /^[+-]?\d+$/;
552 $option{domain} = $opt_domain if defined $opt_domain;
553 } else {
554 # tiny getopt emulation for microperl
555 my $filename;
556 foreach (@ARGV) {
557 if ($_ eq '--noexec' or $_ eq '-n') {
558 $option{noexec} = 1;
559 } elsif ($_ eq '--lines' or $_ eq '-l') {
560 $option{lines} = 1;
561 } elsif ($_ eq '--fast') {
562 $option{fast} = 1;
563 } elsif ($_ eq '--test') {
564 $option{test} = 1;
565 $option{noexec} = 1;
566 $option{lines} = 1;
567 } elsif ($_ eq '--shell') {
568 $option{$_} = 1 foreach qw(shell fast lines);
569 } elsif (/^-/) {
570 printf STDERR "Usage: ferm [--noexec] [--lines] [--fast] [--shell] FILENAME\n";
571 exit 1;
572 } else {
573 $filename = $_;
576 undef @ARGV;
577 push @ARGV, $filename;
580 unless (@ARGV == 1) {
581 require Pod::Usage;
582 Pod::Usage::pod2usage(-exitstatus => 1);
585 if ($has_strict) {
586 open LINES, ">&STDOUT" if $option{lines};
587 open STDOUT, ">&STDERR" if $option{shell};
588 } else {
589 # microperl can't redirect file handles
590 *LINES = *STDOUT;
592 if ($option{fast} and not $option{noexec}) {
593 print STDERR "Sorry, ferm on microperl does not allow --fast without --noexec\n";
594 exit 1
598 unshift @stack, {};
599 open_script($ARGV[0]);
601 my( $volume,$dirs,$file ) = File::Spec->splitpath( $ARGV[0] );
602 $stack[0]{auto}{FILENAME} = $ARGV[0];
603 $stack[0]{auto}{FILEBNAME} = $file;
604 $stack[0]{auto}{DIRNAME} = $dirs;
608 # parse all input recursively
609 enter(0, undef);
610 die unless @stack == 2;
612 # enable/disable hooks depending on --flush
614 if ($option{flush}) {
615 undef @pre_hooks;
616 undef @post_hooks;
617 } else {
618 undef @flush_hooks;
621 # execute all generated rules
622 my $status;
624 foreach my $cmd (@pre_hooks) {
625 print LINES "$cmd\n" if $option{lines};
626 system($cmd) unless $option{noexec};
629 while (my ($domain, $domain_info) = each %domains) {
630 next unless $domain_info->{enabled};
631 my $s = $option{fast} &&
632 defined $domain_info->{tools}{'tables-restore'}
633 ? execute_fast($domain_info) : execute_slow($domain_info);
634 $status = $s if defined $s;
637 foreach my $cmd (@post_hooks, @flush_hooks) {
638 print LINES "$cmd\n" if $option{lines};
639 system($cmd) unless $option{noexec};
642 if (defined $status) {
643 rollback();
644 exit $status;
647 # ask user, and rollback if there is no confirmation
649 if ($option{interactive}) {
650 if ($option{shell}) {
651 print LINES "echo 'ferm has applied the new firewall rules.'\n";
652 print LINES "echo 'Please press Ctrl-C to confirm.'\n";
653 print LINES "sleep $option{timeout}\n";
654 while (my ($domain, $domain_info) = each %domains) {
655 my $restore = $domain_info->{tools}{'tables-restore'};
656 next unless defined $restore;
657 print LINES "$restore <\$${domain}_tmp\n";
661 confirm_rules() or rollback() unless $option{noexec};
664 exit 0;
666 # end of program execution!
669 # funcs
671 sub printversion {
672 print "ferm $VERSION\n";
673 print "Copyright (C) 2001-2012 Max Kellermann, Auke Kok\n";
674 print "This program is free software released under GPLv2.\n";
675 print "See the included COPYING file for license details.\n";
679 sub error {
680 # returns a nice formatted error message, showing the
681 # location of the error.
682 my $tabs = 0;
683 my @lines;
684 my $l = 0;
685 my @words = map { @$_ } @{$script->{past_tokens}};
687 for my $w ( 0 .. $#words ) {
688 if ($words[$w] eq "\x29")
689 { $l++ ; $lines[$l] = " " x ($tabs-- -1) ;};
690 if ($words[$w] eq "\x28")
691 { $l++ ; $lines[$l] = " " x $tabs++ ;};
692 if ($words[$w] eq "\x7d")
693 { $l++ ; $lines[$l] = " " x ($tabs-- -1) ;};
694 if ($words[$w] eq "\x7b")
695 { $l++ ; $lines[$l] = " " x $tabs++ ;};
696 if ( $l > $#lines ) { $lines[$l] = "" };
697 $lines[$l] .= $words[$w] . " ";
698 if ($words[$w] eq "\x28")
699 { $l++ ; $lines[$l] = " " x $tabs ;};
700 if (($words[$w] eq "\x29") && ($words[$w+1] ne "\x7b"))
701 { $l++ ; $lines[$l] = " " x $tabs ;};
702 if ($words[$w] eq "\x7b")
703 { $l++ ; $lines[$l] = " " x $tabs ;};
704 if (($words[$w] eq "\x7d") && ($words[$w+1] ne "\x7d"))
705 { $l++ ; $lines[$l] = " " x $tabs ;};
706 if (($words[$w] eq "\x3b") && ($words[$w+1] ne "\x7d"))
707 { $l++ ; $lines[$l] = " " x $tabs ;}
708 if ($words[$w-1] eq "option")
709 { $l++ ; $lines[$l] = " " x $tabs ;}
711 my $start = $#lines - 4;
712 if ($start < 0) { $start = 0 } ;
713 print STDERR "Error in $script->{filename} line $script->{line}:\n";
714 for $l ( $start .. $#lines)
715 { print STDERR $lines[$l]; if ($l != $#lines ) {print STDERR "\n"} ; };
716 print STDERR "<--\n";
717 die("@_\n");
720 # print a warning message about code from an input file
721 sub warning {
722 print STDERR "Warning in $script->{filename} line $script->{line}: "
723 . (shift) . "\n";
726 sub find_tool($) {
727 my $name = shift;
728 return $name if $option{test};
729 for my $path ('/sbin', split ':', $ENV{PATH}) {
730 my $ret = "$path/$name";
731 return $ret if -x $ret;
733 die "$name not found in PATH\n";
736 sub initialize_domain {
737 my $domain = shift;
738 my $domain_info = $domains{$domain} ||= {};
740 return if exists $domain_info->{initialized};
742 die "Invalid domain '$domain'\n" unless $domain =~ /^(?:ip6?|arp|eb)$/;
744 my @tools = qw(tables);
745 push @tools, qw(tables-save tables-restore)
746 if $domain =~ /^ip6?$/;
748 # determine the location of this domain's tools
749 my %tools = map { $_ => find_tool($domain . $_) } @tools;
750 $domain_info->{tools} = \%tools;
752 # make tables-save tell us about the state of this domain
753 # (which tables and chains do exist?), also remember the old
754 # save data which may be used later by the rollback function
755 local *SAVE;
756 if (!$option{test} &&
757 exists $tools{'tables-save'} &&
758 open(SAVE, "$tools{'tables-save'}|")) {
759 my $save = '';
761 my $table_info;
762 while (<SAVE>) {
763 $save .= $_;
765 if (/^\*(\w+)/) {
766 my $table = $1;
767 $table_info = $domain_info->{tables}{$table} ||= {};
768 } elsif (defined $table_info and /^:(\w+)\s+(\S+)/
769 and $2 ne '-') {
770 $table_info->{chains}{$1}{builtin} = 1;
771 $table_info->{has_builtin} = 1;
775 # for rollback
776 $domain_info->{previous} = $save;
779 if ($option{shell} && $option{interactive} &&
780 exists $tools{'tables-save'}) {
781 print LINES "${domain}_tmp=\$(mktemp ferm.XXXXXXXXXX)\n";
782 print LINES "$tools{'tables-save'} >\$${domain}_tmp\n";
785 $domain_info->{initialized} = 1;
788 sub check_domain($) {
789 my $domain = shift;
790 my @result;
792 return if exists $option{domain}
793 and $domain ne $option{domain};
795 eval {
796 initialize_domain($domain);
798 error($@) if $@;
800 return 1;
803 # split the input string into words and delete comments
804 sub tokenize_string($) {
805 my $string = shift;
807 my @ret;
809 foreach my $word ($string =~ m/(".*?"|'.*?'|`.*?`|[!,=&\$\%\(\){};]|[-+\w\/\.:]+|@\w+|#)/g) {
810 last if $word eq '#';
811 push @ret, $word;
814 return \@ret;
817 # generate a "line" special token, that marks the line number; these
818 # special tokens are inserted after each line break, so ferm keeps
819 # track of line numbers
820 sub make_line_token($) {
821 my $line = shift;
822 return bless(\$line, 'line');
825 # read some more tokens from the input file into a buffer
826 sub prepare_tokens() {
827 my $tokens = $script->{tokens};
828 while (@$tokens == 0) {
829 my $handle = $script->{handle};
830 return unless defined $handle;
831 my $line = <$handle>;
832 return unless defined $line;
834 push @$tokens, make_line_token($script->{line} + 1);
836 # the next parser stage eats this
837 push @$tokens, @{tokenize_string($line)};
840 return 1;
843 sub handle_special_token($) {
844 my $token = shift;
845 die unless ref $token;
846 if (ref $token eq 'line') {
847 $script->{line} = $$token;
848 } else {
849 die;
853 sub handle_special_tokens() {
854 my $tokens = $script->{tokens};
855 while (@$tokens > 0 and ref $tokens->[0]) {
856 handle_special_token(shift @$tokens);
860 # wrapper for prepare_tokens() which handles "special" tokens
861 sub prepare_normal_tokens() {
862 my $tokens = $script->{tokens};
863 while (1) {
864 handle_special_tokens();
865 return 1 if @$tokens > 0;
866 return unless prepare_tokens();
870 # open a ferm sub script
871 sub open_script($) {
872 my $filename = shift;
874 for (my $s = $script; defined $s; $s = $s->{parent}) {
875 die("Circular reference in $script->{filename} line $script->{line}: $filename\n")
876 if $s->{filename} eq $filename;
879 my $handle;
880 if ($filename eq '-') {
881 # Note that this only allowed in the command-line argument and not
882 # @includes, since those are filtered by collect_filenames()
883 $handle = *STDIN;
884 # also set a filename label so that error messages are more helpful
885 $filename = "<stdin>";
886 } else {
887 local *FILE;
888 open FILE, "$filename" or die("Failed to open $filename: $!\n");
889 $handle = *FILE;
892 $script = { filename => $filename,
893 handle => $handle,
894 line => 0,
895 past_tokens => [],
896 tokens => [],
897 parent => $script,
900 return $script;
903 # collect script filenames which are being included
904 sub collect_filenames(@) {
905 my @ret;
907 # determine the current script's parent directory for relative
908 # file names
909 die unless defined $script;
910 my $parent_dir = $script->{filename} =~ m,^(.*/),
911 ? $1 : './';
913 foreach my $pathname (@_) {
914 # non-absolute file names are relative to the parent script's
915 # file name
916 $pathname = $parent_dir . $pathname
917 unless $pathname =~ m,^/|\|$,;
919 if ($pathname =~ m,/$,) {
920 # include all regular files in a directory
922 error("'$pathname' is not a directory")
923 unless -d $pathname;
925 local *DIR;
926 opendir DIR, $pathname
927 or error("Failed to open directory '$pathname': $!");
928 my @names = readdir DIR;
929 closedir DIR;
931 # sort those names for a well-defined order
932 foreach my $name (sort { $a cmp $b } @names) {
933 # ignore dpkg's backup files
934 next if $name =~ /\.dpkg-(old|dist|new|tmp)$/;
935 # don't include hidden and backup files
936 next if $name =~ /^\.|~$/;
938 my $filename = $pathname . $name;
939 push @ret, $filename
940 if -f $filename;
942 } elsif ($pathname =~ m,\|$,) {
943 # run a program and use its output
944 push @ret, $pathname;
945 } elsif ($pathname =~ m,^\|,) {
946 error('This kind of pipe is not allowed');
947 } else {
948 # include a regular file
950 error("'$pathname' is a directory; maybe use trailing '/' to include a directory?")
951 if -d $pathname;
952 error("'$pathname' is not a file")
953 unless -f $pathname;
955 push @ret, $pathname;
959 return @ret;
962 # peek a token from the queue, but don't remove it
963 sub peek_token() {
964 return unless prepare_normal_tokens();
965 return $script->{tokens}[0];
968 # get a token from the queue, including "special" tokens
969 sub next_raw_token() {
970 return unless prepare_tokens();
971 return shift @{$script->{tokens}};
974 # get a token from the queue
975 sub next_token() {
976 return unless prepare_normal_tokens();
977 my $token = shift @{$script->{tokens}};
979 # update $script->{past_tokens}
980 my $past_tokens = $script->{past_tokens};
982 if (@$past_tokens > 0) {
983 my $prev_token = $past_tokens->[-1][-1];
984 $past_tokens->[-1] = @$past_tokens > 1 ? ['{'] : []
985 if $prev_token eq ';';
986 if ($prev_token eq '}') {
987 pop @$past_tokens;
988 $past_tokens->[-1] = $past_tokens->[-1][0] eq '{'
989 ? [ '{' ] : []
990 if @$past_tokens > 0;
994 push @$past_tokens, [] if $token eq '{' or @$past_tokens == 0;
995 push @{$past_tokens->[-1]}, $token;
997 # return
998 return $token;
1001 sub expect_token($;$) {
1002 my $expect = shift;
1003 my $msg = shift;
1004 my $token = next_token();
1005 error($msg || "'$expect' expected")
1006 unless defined $token and $token eq $expect;
1009 # require that another token exists, and that it's not a "special"
1010 # token, e.g. ";" and "{"
1011 sub require_next_token {
1012 my $code = shift || \&next_token;
1014 my $token = &$code(@_);
1016 error('unexpected end of file')
1017 unless defined $token;
1019 error("'$token' not allowed here")
1020 if $token =~ /^[;{}]$/;
1022 return $token;
1025 # return the value of a variable
1026 sub variable_value($) {
1027 my $name = shift;
1029 if ($name eq "LINE") {
1030 return $script->{line};
1033 foreach (@stack) {
1034 return $_->{vars}{$name}
1035 if exists $_->{vars}{$name};
1038 return $stack[0]{auto}{$name}
1039 if exists $stack[0]{auto}{$name};
1041 return;
1044 # determine the value of a variable, die if the value is an array
1045 sub string_variable_value($) {
1046 my $name = shift;
1047 my $value = variable_value($name);
1049 error("variable '$name' must be a string, but it is an array")
1050 if ref $value;
1052 return $value;
1055 # similar to the built-in "join" function, but also handle negated
1056 # values in a special way
1057 sub join_value($$) {
1058 my ($expr, $value) = @_;
1060 unless (ref $value) {
1061 return $value;
1062 } elsif (ref $value eq 'ARRAY') {
1063 return join($expr, @$value);
1064 } elsif (ref $value eq 'negated') {
1065 # bless'negated' is a special marker for negated values
1066 $value = join_value($expr, $value->[0]);
1067 return bless [ $value ], 'negated';
1068 } else {
1069 die;
1073 sub negate_value($$;$) {
1074 my ($value, $class, $allow_array) = @_;
1076 if (ref $value) {
1077 error('double negation is not allowed')
1078 if ref $value eq 'negated' or ref $value eq 'pre_negated';
1080 error('it is not possible to negate an array')
1081 if ref $value eq 'ARRAY' and not $allow_array;
1084 return bless [ $value ], $class || 'negated';
1087 sub format_bool($) {
1088 return $_[0] ? 1 : 0;
1091 sub resolve($\@$) {
1092 my ($resolver, $names, $type) = @_;
1094 my @result;
1095 foreach my $hostname (@$names) {
1096 my $query = $resolver->search($hostname, $type);
1097 error("DNS query for '$hostname' failed: " . $resolver->errorstring)
1098 unless $query;
1100 foreach my $rr ($query->answer) {
1101 next unless $rr->type eq $type;
1103 if ($type eq 'NS') {
1104 push @result, $rr->nsdname;
1105 } elsif ($type eq 'MX') {
1106 push @result, $rr->exchange;
1107 } else {
1108 push @result, $rr->address;
1113 # NS/MX records return host names; resolve these again in the
1114 # second pass (IPv4 only currently)
1115 @result = resolve($resolver, @result, 'A')
1116 if $type eq 'NS' or $type eq 'MX';
1118 return @result;
1121 # returns the next parameter, which may either be a scalar or an array
1122 sub getvalues {
1123 my $code = shift;
1124 my %options = @_;
1126 my $token = require_next_token($code);
1128 if ($token eq '(') {
1129 # read an array until ")"
1130 my @wordlist;
1132 for (;;) {
1133 $token = getvalues($code,
1134 parenthesis_allowed => 1,
1135 comma_allowed => 1);
1137 unless (ref $token) {
1138 last if $token eq ')';
1140 if ($token eq ',') {
1141 error('Comma is not allowed within arrays, please use only a space');
1142 next;
1145 push @wordlist, $token;
1146 } elsif (ref $token eq 'ARRAY') {
1147 push @wordlist, @$token;
1148 } else {
1149 error('unknown toke type');
1153 error('empty array not allowed here')
1154 unless @wordlist or not $options{non_empty};
1156 return @wordlist == 1
1157 ? $wordlist[0]
1158 : \@wordlist;
1159 } elsif ($token =~ /^\`(.*)\`$/s) {
1160 # execute a shell command, insert output
1161 my $command = $1;
1162 my $output = `$command`;
1163 unless ($? == 0) {
1164 if ($? == -1) {
1165 error("failed to execute: $!");
1166 } elsif ($? & 0x7f) {
1167 error("child died with signal " . ($? & 0x7f));
1168 } elsif ($? >> 8) {
1169 error("child exited with status " . ($? >> 8));
1173 # remove comments
1174 $output =~ s/#.*//mg;
1176 # tokenize
1177 my @tokens = grep { length } split /\s+/s, $output;
1179 my @values;
1180 while (@tokens) {
1181 my $value = getvalues(sub { shift @tokens });
1182 push @values, to_array($value);
1185 # and recurse
1186 return @values == 1
1187 ? $values[0]
1188 : \@values;
1189 } elsif ($token =~ /^\'(.*)\'$/s) {
1190 # single quotes: a string
1191 return $1;
1192 } elsif ($token =~ /^\"(.*)\"$/s) {
1193 # double quotes: a string with escapes
1194 $token = $1;
1195 $token =~ s,\$(\w+),string_variable_value($1),eg;
1196 return $token;
1197 } elsif ($token eq '!') {
1198 error('negation is not allowed here')
1199 unless $options{allow_negation};
1201 $token = getvalues($code);
1203 return negate_value($token, undef, $options{allow_array_negation});
1204 } elsif ($token eq ',') {
1205 return $token
1206 if $options{comma_allowed};
1208 error('comma is not allowed here');
1209 } elsif ($token eq '=') {
1210 error('equals operator ("=") is not allowed here');
1211 } elsif ($token eq '$') {
1212 my $name = require_next_token($code);
1213 error('variable name expected - if you want to concatenate strings, try using double quotes')
1214 unless $name =~ /^\w+$/;
1216 my $value = variable_value($name);
1218 error("no such variable: \$$name")
1219 unless defined $value;
1221 return $value;
1222 } elsif ($token eq '&') {
1223 error("function calls are not allowed as keyword parameter");
1224 } elsif ($token eq ')' and not $options{parenthesis_allowed}) {
1225 error('Syntax error');
1226 } elsif ($token =~ /^@/) {
1227 if ($token eq '@resolve') {
1228 my @params = get_function_params();
1229 error('Usage: @resolve((hostname ...), [type])')
1230 unless @params == 1 or @params == 2;
1231 eval { require Net::DNS; };
1232 error('For the @resolve() function, you need the Perl library Net::DNS')
1233 if $@;
1234 my $type = $params[1] || 'A';
1235 error('String expected') if ref $type;
1236 my $resolver = new Net::DNS::Resolver;
1237 @params = to_array($params[0]);
1238 my @result = resolve($resolver, @params, $type);
1239 return @result == 1 ? $result[0] : \@result;
1240 } elsif ($token eq '@eq') {
1241 my @params = get_function_params();
1242 error('Usage: @eq(a, b)') unless @params == 2;
1243 return format_bool($params[0] eq $params[1]);
1244 } elsif ($token eq '@ne') {
1245 my @params = get_function_params();
1246 error('Usage: @ne(a, b)') unless @params == 2;
1247 return format_bool($params[0] ne $params[1]);
1248 } elsif ($token eq '@not') {
1249 my @params = get_function_params();
1250 error('Usage: @not(a)') unless @params == 1;
1251 return format_bool(not $params[0]);
1252 } elsif ($token eq '@cat') {
1253 my $value = '';
1254 map {
1255 error('String expected') if ref $_;
1256 $value .= $_;
1257 } get_function_params();
1258 return $value;
1259 } elsif ($token eq '@substr') {
1260 my @params = get_function_params();
1261 error('Usage: @substr(string, num, num)') unless @params == 3;
1262 error('String expected') if ref $params[0] or ref $params[1] or ref $params[2];
1263 return substr($params[0],$params[1],$params[2]);
1264 } elsif ($token eq '@length') {
1265 my @params = get_function_params();
1266 error('Usage: @length(string)') unless @params == 1;
1267 error('String expected') if ref $params[0];
1268 return length($params[0]);
1269 } elsif ($token eq '@basename') {
1270 my @params = get_function_params();
1271 error('Usage: @basename(path)') unless @params == 1;
1272 error('String expected') if ref $params[0];
1273 my($volume,$path,$file) = File::Spec->splitpath( $params[0] );
1274 return $file;
1275 } elsif ($token eq '@dirname') {
1276 my @params = get_function_params();
1277 error('Usage: @dirname(path)') unless @params == 1;
1278 error('String expected') if ref $params[0];
1279 my($volume,$path,$file) = File::Spec->splitpath( $params[0] );
1280 return $path;
1281 } elsif ($token eq '@ipfilter') {
1282 my @params = get_function_params();
1283 error('Usage: @ipfilter((ip1 ip2 ...))') unless @params == 1;
1284 my $domain = $stack[0]{auto}{DOMAIN};
1285 error('No domain specified') unless defined $domain;
1286 my @ips = ipfilter($domain, to_array($params[0]));
1287 return \@ips;
1288 } else {
1289 error("unknown ferm built-in function");
1291 } else {
1292 return $token;
1296 # returns the next parameter, but only allow a scalar
1297 sub getvar() {
1298 my $token = getvalues();
1300 error('array not allowed here')
1301 if ref $token and ref $token eq 'ARRAY';
1303 return $token;
1306 sub get_function_params(%) {
1307 expect_token('(', 'function name must be followed by "()"');
1309 my $token = peek_token();
1310 if ($token eq ')') {
1311 require_next_token();
1312 return;
1315 my @params;
1317 while (1) {
1318 if (@params > 0) {
1319 $token = require_next_token();
1320 last
1321 if $token eq ')';
1323 error('"," expected')
1324 unless $token eq ',';
1327 push @params, getvalues(undef, @_);
1330 return @params;
1333 # collect all tokens in a flat array reference until the end of the
1334 # command is reached
1335 sub collect_tokens {
1336 my %options = @_;
1338 my @level;
1339 my @tokens;
1341 # re-insert a "line" token, because the starting token of the
1342 # current line has been consumed already
1343 push @tokens, make_line_token($script->{line});
1345 while (1) {
1346 my $keyword = next_raw_token();
1347 error('unexpected end of file within function/variable declaration')
1348 unless defined $keyword;
1350 if (ref $keyword) {
1351 handle_special_token($keyword);
1352 } elsif ($keyword =~ /^[\{\(]$/) {
1353 push @level, $keyword;
1354 } elsif ($keyword =~ /^[\}\)]$/) {
1355 my $expected = $keyword;
1356 $expected =~ tr/\}\)/\{\(/;
1357 my $opener = pop @level;
1358 error("unmatched '$keyword'")
1359 unless defined $opener and $opener eq $expected;
1360 } elsif ($keyword eq ';' and @level == 0) {
1361 push @tokens, $keyword
1362 if $options{include_semicolon};
1364 if ($options{include_else}) {
1365 my $token = peek_token;
1366 next if $token eq '@else';
1369 last;
1372 push @tokens, $keyword;
1374 last
1375 if $keyword eq '}' and @level == 0;
1378 return \@tokens;
1382 # returns the specified value as an array. dereference arrayrefs
1383 sub to_array($) {
1384 my $value = shift;
1385 die unless wantarray;
1386 die if @_;
1387 unless (ref $value) {
1388 return $value;
1389 } elsif (ref $value eq 'ARRAY') {
1390 return @$value;
1391 } else {
1392 die;
1396 # evaluate the specified value as bool
1397 sub eval_bool($) {
1398 my $value = shift;
1399 die if wantarray;
1400 die if @_;
1401 unless (ref $value) {
1402 return $value;
1403 } elsif (ref $value eq 'ARRAY') {
1404 return @$value > 0;
1405 } else {
1406 die;
1410 sub is_netfilter_core_target($) {
1411 my $target = shift;
1412 die unless defined $target and length $target;
1413 return grep { $_ eq $target } qw(ACCEPT DROP RETURN QUEUE);
1416 sub is_netfilter_module_target($$) {
1417 my ($domain_family, $target) = @_;
1418 die unless defined $target and length $target;
1420 return defined $domain_family &&
1421 exists $target_defs{$domain_family} &&
1422 $target_defs{$domain_family}{$target};
1425 sub is_netfilter_builtin_chain($$) {
1426 my ($table, $chain) = @_;
1428 return grep { $_ eq $chain }
1429 qw(PREROUTING INPUT FORWARD OUTPUT POSTROUTING);
1432 sub netfilter_canonical_protocol($) {
1433 my $proto = shift;
1434 return 'icmp'
1435 if $proto eq 'ipv6-icmp' or $proto eq 'icmpv6';
1436 return 'mh'
1437 if $proto eq 'ipv6-mh';
1438 return $proto;
1441 sub netfilter_protocol_module($) {
1442 my $proto = shift;
1443 return unless defined $proto;
1444 return 'icmp6'
1445 if $proto eq 'icmpv6';
1446 return $proto;
1449 # escape the string in a way safe for the shell
1450 sub shell_escape($) {
1451 my $token = shift;
1453 return $token if $token =~ /^[-_a-zA-Z0-9]+$/s;
1455 if ($option{fast}) {
1456 # iptables-save/iptables-restore are quite buggy concerning
1457 # escaping and special characters... we're trying our best
1458 # here
1460 $token =~ s,",\\",g;
1461 $token = '"' . $token . '"'
1462 if $token =~ /[\s\'\\;&]/s or length($token) == 0;
1463 } else {
1464 return $token
1465 if $token =~ /^\`.*\`$/;
1466 $token =~ s/'/'\\''/g;
1467 $token = '\'' . $token . '\''
1468 if $token =~ /[\s\"\\;<>&|]/s or length($token) == 0;
1471 return $token;
1474 # append an option to the shell command line, using information from
1475 # the module definition (see %match_defs etc.)
1476 sub shell_format_option($$) {
1477 my ($keyword, $value) = @_;
1479 my $cmd = '';
1480 if (ref $value) {
1481 if ((ref $value eq 'negated') || (ref $value eq 'pre_negated')) {
1482 $value = $value->[0];
1483 $cmd = ' !';
1487 unless (defined $value) {
1488 $cmd .= " --$keyword";
1489 } elsif (ref $value) {
1490 if (ref $value eq 'params') {
1491 $cmd .= " --$keyword ";
1492 $cmd .= join(' ', map { shell_escape($_) } @$value);
1493 } elsif (ref $value eq 'multi') {
1494 foreach (@$value) {
1495 $cmd .= " --$keyword " . shell_escape($_);
1497 } else {
1498 die;
1500 } else {
1501 $cmd .= " --$keyword " . shell_escape($value);
1504 return $cmd;
1507 sub format_option($$$) {
1508 my ($domain, $name, $value) = @_;
1510 $value = 'icmpv6' if $domain eq 'ip6' and $name eq 'protocol'
1511 and $value eq 'icmp';
1512 $name = 'icmpv6-type' if $domain eq 'ip6' and $name eq 'icmp-type';
1514 if ($domain eq 'ip6' and $name eq 'reject-with') {
1515 my %icmp_map = (
1516 'icmp-net-unreachable' => 'icmp6-no-route',
1517 'icmp-host-unreachable' => 'icmp6-addr-unreachable',
1518 'icmp-port-unreachable' => 'icmp6-port-unreachable',
1519 'icmp-net-prohibited' => 'icmp6-adm-prohibited',
1520 'icmp-host-prohibited' => 'icmp6-adm-prohibited',
1521 'icmp-admin-prohibited' => 'icmp6-adm-prohibited',
1523 $value = $icmp_map{$value} if exists $icmp_map{$value};
1526 return shell_format_option($name, $value);
1529 sub append_rule($$) {
1530 my ($chain_rules, $rule) = @_;
1532 my $cmd = join('', map { $_->[2] } @{$rule->{options}});
1533 push @$chain_rules, { rule => $cmd,
1534 script => $rule->{script},
1538 sub unfold_rule {
1539 my ($domain, $chain_rules, $rule) = (shift, shift, shift);
1540 return append_rule($chain_rules, $rule) unless @_;
1542 my $option = shift;
1543 my @values = @{$option->[1]};
1545 foreach my $value (@values) {
1546 $option->[2] = format_option($domain, $option->[0], $value);
1547 unfold_rule($domain, $chain_rules, $rule, @_);
1551 sub mkrules2($$$) {
1552 my ($domain, $chain_rules, $rule) = @_;
1554 my @unfold;
1555 foreach my $option (@{$rule->{options}}) {
1556 if (ref $option->[1] and ref $option->[1] eq 'ARRAY') {
1557 push @unfold, $option
1558 } else {
1559 $option->[2] = format_option($domain, $option->[0], $option->[1]);
1563 unfold_rule($domain, $chain_rules, $rule, @unfold);
1566 # convert a bunch of internal rule structures in iptables calls,
1567 # unfold arrays during that
1568 sub mkrules($) {
1569 my $rule = shift;
1571 my $domain = $rule->{domain};
1572 my $domain_info = $domains{$domain};
1573 $domain_info->{enabled} = 1;
1575 foreach my $table (to_array $rule->{table}) {
1576 my $table_info = $domain_info->{tables}{$table} ||= {};
1578 foreach my $chain (to_array $rule->{chain}) {
1579 my $chain_rules = $table_info->{chains}{$chain}{rules} ||= [];
1580 mkrules2($domain, $chain_rules, $rule)
1581 if $rule->{has_rule} and not $option{flush};
1586 # parse a keyword from a module definition
1587 sub parse_keyword(\%$$) {
1588 my ($rule, $def, $negated_ref) = @_;
1590 my $params = $def->{params};
1592 my $value;
1594 my $negated;
1595 if ($$negated_ref && exists $def->{pre_negation}) {
1596 $negated = 1;
1597 undef $$negated_ref;
1600 unless (defined $params) {
1601 undef $value;
1602 } elsif (ref $params && ref $params eq 'CODE') {
1603 $value = &$params($rule);
1604 } elsif ($params eq 'm') {
1605 $value = bless [ to_array getvalues() ], 'multi';
1606 } elsif ($params =~ /^[a-z]/) {
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 my @params;
1616 foreach my $p (split(//, $params)) {
1617 if ($p eq 's') {
1618 push @params, getvar();
1619 } elsif ($p eq 'c') {
1620 my @v = to_array getvalues(undef, non_empty => 1);
1621 push @params, join(',', @v);
1622 } else {
1623 die;
1627 $value = @params == 1
1628 ? $params[0]
1629 : bless \@params, 'params';
1630 } elsif ($params == 1) {
1631 if (exists $def->{negation} and not $negated) {
1632 my $token = peek_token();
1633 if ($token eq '!') {
1634 require_next_token();
1635 $negated = 1;
1639 $value = getvalues();
1641 warning("log-prefix is too long; truncating to 29 characters: '$1'")
1642 if $def->{name} eq 'log-prefix' && $value =~ s,^(.{29}).+$,$1,;
1643 } else {
1644 if (exists $def->{negation} and not $negated) {
1645 my $token = peek_token();
1646 if ($token eq '!') {
1647 require_next_token();
1648 $negated = 1;
1652 $value = bless [ map {
1653 getvar()
1654 } (1..$params) ], 'params';
1657 $value = negate_value($value, exists $def->{pre_negation} && 'pre_negated')
1658 if $negated;
1660 return $value;
1663 sub append_option(\%$$) {
1664 my ($rule, $name, $value) = @_;
1665 push @{$rule->{options}}, [ $name, $value ];
1668 # parse options of a module
1669 sub parse_option($\%$) {
1670 my ($def, $rule, $negated_ref) = @_;
1672 append_option(%$rule, $def->{name},
1673 parse_keyword(%$rule, $def, $negated_ref));
1676 sub copy_on_write($$) {
1677 my ($rule, $key) = @_;
1678 return unless exists $rule->{cow}{$key};
1679 $rule->{$key} = {%{$rule->{$key}}};
1680 delete $rule->{cow}{$key};
1683 sub new_level(\%$) {
1684 my ($rule, $prev) = @_;
1686 %$rule = ();
1687 if (defined $prev) {
1688 # copy data from previous level
1689 $rule->{cow} = { keywords => 1, };
1690 $rule->{keywords} = $prev->{keywords};
1691 $rule->{match} = { %{$prev->{match}} };
1692 $rule->{options} = [@{$prev->{options}}];
1693 foreach my $key (qw(domain domain_family domain_both table chain protocol has_rule has_action)) {
1694 $rule->{$key} = $prev->{$key}
1695 if exists $prev->{$key};
1697 } else {
1698 $rule->{cow} = {};
1699 $rule->{keywords} = {};
1700 $rule->{match} = {};
1701 $rule->{options} = [];
1705 sub merge_keywords(\%$) {
1706 my ($rule, $keywords) = @_;
1707 copy_on_write($rule, 'keywords');
1708 while (my ($name, $def) = each %$keywords) {
1709 $rule->{keywords}{$name} = $def;
1713 sub set_domain(\%$) {
1714 my ($rule, $domain) = @_;
1716 return unless check_domain($domain);
1718 my $domain_family;
1719 unless (ref $domain) {
1720 $domain_family = $domain eq 'ip6' ? 'ip' : $domain;
1721 } elsif (@$domain == 0) {
1722 $domain_family = 'none';
1723 } elsif (grep { not /^ip6?$/s } @$domain) {
1724 error('Cannot combine non-IP domains');
1725 } else {
1726 $domain_family = 'ip';
1729 $rule->{domain_family} = $domain_family;
1730 $rule->{keywords} = $match_defs{$domain_family}{''}{keywords};
1731 $rule->{cow}{keywords} = 1;
1733 $rule->{domain} = $stack[0]{auto}{DOMAIN} = $domain;
1736 sub set_target(\%$$) {
1737 my ($rule, $name, $value) = @_;
1738 error('There can only one action per rule')
1739 if exists $rule->{has_action};
1740 $rule->{has_action} = 1;
1741 append_option(%$rule, $name, $value);
1744 sub set_module_target(\%$$) {
1745 my ($rule, $name, $defs) = @_;
1747 if ($name eq 'TCPMSS') {
1748 my $protos = $rule->{protocol};
1749 error('No protocol specified before TCPMSS')
1750 unless defined $protos;
1751 foreach my $proto (to_array $protos) {
1752 error('TCPMSS not available for protocol "$proto"')
1753 unless $proto eq 'tcp';
1757 # in ebtables, there is both "--mark" and "-j mark"... workaround:
1758 $name = 'mark' if $name eq 'MARK' and $rule->{domain_family} eq 'eb';
1760 set_target(%$rule, 'jump', $name);
1761 merge_keywords(%$rule, $defs->{keywords});
1764 # the main parser loop: read tokens, convert them into internal rule
1765 # structures
1766 sub enter($$) {
1767 my $lev = shift; # current recursion depth
1768 my $prev = shift; # previous rule hash
1770 # enter is the core of the firewall setup, it is a
1771 # simple parser program that recognizes keywords and
1772 # retreives parameters to set up the kernel routing
1773 # chains
1775 my $base_level = $script->{base_level} || 0;
1776 die if $base_level > $lev;
1778 my %rule;
1779 new_level(%rule, $prev);
1781 # read keywords 1 by 1 and dump into parser
1782 while (defined (my $keyword = next_token())) {
1783 # check if the current rule should be negated
1784 my $negated = $keyword eq '!';
1785 if ($negated) {
1786 # negation. get the next word which contains the 'real'
1787 # rule
1788 $keyword = getvar();
1790 error('unexpected end of file after negation')
1791 unless defined $keyword;
1794 # the core: parse all data
1795 for ($keyword)
1797 # deprecated keyword?
1798 if (exists $deprecated_keywords{$keyword}) {
1799 my $new_keyword = $deprecated_keywords{$keyword};
1800 warning("'$keyword' is deprecated, please use '$new_keyword' instead");
1801 $keyword = $new_keyword;
1804 # effectuation operator
1805 if ($keyword eq ';') {
1806 error('Empty rule before ";" not allowed')
1807 unless $rule{non_empty};
1809 if ($rule{has_rule} and not exists $rule{has_action}) {
1810 # something is wrong when a rule was specified,
1811 # but no action
1812 error('No action defined; did you mean "NOP"?');
1815 error('No chain defined') unless exists $rule{chain};
1817 $rule{script} = { filename => $script->{filename},
1818 line => $script->{line},
1821 mkrules(\%rule);
1823 # and clean up variables set in this level
1824 new_level(%rule, $prev);
1826 next;
1829 # conditional expression
1830 if ($keyword eq '@if') {
1831 unless (eval_bool(getvalues)) {
1832 collect_tokens;
1833 my $token = peek_token();
1834 if ($token and $token eq '@else') {
1835 require_next_token();
1836 } else {
1837 new_level(%rule, $prev);
1841 next;
1844 if ($keyword eq '@else') {
1845 # hack: if this "else" has not been eaten by the "if"
1846 # handler above, we believe it came from an if clause
1847 # which evaluated "true" - remove the "else" part now.
1848 collect_tokens;
1849 next;
1852 # hooks for custom shell commands
1853 if ($keyword eq 'hook') {
1854 warning("'hook' is deprecated, use '\@hook'");
1855 $keyword = '@hook';
1858 if ($keyword eq '@hook') {
1859 error('"hook" must be the first token in a command')
1860 if exists $rule{domain};
1862 my $position = getvar();
1863 my $hooks;
1864 if ($position eq 'pre') {
1865 $hooks = \@pre_hooks;
1866 } elsif ($position eq 'post') {
1867 $hooks = \@post_hooks;
1868 } elsif ($position eq 'flush') {
1869 $hooks = \@flush_hooks;
1870 } else {
1871 error("Invalid hook position: '$position'");
1874 push @$hooks, getvar();
1876 expect_token(';');
1877 next;
1880 # recursing operators
1881 if ($keyword eq '{') {
1882 # push stack
1883 my $old_stack_depth = @stack;
1885 unshift @stack, { auto => { %{$stack[0]{auto} || {}} } };
1887 # recurse
1888 enter($lev + 1, \%rule);
1890 # pop stack
1891 shift @stack;
1892 die unless @stack == $old_stack_depth;
1894 # after a block, the command is finished, clear this
1895 # level
1896 new_level(%rule, $prev);
1898 next;
1901 if ($keyword eq '}') {
1902 error('Unmatched "}"')
1903 if $lev <= $base_level;
1905 # consistency check: check if they havn't forgotten
1906 # the ';' after the last statement
1907 error('Missing semicolon before "}"')
1908 if $rule{non_empty};
1910 # and exit
1911 return;
1914 # include another file
1915 if ($keyword eq '@include' or $keyword eq 'include') {
1916 my @files = collect_filenames to_array getvalues;
1917 $keyword = next_token;
1918 error('Missing ";" - "include FILENAME" must be the last command in a rule')
1919 unless defined $keyword and $keyword eq ';';
1921 foreach my $filename (@files) {
1922 # save old script, open new script
1923 my $old_script = $script;
1924 open_script($filename);
1925 $script->{base_level} = $lev + 1;
1927 # push stack
1928 my $old_stack_depth = @stack;
1930 my $stack = {};
1932 if (@stack > 0) {
1933 # include files may set variables for their parent
1934 $stack->{vars} = ($stack[0]{vars} ||= {});
1935 $stack->{functions} = ($stack[0]{functions} ||= {});
1936 $stack->{auto} = { %{ $stack[0]{auto} || {} } };
1939 my( $volume,$dirs,$file ) = File::Spec->splitpath( $filename );
1940 $stack->{auto}{FILENAME} = $filename;
1941 $stack->{auto}{FILEBNAME} = $file;
1942 $stack->{auto}{DIRNAME} = $dirs;
1944 unshift @stack, $stack;
1946 # parse the script
1947 enter($lev + 1, \%rule);
1949 # pop stack
1950 shift @stack;
1951 die unless @stack == $old_stack_depth;
1953 # restore old script
1954 $script = $old_script;
1957 next;
1960 # definition of a variable or function
1961 if ($keyword eq '@def' or $keyword eq 'def') {
1962 error('"def" must be the first token in a command')
1963 if $rule{non_empty};
1965 my $type = require_next_token();
1966 if ($type eq '$') {
1967 my $name = require_next_token();
1968 error('invalid variable name')
1969 unless $name =~ /^\w+$/;
1971 expect_token('=');
1973 my $value = getvalues(undef, allow_negation => 1);
1975 expect_token(';');
1977 $stack[0]{vars}{$name} = $value
1978 unless exists $stack[-1]{vars}{$name};
1979 } elsif ($type eq '&') {
1980 my $name = require_next_token();
1981 error('invalid function name')
1982 unless $name =~ /^\w+$/;
1984 expect_token('(', 'function parameter list or "()" expected');
1986 my @params;
1987 while (1) {
1988 my $token = require_next_token();
1989 last if $token eq ')';
1991 if (@params > 0) {
1992 error('"," expected')
1993 unless $token eq ',';
1995 $token = require_next_token();
1998 error('"$" and parameter name expected')
1999 unless $token eq '$';
2001 $token = require_next_token();
2002 error('invalid function parameter name')
2003 unless $token =~ /^\w+$/;
2005 push @params, $token;
2008 my %function;
2010 $function{params} = \@params;
2012 expect_token('=');
2014 my $tokens = collect_tokens();
2015 $function{block} = 1 if grep { $_ eq '{' } @$tokens;
2016 $function{tokens} = $tokens;
2018 $stack[0]{functions}{$name} = \%function
2019 unless exists $stack[-1]{functions}{$name};
2020 } else {
2021 error('"$" (variable) or "&" (function) expected');
2024 next;
2027 # this rule has something which isn't inherited by its
2028 # parent closure. This variable is used in a lot of
2029 # syntax checks.
2031 $rule{non_empty} = 1;
2033 # def references
2034 if ($keyword eq '$') {
2035 error('variable references are only allowed as keyword parameter');
2038 if ($keyword eq '&') {
2039 my $name = require_next_token();
2040 error('function name expected')
2041 unless $name =~ /^\w+$/;
2043 my $function;
2044 foreach (@stack) {
2045 $function = $_->{functions}{$name};
2046 last if defined $function;
2048 error("no such function: \&$name")
2049 unless defined $function;
2051 my $paramdef = $function->{params};
2052 die unless defined $paramdef;
2054 my @params = get_function_params(allow_negation => 1);
2056 error("Wrong number of parameters for function '\&$name': "
2057 . @$paramdef . " expected, " . @params . " given")
2058 unless @params == @$paramdef;
2060 my %vars;
2061 for (my $i = 0; $i < @params; $i++) {
2062 $vars{$paramdef->[$i]} = $params[$i];
2065 if ($function->{block}) {
2066 # block {} always ends the current rule, so if the
2067 # function contains a block, we have to require
2068 # the calling rule also ends here
2069 expect_token(';');
2072 my @tokens = @{$function->{tokens}};
2073 for (my $i = 0; $i < @tokens; $i++) {
2074 if ($tokens[$i] eq '$' and $i + 1 < @tokens and
2075 exists $vars{$tokens[$i + 1]}) {
2076 my @value = to_array($vars{$tokens[$i + 1]});
2077 @value = ('(', @value, ')')
2078 unless @tokens == 1;
2079 splice(@tokens, $i, 2, @value);
2080 $i += @value - 2;
2081 } elsif ($tokens[$i] =~ m,^"(.*)"$,) {
2082 $tokens[$i] =~ s,\$(\w+),exists $vars{$1} ? $vars{$1} : "\$$1",eg;
2086 unshift @{$script->{tokens}}, @tokens;
2088 next;
2091 # where to put the rule?
2092 if ($keyword eq 'domain') {
2093 error('Domain is already specified')
2094 if exists $rule{domain};
2096 my $domains = getvalues();
2097 if (ref $domains) {
2098 my $tokens = collect_tokens(include_semicolon => 1,
2099 include_else => 1);
2101 my $old_line = $script->{line};
2102 my $old_handle = $script->{handle};
2103 my $old_tokens = $script->{tokens};
2104 my $old_base_level = $script->{base_level};
2105 unshift @$old_tokens, make_line_token($script->{line});
2106 delete $script->{handle};
2108 for my $domain (@$domains) {
2109 my %inner;
2110 new_level(%inner, \%rule);
2111 set_domain(%inner, $domain) or next;
2112 $inner{domain_both} = 1;
2113 $script->{base_level} = 0;
2114 $script->{tokens} = [ @$tokens ];
2115 enter(0, \%inner);
2118 $script->{base_level} = $old_base_level;
2119 $script->{tokens} = $old_tokens;
2120 $script->{handle} = $old_handle;
2121 $script->{line} = $old_line;
2123 new_level(%rule, $prev);
2124 } else {
2125 unless (set_domain(%rule, $domains)) {
2126 collect_tokens();
2127 new_level(%rule, $prev);
2131 next;
2134 if ($keyword eq 'table') {
2135 warning('Table is already specified')
2136 if exists $rule{table};
2137 $rule{table} = $stack[0]{auto}{TABLE} = getvalues();
2139 set_domain(%rule, $option{domain} || 'ip')
2140 unless exists $rule{domain};
2142 next;
2145 if ($keyword eq 'chain') {
2146 warning('Chain is already specified')
2147 if exists $rule{chain};
2149 my $chain = $rule{chain} = $stack[0]{auto}{CHAIN} = getvalues();
2151 # ferm 1.1 allowed lower case built-in chain names
2152 foreach (ref $rule{chain} ? @{$rule{chain}} : $rule{chain}) {
2153 error('Please write built-in chain names in upper case')
2154 if /^(?:input|forward|output|prerouting|postrouting)$/;
2157 set_domain(%rule, $option{domain} || 'ip')
2158 unless exists $rule{domain};
2160 $rule{table} = 'filter'
2161 unless exists $rule{table};
2163 my $domain = $rule{domain};
2164 foreach my $table (to_array $rule{table}) {
2165 foreach my $c (to_array $chain) {
2166 $domains{$domain}{tables}{$table}{chains}{$c} ||= {};
2170 next;
2173 error('Chain must be specified')
2174 unless exists $rule{chain};
2176 # policy for built-in chain
2177 if ($keyword eq 'policy') {
2178 error('Cannot specify matches for policy')
2179 if $rule{has_rule};
2181 my $policy = getvar();
2182 error("Invalid policy target: $policy")
2183 unless is_netfilter_core_target($policy);
2185 expect_token(';');
2187 my $domain = $rule{domain};
2188 my $domain_info = $domains{$domain};
2189 $domain_info->{enabled} = 1;
2191 foreach my $table (to_array $rule{table}) {
2192 foreach my $chain (to_array $rule{chain}) {
2193 $domain_info->{tables}{$table}{chains}{$chain}{policy} = $policy;
2197 new_level(%rule, $prev);
2198 next;
2201 # create a subchain
2202 if ($keyword eq '@subchain' or $keyword eq 'subchain') {
2203 error('Chain must be specified')
2204 unless exists $rule{chain};
2206 error('No rule specified before "@subchain"')
2207 unless $rule{has_rule};
2209 my $subchain;
2210 my $token = peek_token();
2212 if ($token =~ /^(["'])(.*)\1$/s) {
2213 $subchain = $2;
2214 next_token();
2215 $keyword = next_token();
2216 } elsif ($token eq '{') {
2217 $keyword = next_token();
2218 $subchain = 'ferm_auto_' . ++$auto_chain;
2219 } else {
2220 $subchain = getvar();
2221 $keyword = next_token();
2224 my $domain = $rule{domain};
2225 foreach my $table (to_array $rule{table}) {
2226 $domains{$domain}{tables}{$table}{chains}{$subchain} ||= {};
2229 set_target(%rule, 'jump', $subchain);
2231 error('"{" or chain name expected after "@subchain"')
2232 unless $keyword eq '{';
2234 # create a deep copy of %rule, only containing values
2235 # which must be in the subchain
2236 my %inner = ( cow => { keywords => 1, },
2237 match => {},
2238 options => [],
2240 $inner{$_} = $rule{$_} foreach qw(domain domain_family domain_both table keywords);
2241 $inner{chain} = $inner{auto}{CHAIN} = $subchain;
2243 if (exists $rule{protocol}) {
2244 $inner{protocol} = $rule{protocol};
2245 append_option(%inner, 'protocol', $inner{protocol});
2248 # create a new stack frame
2249 my $old_stack_depth = @stack;
2250 my $stack = { auto => { %{$stack[0]{auto} || {}} } };
2251 $stack->{auto}{CHAIN} = $subchain;
2252 unshift @stack, $stack;
2254 # enter the block
2255 enter($lev + 1, \%inner);
2257 # pop stack frame
2258 shift @stack;
2259 die unless @stack == $old_stack_depth;
2261 # now handle the parent - it's a jump to the sub chain
2262 $rule{script} = {
2263 filename => $script->{filename},
2264 line => $script->{line},
2267 mkrules(\%rule);
2269 # and clean up variables set in this level
2270 new_level(%rule, $prev);
2271 delete $rule{has_rule};
2273 next;
2276 # everything else must be part of a "real" rule, not just
2277 # "policy only"
2278 $rule{has_rule} = 1;
2280 # extended parameters:
2281 if ($keyword =~ /^mod(?:ule)?$/) {
2282 foreach my $module (to_array getvalues) {
2283 next if exists $rule{match}{$module};
2285 my $domain_family = $rule{domain_family};
2286 my $defs = $match_defs{$domain_family}{$module};
2288 append_option(%rule, 'match', $module);
2289 $rule{match}{$module} = 1;
2291 merge_keywords(%rule, $defs->{keywords})
2292 if defined $defs;
2295 next;
2298 # keywords from $rule{keywords}
2300 if (exists $rule{keywords}{$keyword}) {
2301 my $def = $rule{keywords}{$keyword};
2302 parse_option($def, %rule, \$negated);
2303 next;
2307 # actions
2310 # jump action
2311 if ($keyword eq 'jump') {
2312 set_target(%rule, 'jump', getvar());
2313 next;
2316 # goto action
2317 if ($keyword eq 'realgoto') {
2318 set_target(%rule, 'goto', getvar());
2319 next;
2322 # action keywords
2323 if (is_netfilter_core_target($keyword)) {
2324 set_target(%rule, 'jump', $keyword);
2325 next;
2328 if ($keyword eq 'NOP') {
2329 error('There can only one action per rule')
2330 if exists $rule{has_action};
2331 $rule{has_action} = 1;
2332 next;
2335 if (my $defs = is_netfilter_module_target($rule{domain_family}, $keyword)) {
2336 set_module_target(%rule, $keyword, $defs);
2337 next;
2341 # protocol specific options
2344 if ($keyword eq 'proto' or $keyword eq 'protocol') {
2345 my $protocol = parse_keyword(%rule,
2346 { params => 1, negation => 1 },
2347 \$negated);
2348 $rule{protocol} = $protocol;
2349 append_option(%rule, 'protocol', $rule{protocol});
2351 unless (ref $protocol) {
2352 $protocol = netfilter_canonical_protocol($protocol);
2353 my $domain_family = $rule{domain_family};
2354 if (my $defs = $proto_defs{$domain_family}{$protocol}) {
2355 merge_keywords(%rule, $defs->{keywords});
2356 my $module = netfilter_protocol_module($protocol);
2357 $rule{match}{$module} = 1;
2360 next;
2363 # port switches
2364 if ($keyword =~ /^[sd]port$/) {
2365 my $proto = $rule{protocol};
2366 error('To use sport or dport, you have to specify "proto tcp" or "proto udp" first')
2367 unless defined $proto and grep { /^(?:tcp|udp|udplite|dccp|sctp)$/ } to_array $proto;
2369 append_option(%rule, $keyword,
2370 getvalues(undef, allow_negation => 1));
2371 next;
2374 # default
2375 error("Unrecognized keyword: $keyword");
2378 # if the rule didn't reset the negated flag, it's not
2379 # supported
2380 error("Doesn't support negation: $keyword")
2381 if $negated;
2384 error('Missing "}" at end of file')
2385 if $lev > $base_level;
2387 # consistency check: check if they havn't forgotten
2388 # the ';' before the last statement
2389 error("Missing semicolon before end of file")
2390 if $rule{non_empty};
2393 sub execute_command {
2394 my ($command, $script) = @_;
2396 print LINES "$command\n"
2397 if $option{lines};
2398 return if $option{noexec};
2400 my $ret = system($command);
2401 unless ($ret == 0) {
2402 if ($? == -1) {
2403 print STDERR "failed to execute: $!\n";
2404 exit 1;
2405 } elsif ($? & 0x7f) {
2406 printf STDERR "child died with signal %d\n", $? & 0x7f;
2407 return 1;
2408 } else {
2409 print STDERR "(rule declared in $script->{filename}:$script->{line})\n"
2410 if defined $script;
2411 return $? >> 8;
2415 return;
2418 sub execute_slow($) {
2419 my $domain_info = shift;
2421 my $domain_cmd = $domain_info->{tools}{tables};
2423 my $status;
2424 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2425 my $table_cmd = "$domain_cmd -t $table";
2427 # reset chain policies
2428 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2429 next unless $chain_info->{builtin} or
2430 (not $table_info->{has_builtin} and
2431 is_netfilter_builtin_chain($table, $chain));
2432 $status ||= execute_command("$table_cmd -P $chain ACCEPT")
2433 unless $option{noflush};
2436 # clear
2437 unless ($option{noflush}) {
2438 $status ||= execute_command("$table_cmd -F");
2439 $status ||= execute_command("$table_cmd -X");
2442 next if $option{flush};
2444 # create chains / set policy
2445 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2446 if (is_netfilter_builtin_chain($table, $chain)) {
2447 if (exists $chain_info->{policy}) {
2448 $status ||= execute_command("$table_cmd -P $chain $chain_info->{policy}")
2449 unless $chain_info->{policy} eq 'ACCEPT';
2451 } else {
2452 if (exists $chain_info->{policy}) {
2453 $status ||= execute_command("$table_cmd -N $chain -P $chain_info->{policy}");
2455 else {
2456 $status ||= execute_command("$table_cmd -N $chain");
2461 # dump rules
2462 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2463 my $chain_cmd = "$table_cmd -A $chain";
2464 foreach my $rule (@{$chain_info->{rules}}) {
2465 $status ||= execute_command($chain_cmd . $rule->{rule});
2470 return $status;
2473 sub table_to_save($$) {
2474 my ($result_r, $table_info) = @_;
2476 foreach my $chain (sort keys %{$table_info->{chains}}) {
2477 my $chain_info = $table_info->{chains}{$chain};
2478 foreach my $rule (@{$chain_info->{rules}}) {
2479 $$result_r .= "-A $chain$rule->{rule}\n";
2484 sub rules_to_save($) {
2485 my ($domain_info) = @_;
2487 # convert this into an iptables-save text
2488 my $result = "# Generated by ferm $VERSION on " . localtime() . "\n";
2490 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2491 # select table
2492 $result .= '*' . $table . "\n";
2494 # create chains / set policy
2495 foreach my $chain (sort keys %{$table_info->{chains}}) {
2496 my $chain_info = $table_info->{chains}{$chain};
2497 my $policy = $option{flush} ? undef : $chain_info->{policy};
2498 unless (defined $policy) {
2499 if (is_netfilter_builtin_chain($table, $chain)) {
2500 $policy = 'ACCEPT';
2501 } else {
2502 next if $option{flush};
2503 $policy = '-';
2506 $result .= ":$chain $policy\ [0:0]\n";
2509 table_to_save(\$result, $table_info)
2510 unless $option{flush};
2512 # do it
2513 $result .= "COMMIT\n";
2516 return $result;
2519 sub restore_domain($$) {
2520 my ($domain_info, $save) = @_;
2522 my $path = $domain_info->{tools}{'tables-restore'};
2523 $path .= " --noflush" if $option{noflush};
2525 local *RESTORE;
2526 open RESTORE, "|$path"
2527 or die "Failed to run $path: $!\n";
2529 print RESTORE $save;
2531 close RESTORE
2532 or die "Failed to run $path\n";
2535 sub execute_fast($) {
2536 my $domain_info = shift;
2538 my $save = rules_to_save($domain_info);
2540 if ($option{lines}) {
2541 my $path = $domain_info->{tools}{'tables-restore'};
2542 $path .= " --noflush" if $option{noflush};
2543 print LINES "$path <<EOT\n"
2544 if $option{shell};
2545 print LINES $save;
2546 print LINES "EOT\n"
2547 if $option{shell};
2550 return if $option{noexec};
2552 eval {
2553 restore_domain($domain_info, $save);
2555 if ($@) {
2556 print STDERR $@;
2557 return 1;
2560 return;
2563 sub rollback() {
2564 my $error;
2565 while (my ($domain, $domain_info) = each %domains) {
2566 next unless $domain_info->{enabled};
2567 unless (defined $domain_info->{tools}{'tables-restore'}) {
2568 print STDERR "Cannot rollback domain '$domain' because there is no ${domain}tables-restore\n";
2569 next;
2572 my $reset = '';
2573 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2574 my $reset_chain = '';
2575 foreach my $chain (keys %{$table_info->{chains}}) {
2576 next unless is_netfilter_builtin_chain($table, $chain);
2577 $reset_chain .= ":${chain} ACCEPT [0:0]\n";
2579 $reset .= "*${table}\n${reset_chain}COMMIT\n"
2580 if length $reset_chain;
2583 $reset .= $domain_info->{previous}
2584 if defined $domain_info->{previous};
2586 restore_domain($domain_info, $reset);
2589 print STDERR "\nFirewall rules rolled back.\n" unless $error;
2590 exit 1;
2593 sub alrm_handler {
2594 # do nothing, just interrupt a system call
2597 sub confirm_rules {
2598 $SIG{ALRM} = \&alrm_handler;
2600 alarm(5);
2602 print STDERR "\n"
2603 . "ferm has applied the new firewall rules.\n"
2604 . "Please type 'yes' to confirm:\n";
2605 STDERR->flush();
2607 alarm($option{timeout});
2609 my $line = '';
2610 STDIN->sysread($line, 3);
2612 eval {
2613 require POSIX;
2614 POSIX::tcflush(*STDIN, 2);
2616 print STDERR "$@" if $@;
2618 $SIG{ALRM} = 'DEFAULT';
2620 return $line eq 'yes';
2623 # end of ferm
2625 __END__
2627 =head1 NAME
2629 ferm - a firewall rule parser for linux
2631 =head1 SYNOPSIS
2633 B<ferm> I<options> I<inputfiles>
2635 =head1 OPTIONS
2637 -n, --noexec Do not execute the rules, just simulate
2638 -F, --flush Flush all netfilter tables managed by ferm
2639 -l, --lines Show all rules that were created
2640 -i, --interactive Interactive mode: revert if user does not confirm
2641 -t, --timeout s Define interactive mode timeout in seconds
2642 --remote Remote mode; ignore host specific configuration.
2643 This implies --noexec and --lines.
2644 -V, --version Show current version number
2645 -h, --help Look at this text
2646 --slow Slow mode, don't use iptables-restore
2647 --shell Generate a shell script which calls iptables-restore
2648 --domain {ip|ip6} Handle only the specified domain
2649 --def '$name=v' Override a variable
2651 =cut