support recent/mask
[ferm.git] / src / ferm
blob3ac1fe45a7287150ca19b5782fd2d4e91d0add1e
1 #!/usr/bin/perl
4 # ferm, a firewall setup program that makes firewall rules easy!
6 # Copyright 2001-2017 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.2';
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 'devgroup', qw(!src-group !dst-group);
255 add_match_def 'dscp', qw(dscp dscp-class);
256 add_match_def 'dst', qw(!dst-len=s dst-opts=c);
257 add_match_def 'ecn', qw(ecn-tcp-cwr*0 ecn-tcp-ece*0 ecn-ip-ect);
258 add_match_def 'esp', qw(espspi!);
259 add_match_def 'eui64';
260 add_match_def 'fuzzy', qw(lower-limit=s upper-limit=s);
261 add_match_def 'geoip', qw(!src-cc=s !dst-cc=s);
262 add_match_def 'hbh', qw(hbh-len! hbh-opts=c);
263 add_match_def 'helper', qw(helper);
264 add_match_def 'hl', qw(hl-eq! hl-lt=s hl-gt=s);
265 add_match_def 'hashlimit', qw(hashlimit=s hashlimit-burst=s hashlimit-mode=c hashlimit-name=s),
266 qw(hashlimit-upto=s hashlimit-above=s),
267 qw(hashlimit-srcmask=s hashlimit-dstmask=s),
268 qw(hashlimit-htable-size=s hashlimit-htable-max=s),
269 qw(hashlimit-htable-expire=s hashlimit-htable-gcinterval=s);
270 add_match_def 'iprange', qw(!src-range !dst-range);
271 add_match_def 'ipv4options', qw(ssrr*0 lsrr*0 no-srr*0 !rr*0 !ts*0 !ra*0 !any-opt*0);
272 add_match_def 'ipv6header', qw(header!=c soft*0);
273 add_match_def 'ipvs', qw(!ipvs*0 !vproto !vaddr !vport vdir !vportctl);
274 add_match_def 'length', qw(length!);
275 add_match_def 'limit', qw(limit=s limit-burst=s);
276 add_match_def 'mac', qw(mac-source!);
277 add_match_def 'mark', qw(!mark);
278 add_match_def 'multiport', qw(source-ports!&multiport_params),
279 qw(destination-ports!&multiport_params ports!&multiport_params);
280 add_match_def 'nth', qw(every counter start packet);
281 add_match_def 'osf', qw(!genre ttl=s log=s);
282 add_match_def 'owner', qw(!uid-owner !gid-owner pid-owner sid-owner),
283 qw(cmd-owner !socket-exists=0);
284 add_match_def 'physdev', qw(physdev-in! physdev-out!),
285 qw(!physdev-is-in*0 !physdev-is-out*0 !physdev-is-bridged*0);
286 add_match_def 'pkttype', qw(pkt-type!),
287 add_match_def 'policy',
288 qw(dir pol strict*0 !reqid !spi !proto !mode !tunnel-src !tunnel-dst next*0);
289 add_match_def 'psd', qw(psd-weight-threshold psd-delay-threshold),
290 qw(psd-lo-ports-weight psd-hi-ports-weight);
291 add_match_def 'quota', qw(quota=s);
292 add_match_def 'random', qw(average);
293 add_match_def 'realm', qw(realm!);
294 add_match_def 'recent', qw(name=s !set*0 !remove*0 !rcheck*0 !update*0 !seconds !hitcount rttl*0 rsource*0 rdest*0 mask*0);
295 add_match_def 'rpfilter', qw(loose*0 validmark*0 accept-local*0 invert*0);
296 add_match_def 'rt', qw(rt-type! rt-segsleft! rt-len! rt-0-res*0 rt-0-addrs=c rt-0-not-strict*0);
297 add_match_def 'set', qw(!match-set=sc set:=match-set return-nomatch*0 !update-counters*0 !update-subcounters*0 !packets-eq=s packets-lt=s packets-gt=s !bytes-eq=s bytes-lt=s bytes-gt=s);
298 add_match_def 'socket', qw(transparent*0 nowildcard*0 restore-skmark*0);
299 add_match_def 'state', qw(!state=c);
300 add_match_def 'statistic', qw(mode=s probability=s every=s packet=s);
301 add_match_def 'string', qw(algo=s from=s to=s string hex-string);
302 add_match_def 'tcpmss', qw(!mss);
303 add_match_def 'time', qw(timestart=s timestop=s days=c datestart=s datestop=s),
304 qw(!monthday=c !weekdays=c utc*0 localtz*0);
305 add_match_def 'tos', qw(!tos);
306 add_match_def 'ttl', qw(ttl-eq ttl-lt=s ttl-gt=s);
307 add_match_def 'u32', qw(!u32=m);
309 add_target_def 'AUDIT', qw(type);
310 add_target_def 'BALANCE', qw(to-destination to:=to-destination);
311 add_target_def 'CHECKSUM', qw(checksum-fill*0);
312 add_target_def 'CLASSIFY', qw(set-class);
313 add_target_def 'CLUSTERIP', qw(new*0 hashmode clustermac total-nodes local-node hash-init);
314 add_target_def 'CONNMARK', qw(set-xmark save-mark*0 restore-mark*0 nfmask ctmask),
315 qw(and-mark or-mark xor-mark set-mark mask);
316 add_target_def 'CONNSECMARK', qw(save*0 restore*0);
317 add_target_def 'CT', qw(notrack*0 helper ctevents=c expevents=c zone timeout);
318 add_target_def 'DNAT', qw(to-destination=m to:=to-destination persistent*0 random*0);
319 add_target_def 'DNPT', qw(src-pfx dst-pfx);
320 add_target_def 'DSCP', qw(set-dscp set-dscp-class);
321 add_target_def 'ECN', qw(ecn-tcp-remove*0);
322 add_target_def 'HL', qw(hl-set hl-dec hl-inc);
323 add_target_def 'HMARK', qw(hmark-tuple hmark-mod hmark-offset),
324 qw(hmark-src-prefix hmark-dst-prefix hmark-sport-mask),
325 qw(hmark-dport-mask hmark-spi-mask hmark-proto-mask hmark-rnd);
326 add_target_def 'IDLETIMER', qw(timeout label);
327 add_target_def 'IPV4OPTSSTRIP';
328 add_target_def 'LED', qw(led-trigger-id led-delay led-always-blink*0);
329 add_target_def 'LOG', qw(log-level log-prefix),
330 qw(log-tcp-sequence*0 log-tcp-options*0 log-ip-options*0 log-uid*0);
331 add_target_def 'MARK', qw(set-mark set-xmark and-mark or-mark xor-mark);
332 add_target_def 'MASQUERADE', qw(to-ports random*0);
333 add_target_def 'MIRROR';
334 add_target_def 'NETMAP', qw(to);
335 add_target_def 'NFLOG', qw(nflog-group nflog-prefix nflog-range nflog-threshold);
336 add_target_def 'NFQUEUE', qw(queue-num queue-balance queue-bypass*0 queue-cpu-fanout*0);
337 add_target_def 'NOTRACK';
338 add_target_def 'RATEEST', qw(rateest-name rateest-interval rateest-ewmalog);
339 add_target_def 'REDIRECT', qw(to-ports random*0);
340 add_target_def 'REJECT', qw(reject-with);
341 add_target_def 'ROUTE', qw(oif iif gw continue*0 tee*0);
342 add_target_def 'SAME', qw(to nodst*0 random*0);
343 add_target_def 'SECMARK', qw(selctx);
344 add_target_def 'SET', qw(add-set=sc del-set=sc timeout exist*0);
345 add_target_def 'SNAT', qw(to-source=m to:=to-source persistent*0 random*0);
346 add_target_def 'SNPT', qw(src-pfx dst-pfx);
347 add_target_def 'SYNPROXY', qw(sack-perm*0 timestamps*0 ecn*0 wscale=s mss=s);
348 add_target_def 'TARPIT';
349 add_target_def 'TCPMSS', qw(set-mss clamp-mss-to-pmtu*0);
350 add_target_def 'TCPOPTSTRIP', qw(strip-options=c);
351 add_target_def 'TEE', qw(gateway);
352 add_target_def 'TOS', qw(set-tos and-tos or-tos xor-tos);
353 add_target_def 'TPROXY', qw(tproxy-mark on-ip on-port);
354 add_target_def 'TRACE';
355 add_target_def 'TTL', qw(ttl-set ttl-dec ttl-inc);
356 add_target_def 'ULOG', qw(ulog-nlgroup ulog-prefix ulog-cprange ulog-qthreshold);
358 add_match_def_x 'arp', '',
359 # ip
360 qw(source-ip! destination-ip! saddr:=source-ip daddr:=destination-ip),
361 # mac
362 qw(source-mac! destination-mac!),
363 # --in-interface
364 qw(in-interface! interface:=in-interface if:=in-interface),
365 # --out-interface
366 qw(out-interface! outerface:=out-interface of:=out-interface),
367 # misc
368 qw(h-length=s opcode=s h-type=s proto-type=s),
369 qw(mangle-ip-s=s mangle-ip-d=s mangle-mac-s=s mangle-mac-d=s mangle-target=s);
371 add_proto_def_x 'eb', 'IPv4',
372 qw(ip-source! ip-destination! ip-src:=ip-source ip-dst:=ip-destination),
373 qw(ip-tos!),
374 qw(ip-protocol! ip-proto:=ip-protocol),
375 qw(ip-source-port! ip-sport:=ip-source-port),
376 qw(ip-destination-port! ip-dport:=ip-destination-port);
378 add_proto_def_x 'eb', 'IPv6',
379 qw(ip6-source! ip6-destination! ip6-src:=ip6-source ip6-dst:=ip6-destination),
380 qw(ip6-tclass!),
381 qw(ip6-protocol! ip6-proto:=ip6-protocol),
382 qw(ip6-source-port! ip6-sport:=ip6-source-port),
383 qw(ip6-destination-port! ip6-dport:=ip6-destination-port);
385 add_proto_def_x 'eb', 'ARP',
386 qw(!arp-gratuitous*0),
387 qw(arp-opcode! arp-htype!=ss arp-ptype!=ss),
388 qw(arp-ip-src! arp-ip-dst! arp-mac-src! arp-mac-dst!);
390 add_proto_def_x 'eb', 'RARP',
391 qw(!arp-gratuitous*0),
392 qw(arp-opcode! arp-htype!=ss arp-ptype!=ss),
393 qw(arp-ip-src! arp-ip-dst! arp-mac-src! arp-mac-dst!);
395 add_proto_def_x 'eb', '802_1Q',
396 qw(vlan-id! vlan-prio! vlan-encap!),
398 add_match_def_x 'eb', '',
399 # --in-interface
400 qw(in-interface! interface:=in-interface if:=in-interface),
401 # --out-interface
402 qw(out-interface! outerface:=out-interface of:=out-interface),
403 # logical interface
404 qw(logical-in! logical-out!),
405 # --source, --destination
406 qw(source! saddr:=source destination! daddr:=destination),
407 # 802.3
408 qw(802_3-sap! 802_3-type!),
409 # among
410 qw(!among-dst=c !among-src=c !among-dst-file !among-src-file),
411 # limit
412 qw(limit=s limit-burst=s),
413 # mark_m
414 qw(mark!),
415 # pkttype
416 qw(pkttype-type!),
417 # stp
418 qw(stp-type! stp-flags! stp-root-prio! stp-root-addr! stp-root-cost!),
419 qw(stp-sender-prio! stp-sender-addr! stp-port! stp-msg-age! stp-max-age!),
420 qw(stp-hello-time! stp-forward-delay!),
421 # log
422 qw(log*0 log-level=s log-prefix=s log-ip*0 log-arp*0);
424 add_target_def_x 'eb', 'arpreply', qw(arpreply-mac arpreply-target);
425 add_target_def_x 'eb', 'dnat', qw(to-destination dnat-target);
426 add_target_def_x 'eb', 'MARK', qw(set-mark mark-target);
427 add_target_def_x 'eb', 'redirect', qw(redirect-target);
428 add_target_def_x 'eb', 'snat', qw(to-source snat-target snat-arp*0);
430 # import-ferm uses the above tables
431 return 1 if $0 =~ /import-ferm$/;
433 # parameter parser for ipt_multiport
434 sub multiport_params {
435 my $rule = shift;
437 # multiport only allows 15 ports at a time. For this
438 # reason, we do a little magic here: split the ports
439 # into portions of 15, and handle these portions as
440 # array elements
442 my $proto = $rule->{protocol};
443 error('To use multiport, you have to specify "proto tcp" or "proto udp" first')
444 unless defined $proto and grep { /^(?:tcp|udp|udplite)$/ } to_array($proto);
446 my $value = getvalues(undef, allow_negation => 1,
447 allow_array_negation => 1);
448 if (ref $value and ref $value eq 'ARRAY') {
449 my @value = @$value;
450 my @params;
452 while (@value) {
453 push @params, join(',', splice(@value, 0, 15));
456 return @params == 1
457 ? $params[0]
458 : \@params;
459 } else {
460 return join_value(',', $value);
464 sub ipfilter($@) {
465 my $domain = shift;
466 my @ips;
467 # very crude IPv4/IPv6 address detection
468 if ($domain eq 'ip') {
469 @ips = grep { !/:[0-9a-f]*:/ } @_;
470 } elsif ($domain eq 'ip6') {
471 @ips = grep { !m,^[0-9./]+$,s } @_;
473 return @ips;
476 sub address_magic {
477 my $rule = shift;
478 my $domain = $rule->{domain};
479 my $value = getvalues(undef, allow_negation => 1);
481 my @ips;
482 my $negated = 0;
483 if (ref $value and ref $value eq 'ARRAY') {
484 @ips = @$value;
485 } elsif (ref $value and ref $value eq 'negated') {
486 @ips = @$value;
487 $negated = 1;
488 } elsif (ref $value) {
489 die;
490 } else {
491 @ips = ($value);
494 # only do magic on domain (ip ip6); do not process on a single-stack rule
495 # as to let admins spot their errors instead of silently ignoring them
496 @ips = ipfilter($domain, @ips) if defined $rule->{domain_both};
498 if ($negated && scalar @ips) {
499 return bless \@ips, 'negated';
500 } else {
501 return \@ips;
505 # initialize stack: command line definitions
506 unshift @stack, {};
508 # Get command line stuff
509 if ($has_getopt) {
510 my ($opt_noexec, $opt_flush, $opt_noflush, $opt_lines, $opt_interactive,
511 $opt_timeout, $opt_help,
512 $opt_version, $opt_test, $opt_fast, $opt_slow, $opt_shell,
513 $opt_domain);
515 Getopt::Long::Configure('bundling', 'auto_help', 'no_ignore_case',
516 'no_auto_abbrev');
518 sub opt_def {
519 my ($opt, $value) = @_;
520 die 'Invalid --def specification'
521 unless $value =~ /^\$?(\w+)=(.*)$/s;
522 my ($name, $unparsed_value) = ($1, $2);
523 my $tokens = tokenize_string($unparsed_value);
524 $value = getvalues(sub { shift @$tokens; });
525 die 'Extra tokens after --def'
526 if @$tokens > 0;
527 $stack[0]{vars}{$name} = $value;
530 local $SIG{__WARN__} = sub { die $_[0]; };
531 GetOptions('noexec|n' => \$opt_noexec,
532 'flush|F' => \$opt_flush,
533 'noflush' => \$opt_noflush,
534 'lines|l' => \$opt_lines,
535 'interactive|i' => \$opt_interactive,
536 'timeout|t=s' => \$opt_timeout,
537 'help|h' => \$opt_help,
538 'version|V' => \$opt_version,
539 test => \$opt_test,
540 remote => \$opt_test,
541 fast => \$opt_fast,
542 slow => \$opt_slow,
543 shell => \$opt_shell,
544 'domain=s' => \$opt_domain,
545 'def=s' => \&opt_def,
548 if (defined $opt_help) {
549 require Pod::Usage;
550 Pod::Usage::pod2usage(-exitstatus => 0);
553 if (defined $opt_version) {
554 printversion();
555 exit 0;
558 $option{noexec} = $opt_noexec || $opt_test;
559 $option{flush} = $opt_flush;
560 $option{noflush} = $opt_noflush;
561 $option{lines} = $opt_lines || $opt_test || $opt_shell;
562 $option{interactive} = $opt_interactive && !$opt_noexec;
563 $option{timeout} = defined $opt_timeout ? $opt_timeout : "30";
564 $option{test} = $opt_test;
565 $option{fast} = !$opt_slow;
566 $option{shell} = $opt_shell;
568 die("ferm interactive mode not possible: /dev/stdin is not a tty\n")
569 if $option{interactive} and not -t STDIN;
570 die("ferm interactive mode not possible: /dev/stderr is not a tty\n")
571 if $option{interactive} and not -t STDERR;
572 die("ferm timeout has no sense without interactive mode")
573 if not $opt_interactive and defined $opt_timeout;
574 die("invalid timeout. must be an integer")
575 if defined $opt_timeout and not $opt_timeout =~ /^[+-]?\d+$/;
577 $option{domain} = $opt_domain if defined $opt_domain;
578 } else {
579 # tiny getopt emulation for microperl
580 my $filename;
581 foreach (@ARGV) {
582 if ($_ eq '--noexec' or $_ eq '-n') {
583 $option{noexec} = 1;
584 } elsif ($_ eq '--lines' or $_ eq '-l') {
585 $option{lines} = 1;
586 } elsif ($_ eq '--fast') {
587 $option{fast} = 1;
588 } elsif ($_ eq '--test') {
589 $option{test} = 1;
590 $option{noexec} = 1;
591 $option{lines} = 1;
592 } elsif ($_ eq '--shell') {
593 $option{$_} = 1 foreach qw(shell fast lines);
594 } elsif (/^-/) {
595 printf STDERR "Usage: ferm [--noexec] [--lines] [--fast] [--shell] FILENAME\n";
596 exit 1;
597 } else {
598 $filename = $_;
601 undef @ARGV;
602 push @ARGV, $filename;
605 unless (@ARGV == 1) {
606 require Pod::Usage;
607 Pod::Usage::pod2usage(-exitstatus => 1);
610 if ($has_strict) {
611 open LINES, ">&STDOUT" if $option{lines};
612 open STDOUT, ">&STDERR" if $option{shell};
613 } else {
614 # microperl can't redirect file handles
615 *LINES = *STDOUT;
617 if ($option{fast} and not $option{noexec}) {
618 print STDERR "Sorry, ferm on microperl does not allow --fast without --noexec\n";
619 exit 1
623 unshift @stack, {};
624 open_script($ARGV[0]);
626 my( $volume,$dirs,$file ) = File::Spec->splitpath( $ARGV[0] );
627 $stack[0]{auto}{FILENAME} = $ARGV[0];
628 $stack[0]{auto}{FILEBNAME} = $file;
629 $stack[0]{auto}{DIRNAME} = $dirs;
633 # parse all input recursively
634 enter(0, undef);
635 die unless @stack == 2;
637 # enable/disable hooks depending on --flush
639 if ($option{flush}) {
640 undef @pre_hooks;
641 undef @post_hooks;
642 } else {
643 undef @flush_hooks;
646 # execute all generated rules
647 my $status;
649 foreach my $cmd (@pre_hooks) {
650 print LINES "$cmd\n" if $option{lines};
651 system($cmd) unless $option{noexec};
654 while (my ($domain, $domain_info) = each %domains) {
655 next unless $domain_info->{enabled};
656 my $s = $option{fast} &&
657 defined $domain_info->{tools}{'tables-restore'}
658 ? execute_fast($domain_info) : execute_slow($domain_info);
659 $status = $s if defined $s;
662 foreach my $cmd (@post_hooks, @flush_hooks) {
663 print LINES "$cmd\n" if $option{lines};
664 system($cmd) unless $option{noexec};
667 if (defined $status) {
668 rollback();
669 exit $status;
672 # ask user, and rollback if there is no confirmation
674 if ($option{interactive}) {
675 if ($option{shell}) {
676 print LINES "echo 'ferm has applied the new firewall rules.'\n";
677 print LINES "echo 'Please press Ctrl-C to confirm.'\n";
678 print LINES "sleep $option{timeout}\n";
679 while (my ($domain, $domain_info) = each %domains) {
680 my $restore = $domain_info->{tools}{'tables-restore'};
681 next unless defined $restore;
682 print LINES "$restore <\$${domain}_tmp\n";
686 confirm_rules() or rollback() unless $option{noexec};
689 exit 0;
691 # end of program execution!
694 # funcs
696 sub printversion {
697 print "ferm $VERSION\n";
698 print "Copyright 2001-2017 Max Kellermann, Auke Kok\n";
699 print "This program is free software released under GPLv2.\n";
700 print "See the included COPYING file for license details.\n";
704 sub error {
705 # returns a nice formatted error message, showing the
706 # location of the error.
707 my $tabs = 0;
708 my @lines;
709 my $l = 0;
710 my @words = map { @$_ } @{$script->{past_tokens}};
712 for my $w ( 0 .. $#words ) {
713 if ($words[$w] eq "\x29")
714 { $l++ ; $lines[$l] = " " x ($tabs-- -1) ;};
715 if ($words[$w] eq "\x28")
716 { $l++ ; $lines[$l] = " " x $tabs++ ;};
717 if ($words[$w] eq "\x7d")
718 { $l++ ; $lines[$l] = " " x ($tabs-- -1) ;};
719 if ($words[$w] eq "\x7b")
720 { $l++ ; $lines[$l] = " " x $tabs++ ;};
721 if ( $l > $#lines ) { $lines[$l] = "" };
722 $lines[$l] .= $words[$w] . " ";
723 if ($words[$w] eq "\x28")
724 { $l++ ; $lines[$l] = " " x $tabs ;};
725 if (($words[$w] eq "\x29") && ($words[$w+1] ne "\x7b"))
726 { $l++ ; $lines[$l] = " " x $tabs ;};
727 if ($words[$w] eq "\x7b")
728 { $l++ ; $lines[$l] = " " x $tabs ;};
729 if (($words[$w] eq "\x7d") && ($words[$w+1] ne "\x7d"))
730 { $l++ ; $lines[$l] = " " x $tabs ;};
731 if (($words[$w] eq "\x3b") && ($words[$w+1] ne "\x7d"))
732 { $l++ ; $lines[$l] = " " x $tabs ;}
733 if ($words[$w-1] eq "option")
734 { $l++ ; $lines[$l] = " " x $tabs ;}
736 my $start = $#lines - 4;
737 if ($start < 0) { $start = 0 } ;
738 print STDERR "Error in $script->{filename} line $script->{line}:\n";
739 for $l ( $start .. $#lines)
740 { print STDERR $lines[$l]; if ($l != $#lines ) {print STDERR "\n"} ; };
741 print STDERR "<--\n";
742 die("@_\n");
745 # print a warning message about code from an input file
746 sub warning {
747 print STDERR "Warning in $script->{filename} line $script->{line}: "
748 . (shift) . "\n";
751 sub find_tool($) {
752 my $name = shift;
753 return $name if $option{test};
754 for my $path ('/sbin', split ':', $ENV{PATH}) {
755 my $ret = "$path/$name";
756 return $ret if -x $ret;
758 die "$name not found in PATH\n";
761 sub initialize_domain {
762 my $domain = shift;
763 my $domain_info = $domains{$domain} ||= {};
765 return if exists $domain_info->{initialized};
767 die "Invalid domain '$domain'\n" unless $domain =~ /^(?:ip6?|arp|eb)$/;
769 my @tools = qw(tables);
770 push @tools, qw(tables-save tables-restore)
771 if $domain =~ /^ip6?$/;
773 # determine the location of this domain's tools
774 my %tools = map { $_ => find_tool($domain . $_) } @tools;
775 $domain_info->{tools} = \%tools;
777 # make tables-save tell us about the state of this domain
778 # (which tables and chains do exist?), also remember the old
779 # save data which may be used later by the rollback function
780 local *SAVE;
781 if (!$option{test} &&
782 exists $tools{'tables-save'} &&
783 open(SAVE, "$tools{'tables-save'}|")) {
784 my $save = '';
786 my $table_info;
787 while (<SAVE>) {
788 $save .= $_;
790 if (/^\*(\w+)/) {
791 my $table = $1;
792 $table_info = $domain_info->{tables}{$table} ||= {};
793 } elsif (defined $table_info and /^:(\w+)\s+(\S+)/
794 and $2 ne '-') {
795 $table_info->{chains}{$1}{builtin} = 1;
796 $table_info->{has_builtin} = 1;
800 # for rollback
801 $domain_info->{previous} = $save;
804 if ($option{shell} && $option{interactive} &&
805 exists $tools{'tables-save'}) {
806 print LINES "${domain}_tmp=\$(mktemp ferm.XXXXXXXXXX)\n";
807 print LINES "$tools{'tables-save'} >\$${domain}_tmp\n";
810 $domain_info->{initialized} = 1;
813 sub check_domain($) {
814 my $domain = shift;
815 my @result;
817 return if exists $option{domain}
818 and $domain ne $option{domain};
820 eval {
821 initialize_domain($domain);
823 error($@) if $@;
825 return 1;
828 # split the input string into words and delete comments
829 sub tokenize_string($) {
830 my $string = shift;
832 my @ret;
834 foreach my $word ($string =~ m/(".*?"|'.*?'|`.*?`|[!,=&\$\%\(\){};]|[-+\w\/\.:]+|@\w+|#)/g) {
835 last if $word eq '#';
836 push @ret, $word;
839 return \@ret;
842 # generate a "line" special token, that marks the line number; these
843 # special tokens are inserted after each line break, so ferm keeps
844 # track of line numbers
845 sub make_line_token($) {
846 my $line = shift;
847 return bless(\$line, 'line');
850 # read some more tokens from the input file into a buffer
851 sub prepare_tokens() {
852 my $tokens = $script->{tokens};
853 while (@$tokens == 0) {
854 my $handle = $script->{handle};
855 return unless defined $handle;
856 my $line = <$handle>;
857 return unless defined $line;
859 push @$tokens, make_line_token($script->{line} + 1);
861 # the next parser stage eats this
862 push @$tokens, @{tokenize_string($line)};
865 return 1;
868 sub handle_special_token($) {
869 my $token = shift;
870 die unless ref $token;
871 if (ref $token eq 'line') {
872 $script->{line} = $$token;
873 } else {
874 die;
878 sub handle_special_tokens() {
879 my $tokens = $script->{tokens};
880 while (@$tokens > 0 and ref $tokens->[0]) {
881 handle_special_token(shift @$tokens);
885 # wrapper for prepare_tokens() which handles "special" tokens
886 sub prepare_normal_tokens() {
887 my $tokens = $script->{tokens};
888 while (1) {
889 handle_special_tokens();
890 return 1 if @$tokens > 0;
891 return unless prepare_tokens();
895 # open a ferm sub script
896 sub open_script($) {
897 my $filename = shift;
899 for (my $s = $script; defined $s; $s = $s->{parent}) {
900 die("Circular reference in $script->{filename} line $script->{line}: $filename\n")
901 if $s->{filename} eq $filename;
904 my $handle;
905 if ($filename eq '-') {
906 # Note that this only allowed in the command-line argument and not
907 # @includes, since those are filtered by collect_filenames()
908 $handle = *STDIN;
909 # also set a filename label so that error messages are more helpful
910 $filename = "<stdin>";
911 } else {
912 local *FILE;
913 open FILE, "$filename" or die("Failed to open $filename: $!\n");
914 $handle = *FILE;
917 $script = { filename => $filename,
918 handle => $handle,
919 line => 0,
920 past_tokens => [],
921 tokens => [],
922 parent => $script,
925 return $script;
928 # collect script filenames which are being included
929 sub collect_filenames(@) {
930 my @ret;
932 # determine the current script's parent directory for relative
933 # file names
934 die unless defined $script;
935 my $parent_dir = $script->{filename} =~ m,^(.*/),
936 ? $1 : './';
938 foreach my $pathname (@_) {
939 # non-absolute file names are relative to the parent script's
940 # file name
941 $pathname = $parent_dir . $pathname
942 unless $pathname =~ m,^/|\|$,;
944 if ($pathname =~ m,/$,) {
945 # include all regular files in a directory
947 error("'$pathname' is not a directory")
948 unless -d $pathname;
950 local *DIR;
951 opendir DIR, $pathname
952 or error("Failed to open directory '$pathname': $!");
953 my @names = readdir DIR;
954 closedir DIR;
956 # sort those names for a well-defined order
957 foreach my $name (sort { $a cmp $b } @names) {
958 # ignore dpkg's backup files
959 next if $name =~ /\.dpkg-(old|dist|new|tmp)$/;
960 # don't include hidden and backup files
961 next if $name =~ /^\.|~$/;
963 my $filename = $pathname . $name;
964 push @ret, $filename
965 if -f $filename;
967 } elsif ($pathname =~ m,\|$,) {
968 # run a program and use its output
969 push @ret, $pathname;
970 } elsif ($pathname =~ m,^\|,) {
971 error('This kind of pipe is not allowed');
972 } else {
973 # include a regular file
975 error("'$pathname' is a directory; maybe use trailing '/' to include a directory?")
976 if -d $pathname;
977 error("'$pathname' is not a file")
978 unless -f $pathname;
980 push @ret, $pathname;
984 return @ret;
987 # peek a token from the queue, but don't remove it
988 sub peek_token() {
989 return unless prepare_normal_tokens();
990 return $script->{tokens}[0];
993 # get a token from the queue, including "special" tokens
994 sub next_raw_token() {
995 return unless prepare_tokens();
996 return shift @{$script->{tokens}};
999 # get a token from the queue
1000 sub next_token() {
1001 return unless prepare_normal_tokens();
1002 my $token = shift @{$script->{tokens}};
1004 # update $script->{past_tokens}
1005 my $past_tokens = $script->{past_tokens};
1007 if (@$past_tokens > 0) {
1008 my $prev_token = $past_tokens->[-1][-1];
1009 $past_tokens->[-1] = @$past_tokens > 1 ? ['{'] : []
1010 if $prev_token eq ';';
1011 if ($prev_token eq '}') {
1012 pop @$past_tokens;
1013 $past_tokens->[-1] = $past_tokens->[-1][0] eq '{'
1014 ? [ '{' ] : []
1015 if @$past_tokens > 0;
1019 push @$past_tokens, [] if $token eq '{' or @$past_tokens == 0;
1020 push @{$past_tokens->[-1]}, $token;
1022 # return
1023 return $token;
1026 sub expect_token($;$) {
1027 my $expect = shift;
1028 my $msg = shift;
1029 my $token = next_token();
1030 error($msg || "'$expect' expected")
1031 unless defined $token and $token eq $expect;
1034 # require that another token exists, and that it's not a "special"
1035 # token, e.g. ";" and "{"
1036 sub require_next_token {
1037 my $code = shift || \&next_token;
1039 my $token = &$code(@_);
1041 error('unexpected end of file')
1042 unless defined $token;
1044 error("'$token' not allowed here")
1045 if $token =~ /^[;{}]$/;
1047 return $token;
1050 # return the value of a variable
1051 sub variable_value($) {
1052 my $name = shift;
1054 if ($name eq "LINE") {
1055 return $script->{line};
1058 foreach (@stack) {
1059 return $_->{vars}{$name}
1060 if exists $_->{vars}{$name};
1063 return $stack[0]{auto}{$name}
1064 if exists $stack[0]{auto}{$name};
1066 return;
1069 # determine the value of a variable, die if the value is an array
1070 sub string_variable_value($) {
1071 my $name = shift;
1072 my $value = variable_value($name);
1074 error("variable '$name' must be a string, but it is an array")
1075 if ref $value;
1077 return $value;
1080 # similar to the built-in "join" function, but also handle negated
1081 # values in a special way
1082 sub join_value($$) {
1083 my ($expr, $value) = @_;
1085 unless (ref $value) {
1086 return $value;
1087 } elsif (ref $value eq 'ARRAY') {
1088 return join($expr, @$value);
1089 } elsif (ref $value eq 'negated') {
1090 # bless'negated' is a special marker for negated values
1091 $value = join_value($expr, $value->[0]);
1092 return bless [ $value ], 'negated';
1093 } else {
1094 die;
1098 sub negate_value($$;$) {
1099 my ($value, $class, $allow_array) = @_;
1101 if (ref $value) {
1102 error('double negation is not allowed')
1103 if ref $value eq 'negated' or ref $value eq 'pre_negated';
1105 error('it is not possible to negate an array')
1106 if ref $value eq 'ARRAY' and not $allow_array;
1109 return bless [ $value ], $class || 'negated';
1112 sub format_bool($) {
1113 return $_[0] ? 1 : 0;
1116 sub resolve($\@$) {
1117 my ($resolver, $names, $type) = @_;
1119 my @result;
1120 foreach my $hostname (@$names) {
1121 if (($type eq 'A' and $hostname =~ /^\d+\.\d+\.\d+\.\d+$/) or
1122 (($type eq 'AAAA' and
1123 $hostname =~ /^[0-9a-fA-F:]*:[0-9a-fA-F:]*$/))) {
1124 push @result, $hostname;
1125 next;
1128 my $query = $resolver->search($hostname, $type);
1129 error("DNS query for '$hostname' failed: " . $resolver->errorstring)
1130 unless $query;
1132 foreach my $rr ($query->answer) {
1133 next unless $rr->type eq $type;
1135 if ($type eq 'NS') {
1136 push @result, $rr->nsdname;
1137 } elsif ($type eq 'MX') {
1138 push @result, $rr->exchange;
1139 } else {
1140 push @result, $rr->address;
1145 # NS/MX records return host names; resolve these again in the
1146 # second pass (IPv4 only currently)
1147 @result = resolve($resolver, @result, 'A')
1148 if $type eq 'NS' or $type eq 'MX';
1150 return @result;
1153 sub lookup_function($) {
1154 my $name = shift;
1156 foreach (@stack) {
1157 return $_->{functions}{$name}
1158 if exists $_->{functions}{$name};
1161 return;
1164 # returns the next parameter, which may either be a scalar or an array
1165 sub getvalues {
1166 my $code = shift;
1167 my %options = @_;
1169 my $token = require_next_token($code);
1171 if ($token eq '(') {
1172 # read an array until ")"
1173 my @wordlist;
1175 for (;;) {
1176 $token = getvalues($code,
1177 parenthesis_allowed => 1,
1178 comma_allowed => 1);
1180 unless (ref $token) {
1181 last if $token eq ')';
1183 if ($token eq ',') {
1184 error('Comma is not allowed within arrays, please use only a space');
1185 next;
1188 push @wordlist, $token;
1189 } elsif (ref $token eq 'ARRAY') {
1190 push @wordlist, @$token;
1191 } else {
1192 error('unknown token type');
1196 error('empty array not allowed here')
1197 unless @wordlist or not $options{non_empty};
1199 return @wordlist == 1
1200 ? $wordlist[0]
1201 : \@wordlist;
1202 } elsif ($token =~ /^\`(.*)\`$/s) {
1203 # execute a shell command, insert output
1204 my $command = $1;
1205 my $output = `$command`;
1206 unless ($? == 0) {
1207 if ($? == -1) {
1208 error("failed to execute: $!");
1209 } elsif ($? & 0x7f) {
1210 error("child died with signal " . ($? & 0x7f));
1211 } elsif ($? >> 8) {
1212 error("child exited with status " . ($? >> 8));
1216 # remove comments
1217 $output =~ s/#.*//mg;
1219 # tokenize
1220 my @tokens = grep { length } split /\s+/s, $output;
1222 my @values;
1223 while (@tokens) {
1224 my $value = getvalues(sub { shift @tokens });
1225 push @values, to_array($value);
1228 # and recurse
1229 return @values == 1
1230 ? $values[0]
1231 : \@values;
1232 } elsif ($token =~ /^\'(.*)\'$/s) {
1233 # single quotes: a string
1234 return $1;
1235 } elsif ($token =~ /^\"(.*)\"$/s) {
1236 # double quotes: a string with escapes
1237 $token = $1;
1238 $token =~ s,\$(\w+),string_variable_value($1),eg;
1239 return $token;
1240 } elsif ($token eq '!') {
1241 error('negation is not allowed here')
1242 unless $options{allow_negation};
1244 $token = getvalues($code);
1246 return negate_value($token, undef, $options{allow_array_negation});
1247 } elsif ($token eq ',') {
1248 return $token
1249 if $options{comma_allowed};
1251 error('comma is not allowed here');
1252 } elsif ($token eq '=') {
1253 error('equals operator ("=") is not allowed here');
1254 } elsif ($token eq '$') {
1255 my $name = require_next_token($code);
1256 error('variable name expected - if you want to concatenate strings, try using double quotes')
1257 unless $name =~ /^\w+$/;
1259 my $value = variable_value($name);
1261 error("no such variable: \$$name")
1262 unless defined $value;
1264 return $value;
1265 } elsif ($token eq '&') {
1266 error("function calls are not allowed as keyword parameter");
1267 } elsif ($token eq ')' and not $options{parenthesis_allowed}) {
1268 error('Syntax error');
1269 } elsif ($token =~ /^@/) {
1270 if ($token eq '@resolve') {
1271 my @params = get_function_params();
1272 error('Usage: @resolve((hostname ...), [type])')
1273 unless @params == 1 or @params == 2;
1274 eval { require Net::DNS; };
1275 error('For the @resolve() function, you need the Perl library Net::DNS')
1276 if $@;
1277 my $type = $params[1] || 'A';
1278 error('String expected') if ref $type;
1279 my $resolver = new Net::DNS::Resolver;
1280 @params = to_array($params[0]);
1281 my @result = resolve($resolver, @params, $type);
1282 return @result == 1 ? $result[0] : \@result;
1283 } elsif ($token eq '@defined') {
1284 expect_token('(', 'function name must be followed by "()"');
1285 my $type = require_next_token();
1286 if ($type eq '$') {
1287 my $name = require_next_token();
1288 error('variable name expected')
1289 unless $name =~ /^\w+$/;
1290 expect_token(')');
1291 return defined variable_value($name);
1292 } elsif ($type eq '&') {
1293 my $name = require_next_token();
1294 error('function name expected')
1295 unless $name =~ /^\w+$/;
1296 expect_token(')');
1297 return defined lookup_function($name);
1298 } else {
1299 error("'\$' or '&' expected")
1301 } elsif ($token eq '@eq') {
1302 my @params = get_function_params();
1303 error('Usage: @eq(a, b)') unless @params == 2;
1304 return format_bool($params[0] eq $params[1]);
1305 } elsif ($token eq '@ne') {
1306 my @params = get_function_params();
1307 error('Usage: @ne(a, b)') unless @params == 2;
1308 return format_bool($params[0] ne $params[1]);
1309 } elsif ($token eq '@not') {
1310 my @params = get_function_params();
1311 error('Usage: @not(a)') unless @params == 1;
1312 return format_bool(not $params[0]);
1313 } elsif ($token eq '@cat') {
1314 my $value = '';
1315 map {
1316 error('String expected') if ref $_;
1317 $value .= $_;
1318 } get_function_params();
1319 return $value;
1320 } elsif ($token eq '@substr') {
1321 my @params = get_function_params();
1322 error('Usage: @substr(string, num, num)') unless @params == 3;
1323 error('String expected') if ref $params[0] or ref $params[1] or ref $params[2];
1324 return substr($params[0],$params[1],$params[2]);
1325 } elsif ($token eq '@length') {
1326 my @params = get_function_params();
1327 error('Usage: @length(string)') unless @params == 1;
1328 error('String expected') if ref $params[0];
1329 return length($params[0]);
1330 } elsif ($token eq '@basename') {
1331 my @params = get_function_params();
1332 error('Usage: @basename(path)') unless @params == 1;
1333 error('String expected') if ref $params[0];
1334 my($volume,$path,$file) = File::Spec->splitpath( $params[0] );
1335 return $file;
1336 } elsif ($token eq '@dirname') {
1337 my @params = get_function_params();
1338 error('Usage: @dirname(path)') unless @params == 1;
1339 error('String expected') if ref $params[0];
1340 my($volume,$path,$file) = File::Spec->splitpath( $params[0] );
1341 return $path;
1342 } elsif ($token eq '@glob') {
1343 my @params = get_function_params();
1344 error('Usage: @glob(string)') unless @params == 1;
1346 # determine the current script's parent directory for relative
1347 # file names
1348 die unless defined $script;
1349 my $parent_dir = $script->{filename} =~ m,^(.*/),
1350 ? $1 : './';
1352 my @result = map {
1353 my $path = $_;
1354 $path = $parent_dir . $path unless $path =~ m,^/,;
1355 glob($path);
1356 } to_array($params[0]);
1357 return @result == 1 ? $result[0] : \@result;
1358 } elsif ($token eq '@ipfilter') {
1359 my @params = get_function_params();
1360 error('Usage: @ipfilter((ip1 ip2 ...))') unless @params == 1;
1361 my $domain = $stack[0]{auto}{DOMAIN};
1362 error('No domain specified') unless defined $domain;
1363 my @ips = ipfilter($domain, to_array($params[0]));
1364 return \@ips;
1365 } else {
1366 error("unknown ferm built-in function");
1368 } else {
1369 return $token;
1373 # returns the next parameter, but only allow a scalar
1374 sub getvar() {
1375 my $token = getvalues();
1377 error('array not allowed here')
1378 if ref $token and ref $token eq 'ARRAY';
1380 return $token;
1383 sub get_function_params(%) {
1384 expect_token('(', 'function name must be followed by "()"');
1386 my $token = peek_token();
1387 if ($token eq ')') {
1388 require_next_token();
1389 return;
1392 my @params;
1394 while (1) {
1395 if (@params > 0) {
1396 $token = require_next_token();
1397 last
1398 if $token eq ')';
1400 error('"," expected')
1401 unless $token eq ',';
1404 push @params, getvalues(undef, @_);
1407 return @params;
1410 # collect all tokens in a flat array reference until the end of the
1411 # command is reached
1412 sub collect_tokens {
1413 my %options = @_;
1415 my @level;
1416 my @tokens;
1418 # re-insert a "line" token, because the starting token of the
1419 # current line has been consumed already
1420 push @tokens, make_line_token($script->{line});
1422 while (1) {
1423 my $keyword = next_raw_token();
1424 error('unexpected end of file within function/variable declaration')
1425 unless defined $keyword;
1427 if (ref $keyword) {
1428 handle_special_token($keyword);
1429 } elsif ($keyword =~ /^[\{\(]$/) {
1430 push @level, $keyword;
1431 } elsif ($keyword =~ /^[\}\)]$/) {
1432 my $expected = $keyword;
1433 $expected =~ tr/\}\)/\{\(/;
1434 my $opener = pop @level;
1435 error("unmatched '$keyword'")
1436 unless defined $opener and $opener eq $expected;
1437 } elsif ($keyword eq ';' and @level == 0) {
1438 push @tokens, $keyword
1439 if $options{include_semicolon};
1441 if ($options{include_else}) {
1442 my $token = peek_token;
1443 next if $token eq '@else';
1446 last;
1449 push @tokens, $keyword;
1451 last
1452 if $keyword eq '}' and @level == 0;
1455 return \@tokens;
1459 # returns the specified value as an array. dereference arrayrefs
1460 sub to_array($) {
1461 my $value = shift;
1462 die unless wantarray;
1463 die if @_;
1464 unless (ref $value) {
1465 return $value;
1466 } elsif (ref $value eq 'ARRAY') {
1467 return @$value;
1468 } else {
1469 die;
1473 # evaluate the specified value as bool
1474 sub eval_bool($) {
1475 my $value = shift;
1476 die if wantarray;
1477 die if @_;
1478 unless (ref $value) {
1479 return $value;
1480 } elsif (ref $value eq 'ARRAY') {
1481 return @$value > 0;
1482 } else {
1483 die;
1487 sub is_netfilter_core_target($) {
1488 my $target = shift;
1489 die unless defined $target and length $target;
1490 return grep { $_ eq $target } qw(ACCEPT DROP RETURN QUEUE);
1493 sub is_netfilter_module_target($$) {
1494 my ($domain_family, $target) = @_;
1495 die unless defined $target and length $target;
1497 return defined $domain_family &&
1498 exists $target_defs{$domain_family} &&
1499 $target_defs{$domain_family}{$target};
1502 sub is_netfilter_builtin_chain($$) {
1503 my ($table, $chain) = @_;
1505 return grep { $_ eq $chain }
1506 qw(PREROUTING INPUT FORWARD OUTPUT POSTROUTING BROUTING);
1509 sub netfilter_canonical_protocol($) {
1510 my $proto = shift;
1511 return 'icmp'
1512 if $proto eq 'ipv6-icmp' or $proto eq 'icmpv6';
1513 return 'mh'
1514 if $proto eq 'ipv6-mh';
1515 return $proto;
1518 sub netfilter_protocol_module($) {
1519 my $proto = shift;
1520 return unless defined $proto;
1521 return 'icmp6'
1522 if $proto eq 'icmpv6';
1523 return $proto;
1526 # escape the string in a way safe for the shell
1527 sub shell_escape($) {
1528 my $token = shift;
1530 return $token if $token =~ /^[-_a-zA-Z0-9]+$/s;
1532 if ($option{fast}) {
1533 # iptables-save/iptables-restore are quite buggy concerning
1534 # escaping and special characters... we're trying our best
1535 # here
1537 $token =~ s,",\\",g;
1538 $token = '"' . $token . '"'
1539 if $token =~ /[\s\'\\;&]/s or length($token) == 0;
1540 } else {
1541 return $token
1542 if $token =~ /^\`.*\`$/;
1543 $token =~ s/'/'\\''/g;
1544 $token = '\'' . $token . '\''
1545 if $token =~ /[\s\"\\;<>&|]/s or length($token) == 0;
1548 return $token;
1551 # append an option to the shell command line, using information from
1552 # the module definition (see %match_defs etc.)
1553 sub shell_format_option($$) {
1554 my ($keyword, $value) = @_;
1556 my $cmd = '';
1557 if (ref $value) {
1558 if ((ref $value eq 'negated') || (ref $value eq 'pre_negated')) {
1559 $value = $value->[0];
1560 $cmd = ' !';
1564 unless (defined $value) {
1565 $cmd .= " --$keyword";
1566 } elsif (ref $value) {
1567 if (ref $value eq 'params') {
1568 $cmd .= " --$keyword ";
1569 $cmd .= join(' ', map { shell_escape($_) } @$value);
1570 } elsif (ref $value eq 'multi') {
1571 foreach (@$value) {
1572 $cmd .= " --$keyword " . shell_escape($_);
1574 } else {
1575 die;
1577 } else {
1578 $cmd .= " --$keyword " . shell_escape($value);
1581 return $cmd;
1584 sub format_option($$$) {
1585 my ($domain, $name, $value) = @_;
1587 $value = 'icmpv6' if $domain eq 'ip6' and $name eq 'protocol'
1588 and $value eq 'icmp';
1589 $name = 'icmpv6-type' if $domain eq 'ip6' and $name eq 'icmp-type';
1591 if ($domain eq 'ip6' and $name eq 'reject-with') {
1592 my %icmp_map = (
1593 'icmp-net-unreachable' => 'icmp6-no-route',
1594 'icmp-host-unreachable' => 'icmp6-addr-unreachable',
1595 'icmp-port-unreachable' => 'icmp6-port-unreachable',
1596 'icmp-net-prohibited' => 'icmp6-adm-prohibited',
1597 'icmp-host-prohibited' => 'icmp6-adm-prohibited',
1598 'icmp-admin-prohibited' => 'icmp6-adm-prohibited',
1600 $value = $icmp_map{$value} if exists $icmp_map{$value};
1603 return shell_format_option($name, $value);
1606 sub append_rule($$) {
1607 my ($chain_rules, $rule) = @_;
1609 my $cmd = join('', map { $_->[2] } @{$rule->{options}});
1610 push @$chain_rules, { rule => $cmd,
1611 script => $rule->{script},
1615 sub unfold_rule {
1616 my ($domain, $chain_rules, $rule) = (shift, shift, shift);
1617 return append_rule($chain_rules, $rule) unless @_;
1619 my $option = shift;
1620 my @values = @{$option->[1]};
1622 foreach my $value (@values) {
1623 $option->[2] = format_option($domain, $option->[0], $value);
1624 unfold_rule($domain, $chain_rules, $rule, @_);
1628 sub mkrules2($$$) {
1629 my ($domain, $chain_rules, $rule) = @_;
1631 my @unfold;
1632 foreach my $option (@{$rule->{options}}) {
1633 if (ref $option->[1] and ref $option->[1] eq 'ARRAY') {
1634 push @unfold, $option
1635 } else {
1636 $option->[2] = format_option($domain, $option->[0], $option->[1]);
1640 unfold_rule($domain, $chain_rules, $rule, @unfold);
1643 # convert a bunch of internal rule structures in iptables calls,
1644 # unfold arrays during that
1645 sub mkrules($) {
1646 my $rule = shift;
1648 my $domain = $rule->{domain};
1649 my $domain_info = $domains{$domain};
1650 $domain_info->{enabled} = 1;
1652 foreach my $table (to_array $rule->{table}) {
1653 my $table_info = $domain_info->{tables}{$table} ||= {};
1655 foreach my $chain (to_array $rule->{chain}) {
1656 my $chain_rules = $table_info->{chains}{$chain}{rules} ||= [];
1657 mkrules2($domain, $chain_rules, $rule)
1658 if $rule->{has_rule} and not $option{flush};
1663 # parse a keyword from a module definition
1664 sub parse_keyword(\%$$) {
1665 my ($rule, $def, $negated_ref) = @_;
1667 my $params = $def->{params};
1669 my $value;
1671 my $negated;
1672 if ($$negated_ref && exists $def->{pre_negation}) {
1673 $negated = 1;
1674 undef $$negated_ref;
1677 unless (defined $params) {
1678 undef $value;
1679 } elsif (ref $params && ref $params eq 'CODE') {
1680 $value = &$params($rule);
1681 } elsif ($params eq 'm') {
1682 $value = bless [ to_array getvalues() ], 'multi';
1683 } elsif ($params =~ /^[a-z]/) {
1684 if (exists $def->{negation} and not $negated) {
1685 my $token = peek_token();
1686 if ($token eq '!') {
1687 require_next_token();
1688 $negated = 1;
1692 my @params;
1693 foreach my $p (split(//, $params)) {
1694 if ($p eq 's') {
1695 push @params, getvar();
1696 } elsif ($p eq 'c') {
1697 my @v = to_array getvalues(undef, non_empty => 1);
1698 push @params, join(',', @v);
1699 } else {
1700 die;
1704 $value = @params == 1
1705 ? $params[0]
1706 : bless \@params, 'params';
1707 } elsif ($params == 1) {
1708 if (exists $def->{negation} and not $negated) {
1709 my $token = peek_token();
1710 if ($token eq '!') {
1711 require_next_token();
1712 $negated = 1;
1716 $value = getvalues();
1718 warning("log-prefix is too long; truncating to 29 characters: '$1'")
1719 if $def->{name} eq 'log-prefix' && $value =~ s,^(.{29}).+$,$1,;
1720 } else {
1721 if (exists $def->{negation} and not $negated) {
1722 my $token = peek_token();
1723 if ($token eq '!') {
1724 require_next_token();
1725 $negated = 1;
1729 $value = bless [ map {
1730 getvar()
1731 } (1..$params) ], 'params';
1734 $value = negate_value($value, exists $def->{pre_negation} && 'pre_negated')
1735 if $negated;
1737 return $value;
1740 sub append_option(\%$$) {
1741 my ($rule, $name, $value) = @_;
1742 push @{$rule->{options}}, [ $name, $value ];
1745 # parse options of a module
1746 sub parse_option($\%$) {
1747 my ($def, $rule, $negated_ref) = @_;
1749 append_option(%$rule, $def->{name},
1750 parse_keyword(%$rule, $def, $negated_ref));
1753 sub copy_on_write($$) {
1754 my ($rule, $key) = @_;
1755 return unless exists $rule->{cow}{$key};
1756 $rule->{$key} = {%{$rule->{$key}}};
1757 delete $rule->{cow}{$key};
1760 sub new_level(\%$) {
1761 my ($rule, $prev) = @_;
1763 %$rule = ();
1764 if (defined $prev) {
1765 # copy data from previous level
1766 $rule->{cow} = { keywords => 1, };
1767 $rule->{keywords} = $prev->{keywords};
1768 $rule->{match} = { %{$prev->{match}} };
1769 $rule->{options} = [@{$prev->{options}}];
1770 foreach my $key (qw(domain domain_family domain_both table chain protocol has_rule has_action)) {
1771 $rule->{$key} = $prev->{$key}
1772 if exists $prev->{$key};
1774 } else {
1775 $rule->{cow} = {};
1776 $rule->{keywords} = {};
1777 $rule->{match} = {};
1778 $rule->{options} = [];
1782 sub merge_keywords(\%$) {
1783 my ($rule, $keywords) = @_;
1784 copy_on_write($rule, 'keywords');
1785 while (my ($name, $def) = each %$keywords) {
1786 $rule->{keywords}{$name} = $def;
1790 sub set_domain(\%$) {
1791 my ($rule, $domain) = @_;
1793 return unless check_domain($domain);
1795 my $domain_family;
1796 unless (ref $domain) {
1797 $domain_family = $domain eq 'ip6' ? 'ip' : $domain;
1798 } elsif (@$domain == 0) {
1799 $domain_family = 'none';
1800 } elsif (grep { not /^ip6?$/s } @$domain) {
1801 error('Cannot combine non-IP domains');
1802 } else {
1803 $domain_family = 'ip';
1806 $rule->{domain_family} = $domain_family;
1807 $rule->{keywords} = $match_defs{$domain_family}{''}{keywords};
1808 $rule->{cow}{keywords} = 1;
1810 $rule->{domain} = $stack[0]{auto}{DOMAIN} = $domain;
1813 sub set_target(\%$$) {
1814 my ($rule, $name, $value) = @_;
1815 error('There can only one action per rule')
1816 if exists $rule->{has_action};
1817 $rule->{has_action} = 1;
1818 append_option(%$rule, $name, $value);
1821 sub set_module_target(\%$$) {
1822 my ($rule, $name, $defs) = @_;
1824 if ($name eq 'TCPMSS') {
1825 my $protos = $rule->{protocol};
1826 error('No protocol specified before TCPMSS')
1827 unless defined $protos;
1828 foreach my $proto (to_array $protos) {
1829 error('TCPMSS not available for protocol "$proto"')
1830 unless $proto eq 'tcp';
1834 # in ebtables, there is both "--mark" and "-j mark"... workaround:
1835 $name = 'mark' if $name eq 'MARK' and $rule->{domain_family} eq 'eb';
1837 set_target(%$rule, 'jump', $name);
1838 merge_keywords(%$rule, $defs->{keywords});
1841 # the main parser loop: read tokens, convert them into internal rule
1842 # structures
1843 sub enter($$) {
1844 my $lev = shift; # current recursion depth
1845 my $prev = shift; # previous rule hash
1847 # enter is the core of the firewall setup, it is a
1848 # simple parser program that recognizes keywords and
1849 # retreives parameters to set up the kernel routing
1850 # chains
1852 my $base_level = $script->{base_level} || 0;
1853 die if $base_level > $lev;
1855 my %rule;
1856 new_level(%rule, $prev);
1858 # read keywords 1 by 1 and dump into parser
1859 while (defined (my $keyword = next_token())) {
1860 # check if the current rule should be negated
1861 my $negated = $keyword eq '!';
1862 if ($negated) {
1863 # negation. get the next word which contains the 'real'
1864 # rule
1865 $keyword = getvar();
1867 error('unexpected end of file after negation')
1868 unless defined $keyword;
1871 # the core: parse all data
1872 for ($keyword)
1874 # deprecated keyword?
1875 if (exists $deprecated_keywords{$keyword}) {
1876 my $new_keyword = $deprecated_keywords{$keyword};
1877 warning("'$keyword' is deprecated, please use '$new_keyword' instead");
1878 $keyword = $new_keyword;
1881 # effectuation operator
1882 if ($keyword eq ';') {
1883 error('Empty rule before ";" not allowed')
1884 unless $rule{non_empty};
1886 if ($rule{has_rule} and not exists $rule{has_action}) {
1887 # something is wrong when a rule was specified,
1888 # but no action
1889 error('No action defined; did you mean "NOP"?');
1892 error('No chain defined') unless exists $rule{chain};
1894 $rule{script} = { filename => $script->{filename},
1895 line => $script->{line},
1898 mkrules(\%rule);
1900 # and clean up variables set in this level
1901 new_level(%rule, $prev);
1903 next;
1906 # conditional expression
1907 if ($keyword eq '@if') {
1908 unless (eval_bool(getvalues)) {
1909 collect_tokens;
1910 my $token = peek_token();
1911 if ($token and $token eq '@else') {
1912 require_next_token();
1913 } else {
1914 new_level(%rule, $prev);
1918 next;
1921 if ($keyword eq '@else') {
1922 # hack: if this "else" has not been eaten by the "if"
1923 # handler above, we believe it came from an if clause
1924 # which evaluated "true" - remove the "else" part now.
1925 collect_tokens;
1926 next;
1929 # hooks for custom shell commands
1930 if ($keyword eq 'hook') {
1931 warning("'hook' is deprecated, use '\@hook'");
1932 $keyword = '@hook';
1935 if ($keyword eq '@hook') {
1936 error('"hook" must be the first token in a command')
1937 if exists $rule{domain};
1939 my $position = getvar();
1940 my $hooks;
1941 if ($position eq 'pre') {
1942 $hooks = \@pre_hooks;
1943 } elsif ($position eq 'post') {
1944 $hooks = \@post_hooks;
1945 } elsif ($position eq 'flush') {
1946 $hooks = \@flush_hooks;
1947 } else {
1948 error("Invalid hook position: '$position'");
1951 push @$hooks, getvar();
1953 expect_token(';');
1954 next;
1957 # recursing operators
1958 if ($keyword eq '{') {
1959 # push stack
1960 my $old_stack_depth = @stack;
1962 unshift @stack, { auto => { %{$stack[0]{auto} || {}} } };
1964 # recurse
1965 enter($lev + 1, \%rule);
1967 # pop stack
1968 shift @stack;
1969 die unless @stack == $old_stack_depth;
1971 # after a block, the command is finished, clear this
1972 # level
1973 new_level(%rule, $prev);
1975 next;
1978 if ($keyword eq '}') {
1979 error('Unmatched "}"')
1980 if $lev <= $base_level;
1982 # consistency check: check if they havn't forgotten
1983 # the ';' after the last statement
1984 error('Missing semicolon before "}"')
1985 if $rule{non_empty};
1987 # and exit
1988 return;
1991 # include another file
1992 if ($keyword eq '@include' or $keyword eq 'include') {
1993 # don't call collect_filenames() if the file names
1994 # have been expanded already by @glob()
1995 my @files = peek_token() eq '@glob'
1996 ? to_array(getvalues)
1997 : collect_filenames(to_array(getvalues));
1998 $keyword = next_token;
1999 error('Missing ";" - "include FILENAME" must be the last command in a rule')
2000 unless defined $keyword and $keyword eq ';';
2002 foreach my $filename (@files) {
2003 # save old script, open new script
2004 my $old_script = $script;
2005 open_script($filename);
2006 $script->{base_level} = $lev + 1;
2008 # push stack
2009 my $old_stack_depth = @stack;
2011 my $stack = {};
2013 if (@stack > 0) {
2014 # include files may set variables for their parent
2015 $stack->{vars} = ($stack[0]{vars} ||= {});
2016 $stack->{functions} = ($stack[0]{functions} ||= {});
2017 $stack->{auto} = { %{ $stack[0]{auto} || {} } };
2020 my( $volume,$dirs,$file ) = File::Spec->splitpath( $filename );
2021 $stack->{auto}{FILENAME} = $filename;
2022 $stack->{auto}{FILEBNAME} = $file;
2023 $stack->{auto}{DIRNAME} = $dirs;
2025 unshift @stack, $stack;
2027 # parse the script
2028 enter($lev + 1, \%rule);
2030 #check for exit status
2031 error("'$script->{filename}': exit status is not 0") if not close $script->{handle};
2033 # pop stack
2034 shift @stack;
2035 die unless @stack == $old_stack_depth;
2037 # restore old script
2038 $script = $old_script;
2041 next;
2044 # definition of a variable or function
2045 if ($keyword eq '@def' or $keyword eq 'def') {
2046 error('"def" must be the first token in a command')
2047 if $rule{non_empty};
2049 my $type = require_next_token();
2050 if ($type eq '$') {
2051 my $name = require_next_token();
2052 error('invalid variable name')
2053 unless $name =~ /^\w+$/;
2055 expect_token('=');
2057 my $value = getvalues(undef, allow_negation => 1);
2059 expect_token(';');
2061 $stack[0]{vars}{$name} = $value
2062 unless exists $stack[-1]{vars}{$name};
2063 } elsif ($type eq '&') {
2064 my $name = require_next_token();
2065 error('invalid function name')
2066 unless $name =~ /^\w+$/;
2068 expect_token('(', 'function parameter list or "()" expected');
2070 my @params;
2071 while (1) {
2072 my $token = require_next_token();
2073 last if $token eq ')';
2075 if (@params > 0) {
2076 error('"," expected')
2077 unless $token eq ',';
2079 $token = require_next_token();
2082 error('"$" and parameter name expected')
2083 unless $token eq '$';
2085 $token = require_next_token();
2086 error('invalid function parameter name')
2087 unless $token =~ /^\w+$/;
2089 push @params, $token;
2092 my %function;
2094 $function{params} = \@params;
2096 expect_token('=');
2098 my $tokens = collect_tokens();
2099 $function{block} = 1 if grep { $_ eq '{' } @$tokens;
2100 $function{tokens} = $tokens;
2102 $stack[0]{functions}{$name} = \%function
2103 unless exists $stack[-1]{functions}{$name};
2104 } else {
2105 error('"$" (variable) or "&" (function) expected');
2108 next;
2111 # this rule has something which isn't inherited by its
2112 # parent closure. This variable is used in a lot of
2113 # syntax checks.
2115 $rule{non_empty} = 1;
2117 # def references
2118 if ($keyword eq '$') {
2119 error('variable references are only allowed as keyword parameter');
2122 if ($keyword eq '&') {
2123 my $name = require_next_token();
2124 error('function name expected')
2125 unless $name =~ /^\w+$/;
2127 my $function = lookup_function($name);
2128 error("no such function: \&$name")
2129 unless defined $function;
2131 my $paramdef = $function->{params};
2132 die unless defined $paramdef;
2134 my @params = get_function_params(allow_negation => 1);
2136 error("Wrong number of parameters for function '\&$name': "
2137 . @$paramdef . " expected, " . @params . " given")
2138 unless @params == @$paramdef;
2140 my %vars;
2141 for (my $i = 0; $i < @params; $i++) {
2142 $vars{$paramdef->[$i]} = $params[$i];
2145 if ($function->{block}) {
2146 # block {} always ends the current rule, so if the
2147 # function contains a block, we have to require
2148 # the calling rule also ends here
2149 expect_token(';');
2152 my @tokens = @{$function->{tokens}};
2153 for (my $i = 0; $i < @tokens; $i++) {
2154 if ($tokens[$i] eq '$' and $i + 1 < @tokens and
2155 exists $vars{$tokens[$i + 1]}) {
2156 my @value = to_array($vars{$tokens[$i + 1]});
2157 @value = ('(', @value, ')')
2158 unless @tokens == 1;
2159 splice(@tokens, $i, 2, @value);
2160 $i += @value - 2;
2161 } elsif ($tokens[$i] =~ m,^"(.*)"$,) {
2162 $tokens[$i] =~ s,\$(\w+),exists $vars{$1} ? $vars{$1} : "\$$1",eg;
2166 unshift @{$script->{tokens}}, @tokens;
2168 next;
2171 # where to put the rule?
2172 if ($keyword eq 'domain') {
2173 error('Domain is already specified')
2174 if exists $rule{domain};
2176 my $domains = getvalues();
2177 if (ref $domains) {
2178 my $tokens = collect_tokens(include_semicolon => 1,
2179 include_else => 1);
2181 my $old_line = $script->{line};
2182 my $old_handle = $script->{handle};
2183 my $old_tokens = $script->{tokens};
2184 my $old_base_level = $script->{base_level};
2185 unshift @$old_tokens, make_line_token($script->{line});
2186 delete $script->{handle};
2188 for my $domain (@$domains) {
2189 my %inner;
2190 new_level(%inner, \%rule);
2191 set_domain(%inner, $domain) or next;
2192 $inner{domain_both} = 1;
2193 $script->{base_level} = 0;
2194 $script->{tokens} = [ @$tokens ];
2195 enter(0, \%inner);
2198 $script->{base_level} = $old_base_level;
2199 $script->{tokens} = $old_tokens;
2200 $script->{handle} = $old_handle;
2201 $script->{line} = $old_line;
2203 new_level(%rule, $prev);
2204 } else {
2205 unless (set_domain(%rule, $domains)) {
2206 collect_tokens();
2207 new_level(%rule, $prev);
2211 next;
2214 if ($keyword eq 'table') {
2215 warning('Table is already specified')
2216 if exists $rule{table};
2217 $rule{table} = $stack[0]{auto}{TABLE} = getvalues();
2219 set_domain(%rule, $option{domain} || 'ip')
2220 unless exists $rule{domain};
2222 next;
2225 if ($keyword eq 'chain') {
2226 warning('Chain is already specified')
2227 if exists $rule{chain};
2229 my $chain = $rule{chain} = $stack[0]{auto}{CHAIN} = getvalues();
2231 # ferm 1.1 allowed lower case built-in chain names
2232 foreach (ref $rule{chain} ? @{$rule{chain}} : $rule{chain}) {
2233 error('Please write built-in chain names in upper case')
2234 if /^(?:input|forward|output|prerouting|postrouting)$/;
2237 set_domain(%rule, $option{domain} || 'ip')
2238 unless exists $rule{domain};
2240 $rule{table} = 'filter'
2241 unless exists $rule{table};
2243 my $domain = $rule{domain};
2244 foreach my $table (to_array $rule{table}) {
2245 foreach my $c (to_array $chain) {
2246 $domains{$domain}{tables}{$table}{chains}{$c} ||= {};
2250 next;
2253 error('Chain must be specified')
2254 unless exists $rule{chain};
2256 # policy for built-in chain
2257 if ($keyword eq 'policy') {
2258 error('Cannot specify matches for policy')
2259 if $rule{has_rule};
2261 my $policy = getvar();
2262 error("Invalid policy target: $policy")
2263 unless is_netfilter_core_target($policy);
2265 expect_token(';');
2267 my $domain = $rule{domain};
2268 my $domain_info = $domains{$domain};
2269 $domain_info->{enabled} = 1;
2271 foreach my $table (to_array $rule{table}) {
2272 foreach my $chain (to_array $rule{chain}) {
2273 $domain_info->{tables}{$table}{chains}{$chain}{policy} = $policy;
2277 new_level(%rule, $prev);
2278 next;
2281 # create a subchain
2282 if ($keyword eq '@subchain' or $keyword eq 'subchain' or $keyword eq '@gotosubchain') {
2283 error('Chain must be specified')
2284 unless exists $rule{chain};
2286 my $jumptype = ($keyword =~ /^\@go/) ? 'goto' : 'jump';
2287 my $jumpkey = $keyword;
2288 $jumpkey =~ s/^sub/\@sub/;
2290 error('No rule specified before $jumpkey')
2291 unless $rule{has_rule};
2293 my $subchain;
2294 my $token = peek_token();
2296 if ($token =~ /^(["'])(.*)\1$/s) {
2297 $subchain = $2;
2298 next_token();
2299 $keyword = next_token();
2300 } elsif ($token eq '{') {
2301 $keyword = next_token();
2302 $subchain = 'ferm_auto_' . ++$auto_chain;
2303 } else {
2304 $subchain = getvar();
2305 $keyword = next_token();
2308 my $domain = $rule{domain};
2309 foreach my $table (to_array $rule{table}) {
2310 $domains{$domain}{tables}{$table}{chains}{$subchain} ||= {};
2313 set_target(%rule, $jumptype, $subchain);
2315 error('"{" or chain name expected after $jumpkey')
2316 unless $keyword eq '{';
2318 # create a deep copy of %rule, only containing values
2319 # which must be in the subchain
2320 my %inner = ( cow => { keywords => 1, },
2321 match => {},
2322 options => [],
2324 $inner{$_} = $rule{$_} foreach qw(domain domain_family domain_both table keywords);
2325 $inner{chain} = $inner{auto}{CHAIN} = $subchain;
2327 if (exists $rule{protocol}) {
2328 $inner{protocol} = $rule{protocol};
2329 append_option(%inner, 'protocol', $inner{protocol});
2332 # create a new stack frame
2333 my $old_stack_depth = @stack;
2334 my $stack = { auto => { %{$stack[0]{auto} || {}} } };
2335 $stack->{auto}{CHAIN} = $subchain;
2336 unshift @stack, $stack;
2338 # enter the block
2339 enter($lev + 1, \%inner);
2341 # pop stack frame
2342 shift @stack;
2343 die unless @stack == $old_stack_depth;
2345 # now handle the parent - it's a jump to the sub chain
2346 $rule{script} = {
2347 filename => $script->{filename},
2348 line => $script->{line},
2351 mkrules(\%rule);
2353 # and clean up variables set in this level
2354 new_level(%rule, $prev);
2355 delete $rule{has_rule};
2357 next;
2360 # everything else must be part of a "real" rule, not just
2361 # "policy only"
2362 $rule{has_rule} = 1;
2364 # extended parameters:
2365 if ($keyword =~ /^mod(?:ule)?$/) {
2366 foreach my $module (to_array getvalues) {
2367 next if exists $rule{match}{$module};
2369 my $domain_family = $rule{domain_family};
2370 my $defs = $match_defs{$domain_family}{$module};
2372 append_option(%rule, 'match', $module);
2373 $rule{match}{$module} = 1;
2375 merge_keywords(%rule, $defs->{keywords})
2376 if defined $defs;
2379 next;
2382 # keywords from $rule{keywords}
2384 if (exists $rule{keywords}{$keyword}) {
2385 my $def = $rule{keywords}{$keyword};
2386 parse_option($def, %rule, \$negated);
2387 next;
2391 # actions
2394 # jump action
2395 if ($keyword eq 'jump') {
2396 set_target(%rule, 'jump', getvar());
2397 next;
2400 # goto action
2401 if ($keyword eq 'goto') {
2402 set_target(%rule, 'goto', getvar());
2403 next;
2406 # action keywords
2407 if (is_netfilter_core_target($keyword)) {
2408 set_target(%rule, 'jump', $keyword);
2409 next;
2412 if ($keyword eq 'NOP') {
2413 error('There can only one action per rule')
2414 if exists $rule{has_action};
2415 $rule{has_action} = 1;
2416 next;
2419 if (my $defs = is_netfilter_module_target($rule{domain_family}, $keyword)) {
2420 set_module_target(%rule, $keyword, $defs);
2421 next;
2425 # protocol specific options
2428 if ($keyword eq 'proto' or $keyword eq 'protocol') {
2429 my $protocol = parse_keyword(%rule,
2430 { params => 1, negation => 1 },
2431 \$negated);
2432 $rule{protocol} = $protocol;
2433 append_option(%rule, 'protocol', $rule{protocol});
2435 unless (ref $protocol) {
2436 $protocol = netfilter_canonical_protocol($protocol);
2437 my $domain_family = $rule{domain_family};
2438 if (my $defs = $proto_defs{$domain_family}{$protocol}) {
2439 merge_keywords(%rule, $defs->{keywords});
2440 my $module = netfilter_protocol_module($protocol);
2441 $rule{match}{$module} = 1;
2444 next;
2447 # port switches
2448 if ($keyword =~ /^[sd]port$/) {
2449 my $proto = $rule{protocol};
2450 error('To use sport or dport, you have to specify "proto tcp" or "proto udp" first')
2451 unless defined $proto and grep { /^(?:tcp|udp|udplite|dccp|sctp)$/ } to_array $proto;
2453 append_option(%rule, $keyword,
2454 getvalues(undef, allow_negation => 1));
2455 next;
2458 # default
2459 error("Unrecognized keyword: $keyword");
2462 # if the rule didn't reset the negated flag, it's not
2463 # supported
2464 error("Doesn't support negation: $keyword")
2465 if $negated;
2468 error('Missing "}" at end of file')
2469 if $lev > $base_level;
2471 # consistency check: check if they havn't forgotten
2472 # the ';' before the last statement
2473 error("Missing semicolon before end of file")
2474 if $rule{non_empty};
2477 sub execute_command {
2478 my ($command, $script) = @_;
2480 print LINES "$command\n"
2481 if $option{lines};
2482 return if $option{noexec};
2484 my $ret = system($command);
2485 unless ($ret == 0) {
2486 if ($? == -1) {
2487 print STDERR "failed to execute: $!\n";
2488 exit 1;
2489 } elsif ($? & 0x7f) {
2490 printf STDERR "child died with signal %d\n", $? & 0x7f;
2491 return 1;
2492 } else {
2493 print STDERR "(rule declared in $script->{filename}:$script->{line})\n"
2494 if defined $script;
2495 return $? >> 8;
2499 return;
2502 sub execute_slow($) {
2503 my $domain_info = shift;
2505 my $domain_cmd = $domain_info->{tools}{tables};
2507 my $status;
2508 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2509 my $table_cmd = "$domain_cmd -t $table";
2511 # reset chain policies
2512 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2513 next unless $chain_info->{builtin} or
2514 (not $table_info->{has_builtin} and
2515 is_netfilter_builtin_chain($table, $chain));
2516 $status ||= execute_command("$table_cmd -P $chain ACCEPT")
2517 unless $option{noflush};
2520 # clear
2521 unless ($option{noflush}) {
2522 $status ||= execute_command("$table_cmd -F");
2523 $status ||= execute_command("$table_cmd -X");
2526 next if $option{flush};
2528 # create chains / set policy
2529 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2530 if (is_netfilter_builtin_chain($table, $chain)) {
2531 if (exists $chain_info->{policy}) {
2532 $status ||= execute_command("$table_cmd -P $chain $chain_info->{policy}")
2533 unless $chain_info->{policy} eq 'ACCEPT';
2535 } else {
2536 if (exists $chain_info->{policy}) {
2537 $status ||= execute_command("$table_cmd -N $chain -P $chain_info->{policy}");
2539 else {
2540 $status ||= execute_command("$table_cmd -N $chain");
2545 # dump rules
2546 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2547 my $chain_cmd = "$table_cmd -A $chain";
2548 foreach my $rule (@{$chain_info->{rules}}) {
2549 $status ||= execute_command($chain_cmd . $rule->{rule});
2554 return $status;
2557 sub table_to_save($$) {
2558 my ($result_r, $table_info) = @_;
2560 foreach my $chain (sort keys %{$table_info->{chains}}) {
2561 my $chain_info = $table_info->{chains}{$chain};
2562 foreach my $rule (@{$chain_info->{rules}}) {
2563 $$result_r .= "-A $chain$rule->{rule}\n";
2568 sub rules_to_save($) {
2569 my ($domain_info) = @_;
2571 # convert this into an iptables-save text
2572 my $result = "# Generated by ferm $VERSION on " . localtime() . "\n";
2574 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2575 # select table
2576 $result .= '*' . $table . "\n";
2578 # create chains / set policy
2579 foreach my $chain (sort keys %{$table_info->{chains}}) {
2580 my $chain_info = $table_info->{chains}{$chain};
2581 my $policy = $option{flush} ? undef : $chain_info->{policy};
2582 unless (defined $policy) {
2583 if (is_netfilter_builtin_chain($table, $chain)) {
2584 $policy = 'ACCEPT';
2585 } else {
2586 next if $option{flush};
2587 $policy = '-';
2590 $result .= ":$chain $policy\ [0:0]\n";
2593 table_to_save(\$result, $table_info)
2594 unless $option{flush};
2596 # do it
2597 $result .= "COMMIT\n";
2600 return $result;
2603 sub restore_domain($$) {
2604 my ($domain_info, $save) = @_;
2606 my $path = $domain_info->{tools}{'tables-restore'};
2607 $path .= " --noflush" if $option{noflush};
2609 local *RESTORE;
2610 open RESTORE, "|$path"
2611 or die "Failed to run $path: $!\n";
2613 print RESTORE $save;
2615 close RESTORE
2616 or die "Failed to run $path\n";
2619 sub execute_fast($) {
2620 my $domain_info = shift;
2622 my $save = rules_to_save($domain_info);
2624 if ($option{lines}) {
2625 my $path = $domain_info->{tools}{'tables-restore'};
2626 $path .= " --noflush" if $option{noflush};
2627 print LINES "$path <<EOT\n"
2628 if $option{shell};
2629 print LINES $save;
2630 print LINES "EOT\n"
2631 if $option{shell};
2634 return if $option{noexec};
2636 eval {
2637 restore_domain($domain_info, $save);
2639 if ($@) {
2640 print STDERR $@;
2641 return 1;
2644 return;
2647 sub rollback() {
2648 my $error;
2649 while (my ($domain, $domain_info) = each %domains) {
2650 next unless $domain_info->{enabled};
2651 unless (defined $domain_info->{tools}{'tables-restore'}) {
2652 print STDERR "Cannot rollback domain '$domain' because there is no ${domain}tables-restore\n";
2653 next;
2656 my $reset = '';
2657 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2658 my $reset_chain = '';
2659 foreach my $chain (keys %{$table_info->{chains}}) {
2660 next unless is_netfilter_builtin_chain($table, $chain);
2661 $reset_chain .= ":${chain} ACCEPT [0:0]\n";
2663 $reset .= "*${table}\n${reset_chain}COMMIT\n"
2664 if length $reset_chain;
2667 $reset .= $domain_info->{previous}
2668 if defined $domain_info->{previous};
2670 restore_domain($domain_info, $reset);
2673 print STDERR "\nFirewall rules rolled back.\n" unless $error;
2674 exit 1;
2677 sub alrm_handler {
2678 # do nothing, just interrupt a system call
2681 sub confirm_rules {
2682 $SIG{ALRM} = \&alrm_handler;
2684 alarm(5);
2686 print STDERR "\n"
2687 . "ferm has applied the new firewall rules.\n"
2688 . "Please type 'yes' to confirm:\n";
2689 STDERR->flush();
2691 alarm($option{timeout});
2693 my $line = '';
2694 STDIN->sysread($line, 3);
2696 eval {
2697 require POSIX;
2698 POSIX::tcflush(*STDIN, 2);
2700 print STDERR "$@" if $@;
2702 $SIG{ALRM} = 'DEFAULT';
2704 return $line eq 'yes';
2707 # end of ferm
2709 __END__
2711 =head1 NAME
2713 ferm - a firewall rule parser for linux
2715 =head1 SYNOPSIS
2717 B<ferm> I<options> I<inputfiles>
2719 =head1 OPTIONS
2721 -n, --noexec Do not execute the rules, just simulate
2722 -F, --flush Flush all netfilter tables managed by ferm
2723 -l, --lines Show all rules that were created
2724 -i, --interactive Interactive mode: revert if user does not confirm
2725 -t, --timeout s Define interactive mode timeout in seconds
2726 --remote Remote mode; ignore host specific configuration.
2727 This implies --noexec and --lines.
2728 -V, --version Show current version number
2729 -h, --help Look at this text
2730 --slow Slow mode, don't use iptables-restore
2731 --shell Generate a shell script which calls iptables-restore
2732 --domain {ip|ip6} Handle only the specified domain
2733 --def '$name=v' Override a variable
2735 =cut