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
33 eval { require strict
; import strict
; };
36 # we need no vars.pm if there is not even strict.pm
38 *vars
::import
= sub {};
43 eval { require Getopt
::Long
; import Getopt
::Long
; };
47 use vars
qw($has_strict $has_getopt);
49 use vars qw($VERSION);
54 ## interface variables
55 # %option = command line and other options
59 use vars qw(@pre_hooks @post_hooks @flush_hooks);
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);
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
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
108 # foo*0 option without any arguments
110 # foo=s one argument which must not be a ferm array ('s' stands for
113 # u32=m an array which renders into multiple iptables options in one
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
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
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
146 # add a module definition
149 my $domain_family = shift;
150 my $params_default = shift;
152 die if exists $defs->{$domain_family}{$name};
153 my $def = $defs->{$domain_family}{$name} = {};
158 if ($keyword =~ s,:=(\S+)$,,) {
159 $k = $def->{keywords}{$1} || die;
160 $k->{ferm_name} ||= $keyword;
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";
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;
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', @_);
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();
230 # --source, --destination
231 qw(source!&address_magic saddr:=source),
232 qw(destination!&address_magic daddr:=destination),
234 qw(in-interface! interface:=in-interface if:=in-interface),
236 qw(out-interface! outerface:=out-interface of:=out-interface),
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
'bpf', qw(bytecode);
244 add_match_def
'comment', qw(comment=s);
245 add_match_def
'condition', qw(condition!);
246 add_match_def
'connbytes', qw(!connbytes connbytes-dir connbytes-mode);
247 add_match_def
'connlabel', qw(!label set*0);
248 add_match_def
'connlimit', qw(!connlimit-above connlimit-mask);
249 add_match_def
'connmark', qw(!mark);
250 add_match_def
'conntrack', qw(!ctstate=c !ctproto ctorigsrc! ctorigdst! ctorigsrcport! ctorigdstport!),
251 qw(ctreplsrc! ctrepldst! !ctstatus !ctexpire=s ctdir=s);
252 add_match_def
'cpu', qw(!cpu);
253 add_match_def
'dscp', qw(dscp dscp-class);
254 add_match_def
'dst', qw(!dst-len=s dst-opts=c);
255 add_match_def
'ecn', qw(ecn-tcp-cwr*0 ecn-tcp-ece*0 ecn-ip-ect);
256 add_match_def
'esp', qw(espspi!);
257 add_match_def
'eui64';
258 add_match_def
'fuzzy', qw(lower-limit=s upper-limit=s);
259 add_match_def
'hbh', qw(hbh-len! hbh-opts=c);
260 add_match_def
'helper', qw(helper);
261 add_match_def
'hl', qw(hl-eq! hl-lt=s hl-gt=s);
262 add_match_def
'hashlimit', qw(hashlimit=s hashlimit-burst=s hashlimit-mode=c hashlimit-name=s),
263 qw(hashlimit-upto=s hashlimit-above=s),
264 qw(hashlimit-srcmask=s hashlimit-dstmask=s),
265 qw(hashlimit-htable-size=s hashlimit-htable-max=s),
266 qw(hashlimit-htable-expire=s hashlimit-htable-gcinterval=s);
267 add_match_def
'iprange', qw(!src-range !dst-range);
268 add_match_def
'ipv4options', qw(ssrr*0 lsrr*0 no-srr*0 !rr*0 !ts*0 !ra*0 !any-opt*0);
269 add_match_def
'ipv6header', qw(header!=c soft*0);
270 add_match_def
'ipvs', qw(!ipvs*0 !vproto !vaddr !vport vdir !vportctl);
271 add_match_def
'length', qw(length!);
272 add_match_def
'limit', qw(limit=s limit-burst=s);
273 add_match_def
'mac', qw(mac-source!);
274 add_match_def
'mark', qw(!mark);
275 add_match_def
'multiport', qw(source-ports!&multiport_params),
276 qw(destination-ports!&multiport_params ports!&multiport_params);
277 add_match_def
'nth', qw(every counter start packet);
278 add_match_def
'osf', qw(!genre ttl=s log=s);
279 add_match_def
'owner', qw(!uid-owner !gid-owner pid-owner sid-owner),
280 qw(cmd-owner !socket-exists=0);
281 add_match_def
'physdev', qw(physdev-in! physdev-out!),
282 qw(!physdev-is-in*0 !physdev-is-out*0 !physdev-is-bridged*0);
283 add_match_def
'pkttype', qw(pkt-type!),
284 add_match_def
'policy',
285 qw(dir pol strict*0 !reqid !spi !proto !mode !tunnel-src !tunnel-dst next*0);
286 add_match_def
'psd', qw(psd-weight-threshold psd-delay-threshold),
287 qw(psd-lo-ports-weight psd-hi-ports-weight);
288 add_match_def
'quota', qw(quota=s);
289 add_match_def
'random', qw(average);
290 add_match_def
'realm', qw(realm!);
291 add_match_def
'recent', qw(name=s !set*0 !remove*0 !rcheck*0 !update*0 !seconds !hitcount rttl*0 rsource*0 rdest*0);
292 add_match_def
'rpfilter', qw(loose*0 validmark*0 accept-local*0 invert*0);
293 add_match_def
'rt', qw(rt-type! rt-segsleft! rt-len! rt-0-res*0 rt-0-addrs=c rt-0-not-strict*0);
294 add_match_def
'set', qw(!match-set=sc set:=match-set);
295 add_match_def
'state', qw(!state=c);
296 add_match_def
'statistic', qw(mode=s probability=s every=s packet=s);
297 add_match_def
'string', qw(algo=s from=s to=s string hex-string);
298 add_match_def
'tcpmss', qw(!mss);
299 add_match_def
'time', qw(timestart=s timestop=s days=c datestart=s datestop=s),
300 qw(!monthday=c !weekdays=c utc*0 localtz*0);
301 add_match_def
'tos', qw(!tos);
302 add_match_def
'ttl', qw(ttl-eq ttl-lt=s ttl-gt=s);
303 add_match_def
'u32', qw(!u32=m);
305 add_target_def
'AUDIT', qw(type);
306 add_target_def
'BALANCE', qw(to-destination to:=to-destination);
307 add_target_def
'CHECKSUM', qw(checksum-fill*0);
308 add_target_def
'CLASSIFY', qw(set-class);
309 add_target_def
'CLUSTERIP', qw(new*0 hashmode clustermac total-nodes local-node hash-init);
310 add_target_def
'CONNMARK', qw(set-xmark save-mark*0 restore-mark*0 nfmask ctmask),
311 qw(and-mark or-mark xor-mark set-mark mask);
312 add_target_def
'CONNSECMARK', qw(save*0 restore*0);
313 add_target_def
'CT', qw(notrack*0 helper ctevents=c expevents=c zone timeout);
314 add_target_def
'DNAT', qw(to-destination=m to:=to-destination persistent*0 random*0);
315 add_target_def
'DNPT', qw(src-pfx dst-pfx);
316 add_target_def
'DSCP', qw(set-dscp set-dscp-class);
317 add_target_def
'ECN', qw(ecn-tcp-remove*0);
318 add_target_def
'HL', qw(hl-set hl-dec hl-inc);
319 add_target_def
'HMARK', qw(hmark-tuple hmark-mod hmark-offset),
320 qw(hmark-src-prefix hmark-dst-prefix hmark-sport-mask),
321 qw(hmark-dport-mask hmark-spi-mask hmark-proto-mask hmark-rnd);
322 add_target_def
'IDLETIMER', qw(timeout label);
323 add_target_def
'IPV4OPTSSTRIP';
324 add_target_def
'LED', qw(led-trigger-id led-delay led-always-blink*0);
325 add_target_def
'LOG', qw(log-level log-prefix),
326 qw(log-tcp-sequence*0 log-tcp-options*0 log-ip-options*0 log-uid*0);
327 add_target_def
'MARK', qw(set-mark set-xmark and-mark or-mark xor-mark);
328 add_target_def
'MASQUERADE', qw(to-ports random*0);
329 add_target_def
'MIRROR';
330 add_target_def
'NETMAP', qw(to);
331 add_target_def
'NFLOG', qw(nflog-group nflog-prefix nflog-range nflog-threshold);
332 add_target_def
'NFQUEUE', qw(queue-num queue-balance queue-bypass*0 queue-cpu-fanout*0);
333 add_target_def
'NOTRACK';
334 add_target_def
'RATEEST', qw(rateest-name rateest-interval rateest-ewmalog);
335 add_target_def
'REDIRECT', qw(to-ports random*0);
336 add_target_def
'REJECT', qw(reject-with);
337 add_target_def
'ROUTE', qw(oif iif gw continue*0 tee*0);
338 add_target_def
'SAME', qw(to nodst*0 random*0);
339 add_target_def
'SECMARK', qw(selctx);
340 add_target_def
'SET', qw(add-set=sc del-set=sc timeout exist*0);
341 add_target_def
'SNAT', qw(to-source=m to:=to-source persistent*0 random*0);
342 add_target_def
'SNPT', qw(src-pfx dst-pfx);
343 add_target_def
'SYNPROXY', qw(sack-perm*0 timestamp*0 ecn*0 wscale=s mss=s);
344 add_target_def
'TARPIT';
345 add_target_def
'TCPMSS', qw(set-mss clamp-mss-to-pmtu*0);
346 add_target_def
'TCPOPTSTRIP', qw(strip-options=c);
347 add_target_def
'TEE', qw(gateway);
348 add_target_def
'TOS', qw(set-tos and-tos or-tos xor-tos);
349 add_target_def
'TPROXY', qw(tproxy-mark on-port);
350 add_target_def
'TRACE';
351 add_target_def
'TTL', qw(ttl-set ttl-dec ttl-inc);
352 add_target_def
'ULOG', qw(ulog-nlgroup ulog-prefix ulog-cprange ulog-qthreshold);
354 add_match_def_x
'arp', '',
356 qw(source-ip! destination-ip! saddr:=source-ip daddr:=destination-ip),
358 qw(source-mac! destination-mac!),
360 qw(in-interface! interface:=in-interface if:=in-interface),
362 qw(out-interface! outerface:=out-interface of:=out-interface),
364 qw(h-length=s opcode=s h-type=s proto-type=s),
365 qw(mangle-ip-s=s mangle-ip-d=s mangle-mac-s=s mangle-mac-d=s mangle-target=s);
367 add_proto_def_x
'eb', 'IPv4',
368 qw(ip-source! ip-destination! ip-src:=ip-source ip-dst:=ip-destination),
370 qw(ip-protocol! ip-proto:=ip-protocol),
371 qw(ip-source-port! ip-sport:=ip-source-port),
372 qw(ip-destination-port! ip-dport:=ip-destination-port);
374 add_proto_def_x
'eb', 'IPv6',
375 qw(ip6-source! ip6-destination! ip6-src:=ip6-source ip6-dst:=ip6-destination),
377 qw(ip6-protocol! ip6-proto:=ip6-protocol),
378 qw(ip6-source-port! ip6-sport:=ip6-source-port),
379 qw(ip6-destination-port! ip6-dport:=ip6-destination-port);
381 add_proto_def_x
'eb', 'ARP',
382 qw(!arp-gratuitous*0),
383 qw(arp-opcode! arp-htype!=ss arp-ptype!=ss),
384 qw(arp-ip-src! arp-ip-dst! arp-mac-src! arp-mac-dst!);
386 add_proto_def_x
'eb', 'RARP',
387 qw(!arp-gratuitous*0),
388 qw(arp-opcode! arp-htype!=ss arp-ptype!=ss),
389 qw(arp-ip-src! arp-ip-dst! arp-mac-src! arp-mac-dst!);
391 add_proto_def_x
'eb', '802_1Q',
392 qw(vlan-id! vlan-prio! vlan-encap!),
394 add_match_def_x
'eb', '',
396 qw(in-interface! interface:=in-interface if:=in-interface),
398 qw(out-interface! outerface:=out-interface of:=out-interface),
400 qw(logical-in! logical-out!),
401 # --source, --destination
402 qw(source! saddr:=source destination! daddr:=destination),
404 qw(802_3-sap! 802_3-type!),
406 qw(!among-dst=c !among-src=c !among-dst-file !among-src-file),
408 qw(limit=s limit-burst=s),
414 qw(stp-type! stp-flags! stp-root-prio! stp-root-addr! stp-root-cost!),
415 qw(stp-sender-prio! stp-sender-addr! stp-port! stp-msg-age! stp-max-age!),
416 qw(stp-hello-time! stp-forward-delay!),
418 qw(log*0 log-level=s log-prefix=s log-ip*0 log-arp*0);
420 add_target_def_x
'eb', 'arpreply', qw(arpreply-mac arpreply-target);
421 add_target_def_x
'eb', 'dnat', qw(to-destination dnat-target);
422 add_target_def_x
'eb', 'MARK', qw(set-mark mark-target);
423 add_target_def_x
'eb', 'redirect', qw(redirect-target);
424 add_target_def_x
'eb', 'snat', qw(to-source snat-target snat-arp*0);
426 # import-ferm uses the above tables
427 return 1 if $0 =~ /import-ferm$/;
429 # parameter parser for ipt_multiport
430 sub multiport_params
{
433 # multiport only allows 15 ports at a time. For this
434 # reason, we do a little magic here: split the ports
435 # into portions of 15, and handle these portions as
438 my $proto = $rule->{protocol
};
439 error
('To use multiport, you have to specify "proto tcp" or "proto udp" first')
440 unless defined $proto and grep { /^(?:tcp|udp|udplite)$/ } to_array
($proto);
442 my $value = getvalues
(undef, allow_negation
=> 1,
443 allow_array_negation
=> 1);
444 if (ref $value and ref $value eq 'ARRAY') {
449 push @params, join(',', splice(@value, 0, 15));
456 return join_value
(',', $value);
463 # very crude IPv4/IPv6 address detection
464 if ($domain eq 'ip') {
465 @ips = grep { !/:[0-9a-f]*:/ } @_;
466 } elsif ($domain eq 'ip6') {
467 @ips = grep { !m
,^[0-9./]+$,s
} @_;
474 my $domain = $rule->{domain
};
475 my $value = getvalues
(undef, allow_negation
=> 1);
479 if (ref $value and ref $value eq 'ARRAY') {
481 } elsif (ref $value and ref $value eq 'negated') {
484 } elsif (ref $value) {
490 # only do magic on domain (ip ip6); do not process on a single-stack rule
491 # as to let admins spot their errors instead of silently ignoring them
492 @ips = ipfilter
($domain, @ips) if defined $rule->{domain_both
};
494 if ($negated && scalar @ips) {
495 return bless \
@ips, 'negated';
501 # initialize stack: command line definitions
504 # Get command line stuff
506 my ($opt_noexec, $opt_flush, $opt_noflush, $opt_lines, $opt_interactive,
507 $opt_timeout, $opt_help,
508 $opt_version, $opt_test, $opt_fast, $opt_slow, $opt_shell,
511 Getopt
::Long
::Configure
('bundling', 'auto_help', 'no_ignore_case',
515 my ($opt, $value) = @_;
516 die 'Invalid --def specification'
517 unless $value =~ /^\$?(\w+)=(.*)$/s;
518 my ($name, $unparsed_value) = ($1, $2);
519 my $tokens = tokenize_string
($unparsed_value);
520 $value = getvalues
(sub { shift @
$tokens; });
521 die 'Extra tokens after --def'
523 $stack[0]{vars
}{$name} = $value;
526 local $SIG{__WARN__
} = sub { die $_[0]; };
527 GetOptions
('noexec|n' => \
$opt_noexec,
528 'flush|F' => \
$opt_flush,
529 'noflush' => \
$opt_noflush,
530 'lines|l' => \
$opt_lines,
531 'interactive|i' => \
$opt_interactive,
532 'timeout|t=s' => \
$opt_timeout,
533 'help|h' => \
$opt_help,
534 'version|V' => \
$opt_version,
536 remote
=> \
$opt_test,
539 shell
=> \
$opt_shell,
540 'domain=s' => \
$opt_domain,
541 'def=s' => \
&opt_def
,
544 if (defined $opt_help) {
546 Pod
::Usage
::pod2usage
(-exitstatus
=> 0);
549 if (defined $opt_version) {
554 $option{noexec
} = $opt_noexec || $opt_test;
555 $option{flush
} = $opt_flush;
556 $option{noflush
} = $opt_noflush;
557 $option{lines
} = $opt_lines || $opt_test || $opt_shell;
558 $option{interactive
} = $opt_interactive && !$opt_noexec;
559 $option{timeout
} = defined $opt_timeout ?
$opt_timeout : "30";
560 $option{test
} = $opt_test;
561 $option{fast
} = !$opt_slow;
562 $option{shell
} = $opt_shell;
564 die("ferm interactive mode not possible: /dev/stdin is not a tty\n")
565 if $option{interactive
} and not -t STDIN
;
566 die("ferm interactive mode not possible: /dev/stderr is not a tty\n")
567 if $option{interactive
} and not -t STDERR
;
568 die("ferm timeout has no sense without interactive mode")
569 if not $opt_interactive and defined $opt_timeout;
570 die("invalid timeout. must be an integer")
571 if defined $opt_timeout and not $opt_timeout =~ /^[+-]?\d+$/;
573 $option{domain
} = $opt_domain if defined $opt_domain;
575 # tiny getopt emulation for microperl
578 if ($_ eq '--noexec' or $_ eq '-n') {
580 } elsif ($_ eq '--lines' or $_ eq '-l') {
582 } elsif ($_ eq '--fast') {
584 } elsif ($_ eq '--test') {
588 } elsif ($_ eq '--shell') {
589 $option{$_} = 1 foreach qw(shell fast lines);
591 printf STDERR
"Usage: ferm [--noexec] [--lines] [--fast] [--shell] FILENAME\n";
598 push @ARGV, $filename;
601 unless (@ARGV == 1) {
603 Pod
::Usage
::pod2usage
(-exitstatus
=> 1);
607 open LINES
, ">&STDOUT" if $option{lines
};
608 open STDOUT
, ">&STDERR" if $option{shell
};
610 # microperl can't redirect file handles
613 if ($option{fast
} and not $option{noexec
}) {
614 print STDERR
"Sorry, ferm on microperl does not allow --fast without --noexec\n";
620 open_script
($ARGV[0]);
622 my( $volume,$dirs,$file ) = File
::Spec
->splitpath( $ARGV[0] );
623 $stack[0]{auto
}{FILENAME
} = $ARGV[0];
624 $stack[0]{auto
}{FILEBNAME
} = $file;
625 $stack[0]{auto
}{DIRNAME
} = $dirs;
629 # parse all input recursively
631 die unless @stack == 2;
633 # enable/disable hooks depending on --flush
635 if ($option{flush
}) {
642 # execute all generated rules
645 foreach my $cmd (@pre_hooks) {
646 print LINES
"$cmd\n" if $option{lines
};
647 system($cmd) unless $option{noexec
};
650 while (my ($domain, $domain_info) = each %domains) {
651 next unless $domain_info->{enabled
};
652 my $s = $option{fast
} &&
653 defined $domain_info->{tools
}{'tables-restore'}
654 ? execute_fast
($domain_info) : execute_slow
($domain_info);
655 $status = $s if defined $s;
658 foreach my $cmd (@post_hooks, @flush_hooks) {
659 print LINES
"$cmd\n" if $option{lines
};
660 system($cmd) unless $option{noexec
};
663 if (defined $status) {
668 # ask user, and rollback if there is no confirmation
670 if ($option{interactive
}) {
671 if ($option{shell
}) {
672 print LINES
"echo 'ferm has applied the new firewall rules.'\n";
673 print LINES
"echo 'Please press Ctrl-C to confirm.'\n";
674 print LINES
"sleep $option{timeout}\n";
675 while (my ($domain, $domain_info) = each %domains) {
676 my $restore = $domain_info->{tools
}{'tables-restore'};
677 next unless defined $restore;
678 print LINES
"$restore <\$${domain}_tmp\n";
682 confirm_rules
() or rollback
() unless $option{noexec
};
687 # end of program execution!
693 print "ferm $VERSION\n";
694 print "Copyright (C) 2001-2012 Max Kellermann, Auke Kok\n";
695 print "This program is free software released under GPLv2.\n";
696 print "See the included COPYING file for license details.\n";
701 # returns a nice formatted error message, showing the
702 # location of the error.
706 my @words = map { @
$_ } @
{$script->{past_tokens
}};
708 for my $w ( 0 .. $#words ) {
709 if ($words[$w] eq "\x29")
710 { $l++ ; $lines[$l] = " " x
($tabs-- -1) ;};
711 if ($words[$w] eq "\x28")
712 { $l++ ; $lines[$l] = " " x
$tabs++ ;};
713 if ($words[$w] eq "\x7d")
714 { $l++ ; $lines[$l] = " " x
($tabs-- -1) ;};
715 if ($words[$w] eq "\x7b")
716 { $l++ ; $lines[$l] = " " x
$tabs++ ;};
717 if ( $l > $#lines ) { $lines[$l] = "" };
718 $lines[$l] .= $words[$w] . " ";
719 if ($words[$w] eq "\x28")
720 { $l++ ; $lines[$l] = " " x
$tabs ;};
721 if (($words[$w] eq "\x29") && ($words[$w+1] ne "\x7b"))
722 { $l++ ; $lines[$l] = " " x
$tabs ;};
723 if ($words[$w] eq "\x7b")
724 { $l++ ; $lines[$l] = " " x
$tabs ;};
725 if (($words[$w] eq "\x7d") && ($words[$w+1] ne "\x7d"))
726 { $l++ ; $lines[$l] = " " x
$tabs ;};
727 if (($words[$w] eq "\x3b") && ($words[$w+1] ne "\x7d"))
728 { $l++ ; $lines[$l] = " " x
$tabs ;}
729 if ($words[$w-1] eq "option")
730 { $l++ ; $lines[$l] = " " x
$tabs ;}
732 my $start = $#lines - 4;
733 if ($start < 0) { $start = 0 } ;
734 print STDERR
"Error in $script->{filename} line $script->{line}:\n";
735 for $l ( $start .. $#lines)
736 { print STDERR
$lines[$l]; if ($l != $#lines ) {print STDERR
"\n"} ; };
737 print STDERR
"<--\n";
741 # print a warning message about code from an input file
743 print STDERR
"Warning in $script->{filename} line $script->{line}: "
749 return $name if $option{test
};
750 for my $path ('/sbin', split ':', $ENV{PATH
}) {
751 my $ret = "$path/$name";
752 return $ret if -x
$ret;
754 die "$name not found in PATH\n";
757 sub initialize_domain
{
759 my $domain_info = $domains{$domain} ||= {};
761 return if exists $domain_info->{initialized
};
763 die "Invalid domain '$domain'\n" unless $domain =~ /^(?:ip6?|arp|eb)$/;
765 my @tools = qw(tables);
766 push @tools, qw(tables-save tables-restore)
767 if $domain =~ /^ip6?$/;
769 # determine the location of this domain's tools
770 my %tools = map { $_ => find_tool
($domain . $_) } @tools;
771 $domain_info->{tools
} = \
%tools;
773 # make tables-save tell us about the state of this domain
774 # (which tables and chains do exist?), also remember the old
775 # save data which may be used later by the rollback function
777 if (!$option{test
} &&
778 exists $tools{'tables-save'} &&
779 open(SAVE
, "$tools{'tables-save'}|")) {
788 $table_info = $domain_info->{tables
}{$table} ||= {};
789 } elsif (defined $table_info and /^:(\w+)\s+(\S+)/
791 $table_info->{chains
}{$1}{builtin
} = 1;
792 $table_info->{has_builtin
} = 1;
797 $domain_info->{previous
} = $save;
800 if ($option{shell
} && $option{interactive
} &&
801 exists $tools{'tables-save'}) {
802 print LINES
"${domain}_tmp=\$(mktemp ferm.XXXXXXXXXX)\n";
803 print LINES
"$tools{'tables-save'} >\$${domain}_tmp\n";
806 $domain_info->{initialized
} = 1;
809 sub check_domain
($) {
813 return if exists $option{domain
}
814 and $domain ne $option{domain
};
817 initialize_domain
($domain);
824 # split the input string into words and delete comments
825 sub tokenize_string
($) {
830 foreach my $word ($string =~ m/(".*?"|'.*?'|`.*?`|[!,=&\$\%\(\){};]|[-+\w\/\
.:]+|@\w
+|#)/g) {
831 last if $word eq '#';
838 # generate a "line" special token, that marks the line number; these
839 # special tokens are inserted after each line break, so ferm keeps
840 # track of line numbers
841 sub make_line_token
($) {
843 return bless(\
$line, 'line');
846 # read some more tokens from the input file into a buffer
847 sub prepare_tokens
() {
848 my $tokens = $script->{tokens
};
849 while (@
$tokens == 0) {
850 my $handle = $script->{handle
};
851 return unless defined $handle;
852 my $line = <$handle>;
853 return unless defined $line;
855 push @
$tokens, make_line_token
($script->{line
} + 1);
857 # the next parser stage eats this
858 push @
$tokens, @
{tokenize_string
($line)};
864 sub handle_special_token
($) {
866 die unless ref $token;
867 if (ref $token eq 'line') {
868 $script->{line
} = $$token;
874 sub handle_special_tokens
() {
875 my $tokens = $script->{tokens
};
876 while (@
$tokens > 0 and ref $tokens->[0]) {
877 handle_special_token
(shift @
$tokens);
881 # wrapper for prepare_tokens() which handles "special" tokens
882 sub prepare_normal_tokens
() {
883 my $tokens = $script->{tokens
};
885 handle_special_tokens
();
886 return 1 if @
$tokens > 0;
887 return unless prepare_tokens
();
891 # open a ferm sub script
893 my $filename = shift;
895 for (my $s = $script; defined $s; $s = $s->{parent
}) {
896 die("Circular reference in $script->{filename} line $script->{line}: $filename\n")
897 if $s->{filename
} eq $filename;
901 if ($filename eq '-') {
902 # Note that this only allowed in the command-line argument and not
903 # @includes, since those are filtered by collect_filenames()
905 # also set a filename label so that error messages are more helpful
906 $filename = "<stdin>";
909 open FILE
, "$filename" or die("Failed to open $filename: $!\n");
913 $script = { filename
=> $filename,
924 # collect script filenames which are being included
925 sub collect_filenames
(@
) {
928 # determine the current script's parent directory for relative
930 die unless defined $script;
931 my $parent_dir = $script->{filename
} =~ m
,^(.*/),
934 foreach my $pathname (@_) {
935 # non-absolute file names are relative to the parent script's
937 $pathname = $parent_dir . $pathname
938 unless $pathname =~ m
,^/|\
|$,;
940 if ($pathname =~ m
,/$,) {
941 # include all regular files in a directory
943 error
("'$pathname' is not a directory")
947 opendir DIR
, $pathname
948 or error
("Failed to open directory '$pathname': $!");
949 my @names = readdir DIR
;
952 # sort those names for a well-defined order
953 foreach my $name (sort { $a cmp $b } @names) {
954 # ignore dpkg's backup files
955 next if $name =~ /\.dpkg-(old|dist|new|tmp)$/;
956 # don't include hidden and backup files
957 next if $name =~ /^\.|~$/;
959 my $filename = $pathname . $name;
963 } elsif ($pathname =~ m
,\
|$,) {
964 # run a program and use its output
965 push @ret, $pathname;
966 } elsif ($pathname =~ m
,^\
|,) {
967 error
('This kind of pipe is not allowed');
969 # include a regular file
971 error
("'$pathname' is a directory; maybe use trailing '/' to include a directory?")
973 error
("'$pathname' is not a file")
976 push @ret, $pathname;
983 # peek a token from the queue, but don't remove it
985 return unless prepare_normal_tokens
();
986 return $script->{tokens
}[0];
989 # get a token from the queue, including "special" tokens
990 sub next_raw_token
() {
991 return unless prepare_tokens
();
992 return shift @
{$script->{tokens
}};
995 # get a token from the queue
997 return unless prepare_normal_tokens
();
998 my $token = shift @
{$script->{tokens
}};
1000 # update $script->{past_tokens}
1001 my $past_tokens = $script->{past_tokens
};
1003 if (@
$past_tokens > 0) {
1004 my $prev_token = $past_tokens->[-1][-1];
1005 $past_tokens->[-1] = @
$past_tokens > 1 ?
['{'] : []
1006 if $prev_token eq ';';
1007 if ($prev_token eq '}') {
1009 $past_tokens->[-1] = $past_tokens->[-1][0] eq '{'
1011 if @
$past_tokens > 0;
1015 push @
$past_tokens, [] if $token eq '{' or @
$past_tokens == 0;
1016 push @
{$past_tokens->[-1]}, $token;
1022 sub expect_token
($;$) {
1025 my $token = next_token
();
1026 error
($msg || "'$expect' expected")
1027 unless defined $token and $token eq $expect;
1030 # require that another token exists, and that it's not a "special"
1031 # token, e.g. ";" and "{"
1032 sub require_next_token
{
1033 my $code = shift || \
&next_token
;
1035 my $token = &$code(@_);
1037 error
('unexpected end of file')
1038 unless defined $token;
1040 error
("'$token' not allowed here")
1041 if $token =~ /^[;{}]$/;
1046 # return the value of a variable
1047 sub variable_value
($) {
1050 if ($name eq "LINE") {
1051 return $script->{line
};
1055 return $_->{vars
}{$name}
1056 if exists $_->{vars
}{$name};
1059 return $stack[0]{auto
}{$name}
1060 if exists $stack[0]{auto
}{$name};
1065 # determine the value of a variable, die if the value is an array
1066 sub string_variable_value
($) {
1068 my $value = variable_value
($name);
1070 error
("variable '$name' must be a string, but it is an array")
1076 # similar to the built-in "join" function, but also handle negated
1077 # values in a special way
1078 sub join_value
($$) {
1079 my ($expr, $value) = @_;
1081 unless (ref $value) {
1083 } elsif (ref $value eq 'ARRAY') {
1084 return join($expr, @
$value);
1085 } elsif (ref $value eq 'negated') {
1086 # bless'negated' is a special marker for negated values
1087 $value = join_value
($expr, $value->[0]);
1088 return bless [ $value ], 'negated';
1094 sub negate_value
($$;$) {
1095 my ($value, $class, $allow_array) = @_;
1098 error
('double negation is not allowed')
1099 if ref $value eq 'negated' or ref $value eq 'pre_negated';
1101 error
('it is not possible to negate an array')
1102 if ref $value eq 'ARRAY' and not $allow_array;
1105 return bless [ $value ], $class || 'negated';
1108 sub format_bool
($) {
1109 return $_[0] ?
1 : 0;
1113 my ($resolver, $names, $type) = @_;
1116 foreach my $hostname (@
$names) {
1117 my $query = $resolver->search($hostname, $type);
1118 error
("DNS query for '$hostname' failed: " . $resolver->errorstring)
1121 foreach my $rr ($query->answer) {
1122 next unless $rr->type eq $type;
1124 if ($type eq 'NS') {
1125 push @result, $rr->nsdname;
1126 } elsif ($type eq 'MX') {
1127 push @result, $rr->exchange;
1129 push @result, $rr->address;
1134 # NS/MX records return host names; resolve these again in the
1135 # second pass (IPv4 only currently)
1136 @result = resolve
($resolver, @result, 'A')
1137 if $type eq 'NS' or $type eq 'MX';
1142 sub lookup_function
($) {
1146 return $_->{functions
}{$name}
1147 if exists $_->{functions
}{$name};
1153 # returns the next parameter, which may either be a scalar or an array
1158 my $token = require_next_token
($code);
1160 if ($token eq '(') {
1161 # read an array until ")"
1165 $token = getvalues
($code,
1166 parenthesis_allowed
=> 1,
1167 comma_allowed
=> 1);
1169 unless (ref $token) {
1170 last if $token eq ')';
1172 if ($token eq ',') {
1173 error
('Comma is not allowed within arrays, please use only a space');
1177 push @wordlist, $token;
1178 } elsif (ref $token eq 'ARRAY') {
1179 push @wordlist, @
$token;
1181 error
('unknown token type');
1185 error
('empty array not allowed here')
1186 unless @wordlist or not $options{non_empty
};
1188 return @wordlist == 1
1191 } elsif ($token =~ /^\`(.*)\`$/s) {
1192 # execute a shell command, insert output
1194 my $output = `$command`;
1197 error
("failed to execute: $!");
1198 } elsif ($?
& 0x7f) {
1199 error
("child died with signal " . ($?
& 0x7f));
1201 error
("child exited with status " . ($?
>> 8));
1206 $output =~ s/#.*//mg;
1209 my @tokens = grep { length } split /\s+/s, $output;
1213 my $value = getvalues
(sub { shift @tokens });
1214 push @values, to_array
($value);
1221 } elsif ($token =~ /^\'(.*)\'$/s) {
1222 # single quotes: a string
1224 } elsif ($token =~ /^\"(.*)\"$/s) {
1225 # double quotes: a string with escapes
1227 $token =~ s
,\
$(\w
+),string_variable_value
($1),eg
;
1229 } elsif ($token eq '!') {
1230 error
('negation is not allowed here')
1231 unless $options{allow_negation
};
1233 $token = getvalues
($code);
1235 return negate_value
($token, undef, $options{allow_array_negation
});
1236 } elsif ($token eq ',') {
1238 if $options{comma_allowed
};
1240 error
('comma is not allowed here');
1241 } elsif ($token eq '=') {
1242 error
('equals operator ("=") is not allowed here');
1243 } elsif ($token eq '$') {
1244 my $name = require_next_token
($code);
1245 error
('variable name expected - if you want to concatenate strings, try using double quotes')
1246 unless $name =~ /^\w+$/;
1248 my $value = variable_value
($name);
1250 error
("no such variable: \$$name")
1251 unless defined $value;
1254 } elsif ($token eq '&') {
1255 error
("function calls are not allowed as keyword parameter");
1256 } elsif ($token eq ')' and not $options{parenthesis_allowed
}) {
1257 error
('Syntax error');
1258 } elsif ($token =~ /^@/) {
1259 if ($token eq '@resolve') {
1260 my @params = get_function_params
();
1261 error
('Usage: @resolve((hostname ...), [type])')
1262 unless @params == 1 or @params == 2;
1263 eval { require Net
::DNS
; };
1264 error
('For the @resolve() function, you need the Perl library Net::DNS')
1266 my $type = $params[1] || 'A';
1267 error
('String expected') if ref $type;
1268 my $resolver = new Net
::DNS
::Resolver
;
1269 @params = to_array
($params[0]);
1270 my @result = resolve
($resolver, @params, $type);
1271 return @result == 1 ?
$result[0] : \
@result;
1272 } elsif ($token eq '@defined') {
1273 expect_token
('(', 'function name must be followed by "()"');
1274 my $type = require_next_token
();
1276 my $name = require_next_token
();
1277 error
('variable name expected')
1278 unless $name =~ /^\w+$/;
1280 return defined variable_value
($name);
1281 } elsif ($type eq '&') {
1282 my $name = require_next_token
();
1283 error
('function name expected')
1284 unless $name =~ /^\w+$/;
1286 return defined lookup_function
($name);
1288 error
("'\$' or '&' expected")
1290 } elsif ($token eq '@eq') {
1291 my @params = get_function_params
();
1292 error
('Usage: @eq(a, b)') unless @params == 2;
1293 return format_bool
($params[0] eq $params[1]);
1294 } elsif ($token eq '@ne') {
1295 my @params = get_function_params
();
1296 error
('Usage: @ne(a, b)') unless @params == 2;
1297 return format_bool
($params[0] ne $params[1]);
1298 } elsif ($token eq '@not') {
1299 my @params = get_function_params
();
1300 error
('Usage: @not(a)') unless @params == 1;
1301 return format_bool
(not $params[0]);
1302 } elsif ($token eq '@cat') {
1305 error
('String expected') if ref $_;
1307 } get_function_params
();
1309 } elsif ($token eq '@substr') {
1310 my @params = get_function_params
();
1311 error
('Usage: @substr(string, num, num)') unless @params == 3;
1312 error
('String expected') if ref $params[0] or ref $params[1] or ref $params[2];
1313 return substr($params[0],$params[1],$params[2]);
1314 } elsif ($token eq '@length') {
1315 my @params = get_function_params
();
1316 error
('Usage: @length(string)') unless @params == 1;
1317 error
('String expected') if ref $params[0];
1318 return length($params[0]);
1319 } elsif ($token eq '@basename') {
1320 my @params = get_function_params
();
1321 error
('Usage: @basename(path)') unless @params == 1;
1322 error
('String expected') if ref $params[0];
1323 my($volume,$path,$file) = File
::Spec
->splitpath( $params[0] );
1325 } elsif ($token eq '@dirname') {
1326 my @params = get_function_params
();
1327 error
('Usage: @dirname(path)') unless @params == 1;
1328 error
('String expected') if ref $params[0];
1329 my($volume,$path,$file) = File
::Spec
->splitpath( $params[0] );
1331 } elsif ($token eq '@glob') {
1332 my @params = get_function_params
();
1333 error
('Usage: @glob(string)') unless @params == 1;
1335 # determine the current script's parent directory for relative
1337 die unless defined $script;
1338 my $parent_dir = $script->{filename
} =~ m
,^(.*/),
1343 $path = $parent_dir . $path unless $path =~ m
,^/,;
1345 } to_array
($params[0]);
1346 return @result == 1 ?
$result[0] : \
@result;
1347 } elsif ($token eq '@ipfilter') {
1348 my @params = get_function_params
();
1349 error
('Usage: @ipfilter((ip1 ip2 ...))') unless @params == 1;
1350 my $domain = $stack[0]{auto
}{DOMAIN
};
1351 error
('No domain specified') unless defined $domain;
1352 my @ips = ipfilter
($domain, to_array
($params[0]));
1355 error
("unknown ferm built-in function");
1362 # returns the next parameter, but only allow a scalar
1364 my $token = getvalues
();
1366 error
('array not allowed here')
1367 if ref $token and ref $token eq 'ARRAY';
1372 sub get_function_params
(%) {
1373 expect_token
('(', 'function name must be followed by "()"');
1375 my $token = peek_token
();
1376 if ($token eq ')') {
1377 require_next_token
();
1385 $token = require_next_token
();
1389 error
('"," expected')
1390 unless $token eq ',';
1393 push @params, getvalues
(undef, @_);
1399 # collect all tokens in a flat array reference until the end of the
1400 # command is reached
1401 sub collect_tokens
{
1407 # re-insert a "line" token, because the starting token of the
1408 # current line has been consumed already
1409 push @tokens, make_line_token
($script->{line
});
1412 my $keyword = next_raw_token
();
1413 error
('unexpected end of file within function/variable declaration')
1414 unless defined $keyword;
1417 handle_special_token
($keyword);
1418 } elsif ($keyword =~ /^[\{\(]$/) {
1419 push @level, $keyword;
1420 } elsif ($keyword =~ /^[\}\)]$/) {
1421 my $expected = $keyword;
1422 $expected =~ tr/\}\)/\{\(/;
1423 my $opener = pop @level;
1424 error
("unmatched '$keyword'")
1425 unless defined $opener and $opener eq $expected;
1426 } elsif ($keyword eq ';' and @level == 0) {
1427 push @tokens, $keyword
1428 if $options{include_semicolon
};
1430 if ($options{include_else
}) {
1431 my $token = peek_token
;
1432 next if $token eq '@else';
1438 push @tokens, $keyword;
1441 if $keyword eq '}' and @level == 0;
1448 # returns the specified value as an array. dereference arrayrefs
1451 die unless wantarray;
1453 unless (ref $value) {
1455 } elsif (ref $value eq 'ARRAY') {
1462 # evaluate the specified value as bool
1467 unless (ref $value) {
1469 } elsif (ref $value eq 'ARRAY') {
1476 sub is_netfilter_core_target
($) {
1478 die unless defined $target and length $target;
1479 return grep { $_ eq $target } qw(ACCEPT DROP RETURN QUEUE);
1482 sub is_netfilter_module_target
($$) {
1483 my ($domain_family, $target) = @_;
1484 die unless defined $target and length $target;
1486 return defined $domain_family &&
1487 exists $target_defs{$domain_family} &&
1488 $target_defs{$domain_family}{$target};
1491 sub is_netfilter_builtin_chain
($$) {
1492 my ($table, $chain) = @_;
1494 return grep { $_ eq $chain }
1495 qw(PREROUTING INPUT FORWARD OUTPUT POSTROUTING BROUTING);
1498 sub netfilter_canonical_protocol
($) {
1501 if $proto eq 'ipv6-icmp' or $proto eq 'icmpv6';
1503 if $proto eq 'ipv6-mh';
1507 sub netfilter_protocol_module
($) {
1509 return unless defined $proto;
1511 if $proto eq 'icmpv6';
1515 # escape the string in a way safe for the shell
1516 sub shell_escape
($) {
1519 return $token if $token =~ /^[-_a-zA-Z0-9]+$/s;
1521 if ($option{fast
}) {
1522 # iptables-save/iptables-restore are quite buggy concerning
1523 # escaping and special characters... we're trying our best
1526 $token =~ s
,",\\",g
;
1527 $token = '"' . $token . '"'
1528 if $token =~ /[\s\'\\;&]/s or length($token) == 0;
1531 if $token =~ /^\`.*\`$/;
1532 $token =~ s/'/'\\''/g;
1533 $token = '\'' . $token . '\''
1534 if $token =~ /[\s\"\\;<>&|]/s or length($token) == 0;
1540 # append an option to the shell command line, using information from
1541 # the module definition (see %match_defs etc.)
1542 sub shell_format_option
($$) {
1543 my ($keyword, $value) = @_;
1547 if ((ref $value eq 'negated') || (ref $value eq 'pre_negated')) {
1548 $value = $value->[0];
1553 unless (defined $value) {
1554 $cmd .= " --$keyword";
1555 } elsif (ref $value) {
1556 if (ref $value eq 'params') {
1557 $cmd .= " --$keyword ";
1558 $cmd .= join(' ', map { shell_escape
($_) } @
$value);
1559 } elsif (ref $value eq 'multi') {
1561 $cmd .= " --$keyword " . shell_escape
($_);
1567 $cmd .= " --$keyword " . shell_escape
($value);
1573 sub format_option
($$$) {
1574 my ($domain, $name, $value) = @_;
1576 $value = 'icmpv6' if $domain eq 'ip6' and $name eq 'protocol'
1577 and $value eq 'icmp';
1578 $name = 'icmpv6-type' if $domain eq 'ip6' and $name eq 'icmp-type';
1580 if ($domain eq 'ip6' and $name eq 'reject-with') {
1582 'icmp-net-unreachable' => 'icmp6-no-route',
1583 'icmp-host-unreachable' => 'icmp6-addr-unreachable',
1584 'icmp-port-unreachable' => 'icmp6-port-unreachable',
1585 'icmp-net-prohibited' => 'icmp6-adm-prohibited',
1586 'icmp-host-prohibited' => 'icmp6-adm-prohibited',
1587 'icmp-admin-prohibited' => 'icmp6-adm-prohibited',
1589 $value = $icmp_map{$value} if exists $icmp_map{$value};
1592 return shell_format_option
($name, $value);
1595 sub append_rule
($$) {
1596 my ($chain_rules, $rule) = @_;
1598 my $cmd = join('', map { $_->[2] } @
{$rule->{options
}});
1599 push @
$chain_rules, { rule
=> $cmd,
1600 script
=> $rule->{script
},
1605 my ($domain, $chain_rules, $rule) = (shift, shift, shift);
1606 return append_rule
($chain_rules, $rule) unless @_;
1609 my @values = @
{$option->[1]};
1611 foreach my $value (@values) {
1612 $option->[2] = format_option
($domain, $option->[0], $value);
1613 unfold_rule
($domain, $chain_rules, $rule, @_);
1618 my ($domain, $chain_rules, $rule) = @_;
1621 foreach my $option (@
{$rule->{options
}}) {
1622 if (ref $option->[1] and ref $option->[1] eq 'ARRAY') {
1623 push @unfold, $option
1625 $option->[2] = format_option
($domain, $option->[0], $option->[1]);
1629 unfold_rule
($domain, $chain_rules, $rule, @unfold);
1632 # convert a bunch of internal rule structures in iptables calls,
1633 # unfold arrays during that
1637 my $domain = $rule->{domain
};
1638 my $domain_info = $domains{$domain};
1639 $domain_info->{enabled
} = 1;
1641 foreach my $table (to_array
$rule->{table
}) {
1642 my $table_info = $domain_info->{tables
}{$table} ||= {};
1644 foreach my $chain (to_array
$rule->{chain
}) {
1645 my $chain_rules = $table_info->{chains
}{$chain}{rules
} ||= [];
1646 mkrules2
($domain, $chain_rules, $rule)
1647 if $rule->{has_rule
} and not $option{flush
};
1652 # parse a keyword from a module definition
1653 sub parse_keyword
(\
%$$) {
1654 my ($rule, $def, $negated_ref) = @_;
1656 my $params = $def->{params
};
1661 if ($$negated_ref && exists $def->{pre_negation
}) {
1663 undef $$negated_ref;
1666 unless (defined $params) {
1668 } elsif (ref $params && ref $params eq 'CODE') {
1669 $value = &$params($rule);
1670 } elsif ($params eq 'm') {
1671 $value = bless [ to_array getvalues
() ], 'multi';
1672 } elsif ($params =~ /^[a-z]/) {
1673 if (exists $def->{negation
} and not $negated) {
1674 my $token = peek_token
();
1675 if ($token eq '!') {
1676 require_next_token
();
1682 foreach my $p (split(//, $params)) {
1684 push @params, getvar
();
1685 } elsif ($p eq 'c') {
1686 my @v = to_array getvalues
(undef, non_empty
=> 1);
1687 push @params, join(',', @v);
1693 $value = @params == 1
1695 : bless \
@params, 'params';
1696 } elsif ($params == 1) {
1697 if (exists $def->{negation
} and not $negated) {
1698 my $token = peek_token
();
1699 if ($token eq '!') {
1700 require_next_token
();
1705 $value = getvalues
();
1707 warning
("log-prefix is too long; truncating to 29 characters: '$1'")
1708 if $def->{name
} eq 'log-prefix' && $value =~ s
,^(.{29}).+$,$1,;
1710 if (exists $def->{negation
} and not $negated) {
1711 my $token = peek_token
();
1712 if ($token eq '!') {
1713 require_next_token
();
1718 $value = bless [ map {
1720 } (1..$params) ], 'params';
1723 $value = negate_value
($value, exists $def->{pre_negation
} && 'pre_negated')
1729 sub append_option
(\
%$$) {
1730 my ($rule, $name, $value) = @_;
1731 push @
{$rule->{options
}}, [ $name, $value ];
1734 # parse options of a module
1735 sub parse_option
($\
%$) {
1736 my ($def, $rule, $negated_ref) = @_;
1738 append_option
(%$rule, $def->{name
},
1739 parse_keyword
(%$rule, $def, $negated_ref));
1742 sub copy_on_write
($$) {
1743 my ($rule, $key) = @_;
1744 return unless exists $rule->{cow
}{$key};
1745 $rule->{$key} = {%{$rule->{$key}}};
1746 delete $rule->{cow
}{$key};
1749 sub new_level
(\
%$) {
1750 my ($rule, $prev) = @_;
1753 if (defined $prev) {
1754 # copy data from previous level
1755 $rule->{cow
} = { keywords
=> 1, };
1756 $rule->{keywords
} = $prev->{keywords
};
1757 $rule->{match
} = { %{$prev->{match
}} };
1758 $rule->{options
} = [@
{$prev->{options
}}];
1759 foreach my $key (qw(domain domain_family domain_both table chain protocol has_rule has_action)) {
1760 $rule->{$key} = $prev->{$key}
1761 if exists $prev->{$key};
1765 $rule->{keywords
} = {};
1766 $rule->{match
} = {};
1767 $rule->{options
} = [];
1771 sub merge_keywords
(\
%$) {
1772 my ($rule, $keywords) = @_;
1773 copy_on_write
($rule, 'keywords');
1774 while (my ($name, $def) = each %$keywords) {
1775 $rule->{keywords
}{$name} = $def;
1779 sub set_domain
(\
%$) {
1780 my ($rule, $domain) = @_;
1782 return unless check_domain
($domain);
1785 unless (ref $domain) {
1786 $domain_family = $domain eq 'ip6' ?
'ip' : $domain;
1787 } elsif (@
$domain == 0) {
1788 $domain_family = 'none';
1789 } elsif (grep { not /^ip6?$/s } @
$domain) {
1790 error
('Cannot combine non-IP domains');
1792 $domain_family = 'ip';
1795 $rule->{domain_family
} = $domain_family;
1796 $rule->{keywords
} = $match_defs{$domain_family}{''}{keywords
};
1797 $rule->{cow
}{keywords
} = 1;
1799 $rule->{domain
} = $stack[0]{auto
}{DOMAIN
} = $domain;
1802 sub set_target
(\
%$$) {
1803 my ($rule, $name, $value) = @_;
1804 error
('There can only one action per rule')
1805 if exists $rule->{has_action
};
1806 $rule->{has_action
} = 1;
1807 append_option
(%$rule, $name, $value);
1810 sub set_module_target
(\
%$$) {
1811 my ($rule, $name, $defs) = @_;
1813 if ($name eq 'TCPMSS') {
1814 my $protos = $rule->{protocol
};
1815 error
('No protocol specified before TCPMSS')
1816 unless defined $protos;
1817 foreach my $proto (to_array
$protos) {
1818 error
('TCPMSS not available for protocol "$proto"')
1819 unless $proto eq 'tcp';
1823 # in ebtables, there is both "--mark" and "-j mark"... workaround:
1824 $name = 'mark' if $name eq 'MARK' and $rule->{domain_family
} eq 'eb';
1826 set_target
(%$rule, 'jump', $name);
1827 merge_keywords
(%$rule, $defs->{keywords
});
1830 # the main parser loop: read tokens, convert them into internal rule
1833 my $lev = shift; # current recursion depth
1834 my $prev = shift; # previous rule hash
1836 # enter is the core of the firewall setup, it is a
1837 # simple parser program that recognizes keywords and
1838 # retreives parameters to set up the kernel routing
1841 my $base_level = $script->{base_level
} || 0;
1842 die if $base_level > $lev;
1845 new_level
(%rule, $prev);
1847 # read keywords 1 by 1 and dump into parser
1848 while (defined (my $keyword = next_token
())) {
1849 # check if the current rule should be negated
1850 my $negated = $keyword eq '!';
1852 # negation. get the next word which contains the 'real'
1854 $keyword = getvar
();
1856 error
('unexpected end of file after negation')
1857 unless defined $keyword;
1860 # the core: parse all data
1863 # deprecated keyword?
1864 if (exists $deprecated_keywords{$keyword}) {
1865 my $new_keyword = $deprecated_keywords{$keyword};
1866 warning
("'$keyword' is deprecated, please use '$new_keyword' instead");
1867 $keyword = $new_keyword;
1870 # effectuation operator
1871 if ($keyword eq ';') {
1872 error
('Empty rule before ";" not allowed')
1873 unless $rule{non_empty
};
1875 if ($rule{has_rule
} and not exists $rule{has_action
}) {
1876 # something is wrong when a rule was specified,
1878 error
('No action defined; did you mean "NOP"?');
1881 error
('No chain defined') unless exists $rule{chain
};
1883 $rule{script
} = { filename
=> $script->{filename
},
1884 line
=> $script->{line
},
1889 # and clean up variables set in this level
1890 new_level
(%rule, $prev);
1895 # conditional expression
1896 if ($keyword eq '@if') {
1897 unless (eval_bool
(getvalues
)) {
1899 my $token = peek_token
();
1900 if ($token and $token eq '@else') {
1901 require_next_token
();
1903 new_level
(%rule, $prev);
1910 if ($keyword eq '@else') {
1911 # hack: if this "else" has not been eaten by the "if"
1912 # handler above, we believe it came from an if clause
1913 # which evaluated "true" - remove the "else" part now.
1918 # hooks for custom shell commands
1919 if ($keyword eq 'hook') {
1920 warning
("'hook' is deprecated, use '\@hook'");
1924 if ($keyword eq '@hook') {
1925 error
('"hook" must be the first token in a command')
1926 if exists $rule{domain
};
1928 my $position = getvar
();
1930 if ($position eq 'pre') {
1931 $hooks = \
@pre_hooks;
1932 } elsif ($position eq 'post') {
1933 $hooks = \
@post_hooks;
1934 } elsif ($position eq 'flush') {
1935 $hooks = \
@flush_hooks;
1937 error
("Invalid hook position: '$position'");
1940 push @
$hooks, getvar
();
1946 # recursing operators
1947 if ($keyword eq '{') {
1949 my $old_stack_depth = @stack;
1951 unshift @stack, { auto
=> { %{$stack[0]{auto
} || {}} } };
1954 enter
($lev + 1, \
%rule);
1958 die unless @stack == $old_stack_depth;
1960 # after a block, the command is finished, clear this
1962 new_level
(%rule, $prev);
1967 if ($keyword eq '}') {
1968 error
('Unmatched "}"')
1969 if $lev <= $base_level;
1971 # consistency check: check if they havn't forgotten
1972 # the ';' after the last statement
1973 error
('Missing semicolon before "}"')
1974 if $rule{non_empty
};
1980 # include another file
1981 if ($keyword eq '@include' or $keyword eq 'include') {
1982 # don't call collect_filenames() if the file names
1983 # have been expanded already by @glob()
1984 my @files = peek_token
() eq '@glob'
1985 ? to_array
(getvalues
)
1986 : collect_filenames
(to_array
(getvalues
));
1987 $keyword = next_token
;
1988 error
('Missing ";" - "include FILENAME" must be the last command in a rule')
1989 unless defined $keyword and $keyword eq ';';
1991 foreach my $filename (@files) {
1992 # save old script, open new script
1993 my $old_script = $script;
1994 open_script
($filename);
1995 $script->{base_level
} = $lev + 1;
1998 my $old_stack_depth = @stack;
2003 # include files may set variables for their parent
2004 $stack->{vars
} = ($stack[0]{vars
} ||= {});
2005 $stack->{functions
} = ($stack[0]{functions
} ||= {});
2006 $stack->{auto
} = { %{ $stack[0]{auto
} || {} } };
2009 my( $volume,$dirs,$file ) = File
::Spec
->splitpath( $filename );
2010 $stack->{auto
}{FILENAME
} = $filename;
2011 $stack->{auto
}{FILEBNAME
} = $file;
2012 $stack->{auto
}{DIRNAME
} = $dirs;
2014 unshift @stack, $stack;
2017 enter
($lev + 1, \
%rule);
2019 #check for exit status
2020 error
("'$script->{filename}': exit status is not 0") if not close $script->{handle
};
2024 die unless @stack == $old_stack_depth;
2026 # restore old script
2027 $script = $old_script;
2033 # definition of a variable or function
2034 if ($keyword eq '@def' or $keyword eq 'def') {
2035 error
('"def" must be the first token in a command')
2036 if $rule{non_empty
};
2038 my $type = require_next_token
();
2040 my $name = require_next_token
();
2041 error
('invalid variable name')
2042 unless $name =~ /^\w+$/;
2046 my $value = getvalues
(undef, allow_negation
=> 1);
2050 $stack[0]{vars
}{$name} = $value
2051 unless exists $stack[-1]{vars
}{$name};
2052 } elsif ($type eq '&') {
2053 my $name = require_next_token
();
2054 error
('invalid function name')
2055 unless $name =~ /^\w+$/;
2057 expect_token
('(', 'function parameter list or "()" expected');
2061 my $token = require_next_token
();
2062 last if $token eq ')';
2065 error
('"," expected')
2066 unless $token eq ',';
2068 $token = require_next_token
();
2071 error
('"$" and parameter name expected')
2072 unless $token eq '$';
2074 $token = require_next_token
();
2075 error
('invalid function parameter name')
2076 unless $token =~ /^\w+$/;
2078 push @params, $token;
2083 $function{params
} = \
@params;
2087 my $tokens = collect_tokens
();
2088 $function{block
} = 1 if grep { $_ eq '{' } @
$tokens;
2089 $function{tokens
} = $tokens;
2091 $stack[0]{functions
}{$name} = \
%function
2092 unless exists $stack[-1]{functions
}{$name};
2094 error
('"$" (variable) or "&" (function) expected');
2100 # this rule has something which isn't inherited by its
2101 # parent closure. This variable is used in a lot of
2104 $rule{non_empty
} = 1;
2107 if ($keyword eq '$') {
2108 error
('variable references are only allowed as keyword parameter');
2111 if ($keyword eq '&') {
2112 my $name = require_next_token
();
2113 error
('function name expected')
2114 unless $name =~ /^\w+$/;
2116 my $function = lookup_function
($name);
2117 error
("no such function: \&$name")
2118 unless defined $function;
2120 my $paramdef = $function->{params
};
2121 die unless defined $paramdef;
2123 my @params = get_function_params
(allow_negation
=> 1);
2125 error
("Wrong number of parameters for function '\&$name': "
2126 . @
$paramdef . " expected, " . @params . " given")
2127 unless @params == @
$paramdef;
2130 for (my $i = 0; $i < @params; $i++) {
2131 $vars{$paramdef->[$i]} = $params[$i];
2134 if ($function->{block
}) {
2135 # block {} always ends the current rule, so if the
2136 # function contains a block, we have to require
2137 # the calling rule also ends here
2141 my @tokens = @
{$function->{tokens
}};
2142 for (my $i = 0; $i < @tokens; $i++) {
2143 if ($tokens[$i] eq '$' and $i + 1 < @tokens and
2144 exists $vars{$tokens[$i + 1]}) {
2145 my @value = to_array
($vars{$tokens[$i + 1]});
2146 @value = ('(', @value, ')')
2147 unless @tokens == 1;
2148 splice(@tokens, $i, 2, @value);
2150 } elsif ($tokens[$i] =~ m
,^"(.*)"$,) {
2151 $tokens[$i] =~ s
,\
$(\w
+),exists $vars{$1} ?
$vars{$1} : "\$$1",eg
;
2155 unshift @
{$script->{tokens
}}, @tokens;
2160 # where to put the rule?
2161 if ($keyword eq 'domain') {
2162 error
('Domain is already specified')
2163 if exists $rule{domain
};
2165 my $domains = getvalues
();
2167 my $tokens = collect_tokens
(include_semicolon
=> 1,
2170 my $old_line = $script->{line
};
2171 my $old_handle = $script->{handle
};
2172 my $old_tokens = $script->{tokens
};
2173 my $old_base_level = $script->{base_level
};
2174 unshift @
$old_tokens, make_line_token
($script->{line
});
2175 delete $script->{handle
};
2177 for my $domain (@
$domains) {
2179 new_level
(%inner, \
%rule);
2180 set_domain
(%inner, $domain) or next;
2181 $inner{domain_both
} = 1;
2182 $script->{base_level
} = 0;
2183 $script->{tokens
} = [ @
$tokens ];
2187 $script->{base_level
} = $old_base_level;
2188 $script->{tokens
} = $old_tokens;
2189 $script->{handle
} = $old_handle;
2190 $script->{line
} = $old_line;
2192 new_level
(%rule, $prev);
2194 unless (set_domain
(%rule, $domains)) {
2196 new_level
(%rule, $prev);
2203 if ($keyword eq 'table') {
2204 warning
('Table is already specified')
2205 if exists $rule{table
};
2206 $rule{table
} = $stack[0]{auto
}{TABLE
} = getvalues
();
2208 set_domain
(%rule, $option{domain
} || 'ip')
2209 unless exists $rule{domain
};
2214 if ($keyword eq 'chain') {
2215 warning
('Chain is already specified')
2216 if exists $rule{chain
};
2218 my $chain = $rule{chain
} = $stack[0]{auto
}{CHAIN
} = getvalues
();
2220 # ferm 1.1 allowed lower case built-in chain names
2221 foreach (ref $rule{chain
} ? @
{$rule{chain
}} : $rule{chain
}) {
2222 error
('Please write built-in chain names in upper case')
2223 if /^(?:input|forward|output|prerouting|postrouting)$/;
2226 set_domain
(%rule, $option{domain
} || 'ip')
2227 unless exists $rule{domain
};
2229 $rule{table
} = 'filter'
2230 unless exists $rule{table
};
2232 my $domain = $rule{domain
};
2233 foreach my $table (to_array
$rule{table
}) {
2234 foreach my $c (to_array
$chain) {
2235 $domains{$domain}{tables
}{$table}{chains
}{$c} ||= {};
2242 error
('Chain must be specified')
2243 unless exists $rule{chain
};
2245 # policy for built-in chain
2246 if ($keyword eq 'policy') {
2247 error
('Cannot specify matches for policy')
2250 my $policy = getvar
();
2251 error
("Invalid policy target: $policy")
2252 unless is_netfilter_core_target
($policy);
2256 my $domain = $rule{domain
};
2257 my $domain_info = $domains{$domain};
2258 $domain_info->{enabled
} = 1;
2260 foreach my $table (to_array
$rule{table
}) {
2261 foreach my $chain (to_array
$rule{chain
}) {
2262 $domain_info->{tables
}{$table}{chains
}{$chain}{policy
} = $policy;
2266 new_level
(%rule, $prev);
2271 if ($keyword eq '@subchain' or $keyword eq 'subchain') {
2272 error
('Chain must be specified')
2273 unless exists $rule{chain
};
2275 error
('No rule specified before "@subchain"')
2276 unless $rule{has_rule
};
2279 my $token = peek_token
();
2281 if ($token =~ /^(["'])(.*)\1$/s) {
2284 $keyword = next_token
();
2285 } elsif ($token eq '{') {
2286 $keyword = next_token
();
2287 $subchain = 'ferm_auto_' . ++$auto_chain;
2289 $subchain = getvar
();
2290 $keyword = next_token
();
2293 my $domain = $rule{domain
};
2294 foreach my $table (to_array
$rule{table
}) {
2295 $domains{$domain}{tables
}{$table}{chains
}{$subchain} ||= {};
2298 set_target
(%rule, 'jump', $subchain);
2300 error
('"{" or chain name expected after "@subchain"')
2301 unless $keyword eq '{';
2303 # create a deep copy of %rule, only containing values
2304 # which must be in the subchain
2305 my %inner = ( cow
=> { keywords
=> 1, },
2309 $inner{$_} = $rule{$_} foreach qw(domain domain_family domain_both table keywords);
2310 $inner{chain
} = $inner{auto
}{CHAIN
} = $subchain;
2312 if (exists $rule{protocol
}) {
2313 $inner{protocol
} = $rule{protocol
};
2314 append_option
(%inner, 'protocol', $inner{protocol
});
2317 # create a new stack frame
2318 my $old_stack_depth = @stack;
2319 my $stack = { auto
=> { %{$stack[0]{auto
} || {}} } };
2320 $stack->{auto
}{CHAIN
} = $subchain;
2321 unshift @stack, $stack;
2324 enter
($lev + 1, \
%inner);
2328 die unless @stack == $old_stack_depth;
2330 # now handle the parent - it's a jump to the sub chain
2332 filename
=> $script->{filename
},
2333 line
=> $script->{line
},
2338 # and clean up variables set in this level
2339 new_level
(%rule, $prev);
2340 delete $rule{has_rule
};
2345 # everything else must be part of a "real" rule, not just
2347 $rule{has_rule
} = 1;
2349 # extended parameters:
2350 if ($keyword =~ /^mod(?:ule)?$/) {
2351 foreach my $module (to_array getvalues
) {
2352 next if exists $rule{match
}{$module};
2354 my $domain_family = $rule{domain_family
};
2355 my $defs = $match_defs{$domain_family}{$module};
2357 append_option
(%rule, 'match', $module);
2358 $rule{match
}{$module} = 1;
2360 merge_keywords
(%rule, $defs->{keywords
})
2367 # keywords from $rule{keywords}
2369 if (exists $rule{keywords
}{$keyword}) {
2370 my $def = $rule{keywords
}{$keyword};
2371 parse_option
($def, %rule, \
$negated);
2380 if ($keyword eq 'jump') {
2381 set_target
(%rule, 'jump', getvar
());
2386 if ($keyword eq 'realgoto') {
2387 set_target
(%rule, 'goto', getvar
());
2392 if (is_netfilter_core_target
($keyword)) {
2393 set_target
(%rule, 'jump', $keyword);
2397 if ($keyword eq 'NOP') {
2398 error
('There can only one action per rule')
2399 if exists $rule{has_action
};
2400 $rule{has_action
} = 1;
2404 if (my $defs = is_netfilter_module_target
($rule{domain_family
}, $keyword)) {
2405 set_module_target
(%rule, $keyword, $defs);
2410 # protocol specific options
2413 if ($keyword eq 'proto' or $keyword eq 'protocol') {
2414 my $protocol = parse_keyword
(%rule,
2415 { params
=> 1, negation
=> 1 },
2417 $rule{protocol
} = $protocol;
2418 append_option
(%rule, 'protocol', $rule{protocol
});
2420 unless (ref $protocol) {
2421 $protocol = netfilter_canonical_protocol
($protocol);
2422 my $domain_family = $rule{domain_family
};
2423 if (my $defs = $proto_defs{$domain_family}{$protocol}) {
2424 merge_keywords
(%rule, $defs->{keywords
});
2425 my $module = netfilter_protocol_module
($protocol);
2426 $rule{match
}{$module} = 1;
2433 if ($keyword =~ /^[sd]port$/) {
2434 my $proto = $rule{protocol
};
2435 error
('To use sport or dport, you have to specify "proto tcp" or "proto udp" first')
2436 unless defined $proto and grep { /^(?:tcp|udp|udplite|dccp|sctp)$/ } to_array
$proto;
2438 append_option
(%rule, $keyword,
2439 getvalues
(undef, allow_negation
=> 1));
2444 error
("Unrecognized keyword: $keyword");
2447 # if the rule didn't reset the negated flag, it's not
2449 error
("Doesn't support negation: $keyword")
2453 error
('Missing "}" at end of file')
2454 if $lev > $base_level;
2456 # consistency check: check if they havn't forgotten
2457 # the ';' before the last statement
2458 error
("Missing semicolon before end of file")
2459 if $rule{non_empty
};
2462 sub execute_command
{
2463 my ($command, $script) = @_;
2465 print LINES
"$command\n"
2467 return if $option{noexec
};
2469 my $ret = system($command);
2470 unless ($ret == 0) {
2472 print STDERR
"failed to execute: $!\n";
2474 } elsif ($?
& 0x7f) {
2475 printf STDERR
"child died with signal %d\n", $?
& 0x7f;
2478 print STDERR
"(rule declared in $script->{filename}:$script->{line})\n"
2487 sub execute_slow
($) {
2488 my $domain_info = shift;
2490 my $domain_cmd = $domain_info->{tools
}{tables
};
2493 while (my ($table, $table_info) = each %{$domain_info->{tables
}}) {
2494 my $table_cmd = "$domain_cmd -t $table";
2496 # reset chain policies
2497 while (my ($chain, $chain_info) = each %{$table_info->{chains
}}) {
2498 next unless $chain_info->{builtin
} or
2499 (not $table_info->{has_builtin
} and
2500 is_netfilter_builtin_chain
($table, $chain));
2501 $status ||= execute_command
("$table_cmd -P $chain ACCEPT")
2502 unless $option{noflush
};
2506 unless ($option{noflush
}) {
2507 $status ||= execute_command
("$table_cmd -F");
2508 $status ||= execute_command
("$table_cmd -X");
2511 next if $option{flush
};
2513 # create chains / set policy
2514 while (my ($chain, $chain_info) = each %{$table_info->{chains
}}) {
2515 if (is_netfilter_builtin_chain
($table, $chain)) {
2516 if (exists $chain_info->{policy
}) {
2517 $status ||= execute_command
("$table_cmd -P $chain $chain_info->{policy}")
2518 unless $chain_info->{policy
} eq 'ACCEPT';
2521 if (exists $chain_info->{policy
}) {
2522 $status ||= execute_command
("$table_cmd -N $chain -P $chain_info->{policy}");
2525 $status ||= execute_command
("$table_cmd -N $chain");
2531 while (my ($chain, $chain_info) = each %{$table_info->{chains
}}) {
2532 my $chain_cmd = "$table_cmd -A $chain";
2533 foreach my $rule (@
{$chain_info->{rules
}}) {
2534 $status ||= execute_command
($chain_cmd . $rule->{rule
});
2542 sub table_to_save
($$) {
2543 my ($result_r, $table_info) = @_;
2545 foreach my $chain (sort keys %{$table_info->{chains
}}) {
2546 my $chain_info = $table_info->{chains
}{$chain};
2547 foreach my $rule (@
{$chain_info->{rules
}}) {
2548 $$result_r .= "-A $chain$rule->{rule}\n";
2553 sub rules_to_save
($) {
2554 my ($domain_info) = @_;
2556 # convert this into an iptables-save text
2557 my $result = "# Generated by ferm $VERSION on " . localtime() . "\n";
2559 while (my ($table, $table_info) = each %{$domain_info->{tables
}}) {
2561 $result .= '*' . $table . "\n";
2563 # create chains / set policy
2564 foreach my $chain (sort keys %{$table_info->{chains
}}) {
2565 my $chain_info = $table_info->{chains
}{$chain};
2566 my $policy = $option{flush
} ?
undef : $chain_info->{policy
};
2567 unless (defined $policy) {
2568 if (is_netfilter_builtin_chain
($table, $chain)) {
2571 next if $option{flush
};
2575 $result .= ":$chain $policy\ [0:0]\n";
2578 table_to_save
(\
$result, $table_info)
2579 unless $option{flush
};
2582 $result .= "COMMIT\n";
2588 sub restore_domain
($$) {
2589 my ($domain_info, $save) = @_;
2591 my $path = $domain_info->{tools
}{'tables-restore'};
2592 $path .= " --noflush" if $option{noflush
};
2595 open RESTORE
, "|$path"
2596 or die "Failed to run $path: $!\n";
2598 print RESTORE
$save;
2601 or die "Failed to run $path\n";
2604 sub execute_fast
($) {
2605 my $domain_info = shift;
2607 my $save = rules_to_save
($domain_info);
2609 if ($option{lines
}) {
2610 my $path = $domain_info->{tools
}{'tables-restore'};
2611 $path .= " --noflush" if $option{noflush
};
2612 print LINES
"$path <<EOT\n"
2619 return if $option{noexec};
2622 restore_domain($domain_info, $save);
2634 while (my ($domain, $domain_info) = each %domains) {
2635 next unless $domain_info->{enabled};
2636 unless (defined $domain_info->{tools}{'tables-restore'}) {
2637 print STDERR "Cannot rollback domain
'$domain' because there is
no ${domain
}tables
-restore
\n";
2642 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2643 my $reset_chain = '';
2644 foreach my $chain (keys %{$table_info->{chains}}) {
2645 next unless is_netfilter_builtin_chain($table, $chain);
2646 $reset_chain .= ":${chain
} ACCEPT
[0:0]\n";
2648 $reset .= "*${table
}\n${reset_chain
}COMMIT
\n"
2649 if length $reset_chain;
2652 $reset .= $domain_info->{previous}
2653 if defined $domain_info->{previous};
2655 restore_domain($domain_info, $reset);
2658 print STDERR "\nFirewall rules rolled back
.\n" unless $error;
2663 # do nothing, just interrupt a system call
2667 $SIG{ALRM} = \&alrm_handler;
2672 . "ferm has applied the new firewall rules
.\n"
2673 . "Please type
'yes' to confirm
:\n";
2676 alarm($option{timeout});
2679 STDIN->sysread($line, 3);
2683 POSIX::tcflush(*STDIN, 2);
2685 print STDERR "$@
" if $@;
2687 $SIG{ALRM} = 'DEFAULT';
2689 return $line eq 'yes';
2698 ferm - a firewall rule parser for linux
2702 B<ferm> I<options> I<inputfiles>
2706 -n, --noexec Do not execute the rules, just simulate
2707 -F, --flush Flush all netfilter tables managed by ferm
2708 -l, --lines Show all rules that were created
2709 -i, --interactive Interactive mode: revert if user does not confirm
2710 -t, --timeout s Define interactive mode timeout in seconds
2711 --remote Remote mode; ignore host specific configuration.
2712 This implies --noexec and --lines.
2713 -V, --version Show current version number
2714 -h, --help Look at this text
2715 --slow Slow mode, don't use iptables-restore
2716 --shell Generate a shell script which calls iptables-restore
2717 --domain {ip|ip6} Handle only the specified domain
2718 --def '$name=v' Override a variable