iptables: destination address for TPROXY target
[ferm.git] / src / ferm
blobea649a7c6d103d1e489f9c13da41714008eefba5
1 #!/usr/bin/perl
4 # ferm, a firewall setup program that makes firewall rules easy!
6 # Copyright (C) 2001-2012 Max Kellermann, Auke Kok
8 # Comments, questions, greetings and additions to this program
9 # may be sent to <ferm@foo-projects.org>
13 # This program is free software; you can redistribute it and/or modify
14 # it under the terms of the GNU General Public License as published by
15 # the Free Software Foundation; either version 2 of the License, or
16 # (at your option) any later version.
18 # This program is distributed in the hope that it will be useful,
19 # but WITHOUT ANY WARRANTY; without even the implied warranty of
20 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 # GNU General Public License for more details.
23 # You should have received a copy of the GNU General Public License
24 # along with this program; if not, write to the Free Software
25 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
28 # $Id$
30 use File::Spec;
32 BEGIN {
33 eval { require strict; import strict; };
34 $has_strict = not $@;
35 if ($@) {
36 # we need no vars.pm if there is not even strict.pm
37 $INC{'vars.pm'} = 1;
38 *vars::import = sub {};
39 } else {
40 require IO::Handle;
43 eval { require Getopt::Long; import Getopt::Long; };
44 $has_getopt = not $@;
47 use vars qw($has_strict $has_getopt);
49 use vars qw($VERSION);
51 $VERSION = '2.3.1';
52 $VERSION .= '~git';
54 ## interface variables
55 # %option = command line and other options
56 use vars qw(%option);
58 ## hooks
59 use vars qw(@pre_hooks @post_hooks @flush_hooks);
61 ## parser variables
62 # $script: current script file
63 # @stack = ferm's parser stack containing local variables
64 # $auto_chain = index for the next auto-generated chain
65 use vars qw($script @stack $auto_chain);
67 ## netfilter variables
68 # %domains = state information about all domains ("ip" and "ip6")
69 # - initialized: domain initialization is done
70 # - tools: hash providing the paths of the domain's tools
71 # - previous: save file of the previous ruleset, for rollback
72 # - tables{$name}: ferm state information about tables
73 # - has_builtin: whether built-in chains have been determined in this table
74 # - chains{$chain}: ferm state information about the chains
75 # - builtin: whether this is a built-in chain
76 use vars qw(%domains);
78 ## constants
79 use vars qw(%deprecated_keywords);
81 # keywords from ferm 1.1 which are deprecated, and the new one; these
82 # are automatically replaced, and a warning is printed
83 %deprecated_keywords = ( realgoto => 'goto',
86 # these hashes provide the Netfilter module definitions
87 use vars qw(%proto_defs %match_defs %target_defs);
90 # This subsubsystem allows you to support (most) new netfilter modules
91 # in ferm. Add a call to one of the "add_XY_def()" functions below.
93 # Ok, now about the cryptic syntax: the function "add_XY_def()"
94 # registers a new module. There are three kinds of modules: protocol
95 # module (e.g. TCP, ICMP), match modules (e.g. state, physdev) and
96 # target modules (e.g. DNAT, MARK).
98 # The first parameter is always the module name which is passed to
99 # iptables with "-p", "-m" or "-j" (depending on which kind of module
100 # this is).
102 # After that, you add an encoded string for each option the module
103 # supports. This is where it becomes tricky.
105 # foo defaults to an option with one argument (which may be a ferm
106 # array)
108 # foo*0 option without any arguments
110 # foo=s one argument which must not be a ferm array ('s' stands for
111 # 'scalar')
113 # u32=m an array which renders into multiple iptables options in one
114 # rule
116 # ctstate=c one argument, if it's an array, pass it to iptables as a
117 # single comma separated value; example:
118 # ctstate (ESTABLISHED RELATED) translates to:
119 # --ctstate ESTABLISHED,RELATED
121 # foo=sac three arguments: scalar, array, comma separated; you may
122 # concatenate more than one letter code after the '='
124 # foo&bar one argument; call the perl function '&bar()' which parses
125 # the argument
127 # !foo negation is allowed and the '!' is written before the keyword
129 # foo! same as above, but '!' is after the keyword and before the
130 # parameters
132 # to:=to-destination makes "to" an alias for "to-destination"; you have
133 # to add a declaration for option "to-destination"
136 # prototype declarations
137 sub open_script($);
138 sub resolve($\@$);
139 sub enter($$);
140 sub rollback();
141 sub execute_fast($);
142 sub execute_slow($);
143 sub join_value($$);
144 sub ipfilter($@);
146 # add a module definition
147 sub add_def_x {
148 my $defs = shift;
149 my $domain_family = shift;
150 my $params_default = shift;
151 my $name = shift;
152 die if exists $defs->{$domain_family}{$name};
153 my $def = $defs->{$domain_family}{$name} = {};
154 foreach (@_) {
155 my $keyword = $_;
156 my $k;
158 if ($keyword =~ s,:=(\S+)$,,) {
159 $k = $def->{keywords}{$1} || die;
160 $k->{ferm_name} ||= $keyword;
161 } else {
162 my $params = $params_default;
163 $params = $1 if $keyword =~ s,\*(\d+)$,,;
164 $params = $1 if $keyword =~ s,=([acs]+|m)$,,;
165 if ($keyword =~ s,&(\S+)$,,) {
166 $params = eval "\\&$1";
167 die $@ if $@;
170 $k = {};
171 $k->{params} = $params if $params;
173 $k->{negation} = $k->{pre_negation} = 1 if $keyword =~ s,^!,,;
174 $k->{negation} = 1 if $keyword =~ s,!$,,;
175 $k->{name} = $keyword;
178 $def->{keywords}{$keyword} = $k;
181 return $def;
184 # add a protocol module definition
185 sub add_proto_def_x(@) {
186 my $domain_family = shift;
187 add_def_x(\%proto_defs, $domain_family, 1, @_);
190 # add a match module definition
191 sub add_match_def_x(@) {
192 my $domain_family = shift;
193 add_def_x(\%match_defs, $domain_family, 1, @_);
196 # add a target module definition
197 sub add_target_def_x(@) {
198 my $domain_family = shift;
199 add_def_x(\%target_defs, $domain_family, 's', @_);
202 sub add_def {
203 my $defs = shift;
204 add_def_x($defs, 'ip', @_);
207 # add a protocol module definition
208 sub add_proto_def(@) {
209 add_def(\%proto_defs, 1, @_);
212 # add a match module definition
213 sub add_match_def(@) {
214 add_def(\%match_defs, 1, @_);
217 # add a target module definition
218 sub add_target_def(@) {
219 add_def(\%target_defs, 's', @_);
222 add_proto_def 'dccp', qw(dccp-types!=c dccp-option!);
223 add_proto_def 'mh', qw(mh-type!);
224 add_proto_def 'icmp', qw(icmp-type! icmpv6-type:=icmp-type);
225 add_proto_def 'sctp', qw(chunk-types!=sc);
226 add_proto_def 'tcp', qw(tcp-flags!=cc !syn*0 tcp-option! mss);
227 add_proto_def 'udp', qw();
229 add_match_def '',
230 # --source, --destination
231 qw(source!&address_magic saddr:=source),
232 qw(destination!&address_magic daddr:=destination),
233 # --in-interface
234 qw(in-interface! interface:=in-interface if:=in-interface),
235 # --out-interface
236 qw(out-interface! outerface:=out-interface of:=out-interface),
237 # --fragment
238 qw(!fragment*0);
239 add_match_def 'account', qw(aaddr=s aname=s ashort*0);
240 add_match_def 'addrtype', qw(!src-type !dst-type),
241 qw(limit-iface-in*0 limit-iface-out*0);
242 add_match_def 'ah', qw(ahspi! ahlen! ahres*0);
243 add_match_def 'bpf', qw(bytecode);
244 add_match_def 'comment', qw(comment=s);
245 add_match_def 'condition', qw(condition!);
246 add_match_def 'connbytes', qw(!connbytes connbytes-dir connbytes-mode);
247 add_match_def 'connlabel', qw(!label set*0);
248 add_match_def 'connlimit', qw(!connlimit-upto !connlimit-above connlimit-mask connlimit-saddr*0 connlimit-daddr*0);
249 add_match_def 'connmark', qw(!mark);
250 add_match_def 'conntrack', qw(!ctstate=c !ctproto ctorigsrc! ctorigdst! ctorigsrcport! ctorigdstport!),
251 qw(ctreplsrc! ctrepldst! !ctstatus !ctexpire=s ctdir=s);
252 add_match_def 'cpu', qw(!cpu);
253 add_match_def 'dscp', qw(dscp dscp-class);
254 add_match_def 'dst', qw(!dst-len=s dst-opts=c);
255 add_match_def 'ecn', qw(ecn-tcp-cwr*0 ecn-tcp-ece*0 ecn-ip-ect);
256 add_match_def 'esp', qw(espspi!);
257 add_match_def 'eui64';
258 add_match_def 'fuzzy', qw(lower-limit=s upper-limit=s);
259 add_match_def 'geoip', qw(!src-cc=s !dst-cc=s);
260 add_match_def 'hbh', qw(hbh-len! hbh-opts=c);
261 add_match_def 'helper', qw(helper);
262 add_match_def 'hl', qw(hl-eq! hl-lt=s hl-gt=s);
263 add_match_def 'hashlimit', qw(hashlimit=s hashlimit-burst=s hashlimit-mode=c hashlimit-name=s),
264 qw(hashlimit-upto=s hashlimit-above=s),
265 qw(hashlimit-srcmask=s hashlimit-dstmask=s),
266 qw(hashlimit-htable-size=s hashlimit-htable-max=s),
267 qw(hashlimit-htable-expire=s hashlimit-htable-gcinterval=s);
268 add_match_def 'iprange', qw(!src-range !dst-range);
269 add_match_def 'ipv4options', qw(ssrr*0 lsrr*0 no-srr*0 !rr*0 !ts*0 !ra*0 !any-opt*0);
270 add_match_def 'ipv6header', qw(header!=c soft*0);
271 add_match_def 'ipvs', qw(!ipvs*0 !vproto !vaddr !vport vdir !vportctl);
272 add_match_def 'length', qw(length!);
273 add_match_def 'limit', qw(limit=s limit-burst=s);
274 add_match_def 'mac', qw(mac-source!);
275 add_match_def 'mark', qw(!mark);
276 add_match_def 'multiport', qw(source-ports!&multiport_params),
277 qw(destination-ports!&multiport_params ports!&multiport_params);
278 add_match_def 'nth', qw(every counter start packet);
279 add_match_def 'osf', qw(!genre ttl=s log=s);
280 add_match_def 'owner', qw(!uid-owner !gid-owner pid-owner sid-owner),
281 qw(cmd-owner !socket-exists=0);
282 add_match_def 'physdev', qw(physdev-in! physdev-out!),
283 qw(!physdev-is-in*0 !physdev-is-out*0 !physdev-is-bridged*0);
284 add_match_def 'pkttype', qw(pkt-type!),
285 add_match_def 'policy',
286 qw(dir pol strict*0 !reqid !spi !proto !mode !tunnel-src !tunnel-dst next*0);
287 add_match_def 'psd', qw(psd-weight-threshold psd-delay-threshold),
288 qw(psd-lo-ports-weight psd-hi-ports-weight);
289 add_match_def 'quota', qw(quota=s);
290 add_match_def 'random', qw(average);
291 add_match_def 'realm', qw(realm!);
292 add_match_def 'recent', qw(name=s !set*0 !remove*0 !rcheck*0 !update*0 !seconds !hitcount rttl*0 rsource*0 rdest*0);
293 add_match_def 'rpfilter', qw(loose*0 validmark*0 accept-local*0 invert*0);
294 add_match_def 'rt', qw(rt-type! rt-segsleft! rt-len! rt-0-res*0 rt-0-addrs=c rt-0-not-strict*0);
295 add_match_def 'set', qw(!match-set=sc set:=match-set);
296 add_match_def 'state', qw(!state=c);
297 add_match_def 'statistic', qw(mode=s probability=s every=s packet=s);
298 add_match_def 'string', qw(algo=s from=s to=s string hex-string);
299 add_match_def 'tcpmss', qw(!mss);
300 add_match_def 'time', qw(timestart=s timestop=s days=c datestart=s datestop=s),
301 qw(!monthday=c !weekdays=c utc*0 localtz*0);
302 add_match_def 'tos', qw(!tos);
303 add_match_def 'ttl', qw(ttl-eq ttl-lt=s ttl-gt=s);
304 add_match_def 'u32', qw(!u32=m);
306 add_target_def 'AUDIT', qw(type);
307 add_target_def 'BALANCE', qw(to-destination to:=to-destination);
308 add_target_def 'CHECKSUM', qw(checksum-fill*0);
309 add_target_def 'CLASSIFY', qw(set-class);
310 add_target_def 'CLUSTERIP', qw(new*0 hashmode clustermac total-nodes local-node hash-init);
311 add_target_def 'CONNMARK', qw(set-xmark save-mark*0 restore-mark*0 nfmask ctmask),
312 qw(and-mark or-mark xor-mark set-mark mask);
313 add_target_def 'CONNSECMARK', qw(save*0 restore*0);
314 add_target_def 'CT', qw(notrack*0 helper ctevents=c expevents=c zone timeout);
315 add_target_def 'DNAT', qw(to-destination=m to:=to-destination persistent*0 random*0);
316 add_target_def 'DNPT', qw(src-pfx dst-pfx);
317 add_target_def 'DSCP', qw(set-dscp set-dscp-class);
318 add_target_def 'ECN', qw(ecn-tcp-remove*0);
319 add_target_def 'HL', qw(hl-set hl-dec hl-inc);
320 add_target_def 'HMARK', qw(hmark-tuple hmark-mod hmark-offset),
321 qw(hmark-src-prefix hmark-dst-prefix hmark-sport-mask),
322 qw(hmark-dport-mask hmark-spi-mask hmark-proto-mask hmark-rnd);
323 add_target_def 'IDLETIMER', qw(timeout label);
324 add_target_def 'IPV4OPTSSTRIP';
325 add_target_def 'LED', qw(led-trigger-id led-delay led-always-blink*0);
326 add_target_def 'LOG', qw(log-level log-prefix),
327 qw(log-tcp-sequence*0 log-tcp-options*0 log-ip-options*0 log-uid*0);
328 add_target_def 'MARK', qw(set-mark set-xmark and-mark or-mark xor-mark);
329 add_target_def 'MASQUERADE', qw(to-ports random*0);
330 add_target_def 'MIRROR';
331 add_target_def 'NETMAP', qw(to);
332 add_target_def 'NFLOG', qw(nflog-group nflog-prefix nflog-range nflog-threshold);
333 add_target_def 'NFQUEUE', qw(queue-num queue-balance queue-bypass*0 queue-cpu-fanout*0);
334 add_target_def 'NOTRACK';
335 add_target_def 'RATEEST', qw(rateest-name rateest-interval rateest-ewmalog);
336 add_target_def 'REDIRECT', qw(to-ports random*0);
337 add_target_def 'REJECT', qw(reject-with);
338 add_target_def 'ROUTE', qw(oif iif gw continue*0 tee*0);
339 add_target_def 'SAME', qw(to nodst*0 random*0);
340 add_target_def 'SECMARK', qw(selctx);
341 add_target_def 'SET', qw(add-set=sc del-set=sc timeout exist*0);
342 add_target_def 'SNAT', qw(to-source=m to:=to-source persistent*0 random*0);
343 add_target_def 'SNPT', qw(src-pfx dst-pfx);
344 add_target_def 'SYNPROXY', qw(sack-perm*0 timestamp*0 ecn*0 wscale=s mss=s);
345 add_target_def 'TARPIT';
346 add_target_def 'TCPMSS', qw(set-mss clamp-mss-to-pmtu*0);
347 add_target_def 'TCPOPTSTRIP', qw(strip-options=c);
348 add_target_def 'TEE', qw(gateway);
349 add_target_def 'TOS', qw(set-tos and-tos or-tos xor-tos);
350 add_target_def 'TPROXY', qw(tproxy-mark on-ip on-port);
351 add_target_def 'TRACE';
352 add_target_def 'TTL', qw(ttl-set ttl-dec ttl-inc);
353 add_target_def 'ULOG', qw(ulog-nlgroup ulog-prefix ulog-cprange ulog-qthreshold);
355 add_match_def_x 'arp', '',
356 # ip
357 qw(source-ip! destination-ip! saddr:=source-ip daddr:=destination-ip),
358 # mac
359 qw(source-mac! destination-mac!),
360 # --in-interface
361 qw(in-interface! interface:=in-interface if:=in-interface),
362 # --out-interface
363 qw(out-interface! outerface:=out-interface of:=out-interface),
364 # misc
365 qw(h-length=s opcode=s h-type=s proto-type=s),
366 qw(mangle-ip-s=s mangle-ip-d=s mangle-mac-s=s mangle-mac-d=s mangle-target=s);
368 add_proto_def_x 'eb', 'IPv4',
369 qw(ip-source! ip-destination! ip-src:=ip-source ip-dst:=ip-destination),
370 qw(ip-tos!),
371 qw(ip-protocol! ip-proto:=ip-protocol),
372 qw(ip-source-port! ip-sport:=ip-source-port),
373 qw(ip-destination-port! ip-dport:=ip-destination-port);
375 add_proto_def_x 'eb', 'IPv6',
376 qw(ip6-source! ip6-destination! ip6-src:=ip6-source ip6-dst:=ip6-destination),
377 qw(ip6-tclass!),
378 qw(ip6-protocol! ip6-proto:=ip6-protocol),
379 qw(ip6-source-port! ip6-sport:=ip6-source-port),
380 qw(ip6-destination-port! ip6-dport:=ip6-destination-port);
382 add_proto_def_x 'eb', 'ARP',
383 qw(!arp-gratuitous*0),
384 qw(arp-opcode! arp-htype!=ss arp-ptype!=ss),
385 qw(arp-ip-src! arp-ip-dst! arp-mac-src! arp-mac-dst!);
387 add_proto_def_x 'eb', 'RARP',
388 qw(!arp-gratuitous*0),
389 qw(arp-opcode! arp-htype!=ss arp-ptype!=ss),
390 qw(arp-ip-src! arp-ip-dst! arp-mac-src! arp-mac-dst!);
392 add_proto_def_x 'eb', '802_1Q',
393 qw(vlan-id! vlan-prio! vlan-encap!),
395 add_match_def_x 'eb', '',
396 # --in-interface
397 qw(in-interface! interface:=in-interface if:=in-interface),
398 # --out-interface
399 qw(out-interface! outerface:=out-interface of:=out-interface),
400 # logical interface
401 qw(logical-in! logical-out!),
402 # --source, --destination
403 qw(source! saddr:=source destination! daddr:=destination),
404 # 802.3
405 qw(802_3-sap! 802_3-type!),
406 # among
407 qw(!among-dst=c !among-src=c !among-dst-file !among-src-file),
408 # limit
409 qw(limit=s limit-burst=s),
410 # mark_m
411 qw(mark!),
412 # pkttype
413 qw(pkttype-type!),
414 # stp
415 qw(stp-type! stp-flags! stp-root-prio! stp-root-addr! stp-root-cost!),
416 qw(stp-sender-prio! stp-sender-addr! stp-port! stp-msg-age! stp-max-age!),
417 qw(stp-hello-time! stp-forward-delay!),
418 # log
419 qw(log*0 log-level=s log-prefix=s log-ip*0 log-arp*0);
421 add_target_def_x 'eb', 'arpreply', qw(arpreply-mac arpreply-target);
422 add_target_def_x 'eb', 'dnat', qw(to-destination dnat-target);
423 add_target_def_x 'eb', 'MARK', qw(set-mark mark-target);
424 add_target_def_x 'eb', 'redirect', qw(redirect-target);
425 add_target_def_x 'eb', 'snat', qw(to-source snat-target snat-arp*0);
427 # import-ferm uses the above tables
428 return 1 if $0 =~ /import-ferm$/;
430 # parameter parser for ipt_multiport
431 sub multiport_params {
432 my $rule = shift;
434 # multiport only allows 15 ports at a time. For this
435 # reason, we do a little magic here: split the ports
436 # into portions of 15, and handle these portions as
437 # array elements
439 my $proto = $rule->{protocol};
440 error('To use multiport, you have to specify "proto tcp" or "proto udp" first')
441 unless defined $proto and grep { /^(?:tcp|udp|udplite)$/ } to_array($proto);
443 my $value = getvalues(undef, allow_negation => 1,
444 allow_array_negation => 1);
445 if (ref $value and ref $value eq 'ARRAY') {
446 my @value = @$value;
447 my @params;
449 while (@value) {
450 push @params, join(',', splice(@value, 0, 15));
453 return @params == 1
454 ? $params[0]
455 : \@params;
456 } else {
457 return join_value(',', $value);
461 sub ipfilter($@) {
462 my $domain = shift;
463 my @ips;
464 # very crude IPv4/IPv6 address detection
465 if ($domain eq 'ip') {
466 @ips = grep { !/:[0-9a-f]*:/ } @_;
467 } elsif ($domain eq 'ip6') {
468 @ips = grep { !m,^[0-9./]+$,s } @_;
470 return @ips;
473 sub address_magic {
474 my $rule = shift;
475 my $domain = $rule->{domain};
476 my $value = getvalues(undef, allow_negation => 1);
478 my @ips;
479 my $negated = 0;
480 if (ref $value and ref $value eq 'ARRAY') {
481 @ips = @$value;
482 } elsif (ref $value and ref $value eq 'negated') {
483 @ips = @$value;
484 $negated = 1;
485 } elsif (ref $value) {
486 die;
487 } else {
488 @ips = ($value);
491 # only do magic on domain (ip ip6); do not process on a single-stack rule
492 # as to let admins spot their errors instead of silently ignoring them
493 @ips = ipfilter($domain, @ips) if defined $rule->{domain_both};
495 if ($negated && scalar @ips) {
496 return bless \@ips, 'negated';
497 } else {
498 return \@ips;
502 # initialize stack: command line definitions
503 unshift @stack, {};
505 # Get command line stuff
506 if ($has_getopt) {
507 my ($opt_noexec, $opt_flush, $opt_noflush, $opt_lines, $opt_interactive,
508 $opt_timeout, $opt_help,
509 $opt_version, $opt_test, $opt_fast, $opt_slow, $opt_shell,
510 $opt_domain);
512 Getopt::Long::Configure('bundling', 'auto_help', 'no_ignore_case',
513 'no_auto_abbrev');
515 sub opt_def {
516 my ($opt, $value) = @_;
517 die 'Invalid --def specification'
518 unless $value =~ /^\$?(\w+)=(.*)$/s;
519 my ($name, $unparsed_value) = ($1, $2);
520 my $tokens = tokenize_string($unparsed_value);
521 $value = getvalues(sub { shift @$tokens; });
522 die 'Extra tokens after --def'
523 if @$tokens > 0;
524 $stack[0]{vars}{$name} = $value;
527 local $SIG{__WARN__} = sub { die $_[0]; };
528 GetOptions('noexec|n' => \$opt_noexec,
529 'flush|F' => \$opt_flush,
530 'noflush' => \$opt_noflush,
531 'lines|l' => \$opt_lines,
532 'interactive|i' => \$opt_interactive,
533 'timeout|t=s' => \$opt_timeout,
534 'help|h' => \$opt_help,
535 'version|V' => \$opt_version,
536 test => \$opt_test,
537 remote => \$opt_test,
538 fast => \$opt_fast,
539 slow => \$opt_slow,
540 shell => \$opt_shell,
541 'domain=s' => \$opt_domain,
542 'def=s' => \&opt_def,
545 if (defined $opt_help) {
546 require Pod::Usage;
547 Pod::Usage::pod2usage(-exitstatus => 0);
550 if (defined $opt_version) {
551 printversion();
552 exit 0;
555 $option{noexec} = $opt_noexec || $opt_test;
556 $option{flush} = $opt_flush;
557 $option{noflush} = $opt_noflush;
558 $option{lines} = $opt_lines || $opt_test || $opt_shell;
559 $option{interactive} = $opt_interactive && !$opt_noexec;
560 $option{timeout} = defined $opt_timeout ? $opt_timeout : "30";
561 $option{test} = $opt_test;
562 $option{fast} = !$opt_slow;
563 $option{shell} = $opt_shell;
565 die("ferm interactive mode not possible: /dev/stdin is not a tty\n")
566 if $option{interactive} and not -t STDIN;
567 die("ferm interactive mode not possible: /dev/stderr is not a tty\n")
568 if $option{interactive} and not -t STDERR;
569 die("ferm timeout has no sense without interactive mode")
570 if not $opt_interactive and defined $opt_timeout;
571 die("invalid timeout. must be an integer")
572 if defined $opt_timeout and not $opt_timeout =~ /^[+-]?\d+$/;
574 $option{domain} = $opt_domain if defined $opt_domain;
575 } else {
576 # tiny getopt emulation for microperl
577 my $filename;
578 foreach (@ARGV) {
579 if ($_ eq '--noexec' or $_ eq '-n') {
580 $option{noexec} = 1;
581 } elsif ($_ eq '--lines' or $_ eq '-l') {
582 $option{lines} = 1;
583 } elsif ($_ eq '--fast') {
584 $option{fast} = 1;
585 } elsif ($_ eq '--test') {
586 $option{test} = 1;
587 $option{noexec} = 1;
588 $option{lines} = 1;
589 } elsif ($_ eq '--shell') {
590 $option{$_} = 1 foreach qw(shell fast lines);
591 } elsif (/^-/) {
592 printf STDERR "Usage: ferm [--noexec] [--lines] [--fast] [--shell] FILENAME\n";
593 exit 1;
594 } else {
595 $filename = $_;
598 undef @ARGV;
599 push @ARGV, $filename;
602 unless (@ARGV == 1) {
603 require Pod::Usage;
604 Pod::Usage::pod2usage(-exitstatus => 1);
607 if ($has_strict) {
608 open LINES, ">&STDOUT" if $option{lines};
609 open STDOUT, ">&STDERR" if $option{shell};
610 } else {
611 # microperl can't redirect file handles
612 *LINES = *STDOUT;
614 if ($option{fast} and not $option{noexec}) {
615 print STDERR "Sorry, ferm on microperl does not allow --fast without --noexec\n";
616 exit 1
620 unshift @stack, {};
621 open_script($ARGV[0]);
623 my( $volume,$dirs,$file ) = File::Spec->splitpath( $ARGV[0] );
624 $stack[0]{auto}{FILENAME} = $ARGV[0];
625 $stack[0]{auto}{FILEBNAME} = $file;
626 $stack[0]{auto}{DIRNAME} = $dirs;
630 # parse all input recursively
631 enter(0, undef);
632 die unless @stack == 2;
634 # enable/disable hooks depending on --flush
636 if ($option{flush}) {
637 undef @pre_hooks;
638 undef @post_hooks;
639 } else {
640 undef @flush_hooks;
643 # execute all generated rules
644 my $status;
646 foreach my $cmd (@pre_hooks) {
647 print LINES "$cmd\n" if $option{lines};
648 system($cmd) unless $option{noexec};
651 while (my ($domain, $domain_info) = each %domains) {
652 next unless $domain_info->{enabled};
653 my $s = $option{fast} &&
654 defined $domain_info->{tools}{'tables-restore'}
655 ? execute_fast($domain_info) : execute_slow($domain_info);
656 $status = $s if defined $s;
659 foreach my $cmd (@post_hooks, @flush_hooks) {
660 print LINES "$cmd\n" if $option{lines};
661 system($cmd) unless $option{noexec};
664 if (defined $status) {
665 rollback();
666 exit $status;
669 # ask user, and rollback if there is no confirmation
671 if ($option{interactive}) {
672 if ($option{shell}) {
673 print LINES "echo 'ferm has applied the new firewall rules.'\n";
674 print LINES "echo 'Please press Ctrl-C to confirm.'\n";
675 print LINES "sleep $option{timeout}\n";
676 while (my ($domain, $domain_info) = each %domains) {
677 my $restore = $domain_info->{tools}{'tables-restore'};
678 next unless defined $restore;
679 print LINES "$restore <\$${domain}_tmp\n";
683 confirm_rules() or rollback() unless $option{noexec};
686 exit 0;
688 # end of program execution!
691 # funcs
693 sub printversion {
694 print "ferm $VERSION\n";
695 print "Copyright (C) 2001-2012 Max Kellermann, Auke Kok\n";
696 print "This program is free software released under GPLv2.\n";
697 print "See the included COPYING file for license details.\n";
701 sub error {
702 # returns a nice formatted error message, showing the
703 # location of the error.
704 my $tabs = 0;
705 my @lines;
706 my $l = 0;
707 my @words = map { @$_ } @{$script->{past_tokens}};
709 for my $w ( 0 .. $#words ) {
710 if ($words[$w] eq "\x29")
711 { $l++ ; $lines[$l] = " " x ($tabs-- -1) ;};
712 if ($words[$w] eq "\x28")
713 { $l++ ; $lines[$l] = " " x $tabs++ ;};
714 if ($words[$w] eq "\x7d")
715 { $l++ ; $lines[$l] = " " x ($tabs-- -1) ;};
716 if ($words[$w] eq "\x7b")
717 { $l++ ; $lines[$l] = " " x $tabs++ ;};
718 if ( $l > $#lines ) { $lines[$l] = "" };
719 $lines[$l] .= $words[$w] . " ";
720 if ($words[$w] eq "\x28")
721 { $l++ ; $lines[$l] = " " x $tabs ;};
722 if (($words[$w] eq "\x29") && ($words[$w+1] ne "\x7b"))
723 { $l++ ; $lines[$l] = " " x $tabs ;};
724 if ($words[$w] eq "\x7b")
725 { $l++ ; $lines[$l] = " " x $tabs ;};
726 if (($words[$w] eq "\x7d") && ($words[$w+1] ne "\x7d"))
727 { $l++ ; $lines[$l] = " " x $tabs ;};
728 if (($words[$w] eq "\x3b") && ($words[$w+1] ne "\x7d"))
729 { $l++ ; $lines[$l] = " " x $tabs ;}
730 if ($words[$w-1] eq "option")
731 { $l++ ; $lines[$l] = " " x $tabs ;}
733 my $start = $#lines - 4;
734 if ($start < 0) { $start = 0 } ;
735 print STDERR "Error in $script->{filename} line $script->{line}:\n";
736 for $l ( $start .. $#lines)
737 { print STDERR $lines[$l]; if ($l != $#lines ) {print STDERR "\n"} ; };
738 print STDERR "<--\n";
739 die("@_\n");
742 # print a warning message about code from an input file
743 sub warning {
744 print STDERR "Warning in $script->{filename} line $script->{line}: "
745 . (shift) . "\n";
748 sub find_tool($) {
749 my $name = shift;
750 return $name if $option{test};
751 for my $path ('/sbin', split ':', $ENV{PATH}) {
752 my $ret = "$path/$name";
753 return $ret if -x $ret;
755 die "$name not found in PATH\n";
758 sub initialize_domain {
759 my $domain = shift;
760 my $domain_info = $domains{$domain} ||= {};
762 return if exists $domain_info->{initialized};
764 die "Invalid domain '$domain'\n" unless $domain =~ /^(?:ip6?|arp|eb)$/;
766 my @tools = qw(tables);
767 push @tools, qw(tables-save tables-restore)
768 if $domain =~ /^ip6?$/;
770 # determine the location of this domain's tools
771 my %tools = map { $_ => find_tool($domain . $_) } @tools;
772 $domain_info->{tools} = \%tools;
774 # make tables-save tell us about the state of this domain
775 # (which tables and chains do exist?), also remember the old
776 # save data which may be used later by the rollback function
777 local *SAVE;
778 if (!$option{test} &&
779 exists $tools{'tables-save'} &&
780 open(SAVE, "$tools{'tables-save'}|")) {
781 my $save = '';
783 my $table_info;
784 while (<SAVE>) {
785 $save .= $_;
787 if (/^\*(\w+)/) {
788 my $table = $1;
789 $table_info = $domain_info->{tables}{$table} ||= {};
790 } elsif (defined $table_info and /^:(\w+)\s+(\S+)/
791 and $2 ne '-') {
792 $table_info->{chains}{$1}{builtin} = 1;
793 $table_info->{has_builtin} = 1;
797 # for rollback
798 $domain_info->{previous} = $save;
801 if ($option{shell} && $option{interactive} &&
802 exists $tools{'tables-save'}) {
803 print LINES "${domain}_tmp=\$(mktemp ferm.XXXXXXXXXX)\n";
804 print LINES "$tools{'tables-save'} >\$${domain}_tmp\n";
807 $domain_info->{initialized} = 1;
810 sub check_domain($) {
811 my $domain = shift;
812 my @result;
814 return if exists $option{domain}
815 and $domain ne $option{domain};
817 eval {
818 initialize_domain($domain);
820 error($@) if $@;
822 return 1;
825 # split the input string into words and delete comments
826 sub tokenize_string($) {
827 my $string = shift;
829 my @ret;
831 foreach my $word ($string =~ m/(".*?"|'.*?'|`.*?`|[!,=&\$\%\(\){};]|[-+\w\/\.:]+|@\w+|#)/g) {
832 last if $word eq '#';
833 push @ret, $word;
836 return \@ret;
839 # generate a "line" special token, that marks the line number; these
840 # special tokens are inserted after each line break, so ferm keeps
841 # track of line numbers
842 sub make_line_token($) {
843 my $line = shift;
844 return bless(\$line, 'line');
847 # read some more tokens from the input file into a buffer
848 sub prepare_tokens() {
849 my $tokens = $script->{tokens};
850 while (@$tokens == 0) {
851 my $handle = $script->{handle};
852 return unless defined $handle;
853 my $line = <$handle>;
854 return unless defined $line;
856 push @$tokens, make_line_token($script->{line} + 1);
858 # the next parser stage eats this
859 push @$tokens, @{tokenize_string($line)};
862 return 1;
865 sub handle_special_token($) {
866 my $token = shift;
867 die unless ref $token;
868 if (ref $token eq 'line') {
869 $script->{line} = $$token;
870 } else {
871 die;
875 sub handle_special_tokens() {
876 my $tokens = $script->{tokens};
877 while (@$tokens > 0 and ref $tokens->[0]) {
878 handle_special_token(shift @$tokens);
882 # wrapper for prepare_tokens() which handles "special" tokens
883 sub prepare_normal_tokens() {
884 my $tokens = $script->{tokens};
885 while (1) {
886 handle_special_tokens();
887 return 1 if @$tokens > 0;
888 return unless prepare_tokens();
892 # open a ferm sub script
893 sub open_script($) {
894 my $filename = shift;
896 for (my $s = $script; defined $s; $s = $s->{parent}) {
897 die("Circular reference in $script->{filename} line $script->{line}: $filename\n")
898 if $s->{filename} eq $filename;
901 my $handle;
902 if ($filename eq '-') {
903 # Note that this only allowed in the command-line argument and not
904 # @includes, since those are filtered by collect_filenames()
905 $handle = *STDIN;
906 # also set a filename label so that error messages are more helpful
907 $filename = "<stdin>";
908 } else {
909 local *FILE;
910 open FILE, "$filename" or die("Failed to open $filename: $!\n");
911 $handle = *FILE;
914 $script = { filename => $filename,
915 handle => $handle,
916 line => 0,
917 past_tokens => [],
918 tokens => [],
919 parent => $script,
922 return $script;
925 # collect script filenames which are being included
926 sub collect_filenames(@) {
927 my @ret;
929 # determine the current script's parent directory for relative
930 # file names
931 die unless defined $script;
932 my $parent_dir = $script->{filename} =~ m,^(.*/),
933 ? $1 : './';
935 foreach my $pathname (@_) {
936 # non-absolute file names are relative to the parent script's
937 # file name
938 $pathname = $parent_dir . $pathname
939 unless $pathname =~ m,^/|\|$,;
941 if ($pathname =~ m,/$,) {
942 # include all regular files in a directory
944 error("'$pathname' is not a directory")
945 unless -d $pathname;
947 local *DIR;
948 opendir DIR, $pathname
949 or error("Failed to open directory '$pathname': $!");
950 my @names = readdir DIR;
951 closedir DIR;
953 # sort those names for a well-defined order
954 foreach my $name (sort { $a cmp $b } @names) {
955 # ignore dpkg's backup files
956 next if $name =~ /\.dpkg-(old|dist|new|tmp)$/;
957 # don't include hidden and backup files
958 next if $name =~ /^\.|~$/;
960 my $filename = $pathname . $name;
961 push @ret, $filename
962 if -f $filename;
964 } elsif ($pathname =~ m,\|$,) {
965 # run a program and use its output
966 push @ret, $pathname;
967 } elsif ($pathname =~ m,^\|,) {
968 error('This kind of pipe is not allowed');
969 } else {
970 # include a regular file
972 error("'$pathname' is a directory; maybe use trailing '/' to include a directory?")
973 if -d $pathname;
974 error("'$pathname' is not a file")
975 unless -f $pathname;
977 push @ret, $pathname;
981 return @ret;
984 # peek a token from the queue, but don't remove it
985 sub peek_token() {
986 return unless prepare_normal_tokens();
987 return $script->{tokens}[0];
990 # get a token from the queue, including "special" tokens
991 sub next_raw_token() {
992 return unless prepare_tokens();
993 return shift @{$script->{tokens}};
996 # get a token from the queue
997 sub next_token() {
998 return unless prepare_normal_tokens();
999 my $token = shift @{$script->{tokens}};
1001 # update $script->{past_tokens}
1002 my $past_tokens = $script->{past_tokens};
1004 if (@$past_tokens > 0) {
1005 my $prev_token = $past_tokens->[-1][-1];
1006 $past_tokens->[-1] = @$past_tokens > 1 ? ['{'] : []
1007 if $prev_token eq ';';
1008 if ($prev_token eq '}') {
1009 pop @$past_tokens;
1010 $past_tokens->[-1] = $past_tokens->[-1][0] eq '{'
1011 ? [ '{' ] : []
1012 if @$past_tokens > 0;
1016 push @$past_tokens, [] if $token eq '{' or @$past_tokens == 0;
1017 push @{$past_tokens->[-1]}, $token;
1019 # return
1020 return $token;
1023 sub expect_token($;$) {
1024 my $expect = shift;
1025 my $msg = shift;
1026 my $token = next_token();
1027 error($msg || "'$expect' expected")
1028 unless defined $token and $token eq $expect;
1031 # require that another token exists, and that it's not a "special"
1032 # token, e.g. ";" and "{"
1033 sub require_next_token {
1034 my $code = shift || \&next_token;
1036 my $token = &$code(@_);
1038 error('unexpected end of file')
1039 unless defined $token;
1041 error("'$token' not allowed here")
1042 if $token =~ /^[;{}]$/;
1044 return $token;
1047 # return the value of a variable
1048 sub variable_value($) {
1049 my $name = shift;
1051 if ($name eq "LINE") {
1052 return $script->{line};
1055 foreach (@stack) {
1056 return $_->{vars}{$name}
1057 if exists $_->{vars}{$name};
1060 return $stack[0]{auto}{$name}
1061 if exists $stack[0]{auto}{$name};
1063 return;
1066 # determine the value of a variable, die if the value is an array
1067 sub string_variable_value($) {
1068 my $name = shift;
1069 my $value = variable_value($name);
1071 error("variable '$name' must be a string, but it is an array")
1072 if ref $value;
1074 return $value;
1077 # similar to the built-in "join" function, but also handle negated
1078 # values in a special way
1079 sub join_value($$) {
1080 my ($expr, $value) = @_;
1082 unless (ref $value) {
1083 return $value;
1084 } elsif (ref $value eq 'ARRAY') {
1085 return join($expr, @$value);
1086 } elsif (ref $value eq 'negated') {
1087 # bless'negated' is a special marker for negated values
1088 $value = join_value($expr, $value->[0]);
1089 return bless [ $value ], 'negated';
1090 } else {
1091 die;
1095 sub negate_value($$;$) {
1096 my ($value, $class, $allow_array) = @_;
1098 if (ref $value) {
1099 error('double negation is not allowed')
1100 if ref $value eq 'negated' or ref $value eq 'pre_negated';
1102 error('it is not possible to negate an array')
1103 if ref $value eq 'ARRAY' and not $allow_array;
1106 return bless [ $value ], $class || 'negated';
1109 sub format_bool($) {
1110 return $_[0] ? 1 : 0;
1113 sub resolve($\@$) {
1114 my ($resolver, $names, $type) = @_;
1116 my @result;
1117 foreach my $hostname (@$names) {
1118 if (($type eq 'A' and $hostname =~ /^\d+\.\d+\.\d+\.\d+$/) or
1119 (($type eq 'AAAA' and
1120 $hostname =~ /^[0-9a-fA-F:]*:[0-9a-fA-F:]*$/))) {
1121 push @result, $hostname;
1122 next;
1125 my $query = $resolver->search($hostname, $type);
1126 error("DNS query for '$hostname' failed: " . $resolver->errorstring)
1127 unless $query;
1129 foreach my $rr ($query->answer) {
1130 next unless $rr->type eq $type;
1132 if ($type eq 'NS') {
1133 push @result, $rr->nsdname;
1134 } elsif ($type eq 'MX') {
1135 push @result, $rr->exchange;
1136 } else {
1137 push @result, $rr->address;
1142 # NS/MX records return host names; resolve these again in the
1143 # second pass (IPv4 only currently)
1144 @result = resolve($resolver, @result, 'A')
1145 if $type eq 'NS' or $type eq 'MX';
1147 return @result;
1150 sub lookup_function($) {
1151 my $name = shift;
1153 foreach (@stack) {
1154 return $_->{functions}{$name}
1155 if exists $_->{functions}{$name};
1158 return;
1161 # returns the next parameter, which may either be a scalar or an array
1162 sub getvalues {
1163 my $code = shift;
1164 my %options = @_;
1166 my $token = require_next_token($code);
1168 if ($token eq '(') {
1169 # read an array until ")"
1170 my @wordlist;
1172 for (;;) {
1173 $token = getvalues($code,
1174 parenthesis_allowed => 1,
1175 comma_allowed => 1);
1177 unless (ref $token) {
1178 last if $token eq ')';
1180 if ($token eq ',') {
1181 error('Comma is not allowed within arrays, please use only a space');
1182 next;
1185 push @wordlist, $token;
1186 } elsif (ref $token eq 'ARRAY') {
1187 push @wordlist, @$token;
1188 } else {
1189 error('unknown token type');
1193 error('empty array not allowed here')
1194 unless @wordlist or not $options{non_empty};
1196 return @wordlist == 1
1197 ? $wordlist[0]
1198 : \@wordlist;
1199 } elsif ($token =~ /^\`(.*)\`$/s) {
1200 # execute a shell command, insert output
1201 my $command = $1;
1202 my $output = `$command`;
1203 unless ($? == 0) {
1204 if ($? == -1) {
1205 error("failed to execute: $!");
1206 } elsif ($? & 0x7f) {
1207 error("child died with signal " . ($? & 0x7f));
1208 } elsif ($? >> 8) {
1209 error("child exited with status " . ($? >> 8));
1213 # remove comments
1214 $output =~ s/#.*//mg;
1216 # tokenize
1217 my @tokens = grep { length } split /\s+/s, $output;
1219 my @values;
1220 while (@tokens) {
1221 my $value = getvalues(sub { shift @tokens });
1222 push @values, to_array($value);
1225 # and recurse
1226 return @values == 1
1227 ? $values[0]
1228 : \@values;
1229 } elsif ($token =~ /^\'(.*)\'$/s) {
1230 # single quotes: a string
1231 return $1;
1232 } elsif ($token =~ /^\"(.*)\"$/s) {
1233 # double quotes: a string with escapes
1234 $token = $1;
1235 $token =~ s,\$(\w+),string_variable_value($1),eg;
1236 return $token;
1237 } elsif ($token eq '!') {
1238 error('negation is not allowed here')
1239 unless $options{allow_negation};
1241 $token = getvalues($code);
1243 return negate_value($token, undef, $options{allow_array_negation});
1244 } elsif ($token eq ',') {
1245 return $token
1246 if $options{comma_allowed};
1248 error('comma is not allowed here');
1249 } elsif ($token eq '=') {
1250 error('equals operator ("=") is not allowed here');
1251 } elsif ($token eq '$') {
1252 my $name = require_next_token($code);
1253 error('variable name expected - if you want to concatenate strings, try using double quotes')
1254 unless $name =~ /^\w+$/;
1256 my $value = variable_value($name);
1258 error("no such variable: \$$name")
1259 unless defined $value;
1261 return $value;
1262 } elsif ($token eq '&') {
1263 error("function calls are not allowed as keyword parameter");
1264 } elsif ($token eq ')' and not $options{parenthesis_allowed}) {
1265 error('Syntax error');
1266 } elsif ($token =~ /^@/) {
1267 if ($token eq '@resolve') {
1268 my @params = get_function_params();
1269 error('Usage: @resolve((hostname ...), [type])')
1270 unless @params == 1 or @params == 2;
1271 eval { require Net::DNS; };
1272 error('For the @resolve() function, you need the Perl library Net::DNS')
1273 if $@;
1274 my $type = $params[1] || 'A';
1275 error('String expected') if ref $type;
1276 my $resolver = new Net::DNS::Resolver;
1277 @params = to_array($params[0]);
1278 my @result = resolve($resolver, @params, $type);
1279 return @result == 1 ? $result[0] : \@result;
1280 } elsif ($token eq '@defined') {
1281 expect_token('(', 'function name must be followed by "()"');
1282 my $type = require_next_token();
1283 if ($type eq '$') {
1284 my $name = require_next_token();
1285 error('variable name expected')
1286 unless $name =~ /^\w+$/;
1287 expect_token(')');
1288 return defined variable_value($name);
1289 } elsif ($type eq '&') {
1290 my $name = require_next_token();
1291 error('function name expected')
1292 unless $name =~ /^\w+$/;
1293 expect_token(')');
1294 return defined lookup_function($name);
1295 } else {
1296 error("'\$' or '&' expected")
1298 } elsif ($token eq '@eq') {
1299 my @params = get_function_params();
1300 error('Usage: @eq(a, b)') unless @params == 2;
1301 return format_bool($params[0] eq $params[1]);
1302 } elsif ($token eq '@ne') {
1303 my @params = get_function_params();
1304 error('Usage: @ne(a, b)') unless @params == 2;
1305 return format_bool($params[0] ne $params[1]);
1306 } elsif ($token eq '@not') {
1307 my @params = get_function_params();
1308 error('Usage: @not(a)') unless @params == 1;
1309 return format_bool(not $params[0]);
1310 } elsif ($token eq '@cat') {
1311 my $value = '';
1312 map {
1313 error('String expected') if ref $_;
1314 $value .= $_;
1315 } get_function_params();
1316 return $value;
1317 } elsif ($token eq '@substr') {
1318 my @params = get_function_params();
1319 error('Usage: @substr(string, num, num)') unless @params == 3;
1320 error('String expected') if ref $params[0] or ref $params[1] or ref $params[2];
1321 return substr($params[0],$params[1],$params[2]);
1322 } elsif ($token eq '@length') {
1323 my @params = get_function_params();
1324 error('Usage: @length(string)') unless @params == 1;
1325 error('String expected') if ref $params[0];
1326 return length($params[0]);
1327 } elsif ($token eq '@basename') {
1328 my @params = get_function_params();
1329 error('Usage: @basename(path)') unless @params == 1;
1330 error('String expected') if ref $params[0];
1331 my($volume,$path,$file) = File::Spec->splitpath( $params[0] );
1332 return $file;
1333 } elsif ($token eq '@dirname') {
1334 my @params = get_function_params();
1335 error('Usage: @dirname(path)') unless @params == 1;
1336 error('String expected') if ref $params[0];
1337 my($volume,$path,$file) = File::Spec->splitpath( $params[0] );
1338 return $path;
1339 } elsif ($token eq '@glob') {
1340 my @params = get_function_params();
1341 error('Usage: @glob(string)') unless @params == 1;
1343 # determine the current script's parent directory for relative
1344 # file names
1345 die unless defined $script;
1346 my $parent_dir = $script->{filename} =~ m,^(.*/),
1347 ? $1 : './';
1349 my @result = map {
1350 my $path = $_;
1351 $path = $parent_dir . $path unless $path =~ m,^/,;
1352 glob($path);
1353 } to_array($params[0]);
1354 return @result == 1 ? $result[0] : \@result;
1355 } elsif ($token eq '@ipfilter') {
1356 my @params = get_function_params();
1357 error('Usage: @ipfilter((ip1 ip2 ...))') unless @params == 1;
1358 my $domain = $stack[0]{auto}{DOMAIN};
1359 error('No domain specified') unless defined $domain;
1360 my @ips = ipfilter($domain, to_array($params[0]));
1361 return \@ips;
1362 } else {
1363 error("unknown ferm built-in function");
1365 } else {
1366 return $token;
1370 # returns the next parameter, but only allow a scalar
1371 sub getvar() {
1372 my $token = getvalues();
1374 error('array not allowed here')
1375 if ref $token and ref $token eq 'ARRAY';
1377 return $token;
1380 sub get_function_params(%) {
1381 expect_token('(', 'function name must be followed by "()"');
1383 my $token = peek_token();
1384 if ($token eq ')') {
1385 require_next_token();
1386 return;
1389 my @params;
1391 while (1) {
1392 if (@params > 0) {
1393 $token = require_next_token();
1394 last
1395 if $token eq ')';
1397 error('"," expected')
1398 unless $token eq ',';
1401 push @params, getvalues(undef, @_);
1404 return @params;
1407 # collect all tokens in a flat array reference until the end of the
1408 # command is reached
1409 sub collect_tokens {
1410 my %options = @_;
1412 my @level;
1413 my @tokens;
1415 # re-insert a "line" token, because the starting token of the
1416 # current line has been consumed already
1417 push @tokens, make_line_token($script->{line});
1419 while (1) {
1420 my $keyword = next_raw_token();
1421 error('unexpected end of file within function/variable declaration')
1422 unless defined $keyword;
1424 if (ref $keyword) {
1425 handle_special_token($keyword);
1426 } elsif ($keyword =~ /^[\{\(]$/) {
1427 push @level, $keyword;
1428 } elsif ($keyword =~ /^[\}\)]$/) {
1429 my $expected = $keyword;
1430 $expected =~ tr/\}\)/\{\(/;
1431 my $opener = pop @level;
1432 error("unmatched '$keyword'")
1433 unless defined $opener and $opener eq $expected;
1434 } elsif ($keyword eq ';' and @level == 0) {
1435 push @tokens, $keyword
1436 if $options{include_semicolon};
1438 if ($options{include_else}) {
1439 my $token = peek_token;
1440 next if $token eq '@else';
1443 last;
1446 push @tokens, $keyword;
1448 last
1449 if $keyword eq '}' and @level == 0;
1452 return \@tokens;
1456 # returns the specified value as an array. dereference arrayrefs
1457 sub to_array($) {
1458 my $value = shift;
1459 die unless wantarray;
1460 die if @_;
1461 unless (ref $value) {
1462 return $value;
1463 } elsif (ref $value eq 'ARRAY') {
1464 return @$value;
1465 } else {
1466 die;
1470 # evaluate the specified value as bool
1471 sub eval_bool($) {
1472 my $value = shift;
1473 die if wantarray;
1474 die if @_;
1475 unless (ref $value) {
1476 return $value;
1477 } elsif (ref $value eq 'ARRAY') {
1478 return @$value > 0;
1479 } else {
1480 die;
1484 sub is_netfilter_core_target($) {
1485 my $target = shift;
1486 die unless defined $target and length $target;
1487 return grep { $_ eq $target } qw(ACCEPT DROP RETURN QUEUE);
1490 sub is_netfilter_module_target($$) {
1491 my ($domain_family, $target) = @_;
1492 die unless defined $target and length $target;
1494 return defined $domain_family &&
1495 exists $target_defs{$domain_family} &&
1496 $target_defs{$domain_family}{$target};
1499 sub is_netfilter_builtin_chain($$) {
1500 my ($table, $chain) = @_;
1502 return grep { $_ eq $chain }
1503 qw(PREROUTING INPUT FORWARD OUTPUT POSTROUTING BROUTING);
1506 sub netfilter_canonical_protocol($) {
1507 my $proto = shift;
1508 return 'icmp'
1509 if $proto eq 'ipv6-icmp' or $proto eq 'icmpv6';
1510 return 'mh'
1511 if $proto eq 'ipv6-mh';
1512 return $proto;
1515 sub netfilter_protocol_module($) {
1516 my $proto = shift;
1517 return unless defined $proto;
1518 return 'icmp6'
1519 if $proto eq 'icmpv6';
1520 return $proto;
1523 # escape the string in a way safe for the shell
1524 sub shell_escape($) {
1525 my $token = shift;
1527 return $token if $token =~ /^[-_a-zA-Z0-9]+$/s;
1529 if ($option{fast}) {
1530 # iptables-save/iptables-restore are quite buggy concerning
1531 # escaping and special characters... we're trying our best
1532 # here
1534 $token =~ s,",\\",g;
1535 $token = '"' . $token . '"'
1536 if $token =~ /[\s\'\\;&]/s or length($token) == 0;
1537 } else {
1538 return $token
1539 if $token =~ /^\`.*\`$/;
1540 $token =~ s/'/'\\''/g;
1541 $token = '\'' . $token . '\''
1542 if $token =~ /[\s\"\\;<>&|]/s or length($token) == 0;
1545 return $token;
1548 # append an option to the shell command line, using information from
1549 # the module definition (see %match_defs etc.)
1550 sub shell_format_option($$) {
1551 my ($keyword, $value) = @_;
1553 my $cmd = '';
1554 if (ref $value) {
1555 if ((ref $value eq 'negated') || (ref $value eq 'pre_negated')) {
1556 $value = $value->[0];
1557 $cmd = ' !';
1561 unless (defined $value) {
1562 $cmd .= " --$keyword";
1563 } elsif (ref $value) {
1564 if (ref $value eq 'params') {
1565 $cmd .= " --$keyword ";
1566 $cmd .= join(' ', map { shell_escape($_) } @$value);
1567 } elsif (ref $value eq 'multi') {
1568 foreach (@$value) {
1569 $cmd .= " --$keyword " . shell_escape($_);
1571 } else {
1572 die;
1574 } else {
1575 $cmd .= " --$keyword " . shell_escape($value);
1578 return $cmd;
1581 sub format_option($$$) {
1582 my ($domain, $name, $value) = @_;
1584 $value = 'icmpv6' if $domain eq 'ip6' and $name eq 'protocol'
1585 and $value eq 'icmp';
1586 $name = 'icmpv6-type' if $domain eq 'ip6' and $name eq 'icmp-type';
1588 if ($domain eq 'ip6' and $name eq 'reject-with') {
1589 my %icmp_map = (
1590 'icmp-net-unreachable' => 'icmp6-no-route',
1591 'icmp-host-unreachable' => 'icmp6-addr-unreachable',
1592 'icmp-port-unreachable' => 'icmp6-port-unreachable',
1593 'icmp-net-prohibited' => 'icmp6-adm-prohibited',
1594 'icmp-host-prohibited' => 'icmp6-adm-prohibited',
1595 'icmp-admin-prohibited' => 'icmp6-adm-prohibited',
1597 $value = $icmp_map{$value} if exists $icmp_map{$value};
1600 return shell_format_option($name, $value);
1603 sub append_rule($$) {
1604 my ($chain_rules, $rule) = @_;
1606 my $cmd = join('', map { $_->[2] } @{$rule->{options}});
1607 push @$chain_rules, { rule => $cmd,
1608 script => $rule->{script},
1612 sub unfold_rule {
1613 my ($domain, $chain_rules, $rule) = (shift, shift, shift);
1614 return append_rule($chain_rules, $rule) unless @_;
1616 my $option = shift;
1617 my @values = @{$option->[1]};
1619 foreach my $value (@values) {
1620 $option->[2] = format_option($domain, $option->[0], $value);
1621 unfold_rule($domain, $chain_rules, $rule, @_);
1625 sub mkrules2($$$) {
1626 my ($domain, $chain_rules, $rule) = @_;
1628 my @unfold;
1629 foreach my $option (@{$rule->{options}}) {
1630 if (ref $option->[1] and ref $option->[1] eq 'ARRAY') {
1631 push @unfold, $option
1632 } else {
1633 $option->[2] = format_option($domain, $option->[0], $option->[1]);
1637 unfold_rule($domain, $chain_rules, $rule, @unfold);
1640 # convert a bunch of internal rule structures in iptables calls,
1641 # unfold arrays during that
1642 sub mkrules($) {
1643 my $rule = shift;
1645 my $domain = $rule->{domain};
1646 my $domain_info = $domains{$domain};
1647 $domain_info->{enabled} = 1;
1649 foreach my $table (to_array $rule->{table}) {
1650 my $table_info = $domain_info->{tables}{$table} ||= {};
1652 foreach my $chain (to_array $rule->{chain}) {
1653 my $chain_rules = $table_info->{chains}{$chain}{rules} ||= [];
1654 mkrules2($domain, $chain_rules, $rule)
1655 if $rule->{has_rule} and not $option{flush};
1660 # parse a keyword from a module definition
1661 sub parse_keyword(\%$$) {
1662 my ($rule, $def, $negated_ref) = @_;
1664 my $params = $def->{params};
1666 my $value;
1668 my $negated;
1669 if ($$negated_ref && exists $def->{pre_negation}) {
1670 $negated = 1;
1671 undef $$negated_ref;
1674 unless (defined $params) {
1675 undef $value;
1676 } elsif (ref $params && ref $params eq 'CODE') {
1677 $value = &$params($rule);
1678 } elsif ($params eq 'm') {
1679 $value = bless [ to_array getvalues() ], 'multi';
1680 } elsif ($params =~ /^[a-z]/) {
1681 if (exists $def->{negation} and not $negated) {
1682 my $token = peek_token();
1683 if ($token eq '!') {
1684 require_next_token();
1685 $negated = 1;
1689 my @params;
1690 foreach my $p (split(//, $params)) {
1691 if ($p eq 's') {
1692 push @params, getvar();
1693 } elsif ($p eq 'c') {
1694 my @v = to_array getvalues(undef, non_empty => 1);
1695 push @params, join(',', @v);
1696 } else {
1697 die;
1701 $value = @params == 1
1702 ? $params[0]
1703 : bless \@params, 'params';
1704 } elsif ($params == 1) {
1705 if (exists $def->{negation} and not $negated) {
1706 my $token = peek_token();
1707 if ($token eq '!') {
1708 require_next_token();
1709 $negated = 1;
1713 $value = getvalues();
1715 warning("log-prefix is too long; truncating to 29 characters: '$1'")
1716 if $def->{name} eq 'log-prefix' && $value =~ s,^(.{29}).+$,$1,;
1717 } else {
1718 if (exists $def->{negation} and not $negated) {
1719 my $token = peek_token();
1720 if ($token eq '!') {
1721 require_next_token();
1722 $negated = 1;
1726 $value = bless [ map {
1727 getvar()
1728 } (1..$params) ], 'params';
1731 $value = negate_value($value, exists $def->{pre_negation} && 'pre_negated')
1732 if $negated;
1734 return $value;
1737 sub append_option(\%$$) {
1738 my ($rule, $name, $value) = @_;
1739 push @{$rule->{options}}, [ $name, $value ];
1742 # parse options of a module
1743 sub parse_option($\%$) {
1744 my ($def, $rule, $negated_ref) = @_;
1746 append_option(%$rule, $def->{name},
1747 parse_keyword(%$rule, $def, $negated_ref));
1750 sub copy_on_write($$) {
1751 my ($rule, $key) = @_;
1752 return unless exists $rule->{cow}{$key};
1753 $rule->{$key} = {%{$rule->{$key}}};
1754 delete $rule->{cow}{$key};
1757 sub new_level(\%$) {
1758 my ($rule, $prev) = @_;
1760 %$rule = ();
1761 if (defined $prev) {
1762 # copy data from previous level
1763 $rule->{cow} = { keywords => 1, };
1764 $rule->{keywords} = $prev->{keywords};
1765 $rule->{match} = { %{$prev->{match}} };
1766 $rule->{options} = [@{$prev->{options}}];
1767 foreach my $key (qw(domain domain_family domain_both table chain protocol has_rule has_action)) {
1768 $rule->{$key} = $prev->{$key}
1769 if exists $prev->{$key};
1771 } else {
1772 $rule->{cow} = {};
1773 $rule->{keywords} = {};
1774 $rule->{match} = {};
1775 $rule->{options} = [];
1779 sub merge_keywords(\%$) {
1780 my ($rule, $keywords) = @_;
1781 copy_on_write($rule, 'keywords');
1782 while (my ($name, $def) = each %$keywords) {
1783 $rule->{keywords}{$name} = $def;
1787 sub set_domain(\%$) {
1788 my ($rule, $domain) = @_;
1790 return unless check_domain($domain);
1792 my $domain_family;
1793 unless (ref $domain) {
1794 $domain_family = $domain eq 'ip6' ? 'ip' : $domain;
1795 } elsif (@$domain == 0) {
1796 $domain_family = 'none';
1797 } elsif (grep { not /^ip6?$/s } @$domain) {
1798 error('Cannot combine non-IP domains');
1799 } else {
1800 $domain_family = 'ip';
1803 $rule->{domain_family} = $domain_family;
1804 $rule->{keywords} = $match_defs{$domain_family}{''}{keywords};
1805 $rule->{cow}{keywords} = 1;
1807 $rule->{domain} = $stack[0]{auto}{DOMAIN} = $domain;
1810 sub set_target(\%$$) {
1811 my ($rule, $name, $value) = @_;
1812 error('There can only one action per rule')
1813 if exists $rule->{has_action};
1814 $rule->{has_action} = 1;
1815 append_option(%$rule, $name, $value);
1818 sub set_module_target(\%$$) {
1819 my ($rule, $name, $defs) = @_;
1821 if ($name eq 'TCPMSS') {
1822 my $protos = $rule->{protocol};
1823 error('No protocol specified before TCPMSS')
1824 unless defined $protos;
1825 foreach my $proto (to_array $protos) {
1826 error('TCPMSS not available for protocol "$proto"')
1827 unless $proto eq 'tcp';
1831 # in ebtables, there is both "--mark" and "-j mark"... workaround:
1832 $name = 'mark' if $name eq 'MARK' and $rule->{domain_family} eq 'eb';
1834 set_target(%$rule, 'jump', $name);
1835 merge_keywords(%$rule, $defs->{keywords});
1838 # the main parser loop: read tokens, convert them into internal rule
1839 # structures
1840 sub enter($$) {
1841 my $lev = shift; # current recursion depth
1842 my $prev = shift; # previous rule hash
1844 # enter is the core of the firewall setup, it is a
1845 # simple parser program that recognizes keywords and
1846 # retreives parameters to set up the kernel routing
1847 # chains
1849 my $base_level = $script->{base_level} || 0;
1850 die if $base_level > $lev;
1852 my %rule;
1853 new_level(%rule, $prev);
1855 # read keywords 1 by 1 and dump into parser
1856 while (defined (my $keyword = next_token())) {
1857 # check if the current rule should be negated
1858 my $negated = $keyword eq '!';
1859 if ($negated) {
1860 # negation. get the next word which contains the 'real'
1861 # rule
1862 $keyword = getvar();
1864 error('unexpected end of file after negation')
1865 unless defined $keyword;
1868 # the core: parse all data
1869 for ($keyword)
1871 # deprecated keyword?
1872 if (exists $deprecated_keywords{$keyword}) {
1873 my $new_keyword = $deprecated_keywords{$keyword};
1874 warning("'$keyword' is deprecated, please use '$new_keyword' instead");
1875 $keyword = $new_keyword;
1878 # effectuation operator
1879 if ($keyword eq ';') {
1880 error('Empty rule before ";" not allowed')
1881 unless $rule{non_empty};
1883 if ($rule{has_rule} and not exists $rule{has_action}) {
1884 # something is wrong when a rule was specified,
1885 # but no action
1886 error('No action defined; did you mean "NOP"?');
1889 error('No chain defined') unless exists $rule{chain};
1891 $rule{script} = { filename => $script->{filename},
1892 line => $script->{line},
1895 mkrules(\%rule);
1897 # and clean up variables set in this level
1898 new_level(%rule, $prev);
1900 next;
1903 # conditional expression
1904 if ($keyword eq '@if') {
1905 unless (eval_bool(getvalues)) {
1906 collect_tokens;
1907 my $token = peek_token();
1908 if ($token and $token eq '@else') {
1909 require_next_token();
1910 } else {
1911 new_level(%rule, $prev);
1915 next;
1918 if ($keyword eq '@else') {
1919 # hack: if this "else" has not been eaten by the "if"
1920 # handler above, we believe it came from an if clause
1921 # which evaluated "true" - remove the "else" part now.
1922 collect_tokens;
1923 next;
1926 # hooks for custom shell commands
1927 if ($keyword eq 'hook') {
1928 warning("'hook' is deprecated, use '\@hook'");
1929 $keyword = '@hook';
1932 if ($keyword eq '@hook') {
1933 error('"hook" must be the first token in a command')
1934 if exists $rule{domain};
1936 my $position = getvar();
1937 my $hooks;
1938 if ($position eq 'pre') {
1939 $hooks = \@pre_hooks;
1940 } elsif ($position eq 'post') {
1941 $hooks = \@post_hooks;
1942 } elsif ($position eq 'flush') {
1943 $hooks = \@flush_hooks;
1944 } else {
1945 error("Invalid hook position: '$position'");
1948 push @$hooks, getvar();
1950 expect_token(';');
1951 next;
1954 # recursing operators
1955 if ($keyword eq '{') {
1956 # push stack
1957 my $old_stack_depth = @stack;
1959 unshift @stack, { auto => { %{$stack[0]{auto} || {}} } };
1961 # recurse
1962 enter($lev + 1, \%rule);
1964 # pop stack
1965 shift @stack;
1966 die unless @stack == $old_stack_depth;
1968 # after a block, the command is finished, clear this
1969 # level
1970 new_level(%rule, $prev);
1972 next;
1975 if ($keyword eq '}') {
1976 error('Unmatched "}"')
1977 if $lev <= $base_level;
1979 # consistency check: check if they havn't forgotten
1980 # the ';' after the last statement
1981 error('Missing semicolon before "}"')
1982 if $rule{non_empty};
1984 # and exit
1985 return;
1988 # include another file
1989 if ($keyword eq '@include' or $keyword eq 'include') {
1990 # don't call collect_filenames() if the file names
1991 # have been expanded already by @glob()
1992 my @files = peek_token() eq '@glob'
1993 ? to_array(getvalues)
1994 : collect_filenames(to_array(getvalues));
1995 $keyword = next_token;
1996 error('Missing ";" - "include FILENAME" must be the last command in a rule')
1997 unless defined $keyword and $keyword eq ';';
1999 foreach my $filename (@files) {
2000 # save old script, open new script
2001 my $old_script = $script;
2002 open_script($filename);
2003 $script->{base_level} = $lev + 1;
2005 # push stack
2006 my $old_stack_depth = @stack;
2008 my $stack = {};
2010 if (@stack > 0) {
2011 # include files may set variables for their parent
2012 $stack->{vars} = ($stack[0]{vars} ||= {});
2013 $stack->{functions} = ($stack[0]{functions} ||= {});
2014 $stack->{auto} = { %{ $stack[0]{auto} || {} } };
2017 my( $volume,$dirs,$file ) = File::Spec->splitpath( $filename );
2018 $stack->{auto}{FILENAME} = $filename;
2019 $stack->{auto}{FILEBNAME} = $file;
2020 $stack->{auto}{DIRNAME} = $dirs;
2022 unshift @stack, $stack;
2024 # parse the script
2025 enter($lev + 1, \%rule);
2027 #check for exit status
2028 error("'$script->{filename}': exit status is not 0") if not close $script->{handle};
2030 # pop stack
2031 shift @stack;
2032 die unless @stack == $old_stack_depth;
2034 # restore old script
2035 $script = $old_script;
2038 next;
2041 # definition of a variable or function
2042 if ($keyword eq '@def' or $keyword eq 'def') {
2043 error('"def" must be the first token in a command')
2044 if $rule{non_empty};
2046 my $type = require_next_token();
2047 if ($type eq '$') {
2048 my $name = require_next_token();
2049 error('invalid variable name')
2050 unless $name =~ /^\w+$/;
2052 expect_token('=');
2054 my $value = getvalues(undef, allow_negation => 1);
2056 expect_token(';');
2058 $stack[0]{vars}{$name} = $value
2059 unless exists $stack[-1]{vars}{$name};
2060 } elsif ($type eq '&') {
2061 my $name = require_next_token();
2062 error('invalid function name')
2063 unless $name =~ /^\w+$/;
2065 expect_token('(', 'function parameter list or "()" expected');
2067 my @params;
2068 while (1) {
2069 my $token = require_next_token();
2070 last if $token eq ')';
2072 if (@params > 0) {
2073 error('"," expected')
2074 unless $token eq ',';
2076 $token = require_next_token();
2079 error('"$" and parameter name expected')
2080 unless $token eq '$';
2082 $token = require_next_token();
2083 error('invalid function parameter name')
2084 unless $token =~ /^\w+$/;
2086 push @params, $token;
2089 my %function;
2091 $function{params} = \@params;
2093 expect_token('=');
2095 my $tokens = collect_tokens();
2096 $function{block} = 1 if grep { $_ eq '{' } @$tokens;
2097 $function{tokens} = $tokens;
2099 $stack[0]{functions}{$name} = \%function
2100 unless exists $stack[-1]{functions}{$name};
2101 } else {
2102 error('"$" (variable) or "&" (function) expected');
2105 next;
2108 # this rule has something which isn't inherited by its
2109 # parent closure. This variable is used in a lot of
2110 # syntax checks.
2112 $rule{non_empty} = 1;
2114 # def references
2115 if ($keyword eq '$') {
2116 error('variable references are only allowed as keyword parameter');
2119 if ($keyword eq '&') {
2120 my $name = require_next_token();
2121 error('function name expected')
2122 unless $name =~ /^\w+$/;
2124 my $function = lookup_function($name);
2125 error("no such function: \&$name")
2126 unless defined $function;
2128 my $paramdef = $function->{params};
2129 die unless defined $paramdef;
2131 my @params = get_function_params(allow_negation => 1);
2133 error("Wrong number of parameters for function '\&$name': "
2134 . @$paramdef . " expected, " . @params . " given")
2135 unless @params == @$paramdef;
2137 my %vars;
2138 for (my $i = 0; $i < @params; $i++) {
2139 $vars{$paramdef->[$i]} = $params[$i];
2142 if ($function->{block}) {
2143 # block {} always ends the current rule, so if the
2144 # function contains a block, we have to require
2145 # the calling rule also ends here
2146 expect_token(';');
2149 my @tokens = @{$function->{tokens}};
2150 for (my $i = 0; $i < @tokens; $i++) {
2151 if ($tokens[$i] eq '$' and $i + 1 < @tokens and
2152 exists $vars{$tokens[$i + 1]}) {
2153 my @value = to_array($vars{$tokens[$i + 1]});
2154 @value = ('(', @value, ')')
2155 unless @tokens == 1;
2156 splice(@tokens, $i, 2, @value);
2157 $i += @value - 2;
2158 } elsif ($tokens[$i] =~ m,^"(.*)"$,) {
2159 $tokens[$i] =~ s,\$(\w+),exists $vars{$1} ? $vars{$1} : "\$$1",eg;
2163 unshift @{$script->{tokens}}, @tokens;
2165 next;
2168 # where to put the rule?
2169 if ($keyword eq 'domain') {
2170 error('Domain is already specified')
2171 if exists $rule{domain};
2173 my $domains = getvalues();
2174 if (ref $domains) {
2175 my $tokens = collect_tokens(include_semicolon => 1,
2176 include_else => 1);
2178 my $old_line = $script->{line};
2179 my $old_handle = $script->{handle};
2180 my $old_tokens = $script->{tokens};
2181 my $old_base_level = $script->{base_level};
2182 unshift @$old_tokens, make_line_token($script->{line});
2183 delete $script->{handle};
2185 for my $domain (@$domains) {
2186 my %inner;
2187 new_level(%inner, \%rule);
2188 set_domain(%inner, $domain) or next;
2189 $inner{domain_both} = 1;
2190 $script->{base_level} = 0;
2191 $script->{tokens} = [ @$tokens ];
2192 enter(0, \%inner);
2195 $script->{base_level} = $old_base_level;
2196 $script->{tokens} = $old_tokens;
2197 $script->{handle} = $old_handle;
2198 $script->{line} = $old_line;
2200 new_level(%rule, $prev);
2201 } else {
2202 unless (set_domain(%rule, $domains)) {
2203 collect_tokens();
2204 new_level(%rule, $prev);
2208 next;
2211 if ($keyword eq 'table') {
2212 warning('Table is already specified')
2213 if exists $rule{table};
2214 $rule{table} = $stack[0]{auto}{TABLE} = getvalues();
2216 set_domain(%rule, $option{domain} || 'ip')
2217 unless exists $rule{domain};
2219 next;
2222 if ($keyword eq 'chain') {
2223 warning('Chain is already specified')
2224 if exists $rule{chain};
2226 my $chain = $rule{chain} = $stack[0]{auto}{CHAIN} = getvalues();
2228 # ferm 1.1 allowed lower case built-in chain names
2229 foreach (ref $rule{chain} ? @{$rule{chain}} : $rule{chain}) {
2230 error('Please write built-in chain names in upper case')
2231 if /^(?:input|forward|output|prerouting|postrouting)$/;
2234 set_domain(%rule, $option{domain} || 'ip')
2235 unless exists $rule{domain};
2237 $rule{table} = 'filter'
2238 unless exists $rule{table};
2240 my $domain = $rule{domain};
2241 foreach my $table (to_array $rule{table}) {
2242 foreach my $c (to_array $chain) {
2243 $domains{$domain}{tables}{$table}{chains}{$c} ||= {};
2247 next;
2250 error('Chain must be specified')
2251 unless exists $rule{chain};
2253 # policy for built-in chain
2254 if ($keyword eq 'policy') {
2255 error('Cannot specify matches for policy')
2256 if $rule{has_rule};
2258 my $policy = getvar();
2259 error("Invalid policy target: $policy")
2260 unless is_netfilter_core_target($policy);
2262 expect_token(';');
2264 my $domain = $rule{domain};
2265 my $domain_info = $domains{$domain};
2266 $domain_info->{enabled} = 1;
2268 foreach my $table (to_array $rule{table}) {
2269 foreach my $chain (to_array $rule{chain}) {
2270 $domain_info->{tables}{$table}{chains}{$chain}{policy} = $policy;
2274 new_level(%rule, $prev);
2275 next;
2278 # create a subchain
2279 if ($keyword eq '@subchain' or $keyword eq 'subchain' or $keyword eq '@gotosubchain') {
2280 error('Chain must be specified')
2281 unless exists $rule{chain};
2283 my $jumptype = ($keyword =~ /^\@go/) ? 'goto' : 'jump';
2284 my $jumpkey = $keyword;
2285 $jumpkey =~ s/^sub/\@sub/;
2287 error('No rule specified before $jumpkey')
2288 unless $rule{has_rule};
2290 my $subchain;
2291 my $token = peek_token();
2293 if ($token =~ /^(["'])(.*)\1$/s) {
2294 $subchain = $2;
2295 next_token();
2296 $keyword = next_token();
2297 } elsif ($token eq '{') {
2298 $keyword = next_token();
2299 $subchain = 'ferm_auto_' . ++$auto_chain;
2300 } else {
2301 $subchain = getvar();
2302 $keyword = next_token();
2305 my $domain = $rule{domain};
2306 foreach my $table (to_array $rule{table}) {
2307 $domains{$domain}{tables}{$table}{chains}{$subchain} ||= {};
2310 set_target(%rule, $jumptype, $subchain);
2312 error('"{" or chain name expected after $jumpkey')
2313 unless $keyword eq '{';
2315 # create a deep copy of %rule, only containing values
2316 # which must be in the subchain
2317 my %inner = ( cow => { keywords => 1, },
2318 match => {},
2319 options => [],
2321 $inner{$_} = $rule{$_} foreach qw(domain domain_family domain_both table keywords);
2322 $inner{chain} = $inner{auto}{CHAIN} = $subchain;
2324 if (exists $rule{protocol}) {
2325 $inner{protocol} = $rule{protocol};
2326 append_option(%inner, 'protocol', $inner{protocol});
2329 # create a new stack frame
2330 my $old_stack_depth = @stack;
2331 my $stack = { auto => { %{$stack[0]{auto} || {}} } };
2332 $stack->{auto}{CHAIN} = $subchain;
2333 unshift @stack, $stack;
2335 # enter the block
2336 enter($lev + 1, \%inner);
2338 # pop stack frame
2339 shift @stack;
2340 die unless @stack == $old_stack_depth;
2342 # now handle the parent - it's a jump to the sub chain
2343 $rule{script} = {
2344 filename => $script->{filename},
2345 line => $script->{line},
2348 mkrules(\%rule);
2350 # and clean up variables set in this level
2351 new_level(%rule, $prev);
2352 delete $rule{has_rule};
2354 next;
2357 # everything else must be part of a "real" rule, not just
2358 # "policy only"
2359 $rule{has_rule} = 1;
2361 # extended parameters:
2362 if ($keyword =~ /^mod(?:ule)?$/) {
2363 foreach my $module (to_array getvalues) {
2364 next if exists $rule{match}{$module};
2366 my $domain_family = $rule{domain_family};
2367 my $defs = $match_defs{$domain_family}{$module};
2369 append_option(%rule, 'match', $module);
2370 $rule{match}{$module} = 1;
2372 merge_keywords(%rule, $defs->{keywords})
2373 if defined $defs;
2376 next;
2379 # keywords from $rule{keywords}
2381 if (exists $rule{keywords}{$keyword}) {
2382 my $def = $rule{keywords}{$keyword};
2383 parse_option($def, %rule, \$negated);
2384 next;
2388 # actions
2391 # jump action
2392 if ($keyword eq 'jump') {
2393 set_target(%rule, 'jump', getvar());
2394 next;
2397 # goto action
2398 if ($keyword eq 'goto') {
2399 set_target(%rule, 'goto', getvar());
2400 next;
2403 # action keywords
2404 if (is_netfilter_core_target($keyword)) {
2405 set_target(%rule, 'jump', $keyword);
2406 next;
2409 if ($keyword eq 'NOP') {
2410 error('There can only one action per rule')
2411 if exists $rule{has_action};
2412 $rule{has_action} = 1;
2413 next;
2416 if (my $defs = is_netfilter_module_target($rule{domain_family}, $keyword)) {
2417 set_module_target(%rule, $keyword, $defs);
2418 next;
2422 # protocol specific options
2425 if ($keyword eq 'proto' or $keyword eq 'protocol') {
2426 my $protocol = parse_keyword(%rule,
2427 { params => 1, negation => 1 },
2428 \$negated);
2429 $rule{protocol} = $protocol;
2430 append_option(%rule, 'protocol', $rule{protocol});
2432 unless (ref $protocol) {
2433 $protocol = netfilter_canonical_protocol($protocol);
2434 my $domain_family = $rule{domain_family};
2435 if (my $defs = $proto_defs{$domain_family}{$protocol}) {
2436 merge_keywords(%rule, $defs->{keywords});
2437 my $module = netfilter_protocol_module($protocol);
2438 $rule{match}{$module} = 1;
2441 next;
2444 # port switches
2445 if ($keyword =~ /^[sd]port$/) {
2446 my $proto = $rule{protocol};
2447 error('To use sport or dport, you have to specify "proto tcp" or "proto udp" first')
2448 unless defined $proto and grep { /^(?:tcp|udp|udplite|dccp|sctp)$/ } to_array $proto;
2450 append_option(%rule, $keyword,
2451 getvalues(undef, allow_negation => 1));
2452 next;
2455 # default
2456 error("Unrecognized keyword: $keyword");
2459 # if the rule didn't reset the negated flag, it's not
2460 # supported
2461 error("Doesn't support negation: $keyword")
2462 if $negated;
2465 error('Missing "}" at end of file')
2466 if $lev > $base_level;
2468 # consistency check: check if they havn't forgotten
2469 # the ';' before the last statement
2470 error("Missing semicolon before end of file")
2471 if $rule{non_empty};
2474 sub execute_command {
2475 my ($command, $script) = @_;
2477 print LINES "$command\n"
2478 if $option{lines};
2479 return if $option{noexec};
2481 my $ret = system($command);
2482 unless ($ret == 0) {
2483 if ($? == -1) {
2484 print STDERR "failed to execute: $!\n";
2485 exit 1;
2486 } elsif ($? & 0x7f) {
2487 printf STDERR "child died with signal %d\n", $? & 0x7f;
2488 return 1;
2489 } else {
2490 print STDERR "(rule declared in $script->{filename}:$script->{line})\n"
2491 if defined $script;
2492 return $? >> 8;
2496 return;
2499 sub execute_slow($) {
2500 my $domain_info = shift;
2502 my $domain_cmd = $domain_info->{tools}{tables};
2504 my $status;
2505 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2506 my $table_cmd = "$domain_cmd -t $table";
2508 # reset chain policies
2509 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2510 next unless $chain_info->{builtin} or
2511 (not $table_info->{has_builtin} and
2512 is_netfilter_builtin_chain($table, $chain));
2513 $status ||= execute_command("$table_cmd -P $chain ACCEPT")
2514 unless $option{noflush};
2517 # clear
2518 unless ($option{noflush}) {
2519 $status ||= execute_command("$table_cmd -F");
2520 $status ||= execute_command("$table_cmd -X");
2523 next if $option{flush};
2525 # create chains / set policy
2526 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2527 if (is_netfilter_builtin_chain($table, $chain)) {
2528 if (exists $chain_info->{policy}) {
2529 $status ||= execute_command("$table_cmd -P $chain $chain_info->{policy}")
2530 unless $chain_info->{policy} eq 'ACCEPT';
2532 } else {
2533 if (exists $chain_info->{policy}) {
2534 $status ||= execute_command("$table_cmd -N $chain -P $chain_info->{policy}");
2536 else {
2537 $status ||= execute_command("$table_cmd -N $chain");
2542 # dump rules
2543 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2544 my $chain_cmd = "$table_cmd -A $chain";
2545 foreach my $rule (@{$chain_info->{rules}}) {
2546 $status ||= execute_command($chain_cmd . $rule->{rule});
2551 return $status;
2554 sub table_to_save($$) {
2555 my ($result_r, $table_info) = @_;
2557 foreach my $chain (sort keys %{$table_info->{chains}}) {
2558 my $chain_info = $table_info->{chains}{$chain};
2559 foreach my $rule (@{$chain_info->{rules}}) {
2560 $$result_r .= "-A $chain$rule->{rule}\n";
2565 sub rules_to_save($) {
2566 my ($domain_info) = @_;
2568 # convert this into an iptables-save text
2569 my $result = "# Generated by ferm $VERSION on " . localtime() . "\n";
2571 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2572 # select table
2573 $result .= '*' . $table . "\n";
2575 # create chains / set policy
2576 foreach my $chain (sort keys %{$table_info->{chains}}) {
2577 my $chain_info = $table_info->{chains}{$chain};
2578 my $policy = $option{flush} ? undef : $chain_info->{policy};
2579 unless (defined $policy) {
2580 if (is_netfilter_builtin_chain($table, $chain)) {
2581 $policy = 'ACCEPT';
2582 } else {
2583 next if $option{flush};
2584 $policy = '-';
2587 $result .= ":$chain $policy\ [0:0]\n";
2590 table_to_save(\$result, $table_info)
2591 unless $option{flush};
2593 # do it
2594 $result .= "COMMIT\n";
2597 return $result;
2600 sub restore_domain($$) {
2601 my ($domain_info, $save) = @_;
2603 my $path = $domain_info->{tools}{'tables-restore'};
2604 $path .= " --noflush" if $option{noflush};
2606 local *RESTORE;
2607 open RESTORE, "|$path"
2608 or die "Failed to run $path: $!\n";
2610 print RESTORE $save;
2612 close RESTORE
2613 or die "Failed to run $path\n";
2616 sub execute_fast($) {
2617 my $domain_info = shift;
2619 my $save = rules_to_save($domain_info);
2621 if ($option{lines}) {
2622 my $path = $domain_info->{tools}{'tables-restore'};
2623 $path .= " --noflush" if $option{noflush};
2624 print LINES "$path <<EOT\n"
2625 if $option{shell};
2626 print LINES $save;
2627 print LINES "EOT\n"
2628 if $option{shell};
2631 return if $option{noexec};
2633 eval {
2634 restore_domain($domain_info, $save);
2636 if ($@) {
2637 print STDERR $@;
2638 return 1;
2641 return;
2644 sub rollback() {
2645 my $error;
2646 while (my ($domain, $domain_info) = each %domains) {
2647 next unless $domain_info->{enabled};
2648 unless (defined $domain_info->{tools}{'tables-restore'}) {
2649 print STDERR "Cannot rollback domain '$domain' because there is no ${domain}tables-restore\n";
2650 next;
2653 my $reset = '';
2654 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2655 my $reset_chain = '';
2656 foreach my $chain (keys %{$table_info->{chains}}) {
2657 next unless is_netfilter_builtin_chain($table, $chain);
2658 $reset_chain .= ":${chain} ACCEPT [0:0]\n";
2660 $reset .= "*${table}\n${reset_chain}COMMIT\n"
2661 if length $reset_chain;
2664 $reset .= $domain_info->{previous}
2665 if defined $domain_info->{previous};
2667 restore_domain($domain_info, $reset);
2670 print STDERR "\nFirewall rules rolled back.\n" unless $error;
2671 exit 1;
2674 sub alrm_handler {
2675 # do nothing, just interrupt a system call
2678 sub confirm_rules {
2679 $SIG{ALRM} = \&alrm_handler;
2681 alarm(5);
2683 print STDERR "\n"
2684 . "ferm has applied the new firewall rules.\n"
2685 . "Please type 'yes' to confirm:\n";
2686 STDERR->flush();
2688 alarm($option{timeout});
2690 my $line = '';
2691 STDIN->sysread($line, 3);
2693 eval {
2694 require POSIX;
2695 POSIX::tcflush(*STDIN, 2);
2697 print STDERR "$@" if $@;
2699 $SIG{ALRM} = 'DEFAULT';
2701 return $line eq 'yes';
2704 # end of ferm
2706 __END__
2708 =head1 NAME
2710 ferm - a firewall rule parser for linux
2712 =head1 SYNOPSIS
2714 B<ferm> I<options> I<inputfiles>
2716 =head1 OPTIONS
2718 -n, --noexec Do not execute the rules, just simulate
2719 -F, --flush Flush all netfilter tables managed by ferm
2720 -l, --lines Show all rules that were created
2721 -i, --interactive Interactive mode: revert if user does not confirm
2722 -t, --timeout s Define interactive mode timeout in seconds
2723 --remote Remote mode; ignore host specific configuration.
2724 This implies --noexec and --lines.
2725 -V, --version Show current version number
2726 -h, --help Look at this text
2727 --slow Slow mode, don't use iptables-restore
2728 --shell Generate a shell script which calls iptables-restore
2729 --domain {ip|ip6} Handle only the specified domain
2730 --def '$name=v' Override a variable
2732 =cut