redirect bug reports & patches to GitHub
[ferm.git] / src / ferm
blob6dbd08531082dab2df6bfd779f5d8ae9230bff9e
1 #!/usr/bin/perl
4 # ferm, a firewall setup program that makes firewall rules easy!
6 # Copyright (C) 2001-2012 Max Kellermann, Auke Kok
8 # 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,
26 # MA 02110-1301 USA.
29 # $Id$
31 use File::Spec;
33 BEGIN {
34 eval { require strict; import strict; };
35 $has_strict = not $@;
36 if ($@) {
37 # we need no vars.pm if there is not even strict.pm
38 $INC{'vars.pm'} = 1;
39 *vars::import = sub {};
40 } else {
41 require IO::Handle;
44 eval { require Getopt::Long; import Getopt::Long; };
45 $has_getopt = not $@;
48 use vars qw($has_strict $has_getopt);
50 use vars qw($VERSION);
52 $VERSION = '2.3.1';
53 $VERSION .= '~git';
55 ## interface variables
56 # %option = command line and other options
57 use vars qw(%option);
59 ## hooks
60 use vars qw(@pre_hooks @post_hooks @flush_hooks);
62 ## parser variables
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);
79 ## constants
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
101 # this is).
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
107 # array)
109 # foo*0 option without any arguments
111 # foo=s one argument which must not be a ferm array ('s' stands for
112 # 'scalar')
114 # u32=m an array which renders into multiple iptables options in one
115 # rule
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
126 # the argument
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
131 # parameters
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
138 sub open_script($);
139 sub resolve($\@$);
140 sub enter($$);
141 sub rollback();
142 sub execute_fast($);
143 sub execute_slow($);
144 sub join_value($$);
145 sub ipfilter($@);
147 # add a module definition
148 sub add_def_x {
149 my $defs = shift;
150 my $domain_family = shift;
151 my $params_default = shift;
152 my $name = shift;
153 die if exists $defs->{$domain_family}{$name};
154 my $def = $defs->{$domain_family}{$name} = {};
155 foreach (@_) {
156 my $keyword = $_;
157 my $k;
159 if ($keyword =~ s,:=(\S+)$,,) {
160 $k = $def->{keywords}{$1} || die;
161 $k->{ferm_name} ||= $keyword;
162 } else {
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";
168 die $@ if $@;
171 $k = {};
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;
182 return $def;
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', @_);
203 sub add_def {
204 my $defs = shift;
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();
230 add_match_def '',
231 # --source, --destination
232 qw(source!&address_magic saddr:=source),
233 qw(destination!&address_magic daddr:=destination),
234 # --in-interface
235 qw(in-interface! interface:=in-interface if:=in-interface),
236 # --out-interface
237 qw(out-interface! outerface:=out-interface of:=out-interface),
238 # --fragment
239 qw(!fragment*0);
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', '',
357 # ip
358 qw(source-ip! destination-ip! saddr:=source-ip daddr:=destination-ip),
359 # mac
360 qw(source-mac! destination-mac!),
361 # --in-interface
362 qw(in-interface! interface:=in-interface if:=in-interface),
363 # --out-interface
364 qw(out-interface! outerface:=out-interface of:=out-interface),
365 # misc
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),
371 qw(ip-tos!),
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),
378 qw(ip6-tclass!),
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', '',
397 # --in-interface
398 qw(in-interface! interface:=in-interface if:=in-interface),
399 # --out-interface
400 qw(out-interface! outerface:=out-interface of:=out-interface),
401 # logical interface
402 qw(logical-in! logical-out!),
403 # --source, --destination
404 qw(source! saddr:=source destination! daddr:=destination),
405 # 802.3
406 qw(802_3-sap! 802_3-type!),
407 # among
408 qw(!among-dst=c !among-src=c !among-dst-file !among-src-file),
409 # limit
410 qw(limit=s limit-burst=s),
411 # mark_m
412 qw(mark!),
413 # pkttype
414 qw(pkttype-type!),
415 # stp
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!),
419 # log
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 {
433 my $rule = shift;
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
438 # array elements
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') {
447 my @value = @$value;
448 my @params;
450 while (@value) {
451 push @params, join(',', splice(@value, 0, 15));
454 return @params == 1
455 ? $params[0]
456 : \@params;
457 } else {
458 return join_value(',', $value);
462 sub ipfilter($@) {
463 my $domain = shift;
464 my @ips;
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 } @_;
471 return @ips;
474 sub address_magic {
475 my $rule = shift;
476 my $domain = $rule->{domain};
477 my $value = getvalues(undef, allow_negation => 1);
479 my @ips;
480 my $negated = 0;
481 if (ref $value and ref $value eq 'ARRAY') {
482 @ips = @$value;
483 } elsif (ref $value and ref $value eq 'negated') {
484 @ips = @$value;
485 $negated = 1;
486 } elsif (ref $value) {
487 die;
488 } else {
489 @ips = ($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';
498 } else {
499 return \@ips;
503 # initialize stack: command line definitions
504 unshift @stack, {};
506 # Get command line stuff
507 if ($has_getopt) {
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,
511 $opt_domain);
513 Getopt::Long::Configure('bundling', 'auto_help', 'no_ignore_case',
514 'no_auto_abbrev');
516 sub opt_def {
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'
524 if @$tokens > 0;
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,
537 test => \$opt_test,
538 remote => \$opt_test,
539 fast => \$opt_fast,
540 slow => \$opt_slow,
541 shell => \$opt_shell,
542 'domain=s' => \$opt_domain,
543 'def=s' => \&opt_def,
546 if (defined $opt_help) {
547 require Pod::Usage;
548 Pod::Usage::pod2usage(-exitstatus => 0);
551 if (defined $opt_version) {
552 printversion();
553 exit 0;
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;
576 } else {
577 # tiny getopt emulation for microperl
578 my $filename;
579 foreach (@ARGV) {
580 if ($_ eq '--noexec' or $_ eq '-n') {
581 $option{noexec} = 1;
582 } elsif ($_ eq '--lines' or $_ eq '-l') {
583 $option{lines} = 1;
584 } elsif ($_ eq '--fast') {
585 $option{fast} = 1;
586 } elsif ($_ eq '--test') {
587 $option{test} = 1;
588 $option{noexec} = 1;
589 $option{lines} = 1;
590 } elsif ($_ eq '--shell') {
591 $option{$_} = 1 foreach qw(shell fast lines);
592 } elsif (/^-/) {
593 printf STDERR "Usage: ferm [--noexec] [--lines] [--fast] [--shell] FILENAME\n";
594 exit 1;
595 } else {
596 $filename = $_;
599 undef @ARGV;
600 push @ARGV, $filename;
603 unless (@ARGV == 1) {
604 require Pod::Usage;
605 Pod::Usage::pod2usage(-exitstatus => 1);
608 if ($has_strict) {
609 open LINES, ">&STDOUT" if $option{lines};
610 open STDOUT, ">&STDERR" if $option{shell};
611 } else {
612 # microperl can't redirect file handles
613 *LINES = *STDOUT;
615 if ($option{fast} and not $option{noexec}) {
616 print STDERR "Sorry, ferm on microperl does not allow --fast without --noexec\n";
617 exit 1
621 unshift @stack, {};
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
632 enter(0, undef);
633 die unless @stack == 2;
635 # enable/disable hooks depending on --flush
637 if ($option{flush}) {
638 undef @pre_hooks;
639 undef @post_hooks;
640 } else {
641 undef @flush_hooks;
644 # execute all generated rules
645 my $status;
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) {
666 rollback();
667 exit $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};
687 exit 0;
689 # end of program execution!
692 # funcs
694 sub printversion {
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";
702 sub error {
703 # returns a nice formatted error message, showing the
704 # location of the error.
705 my $tabs = 0;
706 my @lines;
707 my $l = 0;
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";
740 die("@_\n");
743 # print a warning message about code from an input file
744 sub warning {
745 print STDERR "Warning in $script->{filename} line $script->{line}: "
746 . (shift) . "\n";
749 sub find_tool($) {
750 my $name = shift;
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 {
760 my $domain = shift;
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
778 local *SAVE;
779 if (!$option{test} &&
780 exists $tools{'tables-save'} &&
781 open(SAVE, "$tools{'tables-save'}|")) {
782 my $save = '';
784 my $table_info;
785 while (<SAVE>) {
786 $save .= $_;
788 if (/^\*(\w+)/) {
789 my $table = $1;
790 $table_info = $domain_info->{tables}{$table} ||= {};
791 } elsif (defined $table_info and /^:(\w+)\s+(\S+)/
792 and $2 ne '-') {
793 $table_info->{chains}{$1}{builtin} = 1;
794 $table_info->{has_builtin} = 1;
798 # for rollback
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($) {
812 my $domain = shift;
813 my @result;
815 return if exists $option{domain}
816 and $domain ne $option{domain};
818 eval {
819 initialize_domain($domain);
821 error($@) if $@;
823 return 1;
826 # split the input string into words and delete comments
827 sub tokenize_string($) {
828 my $string = shift;
830 my @ret;
832 foreach my $word ($string =~ m/(".*?"|'.*?'|`.*?`|[!,=&\$\%\(\){};]|[-+\w\/\.:]+|@\w+|#)/g) {
833 last if $word eq '#';
834 push @ret, $word;
837 return \@ret;
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($) {
844 my $line = shift;
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)};
863 return 1;
866 sub handle_special_token($) {
867 my $token = shift;
868 die unless ref $token;
869 if (ref $token eq 'line') {
870 $script->{line} = $$token;
871 } else {
872 die;
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};
886 while (1) {
887 handle_special_tokens();
888 return 1 if @$tokens > 0;
889 return unless prepare_tokens();
893 # open a ferm sub script
894 sub open_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;
902 my $handle;
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()
906 $handle = *STDIN;
907 # also set a filename label so that error messages are more helpful
908 $filename = "<stdin>";
909 } else {
910 local *FILE;
911 open FILE, "$filename" or die("Failed to open $filename: $!\n");
912 $handle = *FILE;
915 $script = { filename => $filename,
916 handle => $handle,
917 line => 0,
918 past_tokens => [],
919 tokens => [],
920 parent => $script,
923 return $script;
926 # collect script filenames which are being included
927 sub collect_filenames(@) {
928 my @ret;
930 # determine the current script's parent directory for relative
931 # file names
932 die unless defined $script;
933 my $parent_dir = $script->{filename} =~ m,^(.*/),
934 ? $1 : './';
936 foreach my $pathname (@_) {
937 # non-absolute file names are relative to the parent script's
938 # file name
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")
946 unless -d $pathname;
948 local *DIR;
949 opendir DIR, $pathname
950 or error("Failed to open directory '$pathname': $!");
951 my @names = readdir DIR;
952 closedir 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;
962 push @ret, $filename
963 if -f $filename;
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');
970 } else {
971 # include a regular file
973 error("'$pathname' is a directory; maybe use trailing '/' to include a directory?")
974 if -d $pathname;
975 error("'$pathname' is not a file")
976 unless -f $pathname;
978 push @ret, $pathname;
982 return @ret;
985 # peek a token from the queue, but don't remove it
986 sub peek_token() {
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
998 sub next_token() {
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 '}') {
1010 pop @$past_tokens;
1011 $past_tokens->[-1] = $past_tokens->[-1][0] eq '{'
1012 ? [ '{' ] : []
1013 if @$past_tokens > 0;
1017 push @$past_tokens, [] if $token eq '{' or @$past_tokens == 0;
1018 push @{$past_tokens->[-1]}, $token;
1020 # return
1021 return $token;
1024 sub expect_token($;$) {
1025 my $expect = shift;
1026 my $msg = shift;
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 =~ /^[;{}]$/;
1045 return $token;
1048 # return the value of a variable
1049 sub variable_value($) {
1050 my $name = shift;
1052 if ($name eq "LINE") {
1053 return $script->{line};
1056 foreach (@stack) {
1057 return $_->{vars}{$name}
1058 if exists $_->{vars}{$name};
1061 return $stack[0]{auto}{$name}
1062 if exists $stack[0]{auto}{$name};
1064 return;
1067 # determine the value of a variable, die if the value is an array
1068 sub string_variable_value($) {
1069 my $name = shift;
1070 my $value = variable_value($name);
1072 error("variable '$name' must be a string, but it is an array")
1073 if ref $value;
1075 return $value;
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) {
1084 return $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';
1091 } else {
1092 die;
1096 sub negate_value($$;$) {
1097 my ($value, $class, $allow_array) = @_;
1099 if (ref $value) {
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;
1114 sub resolve($\@$) {
1115 my ($resolver, $names, $type) = @_;
1117 my @result;
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;
1123 next;
1126 my $query = $resolver->search($hostname, $type);
1127 error("DNS query for '$hostname' failed: " . $resolver->errorstring)
1128 unless $query;
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;
1137 } else {
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';
1148 return @result;
1151 sub lookup_function($) {
1152 my $name = shift;
1154 foreach (@stack) {
1155 return $_->{functions}{$name}
1156 if exists $_->{functions}{$name};
1159 return;
1162 # returns the next parameter, which may either be a scalar or an array
1163 sub getvalues {
1164 my $code = shift;
1165 my %options = @_;
1167 my $token = require_next_token($code);
1169 if ($token eq '(') {
1170 # read an array until ")"
1171 my @wordlist;
1173 for (;;) {
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');
1183 next;
1186 push @wordlist, $token;
1187 } elsif (ref $token eq 'ARRAY') {
1188 push @wordlist, @$token;
1189 } else {
1190 error('unknown token type');
1194 error('empty array not allowed here')
1195 unless @wordlist or not $options{non_empty};
1197 return @wordlist == 1
1198 ? $wordlist[0]
1199 : \@wordlist;
1200 } elsif ($token =~ /^\`(.*)\`$/s) {
1201 # execute a shell command, insert output
1202 my $command = $1;
1203 my $output = `$command`;
1204 unless ($? == 0) {
1205 if ($? == -1) {
1206 error("failed to execute: $!");
1207 } elsif ($? & 0x7f) {
1208 error("child died with signal " . ($? & 0x7f));
1209 } elsif ($? >> 8) {
1210 error("child exited with status " . ($? >> 8));
1214 # remove comments
1215 $output =~ s/#.*//mg;
1217 # tokenize
1218 my @tokens = grep { length } split /\s+/s, $output;
1220 my @values;
1221 while (@tokens) {
1222 my $value = getvalues(sub { shift @tokens });
1223 push @values, to_array($value);
1226 # and recurse
1227 return @values == 1
1228 ? $values[0]
1229 : \@values;
1230 } elsif ($token =~ /^\'(.*)\'$/s) {
1231 # single quotes: a string
1232 return $1;
1233 } elsif ($token =~ /^\"(.*)\"$/s) {
1234 # double quotes: a string with escapes
1235 $token = $1;
1236 $token =~ s,\$(\w+),string_variable_value($1),eg;
1237 return $token;
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 ',') {
1246 return $token
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;
1262 return $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')
1274 if $@;
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();
1284 if ($type eq '$') {
1285 my $name = require_next_token();
1286 error('variable name expected')
1287 unless $name =~ /^\w+$/;
1288 expect_token(')');
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+$/;
1294 expect_token(')');
1295 return defined lookup_function($name);
1296 } else {
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') {
1312 my $value = '';
1313 map {
1314 error('String expected') if ref $_;
1315 $value .= $_;
1316 } get_function_params();
1317 return $value;
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] );
1333 return $file;
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] );
1339 return $path;
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
1345 # file names
1346 die unless defined $script;
1347 my $parent_dir = $script->{filename} =~ m,^(.*/),
1348 ? $1 : './';
1350 my @result = map {
1351 my $path = $_;
1352 $path = $parent_dir . $path unless $path =~ m,^/,;
1353 glob($path);
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]));
1362 return \@ips;
1363 } else {
1364 error("unknown ferm built-in function");
1366 } else {
1367 return $token;
1371 # returns the next parameter, but only allow a scalar
1372 sub getvar() {
1373 my $token = getvalues();
1375 error('array not allowed here')
1376 if ref $token and ref $token eq 'ARRAY';
1378 return $token;
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();
1387 return;
1390 my @params;
1392 while (1) {
1393 if (@params > 0) {
1394 $token = require_next_token();
1395 last
1396 if $token eq ')';
1398 error('"," expected')
1399 unless $token eq ',';
1402 push @params, getvalues(undef, @_);
1405 return @params;
1408 # collect all tokens in a flat array reference until the end of the
1409 # command is reached
1410 sub collect_tokens {
1411 my %options = @_;
1413 my @level;
1414 my @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});
1420 while (1) {
1421 my $keyword = next_raw_token();
1422 error('unexpected end of file within function/variable declaration')
1423 unless defined $keyword;
1425 if (ref $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';
1444 last;
1447 push @tokens, $keyword;
1449 last
1450 if $keyword eq '}' and @level == 0;
1453 return \@tokens;
1457 # returns the specified value as an array. dereference arrayrefs
1458 sub to_array($) {
1459 my $value = shift;
1460 die unless wantarray;
1461 die if @_;
1462 unless (ref $value) {
1463 return $value;
1464 } elsif (ref $value eq 'ARRAY') {
1465 return @$value;
1466 } else {
1467 die;
1471 # evaluate the specified value as bool
1472 sub eval_bool($) {
1473 my $value = shift;
1474 die if wantarray;
1475 die if @_;
1476 unless (ref $value) {
1477 return $value;
1478 } elsif (ref $value eq 'ARRAY') {
1479 return @$value > 0;
1480 } else {
1481 die;
1485 sub is_netfilter_core_target($) {
1486 my $target = shift;
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($) {
1508 my $proto = shift;
1509 return 'icmp'
1510 if $proto eq 'ipv6-icmp' or $proto eq 'icmpv6';
1511 return 'mh'
1512 if $proto eq 'ipv6-mh';
1513 return $proto;
1516 sub netfilter_protocol_module($) {
1517 my $proto = shift;
1518 return unless defined $proto;
1519 return 'icmp6'
1520 if $proto eq 'icmpv6';
1521 return $proto;
1524 # escape the string in a way safe for the shell
1525 sub shell_escape($) {
1526 my $token = shift;
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
1533 # here
1535 $token =~ s,",\\",g;
1536 $token = '"' . $token . '"'
1537 if $token =~ /[\s\'\\;&]/s or length($token) == 0;
1538 } else {
1539 return $token
1540 if $token =~ /^\`.*\`$/;
1541 $token =~ s/'/'\\''/g;
1542 $token = '\'' . $token . '\''
1543 if $token =~ /[\s\"\\;<>&|]/s or length($token) == 0;
1546 return $token;
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) = @_;
1554 my $cmd = '';
1555 if (ref $value) {
1556 if ((ref $value eq 'negated') || (ref $value eq 'pre_negated')) {
1557 $value = $value->[0];
1558 $cmd = ' !';
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') {
1569 foreach (@$value) {
1570 $cmd .= " --$keyword " . shell_escape($_);
1572 } else {
1573 die;
1575 } else {
1576 $cmd .= " --$keyword " . shell_escape($value);
1579 return $cmd;
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') {
1590 my %icmp_map = (
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},
1613 sub unfold_rule {
1614 my ($domain, $chain_rules, $rule) = (shift, shift, shift);
1615 return append_rule($chain_rules, $rule) unless @_;
1617 my $option = shift;
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, @_);
1626 sub mkrules2($$$) {
1627 my ($domain, $chain_rules, $rule) = @_;
1629 my @unfold;
1630 foreach my $option (@{$rule->{options}}) {
1631 if (ref $option->[1] and ref $option->[1] eq 'ARRAY') {
1632 push @unfold, $option
1633 } else {
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
1643 sub mkrules($) {
1644 my $rule = shift;
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};
1667 my $value;
1669 my $negated;
1670 if ($$negated_ref && exists $def->{pre_negation}) {
1671 $negated = 1;
1672 undef $$negated_ref;
1675 unless (defined $params) {
1676 undef $value;
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();
1686 $negated = 1;
1690 my @params;
1691 foreach my $p (split(//, $params)) {
1692 if ($p eq 's') {
1693 push @params, getvar();
1694 } elsif ($p eq 'c') {
1695 my @v = to_array getvalues(undef, non_empty => 1);
1696 push @params, join(',', @v);
1697 } else {
1698 die;
1702 $value = @params == 1
1703 ? $params[0]
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();
1710 $negated = 1;
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,;
1718 } else {
1719 if (exists $def->{negation} and not $negated) {
1720 my $token = peek_token();
1721 if ($token eq '!') {
1722 require_next_token();
1723 $negated = 1;
1727 $value = bless [ map {
1728 getvar()
1729 } (1..$params) ], 'params';
1732 $value = negate_value($value, exists $def->{pre_negation} && 'pre_negated')
1733 if $negated;
1735 return $value;
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) = @_;
1761 %$rule = ();
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};
1772 } else {
1773 $rule->{cow} = {};
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);
1793 my $domain_family;
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');
1800 } else {
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
1840 # structures
1841 sub enter($$) {
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
1848 # chains
1850 my $base_level = $script->{base_level} || 0;
1851 die if $base_level > $lev;
1853 my %rule;
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 '!';
1860 if ($negated) {
1861 # negation. get the next word which contains the 'real'
1862 # rule
1863 $keyword = getvar();
1865 error('unexpected end of file after negation')
1866 unless defined $keyword;
1869 # the core: parse all data
1870 for ($keyword)
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,
1886 # but no action
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},
1896 mkrules(\%rule);
1898 # and clean up variables set in this level
1899 new_level(%rule, $prev);
1901 next;
1904 # conditional expression
1905 if ($keyword eq '@if') {
1906 unless (eval_bool(getvalues)) {
1907 collect_tokens;
1908 my $token = peek_token();
1909 if ($token and $token eq '@else') {
1910 require_next_token();
1911 } else {
1912 new_level(%rule, $prev);
1916 next;
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.
1923 collect_tokens;
1924 next;
1927 # hooks for custom shell commands
1928 if ($keyword eq 'hook') {
1929 warning("'hook' is deprecated, use '\@hook'");
1930 $keyword = '@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();
1938 my $hooks;
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;
1945 } else {
1946 error("Invalid hook position: '$position'");
1949 push @$hooks, getvar();
1951 expect_token(';');
1952 next;
1955 # recursing operators
1956 if ($keyword eq '{') {
1957 # push stack
1958 my $old_stack_depth = @stack;
1960 unshift @stack, { auto => { %{$stack[0]{auto} || {}} } };
1962 # recurse
1963 enter($lev + 1, \%rule);
1965 # pop stack
1966 shift @stack;
1967 die unless @stack == $old_stack_depth;
1969 # after a block, the command is finished, clear this
1970 # level
1971 new_level(%rule, $prev);
1973 next;
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};
1985 # and exit
1986 return;
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;
2006 # push stack
2007 my $old_stack_depth = @stack;
2009 my $stack = {};
2011 if (@stack > 0) {
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;
2025 # parse the script
2026 enter($lev + 1, \%rule);
2028 #check for exit status
2029 error("'$script->{filename}': exit status is not 0") if not close $script->{handle};
2031 # pop stack
2032 shift @stack;
2033 die unless @stack == $old_stack_depth;
2035 # restore old script
2036 $script = $old_script;
2039 next;
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();
2048 if ($type eq '$') {
2049 my $name = require_next_token();
2050 error('invalid variable name')
2051 unless $name =~ /^\w+$/;
2053 expect_token('=');
2055 my $value = getvalues(undef, allow_negation => 1);
2057 expect_token(';');
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');
2068 my @params;
2069 while (1) {
2070 my $token = require_next_token();
2071 last if $token eq ')';
2073 if (@params > 0) {
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;
2090 my %function;
2092 $function{params} = \@params;
2094 expect_token('=');
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};
2102 } else {
2103 error('"$" (variable) or "&" (function) expected');
2106 next;
2109 # this rule has something which isn't inherited by its
2110 # parent closure. This variable is used in a lot of
2111 # syntax checks.
2113 $rule{non_empty} = 1;
2115 # def references
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;
2138 my %vars;
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
2147 expect_token(';');
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);
2158 $i += @value - 2;
2159 } elsif ($tokens[$i] =~ m,^"(.*)"$,) {
2160 $tokens[$i] =~ s,\$(\w+),exists $vars{$1} ? $vars{$1} : "\$$1",eg;
2164 unshift @{$script->{tokens}}, @tokens;
2166 next;
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();
2175 if (ref $domains) {
2176 my $tokens = collect_tokens(include_semicolon => 1,
2177 include_else => 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) {
2187 my %inner;
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 ];
2193 enter(0, \%inner);
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);
2202 } else {
2203 unless (set_domain(%rule, $domains)) {
2204 collect_tokens();
2205 new_level(%rule, $prev);
2209 next;
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};
2220 next;
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} ||= {};
2248 next;
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')
2257 if $rule{has_rule};
2259 my $policy = getvar();
2260 error("Invalid policy target: $policy")
2261 unless is_netfilter_core_target($policy);
2263 expect_token(';');
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);
2276 next;
2279 # create a subchain
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};
2291 my $subchain;
2292 my $token = peek_token();
2294 if ($token =~ /^(["'])(.*)\1$/s) {
2295 $subchain = $2;
2296 next_token();
2297 $keyword = next_token();
2298 } elsif ($token eq '{') {
2299 $keyword = next_token();
2300 $subchain = 'ferm_auto_' . ++$auto_chain;
2301 } else {
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, },
2319 match => {},
2320 options => [],
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;
2336 # enter the block
2337 enter($lev + 1, \%inner);
2339 # pop stack frame
2340 shift @stack;
2341 die unless @stack == $old_stack_depth;
2343 # now handle the parent - it's a jump to the sub chain
2344 $rule{script} = {
2345 filename => $script->{filename},
2346 line => $script->{line},
2349 mkrules(\%rule);
2351 # and clean up variables set in this level
2352 new_level(%rule, $prev);
2353 delete $rule{has_rule};
2355 next;
2358 # everything else must be part of a "real" rule, not just
2359 # "policy only"
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})
2374 if defined $defs;
2377 next;
2380 # keywords from $rule{keywords}
2382 if (exists $rule{keywords}{$keyword}) {
2383 my $def = $rule{keywords}{$keyword};
2384 parse_option($def, %rule, \$negated);
2385 next;
2389 # actions
2392 # jump action
2393 if ($keyword eq 'jump') {
2394 set_target(%rule, 'jump', getvar());
2395 next;
2398 # goto action
2399 if ($keyword eq 'goto') {
2400 set_target(%rule, 'goto', getvar());
2401 next;
2404 # action keywords
2405 if (is_netfilter_core_target($keyword)) {
2406 set_target(%rule, 'jump', $keyword);
2407 next;
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;
2414 next;
2417 if (my $defs = is_netfilter_module_target($rule{domain_family}, $keyword)) {
2418 set_module_target(%rule, $keyword, $defs);
2419 next;
2423 # protocol specific options
2426 if ($keyword eq 'proto' or $keyword eq 'protocol') {
2427 my $protocol = parse_keyword(%rule,
2428 { params => 1, negation => 1 },
2429 \$negated);
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;
2442 next;
2445 # port switches
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));
2453 next;
2456 # default
2457 error("Unrecognized keyword: $keyword");
2460 # if the rule didn't reset the negated flag, it's not
2461 # supported
2462 error("Doesn't support negation: $keyword")
2463 if $negated;
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"
2479 if $option{lines};
2480 return if $option{noexec};
2482 my $ret = system($command);
2483 unless ($ret == 0) {
2484 if ($? == -1) {
2485 print STDERR "failed to execute: $!\n";
2486 exit 1;
2487 } elsif ($? & 0x7f) {
2488 printf STDERR "child died with signal %d\n", $? & 0x7f;
2489 return 1;
2490 } else {
2491 print STDERR "(rule declared in $script->{filename}:$script->{line})\n"
2492 if defined $script;
2493 return $? >> 8;
2497 return;
2500 sub execute_slow($) {
2501 my $domain_info = shift;
2503 my $domain_cmd = $domain_info->{tools}{tables};
2505 my $status;
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};
2518 # clear
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';
2533 } else {
2534 if (exists $chain_info->{policy}) {
2535 $status ||= execute_command("$table_cmd -N $chain -P $chain_info->{policy}");
2537 else {
2538 $status ||= execute_command("$table_cmd -N $chain");
2543 # dump rules
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});
2552 return $status;
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}}) {
2573 # select table
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)) {
2582 $policy = 'ACCEPT';
2583 } else {
2584 next if $option{flush};
2585 $policy = '-';
2588 $result .= ":$chain $policy\ [0:0]\n";
2591 table_to_save(\$result, $table_info)
2592 unless $option{flush};
2594 # do it
2595 $result .= "COMMIT\n";
2598 return $result;
2601 sub restore_domain($$) {
2602 my ($domain_info, $save) = @_;
2604 my $path = $domain_info->{tools}{'tables-restore'};
2605 $path .= " --noflush" if $option{noflush};
2607 local *RESTORE;
2608 open RESTORE, "|$path"
2609 or die "Failed to run $path: $!\n";
2611 print RESTORE $save;
2613 close RESTORE
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"
2626 if $option{shell};
2627 print LINES $save;
2628 print LINES "EOT\n"
2629 if $option{shell};
2632 return if $option{noexec};
2634 eval {
2635 restore_domain($domain_info, $save);
2637 if ($@) {
2638 print STDERR $@;
2639 return 1;
2642 return;
2645 sub rollback() {
2646 my $error;
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";
2651 next;
2654 my $reset = '';
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;
2672 exit 1;
2675 sub alrm_handler {
2676 # do nothing, just interrupt a system call
2679 sub confirm_rules {
2680 $SIG{ALRM} = \&alrm_handler;
2682 alarm(5);
2684 print STDERR "\n"
2685 . "ferm has applied the new firewall rules.\n"
2686 . "Please type 'yes' to confirm:\n";
2687 STDERR->flush();
2689 alarm($option{timeout});
2691 my $line = '';
2692 STDIN->sysread($line, 3);
2694 eval {
2695 require POSIX;
2696 POSIX::tcflush(*STDIN, 2);
2698 print STDERR "$@" if $@;
2700 $SIG{ALRM} = 'DEFAULT';
2702 return $line eq 'yes';
2705 # end of ferm
2707 __END__
2709 =head1 NAME
2711 ferm - a firewall rule parser for linux
2713 =head1 SYNOPSIS
2715 B<ferm> I<options> I<inputfiles>
2717 =head1 OPTIONS
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
2733 =cut