4 # ferm, a firewall setup program that makes firewall rules easy!
6 # Copyright (C) 2001-2012 Max Kellermann, Auke Kok
8 # Bug reports and patches for this program may be sent to the GitHub
9 # repository: L<https://github.com/MaxKellermann/ferm>
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., 51 Franklin Street, Fifth Floor, Boston,
34 eval { require strict
; import strict
; };
37 # we need no vars.pm if there is not even strict.pm
39 *vars
::import
= sub {};
44 eval { require Getopt
::Long
; import Getopt
::Long
; };
48 use vars
qw($has_strict $has_getopt);
50 use vars qw($VERSION);
55 ## interface variables
56 # %option = command line and other options
60 use vars qw(@pre_hooks @post_hooks @flush_hooks);
63 # $script: current script file
64 # @stack = ferm's parser stack containing local variables
65 # $auto_chain = index for the next auto-generated chain
66 use vars qw($script @stack $auto_chain);
68 ## netfilter variables
69 # %domains = state information about all domains ("ip" and "ip6")
70 # - initialized: domain initialization is done
71 # - tools: hash providing the paths of the domain's tools
72 # - previous: save file of the previous ruleset, for rollback
73 # - tables{$name}: ferm state information about tables
74 # - has_builtin: whether built-in chains have been determined in this table
75 # - chains{$chain}: ferm state information about the chains
76 # - builtin: whether this is a built-in chain
77 use vars qw(%domains);
80 use vars qw(%deprecated_keywords);
82 # keywords from ferm 1.1 which are deprecated, and the new one; these
83 # are automatically replaced, and a warning is printed
84 %deprecated_keywords = ( realgoto => 'goto',
87 # these hashes provide the Netfilter module definitions
88 use vars qw(%proto_defs %match_defs %target_defs);
91 # This subsubsystem allows you to support (most) new netfilter modules
92 # in ferm. Add a call to one of the "add_XY_def()" functions below.
94 # Ok, now about the cryptic syntax: the function "add_XY_def()"
95 # registers a new module. There are three kinds of modules: protocol
96 # module (e.g. TCP, ICMP), match modules (e.g. state, physdev) and
97 # target modules (e.g. DNAT, MARK).
99 # The first parameter is always the module name which is passed to
100 # iptables with "-p", "-m" or "-j" (depending on which kind of module
103 # After that, you add an encoded string for each option the module
104 # supports. This is where it becomes tricky.
106 # foo defaults to an option with one argument (which may be a ferm
109 # foo*0 option without any arguments
111 # foo=s one argument which must not be a ferm array ('s' stands for
114 # u32=m an array which renders into multiple iptables options in one
117 # ctstate=c one argument, if it's an array, pass it to iptables as a
118 # single comma separated value; example:
119 # ctstate (ESTABLISHED RELATED) translates to:
120 # --ctstate ESTABLISHED,RELATED
122 # foo=sac three arguments: scalar, array, comma separated; you may
123 # concatenate more than one letter code after the '='
125 # foo&bar one argument; call the perl function '&bar()' which parses
128 # !foo negation is allowed and the '!' is written before the keyword
130 # foo! same as above, but '!' is after the keyword and before the
133 # to:=to-destination makes "to" an alias for "to-destination"; you have
134 # to add a declaration for option "to-destination"
137 # prototype declarations
147 # add a module definition
150 my $domain_family = shift;
151 my $params_default = shift;
153 die if exists $defs->{$domain_family}{$name};
154 my $def = $defs->{$domain_family}{$name} = {};
159 if ($keyword =~ s,:=(\S+)$,,) {
160 $k = $def->{keywords}{$1} || die;
161 $k->{ferm_name} ||= $keyword;
163 my $params = $params_default;
164 $params = $1 if $keyword =~ s,\*(\d+)$,,;
165 $params = $1 if $keyword =~ s,=([acs]+|m)$,,;
166 if ($keyword =~ s,&(\S+)$,,) {
167 $params = eval "\\&$1";
172 $k->{params} = $params if $params;
174 $k->{negation} = $k->{pre_negation} = 1 if $keyword =~ s,^!,,;
175 $k->{negation} = 1 if $keyword =~ s,!$,,;
176 $k->{name} = $keyword;
179 $def->{keywords}{$keyword} = $k;
185 # add a protocol module definition
186 sub add_proto_def_x(@) {
187 my $domain_family = shift;
188 add_def_x(\%proto_defs, $domain_family, 1, @_);
191 # add a match module definition
192 sub add_match_def_x(@) {
193 my $domain_family = shift;
194 add_def_x(\%match_defs, $domain_family, 1, @_);
197 # add a target module definition
198 sub add_target_def_x(@) {
199 my $domain_family = shift;
200 add_def_x(\%target_defs, $domain_family, 's', @_);
205 add_def_x($defs, 'ip', @_);
208 # add a protocol module definition
209 sub add_proto_def(@) {
210 add_def(\%proto_defs, 1, @_);
213 # add a match module definition
214 sub add_match_def(@) {
215 add_def(\%match_defs, 1, @_);
218 # add a target module definition
219 sub add_target_def(@) {
220 add_def(\%target_defs, 's', @_);
223 add_proto_def 'dccp', qw(dccp-types!=c dccp-option!);
224 add_proto_def
'mh', qw(mh-type!);
225 add_proto_def
'icmp', qw(icmp-type! icmpv6-type:=icmp-type);
226 add_proto_def
'sctp', qw(chunk-types!=sc);
227 add_proto_def
'tcp', qw(tcp-flags!=cc !syn*0 tcp-option! mss);
228 add_proto_def
'udp', qw();
231 # --source, --destination
232 qw(source!&address_magic saddr:=source),
233 qw(destination!&address_magic daddr:=destination),
235 qw(in-interface! interface:=in-interface if:=in-interface),
237 qw(out-interface! outerface:=out-interface of:=out-interface),
240 add_match_def
'account', qw(aaddr=s aname=s ashort*0);
241 add_match_def
'addrtype', qw(!src-type !dst-type),
242 qw(limit-iface-in*0 limit-iface-out*0);
243 add_match_def
'ah', qw(ahspi! ahlen! ahres*0);
244 add_match_def
'bpf', qw(bytecode);
245 add_match_def
'comment', qw(comment=s);
246 add_match_def
'condition', qw(condition!);
247 add_match_def
'connbytes', qw(!connbytes connbytes-dir connbytes-mode);
248 add_match_def
'connlabel', qw(!label set*0);
249 add_match_def
'connlimit', qw(!connlimit-upto !connlimit-above connlimit-mask connlimit-saddr*0 connlimit-daddr*0);
250 add_match_def
'connmark', qw(!mark);
251 add_match_def
'conntrack', qw(!ctstate=c !ctproto ctorigsrc! ctorigdst! ctorigsrcport! ctorigdstport!),
252 qw(ctreplsrc! ctrepldst! !ctstatus !ctexpire=s ctdir=s);
253 add_match_def
'cpu', qw(!cpu);
254 add_match_def
'dscp', qw(dscp dscp-class);
255 add_match_def
'dst', qw(!dst-len=s dst-opts=c);
256 add_match_def
'ecn', qw(ecn-tcp-cwr*0 ecn-tcp-ece*0 ecn-ip-ect);
257 add_match_def
'esp', qw(espspi!);
258 add_match_def
'eui64';
259 add_match_def
'fuzzy', qw(lower-limit=s upper-limit=s);
260 add_match_def
'geoip', qw(!src-cc=s !dst-cc=s);
261 add_match_def
'hbh', qw(hbh-len! hbh-opts=c);
262 add_match_def
'helper', qw(helper);
263 add_match_def
'hl', qw(hl-eq! hl-lt=s hl-gt=s);
264 add_match_def
'hashlimit', qw(hashlimit=s hashlimit-burst=s hashlimit-mode=c hashlimit-name=s),
265 qw(hashlimit-upto=s hashlimit-above=s),
266 qw(hashlimit-srcmask=s hashlimit-dstmask=s),
267 qw(hashlimit-htable-size=s hashlimit-htable-max=s),
268 qw(hashlimit-htable-expire=s hashlimit-htable-gcinterval=s);
269 add_match_def
'iprange', qw(!src-range !dst-range);
270 add_match_def
'ipv4options', qw(ssrr*0 lsrr*0 no-srr*0 !rr*0 !ts*0 !ra*0 !any-opt*0);
271 add_match_def
'ipv6header', qw(header!=c soft*0);
272 add_match_def
'ipvs', qw(!ipvs*0 !vproto !vaddr !vport vdir !vportctl);
273 add_match_def
'length', qw(length!);
274 add_match_def
'limit', qw(limit=s limit-burst=s);
275 add_match_def
'mac', qw(mac-source!);
276 add_match_def
'mark', qw(!mark);
277 add_match_def
'multiport', qw(source-ports!&multiport_params),
278 qw(destination-ports!&multiport_params ports!&multiport_params);
279 add_match_def
'nth', qw(every counter start packet);
280 add_match_def
'osf', qw(!genre ttl=s log=s);
281 add_match_def
'owner', qw(!uid-owner !gid-owner pid-owner sid-owner),
282 qw(cmd-owner !socket-exists=0);
283 add_match_def
'physdev', qw(physdev-in! physdev-out!),
284 qw(!physdev-is-in*0 !physdev-is-out*0 !physdev-is-bridged*0);
285 add_match_def
'pkttype', qw(pkt-type!),
286 add_match_def
'policy',
287 qw(dir pol strict*0 !reqid !spi !proto !mode !tunnel-src !tunnel-dst next*0);
288 add_match_def
'psd', qw(psd-weight-threshold psd-delay-threshold),
289 qw(psd-lo-ports-weight psd-hi-ports-weight);
290 add_match_def
'quota', qw(quota=s);
291 add_match_def
'random', qw(average);
292 add_match_def
'realm', qw(realm!);
293 add_match_def
'recent', qw(name=s !set*0 !remove*0 !rcheck*0 !update*0 !seconds !hitcount rttl*0 rsource*0 rdest*0);
294 add_match_def
'rpfilter', qw(loose*0 validmark*0 accept-local*0 invert*0);
295 add_match_def
'rt', qw(rt-type! rt-segsleft! rt-len! rt-0-res*0 rt-0-addrs=c rt-0-not-strict*0);
296 add_match_def
'set', qw(!match-set=sc set:=match-set);
297 add_match_def
'state', qw(!state=c);
298 add_match_def
'statistic', qw(mode=s probability=s every=s packet=s);
299 add_match_def
'string', qw(algo=s from=s to=s string hex-string);
300 add_match_def
'tcpmss', qw(!mss);
301 add_match_def
'time', qw(timestart=s timestop=s days=c datestart=s datestop=s),
302 qw(!monthday=c !weekdays=c utc*0 localtz*0);
303 add_match_def
'tos', qw(!tos);
304 add_match_def
'ttl', qw(ttl-eq ttl-lt=s ttl-gt=s);
305 add_match_def
'u32', qw(!u32=m);
307 add_target_def
'AUDIT', qw(type);
308 add_target_def
'BALANCE', qw(to-destination to:=to-destination);
309 add_target_def
'CHECKSUM', qw(checksum-fill*0);
310 add_target_def
'CLASSIFY', qw(set-class);
311 add_target_def
'CLUSTERIP', qw(new*0 hashmode clustermac total-nodes local-node hash-init);
312 add_target_def
'CONNMARK', qw(set-xmark save-mark*0 restore-mark*0 nfmask ctmask),
313 qw(and-mark or-mark xor-mark set-mark mask);
314 add_target_def
'CONNSECMARK', qw(save*0 restore*0);
315 add_target_def
'CT', qw(notrack*0 helper ctevents=c expevents=c zone timeout);
316 add_target_def
'DNAT', qw(to-destination=m to:=to-destination persistent*0 random*0);
317 add_target_def
'DNPT', qw(src-pfx dst-pfx);
318 add_target_def
'DSCP', qw(set-dscp set-dscp-class);
319 add_target_def
'ECN', qw(ecn-tcp-remove*0);
320 add_target_def
'HL', qw(hl-set hl-dec hl-inc);
321 add_target_def
'HMARK', qw(hmark-tuple hmark-mod hmark-offset),
322 qw(hmark-src-prefix hmark-dst-prefix hmark-sport-mask),
323 qw(hmark-dport-mask hmark-spi-mask hmark-proto-mask hmark-rnd);
324 add_target_def
'IDLETIMER', qw(timeout label);
325 add_target_def
'IPV4OPTSSTRIP';
326 add_target_def
'LED', qw(led-trigger-id led-delay led-always-blink*0);
327 add_target_def
'LOG', qw(log-level log-prefix),
328 qw(log-tcp-sequence*0 log-tcp-options*0 log-ip-options*0 log-uid*0);
329 add_target_def
'MARK', qw(set-mark set-xmark and-mark or-mark xor-mark);
330 add_target_def
'MASQUERADE', qw(to-ports random*0);
331 add_target_def
'MIRROR';
332 add_target_def
'NETMAP', qw(to);
333 add_target_def
'NFLOG', qw(nflog-group nflog-prefix nflog-range nflog-threshold);
334 add_target_def
'NFQUEUE', qw(queue-num queue-balance queue-bypass*0 queue-cpu-fanout*0);
335 add_target_def
'NOTRACK';
336 add_target_def
'RATEEST', qw(rateest-name rateest-interval rateest-ewmalog);
337 add_target_def
'REDIRECT', qw(to-ports random*0);
338 add_target_def
'REJECT', qw(reject-with);
339 add_target_def
'ROUTE', qw(oif iif gw continue*0 tee*0);
340 add_target_def
'SAME', qw(to nodst*0 random*0);
341 add_target_def
'SECMARK', qw(selctx);
342 add_target_def
'SET', qw(add-set=sc del-set=sc timeout exist*0);
343 add_target_def
'SNAT', qw(to-source=m to:=to-source persistent*0 random*0);
344 add_target_def
'SNPT', qw(src-pfx dst-pfx);
345 add_target_def
'SYNPROXY', qw(sack-perm*0 timestamp*0 ecn*0 wscale=s mss=s);
346 add_target_def
'TARPIT';
347 add_target_def
'TCPMSS', qw(set-mss clamp-mss-to-pmtu*0);
348 add_target_def
'TCPOPTSTRIP', qw(strip-options=c);
349 add_target_def
'TEE', qw(gateway);
350 add_target_def
'TOS', qw(set-tos and-tos or-tos xor-tos);
351 add_target_def
'TPROXY', qw(tproxy-mark on-ip on-port);
352 add_target_def
'TRACE';
353 add_target_def
'TTL', qw(ttl-set ttl-dec ttl-inc);
354 add_target_def
'ULOG', qw(ulog-nlgroup ulog-prefix ulog-cprange ulog-qthreshold);
356 add_match_def_x
'arp', '',
358 qw(source-ip! destination-ip! saddr:=source-ip daddr:=destination-ip),
360 qw(source-mac! destination-mac!),
362 qw(in-interface! interface:=in-interface if:=in-interface),
364 qw(out-interface! outerface:=out-interface of:=out-interface),
366 qw(h-length=s opcode=s h-type=s proto-type=s),
367 qw(mangle-ip-s=s mangle-ip-d=s mangle-mac-s=s mangle-mac-d=s mangle-target=s);
369 add_proto_def_x
'eb', 'IPv4',
370 qw(ip-source! ip-destination! ip-src:=ip-source ip-dst:=ip-destination),
372 qw(ip-protocol! ip-proto:=ip-protocol),
373 qw(ip-source-port! ip-sport:=ip-source-port),
374 qw(ip-destination-port! ip-dport:=ip-destination-port);
376 add_proto_def_x
'eb', 'IPv6',
377 qw(ip6-source! ip6-destination! ip6-src:=ip6-source ip6-dst:=ip6-destination),
379 qw(ip6-protocol! ip6-proto:=ip6-protocol),
380 qw(ip6-source-port! ip6-sport:=ip6-source-port),
381 qw(ip6-destination-port! ip6-dport:=ip6-destination-port);
383 add_proto_def_x
'eb', 'ARP',
384 qw(!arp-gratuitous*0),
385 qw(arp-opcode! arp-htype!=ss arp-ptype!=ss),
386 qw(arp-ip-src! arp-ip-dst! arp-mac-src! arp-mac-dst!);
388 add_proto_def_x
'eb', 'RARP',
389 qw(!arp-gratuitous*0),
390 qw(arp-opcode! arp-htype!=ss arp-ptype!=ss),
391 qw(arp-ip-src! arp-ip-dst! arp-mac-src! arp-mac-dst!);
393 add_proto_def_x
'eb', '802_1Q',
394 qw(vlan-id! vlan-prio! vlan-encap!),
396 add_match_def_x
'eb', '',
398 qw(in-interface! interface:=in-interface if:=in-interface),
400 qw(out-interface! outerface:=out-interface of:=out-interface),
402 qw(logical-in! logical-out!),
403 # --source, --destination
404 qw(source! saddr:=source destination! daddr:=destination),
406 qw(802_3-sap! 802_3-type!),
408 qw(!among-dst=c !among-src=c !among-dst-file !among-src-file),
410 qw(limit=s limit-burst=s),
416 qw(stp-type! stp-flags! stp-root-prio! stp-root-addr! stp-root-cost!),
417 qw(stp-sender-prio! stp-sender-addr! stp-port! stp-msg-age! stp-max-age!),
418 qw(stp-hello-time! stp-forward-delay!),
420 qw(log*0 log-level=s log-prefix=s log-ip*0 log-arp*0);
422 add_target_def_x
'eb', 'arpreply', qw(arpreply-mac arpreply-target);
423 add_target_def_x
'eb', 'dnat', qw(to-destination dnat-target);
424 add_target_def_x
'eb', 'MARK', qw(set-mark mark-target);
425 add_target_def_x
'eb', 'redirect', qw(redirect-target);
426 add_target_def_x
'eb', 'snat', qw(to-source snat-target snat-arp*0);
428 # import-ferm uses the above tables
429 return 1 if $0 =~ /import-ferm$/;
431 # parameter parser for ipt_multiport
432 sub multiport_params
{
435 # multiport only allows 15 ports at a time. For this
436 # reason, we do a little magic here: split the ports
437 # into portions of 15, and handle these portions as
440 my $proto = $rule->{protocol
};
441 error
('To use multiport, you have to specify "proto tcp" or "proto udp" first')
442 unless defined $proto and grep { /^(?:tcp|udp|udplite)$/ } to_array
($proto);
444 my $value = getvalues
(undef, allow_negation
=> 1,
445 allow_array_negation
=> 1);
446 if (ref $value and ref $value eq 'ARRAY') {
451 push @params, join(',', splice(@value, 0, 15));
458 return join_value
(',', $value);
465 # very crude IPv4/IPv6 address detection
466 if ($domain eq 'ip') {
467 @ips = grep { !/:[0-9a-f]*:/ } @_;
468 } elsif ($domain eq 'ip6') {
469 @ips = grep { !m
,^[0-9./]+$,s
} @_;
476 my $domain = $rule->{domain
};
477 my $value = getvalues
(undef, allow_negation
=> 1);
481 if (ref $value and ref $value eq 'ARRAY') {
483 } elsif (ref $value and ref $value eq 'negated') {
486 } elsif (ref $value) {
492 # only do magic on domain (ip ip6); do not process on a single-stack rule
493 # as to let admins spot their errors instead of silently ignoring them
494 @ips = ipfilter
($domain, @ips) if defined $rule->{domain_both
};
496 if ($negated && scalar @ips) {
497 return bless \
@ips, 'negated';
503 # initialize stack: command line definitions
506 # Get command line stuff
508 my ($opt_noexec, $opt_flush, $opt_noflush, $opt_lines, $opt_interactive,
509 $opt_timeout, $opt_help,
510 $opt_version, $opt_test, $opt_fast, $opt_slow, $opt_shell,
513 Getopt
::Long
::Configure
('bundling', 'auto_help', 'no_ignore_case',
517 my ($opt, $value) = @_;
518 die 'Invalid --def specification'
519 unless $value =~ /^\$?(\w+)=(.*)$/s;
520 my ($name, $unparsed_value) = ($1, $2);
521 my $tokens = tokenize_string
($unparsed_value);
522 $value = getvalues
(sub { shift @
$tokens; });
523 die 'Extra tokens after --def'
525 $stack[0]{vars
}{$name} = $value;
528 local $SIG{__WARN__
} = sub { die $_[0]; };
529 GetOptions
('noexec|n' => \
$opt_noexec,
530 'flush|F' => \
$opt_flush,
531 'noflush' => \
$opt_noflush,
532 'lines|l' => \
$opt_lines,
533 'interactive|i' => \
$opt_interactive,
534 'timeout|t=s' => \
$opt_timeout,
535 'help|h' => \
$opt_help,
536 'version|V' => \
$opt_version,
538 remote
=> \
$opt_test,
541 shell
=> \
$opt_shell,
542 'domain=s' => \
$opt_domain,
543 'def=s' => \
&opt_def
,
546 if (defined $opt_help) {
548 Pod
::Usage
::pod2usage
(-exitstatus
=> 0);
551 if (defined $opt_version) {
556 $option{noexec
} = $opt_noexec || $opt_test;
557 $option{flush
} = $opt_flush;
558 $option{noflush
} = $opt_noflush;
559 $option{lines
} = $opt_lines || $opt_test || $opt_shell;
560 $option{interactive
} = $opt_interactive && !$opt_noexec;
561 $option{timeout
} = defined $opt_timeout ?
$opt_timeout : "30";
562 $option{test
} = $opt_test;
563 $option{fast
} = !$opt_slow;
564 $option{shell
} = $opt_shell;
566 die("ferm interactive mode not possible: /dev/stdin is not a tty\n")
567 if $option{interactive
} and not -t STDIN
;
568 die("ferm interactive mode not possible: /dev/stderr is not a tty\n")
569 if $option{interactive
} and not -t STDERR
;
570 die("ferm timeout has no sense without interactive mode")
571 if not $opt_interactive and defined $opt_timeout;
572 die("invalid timeout. must be an integer")
573 if defined $opt_timeout and not $opt_timeout =~ /^[+-]?\d+$/;
575 $option{domain
} = $opt_domain if defined $opt_domain;
577 # tiny getopt emulation for microperl
580 if ($_ eq '--noexec' or $_ eq '-n') {
582 } elsif ($_ eq '--lines' or $_ eq '-l') {
584 } elsif ($_ eq '--fast') {
586 } elsif ($_ eq '--test') {
590 } elsif ($_ eq '--shell') {
591 $option{$_} = 1 foreach qw(shell fast lines);
593 printf STDERR
"Usage: ferm [--noexec] [--lines] [--fast] [--shell] FILENAME\n";
600 push @ARGV, $filename;
603 unless (@ARGV == 1) {
605 Pod
::Usage
::pod2usage
(-exitstatus
=> 1);
609 open LINES
, ">&STDOUT" if $option{lines
};
610 open STDOUT
, ">&STDERR" if $option{shell
};
612 # microperl can't redirect file handles
615 if ($option{fast
} and not $option{noexec
}) {
616 print STDERR
"Sorry, ferm on microperl does not allow --fast without --noexec\n";
622 open_script
($ARGV[0]);
624 my( $volume,$dirs,$file ) = File
::Spec
->splitpath( $ARGV[0] );
625 $stack[0]{auto
}{FILENAME
} = $ARGV[0];
626 $stack[0]{auto
}{FILEBNAME
} = $file;
627 $stack[0]{auto
}{DIRNAME
} = $dirs;
631 # parse all input recursively
633 die unless @stack == 2;
635 # enable/disable hooks depending on --flush
637 if ($option{flush
}) {
644 # execute all generated rules
647 foreach my $cmd (@pre_hooks) {
648 print LINES
"$cmd\n" if $option{lines
};
649 system($cmd) unless $option{noexec
};
652 while (my ($domain, $domain_info) = each %domains) {
653 next unless $domain_info->{enabled
};
654 my $s = $option{fast
} &&
655 defined $domain_info->{tools
}{'tables-restore'}
656 ? execute_fast
($domain_info) : execute_slow
($domain_info);
657 $status = $s if defined $s;
660 foreach my $cmd (@post_hooks, @flush_hooks) {
661 print LINES
"$cmd\n" if $option{lines
};
662 system($cmd) unless $option{noexec
};
665 if (defined $status) {
670 # ask user, and rollback if there is no confirmation
672 if ($option{interactive
}) {
673 if ($option{shell
}) {
674 print LINES
"echo 'ferm has applied the new firewall rules.'\n";
675 print LINES
"echo 'Please press Ctrl-C to confirm.'\n";
676 print LINES
"sleep $option{timeout}\n";
677 while (my ($domain, $domain_info) = each %domains) {
678 my $restore = $domain_info->{tools
}{'tables-restore'};
679 next unless defined $restore;
680 print LINES
"$restore <\$${domain}_tmp\n";
684 confirm_rules
() or rollback
() unless $option{noexec
};
689 # end of program execution!
695 print "ferm $VERSION\n";
696 print "Copyright (C) 2001-2012 Max Kellermann, Auke Kok\n";
697 print "This program is free software released under GPLv2.\n";
698 print "See the included COPYING file for license details.\n";
703 # returns a nice formatted error message, showing the
704 # location of the error.
708 my @words = map { @
$_ } @
{$script->{past_tokens
}};
710 for my $w ( 0 .. $#words ) {
711 if ($words[$w] eq "\x29")
712 { $l++ ; $lines[$l] = " " x
($tabs-- -1) ;};
713 if ($words[$w] eq "\x28")
714 { $l++ ; $lines[$l] = " " x
$tabs++ ;};
715 if ($words[$w] eq "\x7d")
716 { $l++ ; $lines[$l] = " " x
($tabs-- -1) ;};
717 if ($words[$w] eq "\x7b")
718 { $l++ ; $lines[$l] = " " x
$tabs++ ;};
719 if ( $l > $#lines ) { $lines[$l] = "" };
720 $lines[$l] .= $words[$w] . " ";
721 if ($words[$w] eq "\x28")
722 { $l++ ; $lines[$l] = " " x
$tabs ;};
723 if (($words[$w] eq "\x29") && ($words[$w+1] ne "\x7b"))
724 { $l++ ; $lines[$l] = " " x
$tabs ;};
725 if ($words[$w] eq "\x7b")
726 { $l++ ; $lines[$l] = " " x
$tabs ;};
727 if (($words[$w] eq "\x7d") && ($words[$w+1] ne "\x7d"))
728 { $l++ ; $lines[$l] = " " x
$tabs ;};
729 if (($words[$w] eq "\x3b") && ($words[$w+1] ne "\x7d"))
730 { $l++ ; $lines[$l] = " " x
$tabs ;}
731 if ($words[$w-1] eq "option")
732 { $l++ ; $lines[$l] = " " x
$tabs ;}
734 my $start = $#lines - 4;
735 if ($start < 0) { $start = 0 } ;
736 print STDERR
"Error in $script->{filename} line $script->{line}:\n";
737 for $l ( $start .. $#lines)
738 { print STDERR
$lines[$l]; if ($l != $#lines ) {print STDERR
"\n"} ; };
739 print STDERR
"<--\n";
743 # print a warning message about code from an input file
745 print STDERR
"Warning in $script->{filename} line $script->{line}: "
751 return $name if $option{test
};
752 for my $path ('/sbin', split ':', $ENV{PATH
}) {
753 my $ret = "$path/$name";
754 return $ret if -x
$ret;
756 die "$name not found in PATH\n";
759 sub initialize_domain
{
761 my $domain_info = $domains{$domain} ||= {};
763 return if exists $domain_info->{initialized
};
765 die "Invalid domain '$domain'\n" unless $domain =~ /^(?:ip6?|arp|eb)$/;
767 my @tools = qw(tables);
768 push @tools, qw(tables-save tables-restore)
769 if $domain =~ /^ip6?$/;
771 # determine the location of this domain's tools
772 my %tools = map { $_ => find_tool
($domain . $_) } @tools;
773 $domain_info->{tools
} = \
%tools;
775 # make tables-save tell us about the state of this domain
776 # (which tables and chains do exist?), also remember the old
777 # save data which may be used later by the rollback function
779 if (!$option{test
} &&
780 exists $tools{'tables-save'} &&
781 open(SAVE
, "$tools{'tables-save'}|")) {
790 $table_info = $domain_info->{tables
}{$table} ||= {};
791 } elsif (defined $table_info and /^:(\w+)\s+(\S+)/
793 $table_info->{chains
}{$1}{builtin
} = 1;
794 $table_info->{has_builtin
} = 1;
799 $domain_info->{previous
} = $save;
802 if ($option{shell
} && $option{interactive
} &&
803 exists $tools{'tables-save'}) {
804 print LINES
"${domain}_tmp=\$(mktemp ferm.XXXXXXXXXX)\n";
805 print LINES
"$tools{'tables-save'} >\$${domain}_tmp\n";
808 $domain_info->{initialized
} = 1;
811 sub check_domain
($) {
815 return if exists $option{domain
}
816 and $domain ne $option{domain
};
819 initialize_domain
($domain);
826 # split the input string into words and delete comments
827 sub tokenize_string
($) {
832 foreach my $word ($string =~ m/(".*?"|'.*?'|`.*?`|[!,=&\$\%\(\){};]|[-+\w\/\
.:]+|@\w
+|#)/g) {
833 last if $word eq '#';
840 # generate a "line" special token, that marks the line number; these
841 # special tokens are inserted after each line break, so ferm keeps
842 # track of line numbers
843 sub make_line_token
($) {
845 return bless(\
$line, 'line');
848 # read some more tokens from the input file into a buffer
849 sub prepare_tokens
() {
850 my $tokens = $script->{tokens
};
851 while (@
$tokens == 0) {
852 my $handle = $script->{handle
};
853 return unless defined $handle;
854 my $line = <$handle>;
855 return unless defined $line;
857 push @
$tokens, make_line_token
($script->{line
} + 1);
859 # the next parser stage eats this
860 push @
$tokens, @
{tokenize_string
($line)};
866 sub handle_special_token
($) {
868 die unless ref $token;
869 if (ref $token eq 'line') {
870 $script->{line
} = $$token;
876 sub handle_special_tokens
() {
877 my $tokens = $script->{tokens
};
878 while (@
$tokens > 0 and ref $tokens->[0]) {
879 handle_special_token
(shift @
$tokens);
883 # wrapper for prepare_tokens() which handles "special" tokens
884 sub prepare_normal_tokens
() {
885 my $tokens = $script->{tokens
};
887 handle_special_tokens
();
888 return 1 if @
$tokens > 0;
889 return unless prepare_tokens
();
893 # open a ferm sub script
895 my $filename = shift;
897 for (my $s = $script; defined $s; $s = $s->{parent
}) {
898 die("Circular reference in $script->{filename} line $script->{line}: $filename\n")
899 if $s->{filename
} eq $filename;
903 if ($filename eq '-') {
904 # Note that this only allowed in the command-line argument and not
905 # @includes, since those are filtered by collect_filenames()
907 # also set a filename label so that error messages are more helpful
908 $filename = "<stdin>";
911 open FILE
, "$filename" or die("Failed to open $filename: $!\n");
915 $script = { filename
=> $filename,
926 # collect script filenames which are being included
927 sub collect_filenames
(@
) {
930 # determine the current script's parent directory for relative
932 die unless defined $script;
933 my $parent_dir = $script->{filename
} =~ m
,^(.*/),
936 foreach my $pathname (@_) {
937 # non-absolute file names are relative to the parent script's
939 $pathname = $parent_dir . $pathname
940 unless $pathname =~ m
,^/|\
|$,;
942 if ($pathname =~ m
,/$,) {
943 # include all regular files in a directory
945 error
("'$pathname' is not a directory")
949 opendir DIR
, $pathname
950 or error
("Failed to open directory '$pathname': $!");
951 my @names = readdir DIR
;
954 # sort those names for a well-defined order
955 foreach my $name (sort { $a cmp $b } @names) {
956 # ignore dpkg's backup files
957 next if $name =~ /\.dpkg-(old|dist|new|tmp)$/;
958 # don't include hidden and backup files
959 next if $name =~ /^\.|~$/;
961 my $filename = $pathname . $name;
965 } elsif ($pathname =~ m
,\
|$,) {
966 # run a program and use its output
967 push @ret, $pathname;
968 } elsif ($pathname =~ m
,^\
|,) {
969 error
('This kind of pipe is not allowed');
971 # include a regular file
973 error
("'$pathname' is a directory; maybe use trailing '/' to include a directory?")
975 error
("'$pathname' is not a file")
978 push @ret, $pathname;
985 # peek a token from the queue, but don't remove it
987 return unless prepare_normal_tokens
();
988 return $script->{tokens
}[0];
991 # get a token from the queue, including "special" tokens
992 sub next_raw_token
() {
993 return unless prepare_tokens
();
994 return shift @
{$script->{tokens
}};
997 # get a token from the queue
999 return unless prepare_normal_tokens
();
1000 my $token = shift @
{$script->{tokens
}};
1002 # update $script->{past_tokens}
1003 my $past_tokens = $script->{past_tokens
};
1005 if (@
$past_tokens > 0) {
1006 my $prev_token = $past_tokens->[-1][-1];
1007 $past_tokens->[-1] = @
$past_tokens > 1 ?
['{'] : []
1008 if $prev_token eq ';';
1009 if ($prev_token eq '}') {
1011 $past_tokens->[-1] = $past_tokens->[-1][0] eq '{'
1013 if @
$past_tokens > 0;
1017 push @
$past_tokens, [] if $token eq '{' or @
$past_tokens == 0;
1018 push @
{$past_tokens->[-1]}, $token;
1024 sub expect_token
($;$) {
1027 my $token = next_token
();
1028 error
($msg || "'$expect' expected")
1029 unless defined $token and $token eq $expect;
1032 # require that another token exists, and that it's not a "special"
1033 # token, e.g. ";" and "{"
1034 sub require_next_token
{
1035 my $code = shift || \
&next_token
;
1037 my $token = &$code(@_);
1039 error
('unexpected end of file')
1040 unless defined $token;
1042 error
("'$token' not allowed here")
1043 if $token =~ /^[;{}]$/;
1048 # return the value of a variable
1049 sub variable_value
($) {
1052 if ($name eq "LINE") {
1053 return $script->{line
};
1057 return $_->{vars
}{$name}
1058 if exists $_->{vars
}{$name};
1061 return $stack[0]{auto
}{$name}
1062 if exists $stack[0]{auto
}{$name};
1067 # determine the value of a variable, die if the value is an array
1068 sub string_variable_value
($) {
1070 my $value = variable_value
($name);
1072 error
("variable '$name' must be a string, but it is an array")
1078 # similar to the built-in "join" function, but also handle negated
1079 # values in a special way
1080 sub join_value
($$) {
1081 my ($expr, $value) = @_;
1083 unless (ref $value) {
1085 } elsif (ref $value eq 'ARRAY') {
1086 return join($expr, @
$value);
1087 } elsif (ref $value eq 'negated') {
1088 # bless'negated' is a special marker for negated values
1089 $value = join_value
($expr, $value->[0]);
1090 return bless [ $value ], 'negated';
1096 sub negate_value
($$;$) {
1097 my ($value, $class, $allow_array) = @_;
1100 error
('double negation is not allowed')
1101 if ref $value eq 'negated' or ref $value eq 'pre_negated';
1103 error
('it is not possible to negate an array')
1104 if ref $value eq 'ARRAY' and not $allow_array;
1107 return bless [ $value ], $class || 'negated';
1110 sub format_bool
($) {
1111 return $_[0] ?
1 : 0;
1115 my ($resolver, $names, $type) = @_;
1118 foreach my $hostname (@
$names) {
1119 if (($type eq 'A' and $hostname =~ /^\d+\.\d+\.\d+\.\d+$/) or
1120 (($type eq 'AAAA' and
1121 $hostname =~ /^[0-9a-fA-F:]*:[0-9a-fA-F:]*$/))) {
1122 push @result, $hostname;
1126 my $query = $resolver->search($hostname, $type);
1127 error
("DNS query for '$hostname' failed: " . $resolver->errorstring)
1130 foreach my $rr ($query->answer) {
1131 next unless $rr->type eq $type;
1133 if ($type eq 'NS') {
1134 push @result, $rr->nsdname;
1135 } elsif ($type eq 'MX') {
1136 push @result, $rr->exchange;
1138 push @result, $rr->address;
1143 # NS/MX records return host names; resolve these again in the
1144 # second pass (IPv4 only currently)
1145 @result = resolve
($resolver, @result, 'A')
1146 if $type eq 'NS' or $type eq 'MX';
1151 sub lookup_function
($) {
1155 return $_->{functions
}{$name}
1156 if exists $_->{functions
}{$name};
1162 # returns the next parameter, which may either be a scalar or an array
1167 my $token = require_next_token
($code);
1169 if ($token eq '(') {
1170 # read an array until ")"
1174 $token = getvalues
($code,
1175 parenthesis_allowed
=> 1,
1176 comma_allowed
=> 1);
1178 unless (ref $token) {
1179 last if $token eq ')';
1181 if ($token eq ',') {
1182 error
('Comma is not allowed within arrays, please use only a space');
1186 push @wordlist, $token;
1187 } elsif (ref $token eq 'ARRAY') {
1188 push @wordlist, @
$token;
1190 error
('unknown token type');
1194 error
('empty array not allowed here')
1195 unless @wordlist or not $options{non_empty
};
1197 return @wordlist == 1
1200 } elsif ($token =~ /^\`(.*)\`$/s) {
1201 # execute a shell command, insert output
1203 my $output = `$command`;
1206 error
("failed to execute: $!");
1207 } elsif ($?
& 0x7f) {
1208 error
("child died with signal " . ($?
& 0x7f));
1210 error
("child exited with status " . ($?
>> 8));
1215 $output =~ s/#.*//mg;
1218 my @tokens = grep { length } split /\s+/s, $output;
1222 my $value = getvalues
(sub { shift @tokens });
1223 push @values, to_array
($value);
1230 } elsif ($token =~ /^\'(.*)\'$/s) {
1231 # single quotes: a string
1233 } elsif ($token =~ /^\"(.*)\"$/s) {
1234 # double quotes: a string with escapes
1236 $token =~ s
,\
$(\w
+),string_variable_value
($1),eg
;
1238 } elsif ($token eq '!') {
1239 error
('negation is not allowed here')
1240 unless $options{allow_negation
};
1242 $token = getvalues
($code);
1244 return negate_value
($token, undef, $options{allow_array_negation
});
1245 } elsif ($token eq ',') {
1247 if $options{comma_allowed
};
1249 error
('comma is not allowed here');
1250 } elsif ($token eq '=') {
1251 error
('equals operator ("=") is not allowed here');
1252 } elsif ($token eq '$') {
1253 my $name = require_next_token
($code);
1254 error
('variable name expected - if you want to concatenate strings, try using double quotes')
1255 unless $name =~ /^\w+$/;
1257 my $value = variable_value
($name);
1259 error
("no such variable: \$$name")
1260 unless defined $value;
1263 } elsif ($token eq '&') {
1264 error
("function calls are not allowed as keyword parameter");
1265 } elsif ($token eq ')' and not $options{parenthesis_allowed
}) {
1266 error
('Syntax error');
1267 } elsif ($token =~ /^@/) {
1268 if ($token eq '@resolve') {
1269 my @params = get_function_params
();
1270 error
('Usage: @resolve((hostname ...), [type])')
1271 unless @params == 1 or @params == 2;
1272 eval { require Net
::DNS
; };
1273 error
('For the @resolve() function, you need the Perl library Net::DNS')
1275 my $type = $params[1] || 'A';
1276 error
('String expected') if ref $type;
1277 my $resolver = new Net
::DNS
::Resolver
;
1278 @params = to_array
($params[0]);
1279 my @result = resolve
($resolver, @params, $type);
1280 return @result == 1 ?
$result[0] : \
@result;
1281 } elsif ($token eq '@defined') {
1282 expect_token
('(', 'function name must be followed by "()"');
1283 my $type = require_next_token
();
1285 my $name = require_next_token
();
1286 error
('variable name expected')
1287 unless $name =~ /^\w+$/;
1289 return defined variable_value
($name);
1290 } elsif ($type eq '&') {
1291 my $name = require_next_token
();
1292 error
('function name expected')
1293 unless $name =~ /^\w+$/;
1295 return defined lookup_function
($name);
1297 error
("'\$' or '&' expected")
1299 } elsif ($token eq '@eq') {
1300 my @params = get_function_params
();
1301 error
('Usage: @eq(a, b)') unless @params == 2;
1302 return format_bool
($params[0] eq $params[1]);
1303 } elsif ($token eq '@ne') {
1304 my @params = get_function_params
();
1305 error
('Usage: @ne(a, b)') unless @params == 2;
1306 return format_bool
($params[0] ne $params[1]);
1307 } elsif ($token eq '@not') {
1308 my @params = get_function_params
();
1309 error
('Usage: @not(a)') unless @params == 1;
1310 return format_bool
(not $params[0]);
1311 } elsif ($token eq '@cat') {
1314 error
('String expected') if ref $_;
1316 } get_function_params
();
1318 } elsif ($token eq '@substr') {
1319 my @params = get_function_params
();
1320 error
('Usage: @substr(string, num, num)') unless @params == 3;
1321 error
('String expected') if ref $params[0] or ref $params[1] or ref $params[2];
1322 return substr($params[0],$params[1],$params[2]);
1323 } elsif ($token eq '@length') {
1324 my @params = get_function_params
();
1325 error
('Usage: @length(string)') unless @params == 1;
1326 error
('String expected') if ref $params[0];
1327 return length($params[0]);
1328 } elsif ($token eq '@basename') {
1329 my @params = get_function_params
();
1330 error
('Usage: @basename(path)') unless @params == 1;
1331 error
('String expected') if ref $params[0];
1332 my($volume,$path,$file) = File
::Spec
->splitpath( $params[0] );
1334 } elsif ($token eq '@dirname') {
1335 my @params = get_function_params
();
1336 error
('Usage: @dirname(path)') unless @params == 1;
1337 error
('String expected') if ref $params[0];
1338 my($volume,$path,$file) = File
::Spec
->splitpath( $params[0] );
1340 } elsif ($token eq '@glob') {
1341 my @params = get_function_params
();
1342 error
('Usage: @glob(string)') unless @params == 1;
1344 # determine the current script's parent directory for relative
1346 die unless defined $script;
1347 my $parent_dir = $script->{filename
} =~ m
,^(.*/),
1352 $path = $parent_dir . $path unless $path =~ m
,^/,;
1354 } to_array
($params[0]);
1355 return @result == 1 ?
$result[0] : \
@result;
1356 } elsif ($token eq '@ipfilter') {
1357 my @params = get_function_params
();
1358 error
('Usage: @ipfilter((ip1 ip2 ...))') unless @params == 1;
1359 my $domain = $stack[0]{auto
}{DOMAIN
};
1360 error
('No domain specified') unless defined $domain;
1361 my @ips = ipfilter
($domain, to_array
($params[0]));
1364 error
("unknown ferm built-in function");
1371 # returns the next parameter, but only allow a scalar
1373 my $token = getvalues
();
1375 error
('array not allowed here')
1376 if ref $token and ref $token eq 'ARRAY';
1381 sub get_function_params
(%) {
1382 expect_token
('(', 'function name must be followed by "()"');
1384 my $token = peek_token
();
1385 if ($token eq ')') {
1386 require_next_token
();
1394 $token = require_next_token
();
1398 error
('"," expected')
1399 unless $token eq ',';
1402 push @params, getvalues
(undef, @_);
1408 # collect all tokens in a flat array reference until the end of the
1409 # command is reached
1410 sub collect_tokens
{
1416 # re-insert a "line" token, because the starting token of the
1417 # current line has been consumed already
1418 push @tokens, make_line_token
($script->{line
});
1421 my $keyword = next_raw_token
();
1422 error
('unexpected end of file within function/variable declaration')
1423 unless defined $keyword;
1426 handle_special_token
($keyword);
1427 } elsif ($keyword =~ /^[\{\(]$/) {
1428 push @level, $keyword;
1429 } elsif ($keyword =~ /^[\}\)]$/) {
1430 my $expected = $keyword;
1431 $expected =~ tr/\}\)/\{\(/;
1432 my $opener = pop @level;
1433 error
("unmatched '$keyword'")
1434 unless defined $opener and $opener eq $expected;
1435 } elsif ($keyword eq ';' and @level == 0) {
1436 push @tokens, $keyword
1437 if $options{include_semicolon
};
1439 if ($options{include_else
}) {
1440 my $token = peek_token
;
1441 next if $token eq '@else';
1447 push @tokens, $keyword;
1450 if $keyword eq '}' and @level == 0;
1457 # returns the specified value as an array. dereference arrayrefs
1460 die unless wantarray;
1462 unless (ref $value) {
1464 } elsif (ref $value eq 'ARRAY') {
1471 # evaluate the specified value as bool
1476 unless (ref $value) {
1478 } elsif (ref $value eq 'ARRAY') {
1485 sub is_netfilter_core_target
($) {
1487 die unless defined $target and length $target;
1488 return grep { $_ eq $target } qw(ACCEPT DROP RETURN QUEUE);
1491 sub is_netfilter_module_target
($$) {
1492 my ($domain_family, $target) = @_;
1493 die unless defined $target and length $target;
1495 return defined $domain_family &&
1496 exists $target_defs{$domain_family} &&
1497 $target_defs{$domain_family}{$target};
1500 sub is_netfilter_builtin_chain
($$) {
1501 my ($table, $chain) = @_;
1503 return grep { $_ eq $chain }
1504 qw(PREROUTING INPUT FORWARD OUTPUT POSTROUTING BROUTING);
1507 sub netfilter_canonical_protocol
($) {
1510 if $proto eq 'ipv6-icmp' or $proto eq 'icmpv6';
1512 if $proto eq 'ipv6-mh';
1516 sub netfilter_protocol_module
($) {
1518 return unless defined $proto;
1520 if $proto eq 'icmpv6';
1524 # escape the string in a way safe for the shell
1525 sub shell_escape
($) {
1528 return $token if $token =~ /^[-_a-zA-Z0-9]+$/s;
1530 if ($option{fast
}) {
1531 # iptables-save/iptables-restore are quite buggy concerning
1532 # escaping and special characters... we're trying our best
1535 $token =~ s
,",\\",g
;
1536 $token = '"' . $token . '"'
1537 if $token =~ /[\s\'\\;&]/s or length($token) == 0;
1540 if $token =~ /^\`.*\`$/;
1541 $token =~ s/'/'\\''/g;
1542 $token = '\'' . $token . '\''
1543 if $token =~ /[\s\"\\;<>&|]/s or length($token) == 0;
1549 # append an option to the shell command line, using information from
1550 # the module definition (see %match_defs etc.)
1551 sub shell_format_option
($$) {
1552 my ($keyword, $value) = @_;
1556 if ((ref $value eq 'negated') || (ref $value eq 'pre_negated')) {
1557 $value = $value->[0];
1562 unless (defined $value) {
1563 $cmd .= " --$keyword";
1564 } elsif (ref $value) {
1565 if (ref $value eq 'params') {
1566 $cmd .= " --$keyword ";
1567 $cmd .= join(' ', map { shell_escape
($_) } @
$value);
1568 } elsif (ref $value eq 'multi') {
1570 $cmd .= " --$keyword " . shell_escape
($_);
1576 $cmd .= " --$keyword " . shell_escape
($value);
1582 sub format_option
($$$) {
1583 my ($domain, $name, $value) = @_;
1585 $value = 'icmpv6' if $domain eq 'ip6' and $name eq 'protocol'
1586 and $value eq 'icmp';
1587 $name = 'icmpv6-type' if $domain eq 'ip6' and $name eq 'icmp-type';
1589 if ($domain eq 'ip6' and $name eq 'reject-with') {
1591 'icmp-net-unreachable' => 'icmp6-no-route',
1592 'icmp-host-unreachable' => 'icmp6-addr-unreachable',
1593 'icmp-port-unreachable' => 'icmp6-port-unreachable',
1594 'icmp-net-prohibited' => 'icmp6-adm-prohibited',
1595 'icmp-host-prohibited' => 'icmp6-adm-prohibited',
1596 'icmp-admin-prohibited' => 'icmp6-adm-prohibited',
1598 $value = $icmp_map{$value} if exists $icmp_map{$value};
1601 return shell_format_option
($name, $value);
1604 sub append_rule
($$) {
1605 my ($chain_rules, $rule) = @_;
1607 my $cmd = join('', map { $_->[2] } @
{$rule->{options
}});
1608 push @
$chain_rules, { rule
=> $cmd,
1609 script
=> $rule->{script
},
1614 my ($domain, $chain_rules, $rule) = (shift, shift, shift);
1615 return append_rule
($chain_rules, $rule) unless @_;
1618 my @values = @
{$option->[1]};
1620 foreach my $value (@values) {
1621 $option->[2] = format_option
($domain, $option->[0], $value);
1622 unfold_rule
($domain, $chain_rules, $rule, @_);
1627 my ($domain, $chain_rules, $rule) = @_;
1630 foreach my $option (@
{$rule->{options
}}) {
1631 if (ref $option->[1] and ref $option->[1] eq 'ARRAY') {
1632 push @unfold, $option
1634 $option->[2] = format_option
($domain, $option->[0], $option->[1]);
1638 unfold_rule
($domain, $chain_rules, $rule, @unfold);
1641 # convert a bunch of internal rule structures in iptables calls,
1642 # unfold arrays during that
1646 my $domain = $rule->{domain
};
1647 my $domain_info = $domains{$domain};
1648 $domain_info->{enabled
} = 1;
1650 foreach my $table (to_array
$rule->{table
}) {
1651 my $table_info = $domain_info->{tables
}{$table} ||= {};
1653 foreach my $chain (to_array
$rule->{chain
}) {
1654 my $chain_rules = $table_info->{chains
}{$chain}{rules
} ||= [];
1655 mkrules2
($domain, $chain_rules, $rule)
1656 if $rule->{has_rule
} and not $option{flush
};
1661 # parse a keyword from a module definition
1662 sub parse_keyword
(\
%$$) {
1663 my ($rule, $def, $negated_ref) = @_;
1665 my $params = $def->{params
};
1670 if ($$negated_ref && exists $def->{pre_negation
}) {
1672 undef $$negated_ref;
1675 unless (defined $params) {
1677 } elsif (ref $params && ref $params eq 'CODE') {
1678 $value = &$params($rule);
1679 } elsif ($params eq 'm') {
1680 $value = bless [ to_array getvalues
() ], 'multi';
1681 } elsif ($params =~ /^[a-z]/) {
1682 if (exists $def->{negation
} and not $negated) {
1683 my $token = peek_token
();
1684 if ($token eq '!') {
1685 require_next_token
();
1691 foreach my $p (split(//, $params)) {
1693 push @params, getvar
();
1694 } elsif ($p eq 'c') {
1695 my @v = to_array getvalues
(undef, non_empty
=> 1);
1696 push @params, join(',', @v);
1702 $value = @params == 1
1704 : bless \
@params, 'params';
1705 } elsif ($params == 1) {
1706 if (exists $def->{negation
} and not $negated) {
1707 my $token = peek_token
();
1708 if ($token eq '!') {
1709 require_next_token
();
1714 $value = getvalues
();
1716 warning
("log-prefix is too long; truncating to 29 characters: '$1'")
1717 if $def->{name
} eq 'log-prefix' && $value =~ s
,^(.{29}).+$,$1,;
1719 if (exists $def->{negation
} and not $negated) {
1720 my $token = peek_token
();
1721 if ($token eq '!') {
1722 require_next_token
();
1727 $value = bless [ map {
1729 } (1..$params) ], 'params';
1732 $value = negate_value
($value, exists $def->{pre_negation
} && 'pre_negated')
1738 sub append_option
(\
%$$) {
1739 my ($rule, $name, $value) = @_;
1740 push @
{$rule->{options
}}, [ $name, $value ];
1743 # parse options of a module
1744 sub parse_option
($\
%$) {
1745 my ($def, $rule, $negated_ref) = @_;
1747 append_option
(%$rule, $def->{name
},
1748 parse_keyword
(%$rule, $def, $negated_ref));
1751 sub copy_on_write
($$) {
1752 my ($rule, $key) = @_;
1753 return unless exists $rule->{cow
}{$key};
1754 $rule->{$key} = {%{$rule->{$key}}};
1755 delete $rule->{cow
}{$key};
1758 sub new_level
(\
%$) {
1759 my ($rule, $prev) = @_;
1762 if (defined $prev) {
1763 # copy data from previous level
1764 $rule->{cow
} = { keywords
=> 1, };
1765 $rule->{keywords
} = $prev->{keywords
};
1766 $rule->{match
} = { %{$prev->{match
}} };
1767 $rule->{options
} = [@
{$prev->{options
}}];
1768 foreach my $key (qw(domain domain_family domain_both table chain protocol has_rule has_action)) {
1769 $rule->{$key} = $prev->{$key}
1770 if exists $prev->{$key};
1774 $rule->{keywords
} = {};
1775 $rule->{match
} = {};
1776 $rule->{options
} = [];
1780 sub merge_keywords
(\
%$) {
1781 my ($rule, $keywords) = @_;
1782 copy_on_write
($rule, 'keywords');
1783 while (my ($name, $def) = each %$keywords) {
1784 $rule->{keywords
}{$name} = $def;
1788 sub set_domain
(\
%$) {
1789 my ($rule, $domain) = @_;
1791 return unless check_domain
($domain);
1794 unless (ref $domain) {
1795 $domain_family = $domain eq 'ip6' ?
'ip' : $domain;
1796 } elsif (@
$domain == 0) {
1797 $domain_family = 'none';
1798 } elsif (grep { not /^ip6?$/s } @
$domain) {
1799 error
('Cannot combine non-IP domains');
1801 $domain_family = 'ip';
1804 $rule->{domain_family
} = $domain_family;
1805 $rule->{keywords
} = $match_defs{$domain_family}{''}{keywords
};
1806 $rule->{cow
}{keywords
} = 1;
1808 $rule->{domain
} = $stack[0]{auto
}{DOMAIN
} = $domain;
1811 sub set_target
(\
%$$) {
1812 my ($rule, $name, $value) = @_;
1813 error
('There can only one action per rule')
1814 if exists $rule->{has_action
};
1815 $rule->{has_action
} = 1;
1816 append_option
(%$rule, $name, $value);
1819 sub set_module_target
(\
%$$) {
1820 my ($rule, $name, $defs) = @_;
1822 if ($name eq 'TCPMSS') {
1823 my $protos = $rule->{protocol
};
1824 error
('No protocol specified before TCPMSS')
1825 unless defined $protos;
1826 foreach my $proto (to_array
$protos) {
1827 error
('TCPMSS not available for protocol "$proto"')
1828 unless $proto eq 'tcp';
1832 # in ebtables, there is both "--mark" and "-j mark"... workaround:
1833 $name = 'mark' if $name eq 'MARK' and $rule->{domain_family
} eq 'eb';
1835 set_target
(%$rule, 'jump', $name);
1836 merge_keywords
(%$rule, $defs->{keywords
});
1839 # the main parser loop: read tokens, convert them into internal rule
1842 my $lev = shift; # current recursion depth
1843 my $prev = shift; # previous rule hash
1845 # enter is the core of the firewall setup, it is a
1846 # simple parser program that recognizes keywords and
1847 # retreives parameters to set up the kernel routing
1850 my $base_level = $script->{base_level
} || 0;
1851 die if $base_level > $lev;
1854 new_level
(%rule, $prev);
1856 # read keywords 1 by 1 and dump into parser
1857 while (defined (my $keyword = next_token
())) {
1858 # check if the current rule should be negated
1859 my $negated = $keyword eq '!';
1861 # negation. get the next word which contains the 'real'
1863 $keyword = getvar
();
1865 error
('unexpected end of file after negation')
1866 unless defined $keyword;
1869 # the core: parse all data
1872 # deprecated keyword?
1873 if (exists $deprecated_keywords{$keyword}) {
1874 my $new_keyword = $deprecated_keywords{$keyword};
1875 warning
("'$keyword' is deprecated, please use '$new_keyword' instead");
1876 $keyword = $new_keyword;
1879 # effectuation operator
1880 if ($keyword eq ';') {
1881 error
('Empty rule before ";" not allowed')
1882 unless $rule{non_empty
};
1884 if ($rule{has_rule
} and not exists $rule{has_action
}) {
1885 # something is wrong when a rule was specified,
1887 error
('No action defined; did you mean "NOP"?');
1890 error
('No chain defined') unless exists $rule{chain
};
1892 $rule{script
} = { filename
=> $script->{filename
},
1893 line
=> $script->{line
},
1898 # and clean up variables set in this level
1899 new_level
(%rule, $prev);
1904 # conditional expression
1905 if ($keyword eq '@if') {
1906 unless (eval_bool
(getvalues
)) {
1908 my $token = peek_token
();
1909 if ($token and $token eq '@else') {
1910 require_next_token
();
1912 new_level
(%rule, $prev);
1919 if ($keyword eq '@else') {
1920 # hack: if this "else" has not been eaten by the "if"
1921 # handler above, we believe it came from an if clause
1922 # which evaluated "true" - remove the "else" part now.
1927 # hooks for custom shell commands
1928 if ($keyword eq 'hook') {
1929 warning
("'hook' is deprecated, use '\@hook'");
1933 if ($keyword eq '@hook') {
1934 error
('"hook" must be the first token in a command')
1935 if exists $rule{domain
};
1937 my $position = getvar
();
1939 if ($position eq 'pre') {
1940 $hooks = \
@pre_hooks;
1941 } elsif ($position eq 'post') {
1942 $hooks = \
@post_hooks;
1943 } elsif ($position eq 'flush') {
1944 $hooks = \
@flush_hooks;
1946 error
("Invalid hook position: '$position'");
1949 push @
$hooks, getvar
();
1955 # recursing operators
1956 if ($keyword eq '{') {
1958 my $old_stack_depth = @stack;
1960 unshift @stack, { auto
=> { %{$stack[0]{auto
} || {}} } };
1963 enter
($lev + 1, \
%rule);
1967 die unless @stack == $old_stack_depth;
1969 # after a block, the command is finished, clear this
1971 new_level
(%rule, $prev);
1976 if ($keyword eq '}') {
1977 error
('Unmatched "}"')
1978 if $lev <= $base_level;
1980 # consistency check: check if they havn't forgotten
1981 # the ';' after the last statement
1982 error
('Missing semicolon before "}"')
1983 if $rule{non_empty
};
1989 # include another file
1990 if ($keyword eq '@include' or $keyword eq 'include') {
1991 # don't call collect_filenames() if the file names
1992 # have been expanded already by @glob()
1993 my @files = peek_token
() eq '@glob'
1994 ? to_array
(getvalues
)
1995 : collect_filenames
(to_array
(getvalues
));
1996 $keyword = next_token
;
1997 error
('Missing ";" - "include FILENAME" must be the last command in a rule')
1998 unless defined $keyword and $keyword eq ';';
2000 foreach my $filename (@files) {
2001 # save old script, open new script
2002 my $old_script = $script;
2003 open_script
($filename);
2004 $script->{base_level
} = $lev + 1;
2007 my $old_stack_depth = @stack;
2012 # include files may set variables for their parent
2013 $stack->{vars
} = ($stack[0]{vars
} ||= {});
2014 $stack->{functions
} = ($stack[0]{functions
} ||= {});
2015 $stack->{auto
} = { %{ $stack[0]{auto
} || {} } };
2018 my( $volume,$dirs,$file ) = File
::Spec
->splitpath( $filename );
2019 $stack->{auto
}{FILENAME
} = $filename;
2020 $stack->{auto
}{FILEBNAME
} = $file;
2021 $stack->{auto
}{DIRNAME
} = $dirs;
2023 unshift @stack, $stack;
2026 enter
($lev + 1, \
%rule);
2028 #check for exit status
2029 error
("'$script->{filename}': exit status is not 0") if not close $script->{handle
};
2033 die unless @stack == $old_stack_depth;
2035 # restore old script
2036 $script = $old_script;
2042 # definition of a variable or function
2043 if ($keyword eq '@def' or $keyword eq 'def') {
2044 error
('"def" must be the first token in a command')
2045 if $rule{non_empty
};
2047 my $type = require_next_token
();
2049 my $name = require_next_token
();
2050 error
('invalid variable name')
2051 unless $name =~ /^\w+$/;
2055 my $value = getvalues
(undef, allow_negation
=> 1);
2059 $stack[0]{vars
}{$name} = $value
2060 unless exists $stack[-1]{vars
}{$name};
2061 } elsif ($type eq '&') {
2062 my $name = require_next_token
();
2063 error
('invalid function name')
2064 unless $name =~ /^\w+$/;
2066 expect_token
('(', 'function parameter list or "()" expected');
2070 my $token = require_next_token
();
2071 last if $token eq ')';
2074 error
('"," expected')
2075 unless $token eq ',';
2077 $token = require_next_token
();
2080 error
('"$" and parameter name expected')
2081 unless $token eq '$';
2083 $token = require_next_token
();
2084 error
('invalid function parameter name')
2085 unless $token =~ /^\w+$/;
2087 push @params, $token;
2092 $function{params
} = \
@params;
2096 my $tokens = collect_tokens
();
2097 $function{block
} = 1 if grep { $_ eq '{' } @
$tokens;
2098 $function{tokens
} = $tokens;
2100 $stack[0]{functions
}{$name} = \
%function
2101 unless exists $stack[-1]{functions
}{$name};
2103 error
('"$" (variable) or "&" (function) expected');
2109 # this rule has something which isn't inherited by its
2110 # parent closure. This variable is used in a lot of
2113 $rule{non_empty
} = 1;
2116 if ($keyword eq '$') {
2117 error
('variable references are only allowed as keyword parameter');
2120 if ($keyword eq '&') {
2121 my $name = require_next_token
();
2122 error
('function name expected')
2123 unless $name =~ /^\w+$/;
2125 my $function = lookup_function
($name);
2126 error
("no such function: \&$name")
2127 unless defined $function;
2129 my $paramdef = $function->{params
};
2130 die unless defined $paramdef;
2132 my @params = get_function_params
(allow_negation
=> 1);
2134 error
("Wrong number of parameters for function '\&$name': "
2135 . @
$paramdef . " expected, " . @params . " given")
2136 unless @params == @
$paramdef;
2139 for (my $i = 0; $i < @params; $i++) {
2140 $vars{$paramdef->[$i]} = $params[$i];
2143 if ($function->{block
}) {
2144 # block {} always ends the current rule, so if the
2145 # function contains a block, we have to require
2146 # the calling rule also ends here
2150 my @tokens = @
{$function->{tokens
}};
2151 for (my $i = 0; $i < @tokens; $i++) {
2152 if ($tokens[$i] eq '$' and $i + 1 < @tokens and
2153 exists $vars{$tokens[$i + 1]}) {
2154 my @value = to_array
($vars{$tokens[$i + 1]});
2155 @value = ('(', @value, ')')
2156 unless @tokens == 1;
2157 splice(@tokens, $i, 2, @value);
2159 } elsif ($tokens[$i] =~ m
,^"(.*)"$,) {
2160 $tokens[$i] =~ s
,\
$(\w
+),exists $vars{$1} ?
$vars{$1} : "\$$1",eg
;
2164 unshift @
{$script->{tokens
}}, @tokens;
2169 # where to put the rule?
2170 if ($keyword eq 'domain') {
2171 error
('Domain is already specified')
2172 if exists $rule{domain
};
2174 my $domains = getvalues
();
2176 my $tokens = collect_tokens
(include_semicolon
=> 1,
2179 my $old_line = $script->{line
};
2180 my $old_handle = $script->{handle
};
2181 my $old_tokens = $script->{tokens
};
2182 my $old_base_level = $script->{base_level
};
2183 unshift @
$old_tokens, make_line_token
($script->{line
});
2184 delete $script->{handle
};
2186 for my $domain (@
$domains) {
2188 new_level
(%inner, \
%rule);
2189 set_domain
(%inner, $domain) or next;
2190 $inner{domain_both
} = 1;
2191 $script->{base_level
} = 0;
2192 $script->{tokens
} = [ @
$tokens ];
2196 $script->{base_level
} = $old_base_level;
2197 $script->{tokens
} = $old_tokens;
2198 $script->{handle
} = $old_handle;
2199 $script->{line
} = $old_line;
2201 new_level
(%rule, $prev);
2203 unless (set_domain
(%rule, $domains)) {
2205 new_level
(%rule, $prev);
2212 if ($keyword eq 'table') {
2213 warning
('Table is already specified')
2214 if exists $rule{table
};
2215 $rule{table
} = $stack[0]{auto
}{TABLE
} = getvalues
();
2217 set_domain
(%rule, $option{domain
} || 'ip')
2218 unless exists $rule{domain
};
2223 if ($keyword eq 'chain') {
2224 warning
('Chain is already specified')
2225 if exists $rule{chain
};
2227 my $chain = $rule{chain
} = $stack[0]{auto
}{CHAIN
} = getvalues
();
2229 # ferm 1.1 allowed lower case built-in chain names
2230 foreach (ref $rule{chain
} ? @
{$rule{chain
}} : $rule{chain
}) {
2231 error
('Please write built-in chain names in upper case')
2232 if /^(?:input|forward|output|prerouting|postrouting)$/;
2235 set_domain
(%rule, $option{domain
} || 'ip')
2236 unless exists $rule{domain
};
2238 $rule{table
} = 'filter'
2239 unless exists $rule{table
};
2241 my $domain = $rule{domain
};
2242 foreach my $table (to_array
$rule{table
}) {
2243 foreach my $c (to_array
$chain) {
2244 $domains{$domain}{tables
}{$table}{chains
}{$c} ||= {};
2251 error
('Chain must be specified')
2252 unless exists $rule{chain
};
2254 # policy for built-in chain
2255 if ($keyword eq 'policy') {
2256 error
('Cannot specify matches for policy')
2259 my $policy = getvar
();
2260 error
("Invalid policy target: $policy")
2261 unless is_netfilter_core_target
($policy);
2265 my $domain = $rule{domain
};
2266 my $domain_info = $domains{$domain};
2267 $domain_info->{enabled
} = 1;
2269 foreach my $table (to_array
$rule{table
}) {
2270 foreach my $chain (to_array
$rule{chain
}) {
2271 $domain_info->{tables
}{$table}{chains
}{$chain}{policy
} = $policy;
2275 new_level
(%rule, $prev);
2280 if ($keyword eq '@subchain' or $keyword eq 'subchain' or $keyword eq '@gotosubchain') {
2281 error
('Chain must be specified')
2282 unless exists $rule{chain
};
2284 my $jumptype = ($keyword =~ /^\@go/) ?
'goto' : 'jump';
2285 my $jumpkey = $keyword;
2286 $jumpkey =~ s/^sub/\@sub/;
2288 error
('No rule specified before $jumpkey')
2289 unless $rule{has_rule
};
2292 my $token = peek_token
();
2294 if ($token =~ /^(["'])(.*)\1$/s) {
2297 $keyword = next_token
();
2298 } elsif ($token eq '{') {
2299 $keyword = next_token
();
2300 $subchain = 'ferm_auto_' . ++$auto_chain;
2302 $subchain = getvar
();
2303 $keyword = next_token
();
2306 my $domain = $rule{domain
};
2307 foreach my $table (to_array
$rule{table
}) {
2308 $domains{$domain}{tables
}{$table}{chains
}{$subchain} ||= {};
2311 set_target
(%rule, $jumptype, $subchain);
2313 error
('"{" or chain name expected after $jumpkey')
2314 unless $keyword eq '{';
2316 # create a deep copy of %rule, only containing values
2317 # which must be in the subchain
2318 my %inner = ( cow
=> { keywords
=> 1, },
2322 $inner{$_} = $rule{$_} foreach qw(domain domain_family domain_both table keywords);
2323 $inner{chain
} = $inner{auto
}{CHAIN
} = $subchain;
2325 if (exists $rule{protocol
}) {
2326 $inner{protocol
} = $rule{protocol
};
2327 append_option
(%inner, 'protocol', $inner{protocol
});
2330 # create a new stack frame
2331 my $old_stack_depth = @stack;
2332 my $stack = { auto
=> { %{$stack[0]{auto
} || {}} } };
2333 $stack->{auto
}{CHAIN
} = $subchain;
2334 unshift @stack, $stack;
2337 enter
($lev + 1, \
%inner);
2341 die unless @stack == $old_stack_depth;
2343 # now handle the parent - it's a jump to the sub chain
2345 filename
=> $script->{filename
},
2346 line
=> $script->{line
},
2351 # and clean up variables set in this level
2352 new_level
(%rule, $prev);
2353 delete $rule{has_rule
};
2358 # everything else must be part of a "real" rule, not just
2360 $rule{has_rule
} = 1;
2362 # extended parameters:
2363 if ($keyword =~ /^mod(?:ule)?$/) {
2364 foreach my $module (to_array getvalues
) {
2365 next if exists $rule{match
}{$module};
2367 my $domain_family = $rule{domain_family
};
2368 my $defs = $match_defs{$domain_family}{$module};
2370 append_option
(%rule, 'match', $module);
2371 $rule{match
}{$module} = 1;
2373 merge_keywords
(%rule, $defs->{keywords
})
2380 # keywords from $rule{keywords}
2382 if (exists $rule{keywords
}{$keyword}) {
2383 my $def = $rule{keywords
}{$keyword};
2384 parse_option
($def, %rule, \
$negated);
2393 if ($keyword eq 'jump') {
2394 set_target
(%rule, 'jump', getvar
());
2399 if ($keyword eq 'goto') {
2400 set_target
(%rule, 'goto', getvar
());
2405 if (is_netfilter_core_target
($keyword)) {
2406 set_target
(%rule, 'jump', $keyword);
2410 if ($keyword eq 'NOP') {
2411 error
('There can only one action per rule')
2412 if exists $rule{has_action
};
2413 $rule{has_action
} = 1;
2417 if (my $defs = is_netfilter_module_target
($rule{domain_family
}, $keyword)) {
2418 set_module_target
(%rule, $keyword, $defs);
2423 # protocol specific options
2426 if ($keyword eq 'proto' or $keyword eq 'protocol') {
2427 my $protocol = parse_keyword
(%rule,
2428 { params
=> 1, negation
=> 1 },
2430 $rule{protocol
} = $protocol;
2431 append_option
(%rule, 'protocol', $rule{protocol
});
2433 unless (ref $protocol) {
2434 $protocol = netfilter_canonical_protocol
($protocol);
2435 my $domain_family = $rule{domain_family
};
2436 if (my $defs = $proto_defs{$domain_family}{$protocol}) {
2437 merge_keywords
(%rule, $defs->{keywords
});
2438 my $module = netfilter_protocol_module
($protocol);
2439 $rule{match
}{$module} = 1;
2446 if ($keyword =~ /^[sd]port$/) {
2447 my $proto = $rule{protocol
};
2448 error
('To use sport or dport, you have to specify "proto tcp" or "proto udp" first')
2449 unless defined $proto and grep { /^(?:tcp|udp|udplite|dccp|sctp)$/ } to_array
$proto;
2451 append_option
(%rule, $keyword,
2452 getvalues
(undef, allow_negation
=> 1));
2457 error
("Unrecognized keyword: $keyword");
2460 # if the rule didn't reset the negated flag, it's not
2462 error
("Doesn't support negation: $keyword")
2466 error
('Missing "}" at end of file')
2467 if $lev > $base_level;
2469 # consistency check: check if they havn't forgotten
2470 # the ';' before the last statement
2471 error
("Missing semicolon before end of file")
2472 if $rule{non_empty
};
2475 sub execute_command
{
2476 my ($command, $script) = @_;
2478 print LINES
"$command\n"
2480 return if $option{noexec
};
2482 my $ret = system($command);
2483 unless ($ret == 0) {
2485 print STDERR
"failed to execute: $!\n";
2487 } elsif ($?
& 0x7f) {
2488 printf STDERR
"child died with signal %d\n", $?
& 0x7f;
2491 print STDERR
"(rule declared in $script->{filename}:$script->{line})\n"
2500 sub execute_slow
($) {
2501 my $domain_info = shift;
2503 my $domain_cmd = $domain_info->{tools
}{tables
};
2506 while (my ($table, $table_info) = each %{$domain_info->{tables
}}) {
2507 my $table_cmd = "$domain_cmd -t $table";
2509 # reset chain policies
2510 while (my ($chain, $chain_info) = each %{$table_info->{chains
}}) {
2511 next unless $chain_info->{builtin
} or
2512 (not $table_info->{has_builtin
} and
2513 is_netfilter_builtin_chain
($table, $chain));
2514 $status ||= execute_command
("$table_cmd -P $chain ACCEPT")
2515 unless $option{noflush
};
2519 unless ($option{noflush
}) {
2520 $status ||= execute_command
("$table_cmd -F");
2521 $status ||= execute_command
("$table_cmd -X");
2524 next if $option{flush
};
2526 # create chains / set policy
2527 while (my ($chain, $chain_info) = each %{$table_info->{chains
}}) {
2528 if (is_netfilter_builtin_chain
($table, $chain)) {
2529 if (exists $chain_info->{policy
}) {
2530 $status ||= execute_command
("$table_cmd -P $chain $chain_info->{policy}")
2531 unless $chain_info->{policy
} eq 'ACCEPT';
2534 if (exists $chain_info->{policy
}) {
2535 $status ||= execute_command
("$table_cmd -N $chain -P $chain_info->{policy}");
2538 $status ||= execute_command
("$table_cmd -N $chain");
2544 while (my ($chain, $chain_info) = each %{$table_info->{chains
}}) {
2545 my $chain_cmd = "$table_cmd -A $chain";
2546 foreach my $rule (@
{$chain_info->{rules
}}) {
2547 $status ||= execute_command
($chain_cmd . $rule->{rule
});
2555 sub table_to_save
($$) {
2556 my ($result_r, $table_info) = @_;
2558 foreach my $chain (sort keys %{$table_info->{chains
}}) {
2559 my $chain_info = $table_info->{chains
}{$chain};
2560 foreach my $rule (@
{$chain_info->{rules
}}) {
2561 $$result_r .= "-A $chain$rule->{rule}\n";
2566 sub rules_to_save
($) {
2567 my ($domain_info) = @_;
2569 # convert this into an iptables-save text
2570 my $result = "# Generated by ferm $VERSION on " . localtime() . "\n";
2572 while (my ($table, $table_info) = each %{$domain_info->{tables
}}) {
2574 $result .= '*' . $table . "\n";
2576 # create chains / set policy
2577 foreach my $chain (sort keys %{$table_info->{chains
}}) {
2578 my $chain_info = $table_info->{chains
}{$chain};
2579 my $policy = $option{flush
} ?
undef : $chain_info->{policy
};
2580 unless (defined $policy) {
2581 if (is_netfilter_builtin_chain
($table, $chain)) {
2584 next if $option{flush
};
2588 $result .= ":$chain $policy\ [0:0]\n";
2591 table_to_save
(\
$result, $table_info)
2592 unless $option{flush
};
2595 $result .= "COMMIT\n";
2601 sub restore_domain
($$) {
2602 my ($domain_info, $save) = @_;
2604 my $path = $domain_info->{tools
}{'tables-restore'};
2605 $path .= " --noflush" if $option{noflush
};
2608 open RESTORE
, "|$path"
2609 or die "Failed to run $path: $!\n";
2611 print RESTORE
$save;
2614 or die "Failed to run $path\n";
2617 sub execute_fast
($) {
2618 my $domain_info = shift;
2620 my $save = rules_to_save
($domain_info);
2622 if ($option{lines
}) {
2623 my $path = $domain_info->{tools
}{'tables-restore'};
2624 $path .= " --noflush" if $option{noflush
};
2625 print LINES
"$path <<EOT\n"
2632 return if $option{noexec};
2635 restore_domain($domain_info, $save);
2647 while (my ($domain, $domain_info) = each %domains) {
2648 next unless $domain_info->{enabled};
2649 unless (defined $domain_info->{tools}{'tables-restore'}) {
2650 print STDERR "Cannot rollback domain
'$domain' because there is
no ${domain
}tables
-restore
\n";
2655 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2656 my $reset_chain = '';
2657 foreach my $chain (keys %{$table_info->{chains}}) {
2658 next unless is_netfilter_builtin_chain($table, $chain);
2659 $reset_chain .= ":${chain
} ACCEPT
[0:0]\n";
2661 $reset .= "*${table
}\n${reset_chain
}COMMIT
\n"
2662 if length $reset_chain;
2665 $reset .= $domain_info->{previous}
2666 if defined $domain_info->{previous};
2668 restore_domain($domain_info, $reset);
2671 print STDERR "\nFirewall rules rolled back
.\n" unless $error;
2676 # do nothing, just interrupt a system call
2680 $SIG{ALRM} = \&alrm_handler;
2685 . "ferm has applied the new firewall rules
.\n"
2686 . "Please type
'yes' to confirm
:\n";
2689 alarm($option{timeout});
2692 STDIN->sysread($line, 3);
2696 POSIX::tcflush(*STDIN, 2);
2698 print STDERR "$@
" if $@;
2700 $SIG{ALRM} = 'DEFAULT';
2702 return $line eq 'yes';
2711 ferm - a firewall rule parser for linux
2715 B<ferm> I<options> I<inputfiles>
2719 -n, --noexec Do not execute the rules, just simulate
2720 -F, --flush Flush all netfilter tables managed by ferm
2721 -l, --lines Show all rules that were created
2722 -i, --interactive Interactive mode: revert if user does not confirm
2723 -t, --timeout s Define interactive mode timeout in seconds
2724 --remote Remote mode; ignore host specific configuration.
2725 This implies --noexec and --lines.
2726 -V, --version Show current version number
2727 -h, --help Look at this text
2728 --slow Slow mode, don't use iptables-restore
2729 --shell Generate a shell script which calls iptables-restore
2730 --domain {ip|ip6} Handle only the specified domain
2731 --def '$name=v' Override a variable