support various target modules
[ferm.git] / src / ferm
blob044c728019bf44276dafe6a4fcfed9a032e91d46
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.2.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 = ( goto => 'jump',
86 # these hashes provide the Netfilter module definitions
87 use vars qw(%proto_defs %match_defs %target_defs);
90 # This subsubsystem allows you to support (most) new netfilter modules
91 # in ferm. Add a call to one of the "add_XY_def()" functions below.
93 # Ok, now about the cryptic syntax: the function "add_XY_def()"
94 # registers a new module. There are three kinds of modules: protocol
95 # module (e.g. TCP, ICMP), match modules (e.g. state, physdev) and
96 # target modules (e.g. DNAT, MARK).
98 # The first parameter is always the module name which is passed to
99 # iptables with "-p", "-m" or "-j" (depending on which kind of module
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-above connlimit-mask);
249 add_match_def 'connmark', qw(!mark);
250 add_match_def 'conntrack', qw(!ctstate=c !ctproto ctorigsrc! ctorigdst! ctorigsrcport! ctorigdstport!),
251 qw(ctreplsrc! ctrepldst! !ctstatus !ctexpire=s ctdir=s);
252 add_match_def 'cpu', qw(!cpu);
253 add_match_def 'dscp', qw(dscp dscp-class);
254 add_match_def 'dst', qw(!dst-len=s dst-opts=c);
255 add_match_def 'ecn', qw(ecn-tcp-cwr*0 ecn-tcp-ece*0 ecn-ip-ect);
256 add_match_def 'esp', qw(espspi!);
257 add_match_def 'eui64';
258 add_match_def 'fuzzy', qw(lower-limit=s upper-limit=s);
259 add_match_def 'hbh', qw(hbh-len! hbh-opts=c);
260 add_match_def 'helper', qw(helper);
261 add_match_def 'hl', qw(hl-eq! hl-lt=s hl-gt=s);
262 add_match_def 'hashlimit', qw(hashlimit=s hashlimit-burst=s hashlimit-mode=c hashlimit-name=s),
263 qw(hashlimit-htable-size=s hashlimit-htable-max=s),
264 qw(hashlimit-htable-expire=s hashlimit-htable-gcinterval=s);
265 add_match_def 'iprange', qw(!src-range !dst-range);
266 add_match_def 'ipv4options', qw(ssrr*0 lsrr*0 no-srr*0 !rr*0 !ts*0 !ra*0 !any-opt*0);
267 add_match_def 'ipv6header', qw(header!=c soft*0);
268 add_match_def 'length', qw(length!);
269 add_match_def 'limit', qw(limit=s limit-burst=s);
270 add_match_def 'mac', qw(mac-source!);
271 add_match_def 'mark', qw(!mark);
272 add_match_def 'multiport', qw(source-ports!&multiport_params),
273 qw(destination-ports!&multiport_params ports!&multiport_params);
274 add_match_def 'nth', qw(every counter start packet);
275 add_match_def 'osf', qw(!genre ttl=s log=s);
276 add_match_def 'owner', qw(!uid-owner !gid-owner pid-owner sid-owner),
277 qw(cmd-owner !socket-exists=0);
278 add_match_def 'physdev', qw(physdev-in! physdev-out!),
279 qw(!physdev-is-in*0 !physdev-is-out*0 !physdev-is-bridged*0);
280 add_match_def 'pkttype', qw(pkt-type!),
281 add_match_def 'policy',
282 qw(dir pol strict*0 !reqid !spi !proto !mode !tunnel-src !tunnel-dst next*0);
283 add_match_def 'psd', qw(psd-weight-threshold psd-delay-threshold),
284 qw(psd-lo-ports-weight psd-hi-ports-weight);
285 add_match_def 'quota', qw(quota=s);
286 add_match_def 'random', qw(average);
287 add_match_def 'realm', qw(realm!);
288 add_match_def 'recent', qw(name=s !set*0 !remove*0 !rcheck*0 !update*0 !seconds !hitcount rttl*0 rsource*0 rdest*0);
289 add_match_def 'rpfilter', qw(loose*0 validmark*0 accept-local*0 invert*0);
290 add_match_def 'rt', qw(rt-type! rt-segsleft! rt-len! rt-0-res*0 rt-0-addrs=c rt-0-not-strict*0);
291 add_match_def 'set', qw(!match-set=sc set:=match-set);
292 add_match_def 'state', qw(!state=c);
293 add_match_def 'statistic', qw(mode=s probability=s every=s packet=s);
294 add_match_def 'string', qw(algo=s from=s to=s string hex-string);
295 add_match_def 'tcpmss', qw(!mss);
296 add_match_def 'time', qw(timestart=s timestop=s days=c datestart=s datestop=s),
297 qw(!monthday=c !weekdays=c utc*0 localtz*0);
298 add_match_def 'tos', qw(!tos);
299 add_match_def 'ttl', qw(ttl-eq ttl-lt=s ttl-gt=s);
300 add_match_def 'u32', qw(!u32=m);
302 add_target_def 'AUDIT', qw(type);
303 add_target_def 'BALANCE', qw(to-destination to:=to-destination);
304 add_target_def 'CHECKSUM', qw(checksum-fill*0);
305 add_target_def 'CLASSIFY', qw(set-class);
306 add_target_def 'CLUSTERIP', qw(new*0 hashmode clustermac total-nodes local-node hash-init);
307 add_target_def 'CONNMARK', qw(set-xmark save-mark*0 restore-mark*0 nfmask ctmask),
308 qw(and-mark or-mark xor-mark set-mark mask);
309 add_target_def 'CONNSECMARK', qw(save*0 restore*0);
310 add_target_def 'CT', qw(notrack*0 helper ctevents=c expevents=c zone timeout);
311 add_target_def 'DNAT', qw(to-destination=m to:=to-destination persistent*0 random*0);
312 add_target_def 'DNPT', qw(src-pfx dst-pfx);
313 add_target_def 'DSCP', qw(set-dscp set-dscp-class);
314 add_target_def 'ECN', qw(ecn-tcp-remove*0);
315 add_target_def 'HL', qw(hl-set hl-dec hl-inc);
316 add_target_def 'HMARK', qw(hmark-tuple hmark-mod hmark-offset),
317 qw(hmark-src-prefix hmark-dst-prefix hmark-sport-mask),
318 qw(hmark-dport-mask hmark-spi-mask hmark-proto-mask hmark-rnd);
319 add_target_def 'IDLETIMER', qw(timeout label);
320 add_target_def 'IPV4OPTSSTRIP';
321 add_target_def 'LED', qw(led-trigger-id led-delay led-always-blink*0);
322 add_target_def 'LOG', qw(log-level log-prefix),
323 qw(log-tcp-sequence*0 log-tcp-options*0 log-ip-options*0 log-uid*0);
324 add_target_def 'MARK', qw(set-mark set-xmark and-mark or-mark xor-mark);
325 add_target_def 'MASQUERADE', qw(to-ports random*0);
326 add_target_def 'MIRROR';
327 add_target_def 'NETMAP', qw(to);
328 add_target_def 'NFLOG', qw(nflog-group nflog-prefix nflog-range nflog-threshold);
329 add_target_def 'NFQUEUE', qw(queue-num queue-balance queue-bypass*0 queue-cpu-fanout*0);
330 add_target_def 'NOTRACK';
331 add_target_def 'RATEEST', qw(rateest-name rateest-interval rateest-ewmalog);
332 add_target_def 'REDIRECT', qw(to-ports random*0);
333 add_target_def 'REJECT', qw(reject-with);
334 add_target_def 'ROUTE', qw(oif iif gw continue*0 tee*0);
335 add_target_def 'SAME', qw(to nodst*0 random*0);
336 add_target_def 'SECMARK', qw(selctx);
337 add_target_def 'SET', qw(add-set=sc del-set=sc timeout exist*0);
338 add_target_def 'SNAT', qw(to-source=m to:=to-source persistent*0 random*0);
339 add_target_def 'SNPT', qw(src-pfx dst-pfx);
340 add_target_def 'TARPIT';
341 add_target_def 'TCPMSS', qw(set-mss clamp-mss-to-pmtu*0);
342 add_target_def 'TCPOPTSTRIP', qw(strip-options=c);
343 add_target_def 'TEE', qw(gateway);
344 add_target_def 'TOS', qw(set-tos and-tos or-tos xor-tos);
345 add_target_def 'TPROXY', qw(tproxy-mark on-port);
346 add_target_def 'TRACE';
347 add_target_def 'TTL', qw(ttl-set ttl-dec ttl-inc);
348 add_target_def 'ULOG', qw(ulog-nlgroup ulog-prefix ulog-cprange ulog-qthreshold);
350 add_match_def_x 'arp', '',
351 # ip
352 qw(source-ip! destination-ip! saddr:=source-ip daddr:=destination-ip),
353 # mac
354 qw(source-mac! destination-mac!),
355 # --in-interface
356 qw(in-interface! interface:=in-interface if:=in-interface),
357 # --out-interface
358 qw(out-interface! outerface:=out-interface of:=out-interface),
359 # misc
360 qw(h-length=s opcode=s h-type=s proto-type=s),
361 qw(mangle-ip-s=s mangle-ip-d=s mangle-mac-s=s mangle-mac-d=s mangle-target=s);
363 add_proto_def_x 'eb', 'IPv4',
364 qw(ip-source! ip-destination! ip-src:=ip-source ip-dst:=ip-destination),
365 qw(ip-tos!),
366 qw(ip-protocol! ip-proto:=ip-protocol),
367 qw(ip-source-port! ip-sport:=ip-source-port),
368 qw(ip-destination-port! ip-dport:=ip-destination-port);
370 add_proto_def_x 'eb', 'IPv6',
371 qw(ip6-source! ip6-destination! ip6-src:=ip6-source ip6-dst:=ip6-destination),
372 qw(ip6-tclass!),
373 qw(ip6-protocol! ip6-proto:=ip6-protocol),
374 qw(ip6-source-port! ip6-sport:=ip6-source-port),
375 qw(ip6-destination-port! ip6-dport:=ip6-destination-port);
377 add_proto_def_x 'eb', 'ARP',
378 qw(!arp-gratuitous*0),
379 qw(arp-opcode! arp-htype!=ss arp-ptype!=ss),
380 qw(arp-ip-src! arp-ip-dst! arp-mac-src! arp-mac-dst!);
382 add_proto_def_x 'eb', 'RARP',
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', '802_1Q',
388 qw(vlan-id! vlan-prio! vlan-encap!),
390 add_match_def_x 'eb', '',
391 # --in-interface
392 qw(in-interface! interface:=in-interface if:=in-interface),
393 # --out-interface
394 qw(out-interface! outerface:=out-interface of:=out-interface),
395 # logical interface
396 qw(logical-in! logical-out!),
397 # --source, --destination
398 qw(source! saddr:=source destination! daddr:=destination),
399 # 802.3
400 qw(802_3-sap! 802_3-type!),
401 # among
402 qw(!among-dst=c !among-src=c !among-dst-file !among-src-file),
403 # limit
404 qw(limit=s limit-burst=s),
405 # mark_m
406 qw(mark!),
407 # pkttype
408 qw(pkttype-type!),
409 # stp
410 qw(stp-type! stp-flags! stp-root-prio! stp-root-addr! stp-root-cost!),
411 qw(stp-sender-prio! stp-sender-addr! stp-port! stp-msg-age! stp-max-age!),
412 qw(stp-hello-time! stp-forward-delay!),
413 # log
414 qw(log*0 log-level=s log-prefix=s log-ip*0 log-arp*0);
416 add_target_def_x 'eb', 'arpreply', qw(arpreply-mac arpreply-target);
417 add_target_def_x 'eb', 'dnat', qw(to-destination dnat-target);
418 add_target_def_x 'eb', 'MARK', qw(set-mark mark-target);
419 add_target_def_x 'eb', 'redirect', qw(redirect-target);
420 add_target_def_x 'eb', 'snat', qw(to-source snat-target snat-arp*0);
422 # import-ferm uses the above tables
423 return 1 if $0 =~ /import-ferm$/;
425 # parameter parser for ipt_multiport
426 sub multiport_params {
427 my $rule = shift;
429 # multiport only allows 15 ports at a time. For this
430 # reason, we do a little magic here: split the ports
431 # into portions of 15, and handle these portions as
432 # array elements
434 my $proto = $rule->{protocol};
435 error('To use multiport, you have to specify "proto tcp" or "proto udp" first')
436 unless defined $proto and grep { /^(?:tcp|udp|udplite)$/ } to_array($proto);
438 my $value = getvalues(undef, allow_negation => 1,
439 allow_array_negation => 1);
440 if (ref $value and ref $value eq 'ARRAY') {
441 my @value = @$value;
442 my @params;
444 while (@value) {
445 push @params, join(',', splice(@value, 0, 15));
448 return @params == 1
449 ? $params[0]
450 : \@params;
451 } else {
452 return join_value(',', $value);
456 sub ipfilter($@) {
457 my $domain = shift;
458 my @ips;
459 # very crude IPv4/IPv6 address detection
460 if ($domain eq 'ip') {
461 @ips = grep { !/:[0-9a-f]*:/ } @_;
462 } elsif ($domain eq 'ip6') {
463 @ips = grep { !m,^[0-9./]+$,s } @_;
465 return @ips;
468 sub address_magic {
469 my $rule = shift;
470 my $domain = $rule->{domain};
471 my $value = getvalues(undef, allow_negation => 1);
473 my @ips;
474 my $negated = 0;
475 if (ref $value and ref $value eq 'ARRAY') {
476 @ips = @$value;
477 } elsif (ref $value and ref $value eq 'negated') {
478 @ips = @$value;
479 $negated = 1;
480 } elsif (ref $value) {
481 die;
482 } else {
483 @ips = ($value);
486 # only do magic on domain (ip ip6); do not process on a single-stack rule
487 # as to let admins spot their errors instead of silently ignoring them
488 @ips = ipfilter($domain, @ips) if defined $rule->{domain_both};
490 if ($negated && scalar @ips) {
491 return bless \@ips, 'negated';
492 } else {
493 return \@ips;
497 # initialize stack: command line definitions
498 unshift @stack, {};
500 # Get command line stuff
501 if ($has_getopt) {
502 my ($opt_noexec, $opt_flush, $opt_noflush, $opt_lines, $opt_interactive,
503 $opt_timeout, $opt_help,
504 $opt_version, $opt_test, $opt_fast, $opt_slow, $opt_shell,
505 $opt_domain);
507 Getopt::Long::Configure('bundling', 'auto_help', 'no_ignore_case',
508 'no_auto_abbrev');
510 sub opt_def {
511 my ($opt, $value) = @_;
512 die 'Invalid --def specification'
513 unless $value =~ /^\$?(\w+)=(.*)$/s;
514 my ($name, $unparsed_value) = ($1, $2);
515 my $tokens = tokenize_string($unparsed_value);
516 $value = getvalues(sub { shift @$tokens; });
517 die 'Extra tokens after --def'
518 if @$tokens > 0;
519 $stack[0]{vars}{$name} = $value;
522 local $SIG{__WARN__} = sub { die $_[0]; };
523 GetOptions('noexec|n' => \$opt_noexec,
524 'flush|F' => \$opt_flush,
525 'noflush' => \$opt_noflush,
526 'lines|l' => \$opt_lines,
527 'interactive|i' => \$opt_interactive,
528 'timeout|t=s' => \$opt_timeout,
529 'help|h' => \$opt_help,
530 'version|V' => \$opt_version,
531 test => \$opt_test,
532 remote => \$opt_test,
533 fast => \$opt_fast,
534 slow => \$opt_slow,
535 shell => \$opt_shell,
536 'domain=s' => \$opt_domain,
537 'def=s' => \&opt_def,
540 if (defined $opt_help) {
541 require Pod::Usage;
542 Pod::Usage::pod2usage(-exitstatus => 0);
545 if (defined $opt_version) {
546 printversion();
547 exit 0;
550 $option{noexec} = $opt_noexec || $opt_test;
551 $option{flush} = $opt_flush;
552 $option{noflush} = $opt_noflush;
553 $option{lines} = $opt_lines || $opt_test || $opt_shell;
554 $option{interactive} = $opt_interactive && !$opt_noexec;
555 $option{timeout} = defined $opt_timeout ? $opt_timeout : "30";
556 $option{test} = $opt_test;
557 $option{fast} = !$opt_slow;
558 $option{shell} = $opt_shell;
560 die("ferm interactive mode not possible: /dev/stdin is not a tty\n")
561 if $option{interactive} and not -t STDIN;
562 die("ferm interactive mode not possible: /dev/stderr is not a tty\n")
563 if $option{interactive} and not -t STDERR;
564 die("ferm timeout has no sense without interactive mode")
565 if not $opt_interactive and defined $opt_timeout;
566 die("invalid timeout. must be an integer")
567 if defined $opt_timeout and not $opt_timeout =~ /^[+-]?\d+$/;
569 $option{domain} = $opt_domain if defined $opt_domain;
570 } else {
571 # tiny getopt emulation for microperl
572 my $filename;
573 foreach (@ARGV) {
574 if ($_ eq '--noexec' or $_ eq '-n') {
575 $option{noexec} = 1;
576 } elsif ($_ eq '--lines' or $_ eq '-l') {
577 $option{lines} = 1;
578 } elsif ($_ eq '--fast') {
579 $option{fast} = 1;
580 } elsif ($_ eq '--test') {
581 $option{test} = 1;
582 $option{noexec} = 1;
583 $option{lines} = 1;
584 } elsif ($_ eq '--shell') {
585 $option{$_} = 1 foreach qw(shell fast lines);
586 } elsif (/^-/) {
587 printf STDERR "Usage: ferm [--noexec] [--lines] [--fast] [--shell] FILENAME\n";
588 exit 1;
589 } else {
590 $filename = $_;
593 undef @ARGV;
594 push @ARGV, $filename;
597 unless (@ARGV == 1) {
598 require Pod::Usage;
599 Pod::Usage::pod2usage(-exitstatus => 1);
602 if ($has_strict) {
603 open LINES, ">&STDOUT" if $option{lines};
604 open STDOUT, ">&STDERR" if $option{shell};
605 } else {
606 # microperl can't redirect file handles
607 *LINES = *STDOUT;
609 if ($option{fast} and not $option{noexec}) {
610 print STDERR "Sorry, ferm on microperl does not allow --fast without --noexec\n";
611 exit 1
615 unshift @stack, {};
616 open_script($ARGV[0]);
618 my( $volume,$dirs,$file ) = File::Spec->splitpath( $ARGV[0] );
619 $stack[0]{auto}{FILENAME} = $ARGV[0];
620 $stack[0]{auto}{FILEBNAME} = $file;
621 $stack[0]{auto}{DIRNAME} = $dirs;
625 # parse all input recursively
626 enter(0, undef);
627 die unless @stack == 2;
629 # enable/disable hooks depending on --flush
631 if ($option{flush}) {
632 undef @pre_hooks;
633 undef @post_hooks;
634 } else {
635 undef @flush_hooks;
638 # execute all generated rules
639 my $status;
641 foreach my $cmd (@pre_hooks) {
642 print LINES "$cmd\n" if $option{lines};
643 system($cmd) unless $option{noexec};
646 while (my ($domain, $domain_info) = each %domains) {
647 next unless $domain_info->{enabled};
648 my $s = $option{fast} &&
649 defined $domain_info->{tools}{'tables-restore'}
650 ? execute_fast($domain_info) : execute_slow($domain_info);
651 $status = $s if defined $s;
654 foreach my $cmd (@post_hooks, @flush_hooks) {
655 print LINES "$cmd\n" if $option{lines};
656 system($cmd) unless $option{noexec};
659 if (defined $status) {
660 rollback();
661 exit $status;
664 # ask user, and rollback if there is no confirmation
666 if ($option{interactive}) {
667 if ($option{shell}) {
668 print LINES "echo 'ferm has applied the new firewall rules.'\n";
669 print LINES "echo 'Please press Ctrl-C to confirm.'\n";
670 print LINES "sleep $option{timeout}\n";
671 while (my ($domain, $domain_info) = each %domains) {
672 my $restore = $domain_info->{tools}{'tables-restore'};
673 next unless defined $restore;
674 print LINES "$restore <\$${domain}_tmp\n";
678 confirm_rules() or rollback() unless $option{noexec};
681 exit 0;
683 # end of program execution!
686 # funcs
688 sub printversion {
689 print "ferm $VERSION\n";
690 print "Copyright (C) 2001-2012 Max Kellermann, Auke Kok\n";
691 print "This program is free software released under GPLv2.\n";
692 print "See the included COPYING file for license details.\n";
696 sub error {
697 # returns a nice formatted error message, showing the
698 # location of the error.
699 my $tabs = 0;
700 my @lines;
701 my $l = 0;
702 my @words = map { @$_ } @{$script->{past_tokens}};
704 for my $w ( 0 .. $#words ) {
705 if ($words[$w] eq "\x29")
706 { $l++ ; $lines[$l] = " " x ($tabs-- -1) ;};
707 if ($words[$w] eq "\x28")
708 { $l++ ; $lines[$l] = " " x $tabs++ ;};
709 if ($words[$w] eq "\x7d")
710 { $l++ ; $lines[$l] = " " x ($tabs-- -1) ;};
711 if ($words[$w] eq "\x7b")
712 { $l++ ; $lines[$l] = " " x $tabs++ ;};
713 if ( $l > $#lines ) { $lines[$l] = "" };
714 $lines[$l] .= $words[$w] . " ";
715 if ($words[$w] eq "\x28")
716 { $l++ ; $lines[$l] = " " x $tabs ;};
717 if (($words[$w] eq "\x29") && ($words[$w+1] ne "\x7b"))
718 { $l++ ; $lines[$l] = " " x $tabs ;};
719 if ($words[$w] eq "\x7b")
720 { $l++ ; $lines[$l] = " " x $tabs ;};
721 if (($words[$w] eq "\x7d") && ($words[$w+1] ne "\x7d"))
722 { $l++ ; $lines[$l] = " " x $tabs ;};
723 if (($words[$w] eq "\x3b") && ($words[$w+1] ne "\x7d"))
724 { $l++ ; $lines[$l] = " " x $tabs ;}
725 if ($words[$w-1] eq "option")
726 { $l++ ; $lines[$l] = " " x $tabs ;}
728 my $start = $#lines - 4;
729 if ($start < 0) { $start = 0 } ;
730 print STDERR "Error in $script->{filename} line $script->{line}:\n";
731 for $l ( $start .. $#lines)
732 { print STDERR $lines[$l]; if ($l != $#lines ) {print STDERR "\n"} ; };
733 print STDERR "<--\n";
734 die("@_\n");
737 # print a warning message about code from an input file
738 sub warning {
739 print STDERR "Warning in $script->{filename} line $script->{line}: "
740 . (shift) . "\n";
743 sub find_tool($) {
744 my $name = shift;
745 return $name if $option{test};
746 for my $path ('/sbin', split ':', $ENV{PATH}) {
747 my $ret = "$path/$name";
748 return $ret if -x $ret;
750 die "$name not found in PATH\n";
753 sub initialize_domain {
754 my $domain = shift;
755 my $domain_info = $domains{$domain} ||= {};
757 return if exists $domain_info->{initialized};
759 die "Invalid domain '$domain'\n" unless $domain =~ /^(?:ip6?|arp|eb)$/;
761 my @tools = qw(tables);
762 push @tools, qw(tables-save tables-restore)
763 if $domain =~ /^ip6?$/;
765 # determine the location of this domain's tools
766 my %tools = map { $_ => find_tool($domain . $_) } @tools;
767 $domain_info->{tools} = \%tools;
769 # make tables-save tell us about the state of this domain
770 # (which tables and chains do exist?), also remember the old
771 # save data which may be used later by the rollback function
772 local *SAVE;
773 if (!$option{test} &&
774 exists $tools{'tables-save'} &&
775 open(SAVE, "$tools{'tables-save'}|")) {
776 my $save = '';
778 my $table_info;
779 while (<SAVE>) {
780 $save .= $_;
782 if (/^\*(\w+)/) {
783 my $table = $1;
784 $table_info = $domain_info->{tables}{$table} ||= {};
785 } elsif (defined $table_info and /^:(\w+)\s+(\S+)/
786 and $2 ne '-') {
787 $table_info->{chains}{$1}{builtin} = 1;
788 $table_info->{has_builtin} = 1;
792 # for rollback
793 $domain_info->{previous} = $save;
796 if ($option{shell} && $option{interactive} &&
797 exists $tools{'tables-save'}) {
798 print LINES "${domain}_tmp=\$(mktemp ferm.XXXXXXXXXX)\n";
799 print LINES "$tools{'tables-save'} >\$${domain}_tmp\n";
802 $domain_info->{initialized} = 1;
805 sub check_domain($) {
806 my $domain = shift;
807 my @result;
809 return if exists $option{domain}
810 and $domain ne $option{domain};
812 eval {
813 initialize_domain($domain);
815 error($@) if $@;
817 return 1;
820 # split the input string into words and delete comments
821 sub tokenize_string($) {
822 my $string = shift;
824 my @ret;
826 foreach my $word ($string =~ m/(".*?"|'.*?'|`.*?`|[!,=&\$\%\(\){};]|[-+\w\/\.:]+|@\w+|#)/g) {
827 last if $word eq '#';
828 push @ret, $word;
831 return \@ret;
834 # generate a "line" special token, that marks the line number; these
835 # special tokens are inserted after each line break, so ferm keeps
836 # track of line numbers
837 sub make_line_token($) {
838 my $line = shift;
839 return bless(\$line, 'line');
842 # read some more tokens from the input file into a buffer
843 sub prepare_tokens() {
844 my $tokens = $script->{tokens};
845 while (@$tokens == 0) {
846 my $handle = $script->{handle};
847 return unless defined $handle;
848 my $line = <$handle>;
849 return unless defined $line;
851 push @$tokens, make_line_token($script->{line} + 1);
853 # the next parser stage eats this
854 push @$tokens, @{tokenize_string($line)};
857 return 1;
860 sub handle_special_token($) {
861 my $token = shift;
862 die unless ref $token;
863 if (ref $token eq 'line') {
864 $script->{line} = $$token;
865 } else {
866 die;
870 sub handle_special_tokens() {
871 my $tokens = $script->{tokens};
872 while (@$tokens > 0 and ref $tokens->[0]) {
873 handle_special_token(shift @$tokens);
877 # wrapper for prepare_tokens() which handles "special" tokens
878 sub prepare_normal_tokens() {
879 my $tokens = $script->{tokens};
880 while (1) {
881 handle_special_tokens();
882 return 1 if @$tokens > 0;
883 return unless prepare_tokens();
887 # open a ferm sub script
888 sub open_script($) {
889 my $filename = shift;
891 for (my $s = $script; defined $s; $s = $s->{parent}) {
892 die("Circular reference in $script->{filename} line $script->{line}: $filename\n")
893 if $s->{filename} eq $filename;
896 my $handle;
897 if ($filename eq '-') {
898 # Note that this only allowed in the command-line argument and not
899 # @includes, since those are filtered by collect_filenames()
900 $handle = *STDIN;
901 # also set a filename label so that error messages are more helpful
902 $filename = "<stdin>";
903 } else {
904 local *FILE;
905 open FILE, "$filename" or die("Failed to open $filename: $!\n");
906 $handle = *FILE;
909 $script = { filename => $filename,
910 handle => $handle,
911 line => 0,
912 past_tokens => [],
913 tokens => [],
914 parent => $script,
917 return $script;
920 # collect script filenames which are being included
921 sub collect_filenames(@) {
922 my @ret;
924 # determine the current script's parent directory for relative
925 # file names
926 die unless defined $script;
927 my $parent_dir = $script->{filename} =~ m,^(.*/),
928 ? $1 : './';
930 foreach my $pathname (@_) {
931 # non-absolute file names are relative to the parent script's
932 # file name
933 $pathname = $parent_dir . $pathname
934 unless $pathname =~ m,^/|\|$,;
936 if ($pathname =~ m,/$,) {
937 # include all regular files in a directory
939 error("'$pathname' is not a directory")
940 unless -d $pathname;
942 local *DIR;
943 opendir DIR, $pathname
944 or error("Failed to open directory '$pathname': $!");
945 my @names = readdir DIR;
946 closedir DIR;
948 # sort those names for a well-defined order
949 foreach my $name (sort { $a cmp $b } @names) {
950 # ignore dpkg's backup files
951 next if $name =~ /\.dpkg-(old|dist|new|tmp)$/;
952 # don't include hidden and backup files
953 next if $name =~ /^\.|~$/;
955 my $filename = $pathname . $name;
956 push @ret, $filename
957 if -f $filename;
959 } elsif ($pathname =~ m,\|$,) {
960 # run a program and use its output
961 push @ret, $pathname;
962 } elsif ($pathname =~ m,^\|,) {
963 error('This kind of pipe is not allowed');
964 } else {
965 # include a regular file
967 error("'$pathname' is a directory; maybe use trailing '/' to include a directory?")
968 if -d $pathname;
969 error("'$pathname' is not a file")
970 unless -f $pathname;
972 push @ret, $pathname;
976 return @ret;
979 # peek a token from the queue, but don't remove it
980 sub peek_token() {
981 return unless prepare_normal_tokens();
982 return $script->{tokens}[0];
985 # get a token from the queue, including "special" tokens
986 sub next_raw_token() {
987 return unless prepare_tokens();
988 return shift @{$script->{tokens}};
991 # get a token from the queue
992 sub next_token() {
993 return unless prepare_normal_tokens();
994 my $token = shift @{$script->{tokens}};
996 # update $script->{past_tokens}
997 my $past_tokens = $script->{past_tokens};
999 if (@$past_tokens > 0) {
1000 my $prev_token = $past_tokens->[-1][-1];
1001 $past_tokens->[-1] = @$past_tokens > 1 ? ['{'] : []
1002 if $prev_token eq ';';
1003 if ($prev_token eq '}') {
1004 pop @$past_tokens;
1005 $past_tokens->[-1] = $past_tokens->[-1][0] eq '{'
1006 ? [ '{' ] : []
1007 if @$past_tokens > 0;
1011 push @$past_tokens, [] if $token eq '{' or @$past_tokens == 0;
1012 push @{$past_tokens->[-1]}, $token;
1014 # return
1015 return $token;
1018 sub expect_token($;$) {
1019 my $expect = shift;
1020 my $msg = shift;
1021 my $token = next_token();
1022 error($msg || "'$expect' expected")
1023 unless defined $token and $token eq $expect;
1026 # require that another token exists, and that it's not a "special"
1027 # token, e.g. ";" and "{"
1028 sub require_next_token {
1029 my $code = shift || \&next_token;
1031 my $token = &$code(@_);
1033 error('unexpected end of file')
1034 unless defined $token;
1036 error("'$token' not allowed here")
1037 if $token =~ /^[;{}]$/;
1039 return $token;
1042 # return the value of a variable
1043 sub variable_value($) {
1044 my $name = shift;
1046 if ($name eq "LINE") {
1047 return $script->{line};
1050 foreach (@stack) {
1051 return $_->{vars}{$name}
1052 if exists $_->{vars}{$name};
1055 return $stack[0]{auto}{$name}
1056 if exists $stack[0]{auto}{$name};
1058 return;
1061 # determine the value of a variable, die if the value is an array
1062 sub string_variable_value($) {
1063 my $name = shift;
1064 my $value = variable_value($name);
1066 error("variable '$name' must be a string, but it is an array")
1067 if ref $value;
1069 return $value;
1072 # similar to the built-in "join" function, but also handle negated
1073 # values in a special way
1074 sub join_value($$) {
1075 my ($expr, $value) = @_;
1077 unless (ref $value) {
1078 return $value;
1079 } elsif (ref $value eq 'ARRAY') {
1080 return join($expr, @$value);
1081 } elsif (ref $value eq 'negated') {
1082 # bless'negated' is a special marker for negated values
1083 $value = join_value($expr, $value->[0]);
1084 return bless [ $value ], 'negated';
1085 } else {
1086 die;
1090 sub negate_value($$;$) {
1091 my ($value, $class, $allow_array) = @_;
1093 if (ref $value) {
1094 error('double negation is not allowed')
1095 if ref $value eq 'negated' or ref $value eq 'pre_negated';
1097 error('it is not possible to negate an array')
1098 if ref $value eq 'ARRAY' and not $allow_array;
1101 return bless [ $value ], $class || 'negated';
1104 sub format_bool($) {
1105 return $_[0] ? 1 : 0;
1108 sub resolve($\@$) {
1109 my ($resolver, $names, $type) = @_;
1111 my @result;
1112 foreach my $hostname (@$names) {
1113 my $query = $resolver->search($hostname, $type);
1114 error("DNS query for '$hostname' failed: " . $resolver->errorstring)
1115 unless $query;
1117 foreach my $rr ($query->answer) {
1118 next unless $rr->type eq $type;
1120 if ($type eq 'NS') {
1121 push @result, $rr->nsdname;
1122 } elsif ($type eq 'MX') {
1123 push @result, $rr->exchange;
1124 } else {
1125 push @result, $rr->address;
1130 # NS/MX records return host names; resolve these again in the
1131 # second pass (IPv4 only currently)
1132 @result = resolve($resolver, @result, 'A')
1133 if $type eq 'NS' or $type eq 'MX';
1135 return @result;
1138 sub lookup_function($) {
1139 my $name = shift;
1141 foreach (@stack) {
1142 return $_->{functions}{$name}
1143 if exists $_->{functions}{$name};
1146 return;
1149 # returns the next parameter, which may either be a scalar or an array
1150 sub getvalues {
1151 my $code = shift;
1152 my %options = @_;
1154 my $token = require_next_token($code);
1156 if ($token eq '(') {
1157 # read an array until ")"
1158 my @wordlist;
1160 for (;;) {
1161 $token = getvalues($code,
1162 parenthesis_allowed => 1,
1163 comma_allowed => 1);
1165 unless (ref $token) {
1166 last if $token eq ')';
1168 if ($token eq ',') {
1169 error('Comma is not allowed within arrays, please use only a space');
1170 next;
1173 push @wordlist, $token;
1174 } elsif (ref $token eq 'ARRAY') {
1175 push @wordlist, @$token;
1176 } else {
1177 error('unknown token type');
1181 error('empty array not allowed here')
1182 unless @wordlist or not $options{non_empty};
1184 return @wordlist == 1
1185 ? $wordlist[0]
1186 : \@wordlist;
1187 } elsif ($token =~ /^\`(.*)\`$/s) {
1188 # execute a shell command, insert output
1189 my $command = $1;
1190 my $output = `$command`;
1191 unless ($? == 0) {
1192 if ($? == -1) {
1193 error("failed to execute: $!");
1194 } elsif ($? & 0x7f) {
1195 error("child died with signal " . ($? & 0x7f));
1196 } elsif ($? >> 8) {
1197 error("child exited with status " . ($? >> 8));
1201 # remove comments
1202 $output =~ s/#.*//mg;
1204 # tokenize
1205 my @tokens = grep { length } split /\s+/s, $output;
1207 my @values;
1208 while (@tokens) {
1209 my $value = getvalues(sub { shift @tokens });
1210 push @values, to_array($value);
1213 # and recurse
1214 return @values == 1
1215 ? $values[0]
1216 : \@values;
1217 } elsif ($token =~ /^\'(.*)\'$/s) {
1218 # single quotes: a string
1219 return $1;
1220 } elsif ($token =~ /^\"(.*)\"$/s) {
1221 # double quotes: a string with escapes
1222 $token = $1;
1223 $token =~ s,\$(\w+),string_variable_value($1),eg;
1224 return $token;
1225 } elsif ($token eq '!') {
1226 error('negation is not allowed here')
1227 unless $options{allow_negation};
1229 $token = getvalues($code);
1231 return negate_value($token, undef, $options{allow_array_negation});
1232 } elsif ($token eq ',') {
1233 return $token
1234 if $options{comma_allowed};
1236 error('comma is not allowed here');
1237 } elsif ($token eq '=') {
1238 error('equals operator ("=") is not allowed here');
1239 } elsif ($token eq '$') {
1240 my $name = require_next_token($code);
1241 error('variable name expected - if you want to concatenate strings, try using double quotes')
1242 unless $name =~ /^\w+$/;
1244 my $value = variable_value($name);
1246 error("no such variable: \$$name")
1247 unless defined $value;
1249 return $value;
1250 } elsif ($token eq '&') {
1251 error("function calls are not allowed as keyword parameter");
1252 } elsif ($token eq ')' and not $options{parenthesis_allowed}) {
1253 error('Syntax error');
1254 } elsif ($token =~ /^@/) {
1255 if ($token eq '@resolve') {
1256 my @params = get_function_params();
1257 error('Usage: @resolve((hostname ...), [type])')
1258 unless @params == 1 or @params == 2;
1259 eval { require Net::DNS; };
1260 error('For the @resolve() function, you need the Perl library Net::DNS')
1261 if $@;
1262 my $type = $params[1] || 'A';
1263 error('String expected') if ref $type;
1264 my $resolver = new Net::DNS::Resolver;
1265 @params = to_array($params[0]);
1266 my @result = resolve($resolver, @params, $type);
1267 return @result == 1 ? $result[0] : \@result;
1268 } elsif ($token eq '@defined') {
1269 expect_token('(', 'function name must be followed by "()"');
1270 my $type = require_next_token();
1271 if ($type eq '$') {
1272 my $name = require_next_token();
1273 error('variable name expected')
1274 unless $name =~ /^\w+$/;
1275 expect_token(')');
1276 return defined variable_value($name);
1277 } elsif ($type eq '&') {
1278 my $name = require_next_token();
1279 error('function name expected')
1280 unless $name =~ /^\w+$/;
1281 expect_token(')');
1282 return defined lookup_function($name);
1283 } else {
1284 error("'\$' or '&' expected")
1286 } elsif ($token eq '@eq') {
1287 my @params = get_function_params();
1288 error('Usage: @eq(a, b)') unless @params == 2;
1289 return format_bool($params[0] eq $params[1]);
1290 } elsif ($token eq '@ne') {
1291 my @params = get_function_params();
1292 error('Usage: @ne(a, b)') unless @params == 2;
1293 return format_bool($params[0] ne $params[1]);
1294 } elsif ($token eq '@not') {
1295 my @params = get_function_params();
1296 error('Usage: @not(a)') unless @params == 1;
1297 return format_bool(not $params[0]);
1298 } elsif ($token eq '@cat') {
1299 my $value = '';
1300 map {
1301 error('String expected') if ref $_;
1302 $value .= $_;
1303 } get_function_params();
1304 return $value;
1305 } elsif ($token eq '@substr') {
1306 my @params = get_function_params();
1307 error('Usage: @substr(string, num, num)') unless @params == 3;
1308 error('String expected') if ref $params[0] or ref $params[1] or ref $params[2];
1309 return substr($params[0],$params[1],$params[2]);
1310 } elsif ($token eq '@length') {
1311 my @params = get_function_params();
1312 error('Usage: @length(string)') unless @params == 1;
1313 error('String expected') if ref $params[0];
1314 return length($params[0]);
1315 } elsif ($token eq '@basename') {
1316 my @params = get_function_params();
1317 error('Usage: @basename(path)') unless @params == 1;
1318 error('String expected') if ref $params[0];
1319 my($volume,$path,$file) = File::Spec->splitpath( $params[0] );
1320 return $file;
1321 } elsif ($token eq '@dirname') {
1322 my @params = get_function_params();
1323 error('Usage: @dirname(path)') unless @params == 1;
1324 error('String expected') if ref $params[0];
1325 my($volume,$path,$file) = File::Spec->splitpath( $params[0] );
1326 return $path;
1327 } elsif ($token eq '@ipfilter') {
1328 my @params = get_function_params();
1329 error('Usage: @ipfilter((ip1 ip2 ...))') unless @params == 1;
1330 my $domain = $stack[0]{auto}{DOMAIN};
1331 error('No domain specified') unless defined $domain;
1332 my @ips = ipfilter($domain, to_array($params[0]));
1333 return \@ips;
1334 } else {
1335 error("unknown ferm built-in function");
1337 } else {
1338 return $token;
1342 # returns the next parameter, but only allow a scalar
1343 sub getvar() {
1344 my $token = getvalues();
1346 error('array not allowed here')
1347 if ref $token and ref $token eq 'ARRAY';
1349 return $token;
1352 sub get_function_params(%) {
1353 expect_token('(', 'function name must be followed by "()"');
1355 my $token = peek_token();
1356 if ($token eq ')') {
1357 require_next_token();
1358 return;
1361 my @params;
1363 while (1) {
1364 if (@params > 0) {
1365 $token = require_next_token();
1366 last
1367 if $token eq ')';
1369 error('"," expected')
1370 unless $token eq ',';
1373 push @params, getvalues(undef, @_);
1376 return @params;
1379 # collect all tokens in a flat array reference until the end of the
1380 # command is reached
1381 sub collect_tokens {
1382 my %options = @_;
1384 my @level;
1385 my @tokens;
1387 # re-insert a "line" token, because the starting token of the
1388 # current line has been consumed already
1389 push @tokens, make_line_token($script->{line});
1391 while (1) {
1392 my $keyword = next_raw_token();
1393 error('unexpected end of file within function/variable declaration')
1394 unless defined $keyword;
1396 if (ref $keyword) {
1397 handle_special_token($keyword);
1398 } elsif ($keyword =~ /^[\{\(]$/) {
1399 push @level, $keyword;
1400 } elsif ($keyword =~ /^[\}\)]$/) {
1401 my $expected = $keyword;
1402 $expected =~ tr/\}\)/\{\(/;
1403 my $opener = pop @level;
1404 error("unmatched '$keyword'")
1405 unless defined $opener and $opener eq $expected;
1406 } elsif ($keyword eq ';' and @level == 0) {
1407 push @tokens, $keyword
1408 if $options{include_semicolon};
1410 if ($options{include_else}) {
1411 my $token = peek_token;
1412 next if $token eq '@else';
1415 last;
1418 push @tokens, $keyword;
1420 last
1421 if $keyword eq '}' and @level == 0;
1424 return \@tokens;
1428 # returns the specified value as an array. dereference arrayrefs
1429 sub to_array($) {
1430 my $value = shift;
1431 die unless wantarray;
1432 die if @_;
1433 unless (ref $value) {
1434 return $value;
1435 } elsif (ref $value eq 'ARRAY') {
1436 return @$value;
1437 } else {
1438 die;
1442 # evaluate the specified value as bool
1443 sub eval_bool($) {
1444 my $value = shift;
1445 die if wantarray;
1446 die if @_;
1447 unless (ref $value) {
1448 return $value;
1449 } elsif (ref $value eq 'ARRAY') {
1450 return @$value > 0;
1451 } else {
1452 die;
1456 sub is_netfilter_core_target($) {
1457 my $target = shift;
1458 die unless defined $target and length $target;
1459 return grep { $_ eq $target } qw(ACCEPT DROP RETURN QUEUE);
1462 sub is_netfilter_module_target($$) {
1463 my ($domain_family, $target) = @_;
1464 die unless defined $target and length $target;
1466 return defined $domain_family &&
1467 exists $target_defs{$domain_family} &&
1468 $target_defs{$domain_family}{$target};
1471 sub is_netfilter_builtin_chain($$) {
1472 my ($table, $chain) = @_;
1474 return grep { $_ eq $chain }
1475 qw(PREROUTING INPUT FORWARD OUTPUT POSTROUTING BROUTING);
1478 sub netfilter_canonical_protocol($) {
1479 my $proto = shift;
1480 return 'icmp'
1481 if $proto eq 'ipv6-icmp' or $proto eq 'icmpv6';
1482 return 'mh'
1483 if $proto eq 'ipv6-mh';
1484 return $proto;
1487 sub netfilter_protocol_module($) {
1488 my $proto = shift;
1489 return unless defined $proto;
1490 return 'icmp6'
1491 if $proto eq 'icmpv6';
1492 return $proto;
1495 # escape the string in a way safe for the shell
1496 sub shell_escape($) {
1497 my $token = shift;
1499 return $token if $token =~ /^[-_a-zA-Z0-9]+$/s;
1501 if ($option{fast}) {
1502 # iptables-save/iptables-restore are quite buggy concerning
1503 # escaping and special characters... we're trying our best
1504 # here
1506 $token =~ s,",\\",g;
1507 $token = '"' . $token . '"'
1508 if $token =~ /[\s\'\\;&]/s or length($token) == 0;
1509 } else {
1510 return $token
1511 if $token =~ /^\`.*\`$/;
1512 $token =~ s/'/'\\''/g;
1513 $token = '\'' . $token . '\''
1514 if $token =~ /[\s\"\\;<>&|]/s or length($token) == 0;
1517 return $token;
1520 # append an option to the shell command line, using information from
1521 # the module definition (see %match_defs etc.)
1522 sub shell_format_option($$) {
1523 my ($keyword, $value) = @_;
1525 my $cmd = '';
1526 if (ref $value) {
1527 if ((ref $value eq 'negated') || (ref $value eq 'pre_negated')) {
1528 $value = $value->[0];
1529 $cmd = ' !';
1533 unless (defined $value) {
1534 $cmd .= " --$keyword";
1535 } elsif (ref $value) {
1536 if (ref $value eq 'params') {
1537 $cmd .= " --$keyword ";
1538 $cmd .= join(' ', map { shell_escape($_) } @$value);
1539 } elsif (ref $value eq 'multi') {
1540 foreach (@$value) {
1541 $cmd .= " --$keyword " . shell_escape($_);
1543 } else {
1544 die;
1546 } else {
1547 $cmd .= " --$keyword " . shell_escape($value);
1550 return $cmd;
1553 sub format_option($$$) {
1554 my ($domain, $name, $value) = @_;
1556 $value = 'icmpv6' if $domain eq 'ip6' and $name eq 'protocol'
1557 and $value eq 'icmp';
1558 $name = 'icmpv6-type' if $domain eq 'ip6' and $name eq 'icmp-type';
1560 if ($domain eq 'ip6' and $name eq 'reject-with') {
1561 my %icmp_map = (
1562 'icmp-net-unreachable' => 'icmp6-no-route',
1563 'icmp-host-unreachable' => 'icmp6-addr-unreachable',
1564 'icmp-port-unreachable' => 'icmp6-port-unreachable',
1565 'icmp-net-prohibited' => 'icmp6-adm-prohibited',
1566 'icmp-host-prohibited' => 'icmp6-adm-prohibited',
1567 'icmp-admin-prohibited' => 'icmp6-adm-prohibited',
1569 $value = $icmp_map{$value} if exists $icmp_map{$value};
1572 return shell_format_option($name, $value);
1575 sub append_rule($$) {
1576 my ($chain_rules, $rule) = @_;
1578 my $cmd = join('', map { $_->[2] } @{$rule->{options}});
1579 push @$chain_rules, { rule => $cmd,
1580 script => $rule->{script},
1584 sub unfold_rule {
1585 my ($domain, $chain_rules, $rule) = (shift, shift, shift);
1586 return append_rule($chain_rules, $rule) unless @_;
1588 my $option = shift;
1589 my @values = @{$option->[1]};
1591 foreach my $value (@values) {
1592 $option->[2] = format_option($domain, $option->[0], $value);
1593 unfold_rule($domain, $chain_rules, $rule, @_);
1597 sub mkrules2($$$) {
1598 my ($domain, $chain_rules, $rule) = @_;
1600 my @unfold;
1601 foreach my $option (@{$rule->{options}}) {
1602 if (ref $option->[1] and ref $option->[1] eq 'ARRAY') {
1603 push @unfold, $option
1604 } else {
1605 $option->[2] = format_option($domain, $option->[0], $option->[1]);
1609 unfold_rule($domain, $chain_rules, $rule, @unfold);
1612 # convert a bunch of internal rule structures in iptables calls,
1613 # unfold arrays during that
1614 sub mkrules($) {
1615 my $rule = shift;
1617 my $domain = $rule->{domain};
1618 my $domain_info = $domains{$domain};
1619 $domain_info->{enabled} = 1;
1621 foreach my $table (to_array $rule->{table}) {
1622 my $table_info = $domain_info->{tables}{$table} ||= {};
1624 foreach my $chain (to_array $rule->{chain}) {
1625 my $chain_rules = $table_info->{chains}{$chain}{rules} ||= [];
1626 mkrules2($domain, $chain_rules, $rule)
1627 if $rule->{has_rule} and not $option{flush};
1632 # parse a keyword from a module definition
1633 sub parse_keyword(\%$$) {
1634 my ($rule, $def, $negated_ref) = @_;
1636 my $params = $def->{params};
1638 my $value;
1640 my $negated;
1641 if ($$negated_ref && exists $def->{pre_negation}) {
1642 $negated = 1;
1643 undef $$negated_ref;
1646 unless (defined $params) {
1647 undef $value;
1648 } elsif (ref $params && ref $params eq 'CODE') {
1649 $value = &$params($rule);
1650 } elsif ($params eq 'm') {
1651 $value = bless [ to_array getvalues() ], 'multi';
1652 } elsif ($params =~ /^[a-z]/) {
1653 if (exists $def->{negation} and not $negated) {
1654 my $token = peek_token();
1655 if ($token eq '!') {
1656 require_next_token();
1657 $negated = 1;
1661 my @params;
1662 foreach my $p (split(//, $params)) {
1663 if ($p eq 's') {
1664 push @params, getvar();
1665 } elsif ($p eq 'c') {
1666 my @v = to_array getvalues(undef, non_empty => 1);
1667 push @params, join(',', @v);
1668 } else {
1669 die;
1673 $value = @params == 1
1674 ? $params[0]
1675 : bless \@params, 'params';
1676 } elsif ($params == 1) {
1677 if (exists $def->{negation} and not $negated) {
1678 my $token = peek_token();
1679 if ($token eq '!') {
1680 require_next_token();
1681 $negated = 1;
1685 $value = getvalues();
1687 warning("log-prefix is too long; truncating to 29 characters: '$1'")
1688 if $def->{name} eq 'log-prefix' && $value =~ s,^(.{29}).+$,$1,;
1689 } else {
1690 if (exists $def->{negation} and not $negated) {
1691 my $token = peek_token();
1692 if ($token eq '!') {
1693 require_next_token();
1694 $negated = 1;
1698 $value = bless [ map {
1699 getvar()
1700 } (1..$params) ], 'params';
1703 $value = negate_value($value, exists $def->{pre_negation} && 'pre_negated')
1704 if $negated;
1706 return $value;
1709 sub append_option(\%$$) {
1710 my ($rule, $name, $value) = @_;
1711 push @{$rule->{options}}, [ $name, $value ];
1714 # parse options of a module
1715 sub parse_option($\%$) {
1716 my ($def, $rule, $negated_ref) = @_;
1718 append_option(%$rule, $def->{name},
1719 parse_keyword(%$rule, $def, $negated_ref));
1722 sub copy_on_write($$) {
1723 my ($rule, $key) = @_;
1724 return unless exists $rule->{cow}{$key};
1725 $rule->{$key} = {%{$rule->{$key}}};
1726 delete $rule->{cow}{$key};
1729 sub new_level(\%$) {
1730 my ($rule, $prev) = @_;
1732 %$rule = ();
1733 if (defined $prev) {
1734 # copy data from previous level
1735 $rule->{cow} = { keywords => 1, };
1736 $rule->{keywords} = $prev->{keywords};
1737 $rule->{match} = { %{$prev->{match}} };
1738 $rule->{options} = [@{$prev->{options}}];
1739 foreach my $key (qw(domain domain_family domain_both table chain protocol has_rule has_action)) {
1740 $rule->{$key} = $prev->{$key}
1741 if exists $prev->{$key};
1743 } else {
1744 $rule->{cow} = {};
1745 $rule->{keywords} = {};
1746 $rule->{match} = {};
1747 $rule->{options} = [];
1751 sub merge_keywords(\%$) {
1752 my ($rule, $keywords) = @_;
1753 copy_on_write($rule, 'keywords');
1754 while (my ($name, $def) = each %$keywords) {
1755 $rule->{keywords}{$name} = $def;
1759 sub set_domain(\%$) {
1760 my ($rule, $domain) = @_;
1762 return unless check_domain($domain);
1764 my $domain_family;
1765 unless (ref $domain) {
1766 $domain_family = $domain eq 'ip6' ? 'ip' : $domain;
1767 } elsif (@$domain == 0) {
1768 $domain_family = 'none';
1769 } elsif (grep { not /^ip6?$/s } @$domain) {
1770 error('Cannot combine non-IP domains');
1771 } else {
1772 $domain_family = 'ip';
1775 $rule->{domain_family} = $domain_family;
1776 $rule->{keywords} = $match_defs{$domain_family}{''}{keywords};
1777 $rule->{cow}{keywords} = 1;
1779 $rule->{domain} = $stack[0]{auto}{DOMAIN} = $domain;
1782 sub set_target(\%$$) {
1783 my ($rule, $name, $value) = @_;
1784 error('There can only one action per rule')
1785 if exists $rule->{has_action};
1786 $rule->{has_action} = 1;
1787 append_option(%$rule, $name, $value);
1790 sub set_module_target(\%$$) {
1791 my ($rule, $name, $defs) = @_;
1793 if ($name eq 'TCPMSS') {
1794 my $protos = $rule->{protocol};
1795 error('No protocol specified before TCPMSS')
1796 unless defined $protos;
1797 foreach my $proto (to_array $protos) {
1798 error('TCPMSS not available for protocol "$proto"')
1799 unless $proto eq 'tcp';
1803 # in ebtables, there is both "--mark" and "-j mark"... workaround:
1804 $name = 'mark' if $name eq 'MARK' and $rule->{domain_family} eq 'eb';
1806 set_target(%$rule, 'jump', $name);
1807 merge_keywords(%$rule, $defs->{keywords});
1810 # the main parser loop: read tokens, convert them into internal rule
1811 # structures
1812 sub enter($$) {
1813 my $lev = shift; # current recursion depth
1814 my $prev = shift; # previous rule hash
1816 # enter is the core of the firewall setup, it is a
1817 # simple parser program that recognizes keywords and
1818 # retreives parameters to set up the kernel routing
1819 # chains
1821 my $base_level = $script->{base_level} || 0;
1822 die if $base_level > $lev;
1824 my %rule;
1825 new_level(%rule, $prev);
1827 # read keywords 1 by 1 and dump into parser
1828 while (defined (my $keyword = next_token())) {
1829 # check if the current rule should be negated
1830 my $negated = $keyword eq '!';
1831 if ($negated) {
1832 # negation. get the next word which contains the 'real'
1833 # rule
1834 $keyword = getvar();
1836 error('unexpected end of file after negation')
1837 unless defined $keyword;
1840 # the core: parse all data
1841 for ($keyword)
1843 # deprecated keyword?
1844 if (exists $deprecated_keywords{$keyword}) {
1845 my $new_keyword = $deprecated_keywords{$keyword};
1846 warning("'$keyword' is deprecated, please use '$new_keyword' instead");
1847 $keyword = $new_keyword;
1850 # effectuation operator
1851 if ($keyword eq ';') {
1852 error('Empty rule before ";" not allowed')
1853 unless $rule{non_empty};
1855 if ($rule{has_rule} and not exists $rule{has_action}) {
1856 # something is wrong when a rule was specified,
1857 # but no action
1858 error('No action defined; did you mean "NOP"?');
1861 error('No chain defined') unless exists $rule{chain};
1863 $rule{script} = { filename => $script->{filename},
1864 line => $script->{line},
1867 mkrules(\%rule);
1869 # and clean up variables set in this level
1870 new_level(%rule, $prev);
1872 next;
1875 # conditional expression
1876 if ($keyword eq '@if') {
1877 unless (eval_bool(getvalues)) {
1878 collect_tokens;
1879 my $token = peek_token();
1880 if ($token and $token eq '@else') {
1881 require_next_token();
1882 } else {
1883 new_level(%rule, $prev);
1887 next;
1890 if ($keyword eq '@else') {
1891 # hack: if this "else" has not been eaten by the "if"
1892 # handler above, we believe it came from an if clause
1893 # which evaluated "true" - remove the "else" part now.
1894 collect_tokens;
1895 next;
1898 # hooks for custom shell commands
1899 if ($keyword eq 'hook') {
1900 warning("'hook' is deprecated, use '\@hook'");
1901 $keyword = '@hook';
1904 if ($keyword eq '@hook') {
1905 error('"hook" must be the first token in a command')
1906 if exists $rule{domain};
1908 my $position = getvar();
1909 my $hooks;
1910 if ($position eq 'pre') {
1911 $hooks = \@pre_hooks;
1912 } elsif ($position eq 'post') {
1913 $hooks = \@post_hooks;
1914 } elsif ($position eq 'flush') {
1915 $hooks = \@flush_hooks;
1916 } else {
1917 error("Invalid hook position: '$position'");
1920 push @$hooks, getvar();
1922 expect_token(';');
1923 next;
1926 # recursing operators
1927 if ($keyword eq '{') {
1928 # push stack
1929 my $old_stack_depth = @stack;
1931 unshift @stack, { auto => { %{$stack[0]{auto} || {}} } };
1933 # recurse
1934 enter($lev + 1, \%rule);
1936 # pop stack
1937 shift @stack;
1938 die unless @stack == $old_stack_depth;
1940 # after a block, the command is finished, clear this
1941 # level
1942 new_level(%rule, $prev);
1944 next;
1947 if ($keyword eq '}') {
1948 error('Unmatched "}"')
1949 if $lev <= $base_level;
1951 # consistency check: check if they havn't forgotten
1952 # the ';' after the last statement
1953 error('Missing semicolon before "}"')
1954 if $rule{non_empty};
1956 # and exit
1957 return;
1960 # include another file
1961 if ($keyword eq '@include' or $keyword eq 'include') {
1962 my @files = collect_filenames to_array getvalues;
1963 $keyword = next_token;
1964 error('Missing ";" - "include FILENAME" must be the last command in a rule')
1965 unless defined $keyword and $keyword eq ';';
1967 foreach my $filename (@files) {
1968 # save old script, open new script
1969 my $old_script = $script;
1970 open_script($filename);
1971 $script->{base_level} = $lev + 1;
1973 # push stack
1974 my $old_stack_depth = @stack;
1976 my $stack = {};
1978 if (@stack > 0) {
1979 # include files may set variables for their parent
1980 $stack->{vars} = ($stack[0]{vars} ||= {});
1981 $stack->{functions} = ($stack[0]{functions} ||= {});
1982 $stack->{auto} = { %{ $stack[0]{auto} || {} } };
1985 my( $volume,$dirs,$file ) = File::Spec->splitpath( $filename );
1986 $stack->{auto}{FILENAME} = $filename;
1987 $stack->{auto}{FILEBNAME} = $file;
1988 $stack->{auto}{DIRNAME} = $dirs;
1990 unshift @stack, $stack;
1992 # parse the script
1993 enter($lev + 1, \%rule);
1995 #check for exit status
1996 error("'$script->{filename}': exit status is not 0") if not close $script->{handle};
1998 # pop stack
1999 shift @stack;
2000 die unless @stack == $old_stack_depth;
2002 # restore old script
2003 $script = $old_script;
2006 next;
2009 # definition of a variable or function
2010 if ($keyword eq '@def' or $keyword eq 'def') {
2011 error('"def" must be the first token in a command')
2012 if $rule{non_empty};
2014 my $type = require_next_token();
2015 if ($type eq '$') {
2016 my $name = require_next_token();
2017 error('invalid variable name')
2018 unless $name =~ /^\w+$/;
2020 expect_token('=');
2022 my $value = getvalues(undef, allow_negation => 1);
2024 expect_token(';');
2026 $stack[0]{vars}{$name} = $value
2027 unless exists $stack[-1]{vars}{$name};
2028 } elsif ($type eq '&') {
2029 my $name = require_next_token();
2030 error('invalid function name')
2031 unless $name =~ /^\w+$/;
2033 expect_token('(', 'function parameter list or "()" expected');
2035 my @params;
2036 while (1) {
2037 my $token = require_next_token();
2038 last if $token eq ')';
2040 if (@params > 0) {
2041 error('"," expected')
2042 unless $token eq ',';
2044 $token = require_next_token();
2047 error('"$" and parameter name expected')
2048 unless $token eq '$';
2050 $token = require_next_token();
2051 error('invalid function parameter name')
2052 unless $token =~ /^\w+$/;
2054 push @params, $token;
2057 my %function;
2059 $function{params} = \@params;
2061 expect_token('=');
2063 my $tokens = collect_tokens();
2064 $function{block} = 1 if grep { $_ eq '{' } @$tokens;
2065 $function{tokens} = $tokens;
2067 $stack[0]{functions}{$name} = \%function
2068 unless exists $stack[-1]{functions}{$name};
2069 } else {
2070 error('"$" (variable) or "&" (function) expected');
2073 next;
2076 # this rule has something which isn't inherited by its
2077 # parent closure. This variable is used in a lot of
2078 # syntax checks.
2080 $rule{non_empty} = 1;
2082 # def references
2083 if ($keyword eq '$') {
2084 error('variable references are only allowed as keyword parameter');
2087 if ($keyword eq '&') {
2088 my $name = require_next_token();
2089 error('function name expected')
2090 unless $name =~ /^\w+$/;
2092 my $function = lookup_function($name);
2093 error("no such function: \&$name")
2094 unless defined $function;
2096 my $paramdef = $function->{params};
2097 die unless defined $paramdef;
2099 my @params = get_function_params(allow_negation => 1);
2101 error("Wrong number of parameters for function '\&$name': "
2102 . @$paramdef . " expected, " . @params . " given")
2103 unless @params == @$paramdef;
2105 my %vars;
2106 for (my $i = 0; $i < @params; $i++) {
2107 $vars{$paramdef->[$i]} = $params[$i];
2110 if ($function->{block}) {
2111 # block {} always ends the current rule, so if the
2112 # function contains a block, we have to require
2113 # the calling rule also ends here
2114 expect_token(';');
2117 my @tokens = @{$function->{tokens}};
2118 for (my $i = 0; $i < @tokens; $i++) {
2119 if ($tokens[$i] eq '$' and $i + 1 < @tokens and
2120 exists $vars{$tokens[$i + 1]}) {
2121 my @value = to_array($vars{$tokens[$i + 1]});
2122 @value = ('(', @value, ')')
2123 unless @tokens == 1;
2124 splice(@tokens, $i, 2, @value);
2125 $i += @value - 2;
2126 } elsif ($tokens[$i] =~ m,^"(.*)"$,) {
2127 $tokens[$i] =~ s,\$(\w+),exists $vars{$1} ? $vars{$1} : "\$$1",eg;
2131 unshift @{$script->{tokens}}, @tokens;
2133 next;
2136 # where to put the rule?
2137 if ($keyword eq 'domain') {
2138 error('Domain is already specified')
2139 if exists $rule{domain};
2141 my $domains = getvalues();
2142 if (ref $domains) {
2143 my $tokens = collect_tokens(include_semicolon => 1,
2144 include_else => 1);
2146 my $old_line = $script->{line};
2147 my $old_handle = $script->{handle};
2148 my $old_tokens = $script->{tokens};
2149 my $old_base_level = $script->{base_level};
2150 unshift @$old_tokens, make_line_token($script->{line});
2151 delete $script->{handle};
2153 for my $domain (@$domains) {
2154 my %inner;
2155 new_level(%inner, \%rule);
2156 set_domain(%inner, $domain) or next;
2157 $inner{domain_both} = 1;
2158 $script->{base_level} = 0;
2159 $script->{tokens} = [ @$tokens ];
2160 enter(0, \%inner);
2163 $script->{base_level} = $old_base_level;
2164 $script->{tokens} = $old_tokens;
2165 $script->{handle} = $old_handle;
2166 $script->{line} = $old_line;
2168 new_level(%rule, $prev);
2169 } else {
2170 unless (set_domain(%rule, $domains)) {
2171 collect_tokens();
2172 new_level(%rule, $prev);
2176 next;
2179 if ($keyword eq 'table') {
2180 warning('Table is already specified')
2181 if exists $rule{table};
2182 $rule{table} = $stack[0]{auto}{TABLE} = getvalues();
2184 set_domain(%rule, $option{domain} || 'ip')
2185 unless exists $rule{domain};
2187 next;
2190 if ($keyword eq 'chain') {
2191 warning('Chain is already specified')
2192 if exists $rule{chain};
2194 my $chain = $rule{chain} = $stack[0]{auto}{CHAIN} = getvalues();
2196 # ferm 1.1 allowed lower case built-in chain names
2197 foreach (ref $rule{chain} ? @{$rule{chain}} : $rule{chain}) {
2198 error('Please write built-in chain names in upper case')
2199 if /^(?:input|forward|output|prerouting|postrouting)$/;
2202 set_domain(%rule, $option{domain} || 'ip')
2203 unless exists $rule{domain};
2205 $rule{table} = 'filter'
2206 unless exists $rule{table};
2208 my $domain = $rule{domain};
2209 foreach my $table (to_array $rule{table}) {
2210 foreach my $c (to_array $chain) {
2211 $domains{$domain}{tables}{$table}{chains}{$c} ||= {};
2215 next;
2218 error('Chain must be specified')
2219 unless exists $rule{chain};
2221 # policy for built-in chain
2222 if ($keyword eq 'policy') {
2223 error('Cannot specify matches for policy')
2224 if $rule{has_rule};
2226 my $policy = getvar();
2227 error("Invalid policy target: $policy")
2228 unless is_netfilter_core_target($policy);
2230 expect_token(';');
2232 my $domain = $rule{domain};
2233 my $domain_info = $domains{$domain};
2234 $domain_info->{enabled} = 1;
2236 foreach my $table (to_array $rule{table}) {
2237 foreach my $chain (to_array $rule{chain}) {
2238 $domain_info->{tables}{$table}{chains}{$chain}{policy} = $policy;
2242 new_level(%rule, $prev);
2243 next;
2246 # create a subchain
2247 if ($keyword eq '@subchain' or $keyword eq 'subchain') {
2248 error('Chain must be specified')
2249 unless exists $rule{chain};
2251 error('No rule specified before "@subchain"')
2252 unless $rule{has_rule};
2254 my $subchain;
2255 my $token = peek_token();
2257 if ($token =~ /^(["'])(.*)\1$/s) {
2258 $subchain = $2;
2259 next_token();
2260 $keyword = next_token();
2261 } elsif ($token eq '{') {
2262 $keyword = next_token();
2263 $subchain = 'ferm_auto_' . ++$auto_chain;
2264 } else {
2265 $subchain = getvar();
2266 $keyword = next_token();
2269 my $domain = $rule{domain};
2270 foreach my $table (to_array $rule{table}) {
2271 $domains{$domain}{tables}{$table}{chains}{$subchain} ||= {};
2274 set_target(%rule, 'jump', $subchain);
2276 error('"{" or chain name expected after "@subchain"')
2277 unless $keyword eq '{';
2279 # create a deep copy of %rule, only containing values
2280 # which must be in the subchain
2281 my %inner = ( cow => { keywords => 1, },
2282 match => {},
2283 options => [],
2285 $inner{$_} = $rule{$_} foreach qw(domain domain_family domain_both table keywords);
2286 $inner{chain} = $inner{auto}{CHAIN} = $subchain;
2288 if (exists $rule{protocol}) {
2289 $inner{protocol} = $rule{protocol};
2290 append_option(%inner, 'protocol', $inner{protocol});
2293 # create a new stack frame
2294 my $old_stack_depth = @stack;
2295 my $stack = { auto => { %{$stack[0]{auto} || {}} } };
2296 $stack->{auto}{CHAIN} = $subchain;
2297 unshift @stack, $stack;
2299 # enter the block
2300 enter($lev + 1, \%inner);
2302 # pop stack frame
2303 shift @stack;
2304 die unless @stack == $old_stack_depth;
2306 # now handle the parent - it's a jump to the sub chain
2307 $rule{script} = {
2308 filename => $script->{filename},
2309 line => $script->{line},
2312 mkrules(\%rule);
2314 # and clean up variables set in this level
2315 new_level(%rule, $prev);
2316 delete $rule{has_rule};
2318 next;
2321 # everything else must be part of a "real" rule, not just
2322 # "policy only"
2323 $rule{has_rule} = 1;
2325 # extended parameters:
2326 if ($keyword =~ /^mod(?:ule)?$/) {
2327 foreach my $module (to_array getvalues) {
2328 next if exists $rule{match}{$module};
2330 my $domain_family = $rule{domain_family};
2331 my $defs = $match_defs{$domain_family}{$module};
2333 append_option(%rule, 'match', $module);
2334 $rule{match}{$module} = 1;
2336 merge_keywords(%rule, $defs->{keywords})
2337 if defined $defs;
2340 next;
2343 # keywords from $rule{keywords}
2345 if (exists $rule{keywords}{$keyword}) {
2346 my $def = $rule{keywords}{$keyword};
2347 parse_option($def, %rule, \$negated);
2348 next;
2352 # actions
2355 # jump action
2356 if ($keyword eq 'jump') {
2357 set_target(%rule, 'jump', getvar());
2358 next;
2361 # goto action
2362 if ($keyword eq 'realgoto') {
2363 set_target(%rule, 'goto', getvar());
2364 next;
2367 # action keywords
2368 if (is_netfilter_core_target($keyword)) {
2369 set_target(%rule, 'jump', $keyword);
2370 next;
2373 if ($keyword eq 'NOP') {
2374 error('There can only one action per rule')
2375 if exists $rule{has_action};
2376 $rule{has_action} = 1;
2377 next;
2380 if (my $defs = is_netfilter_module_target($rule{domain_family}, $keyword)) {
2381 set_module_target(%rule, $keyword, $defs);
2382 next;
2386 # protocol specific options
2389 if ($keyword eq 'proto' or $keyword eq 'protocol') {
2390 my $protocol = parse_keyword(%rule,
2391 { params => 1, negation => 1 },
2392 \$negated);
2393 $rule{protocol} = $protocol;
2394 append_option(%rule, 'protocol', $rule{protocol});
2396 unless (ref $protocol) {
2397 $protocol = netfilter_canonical_protocol($protocol);
2398 my $domain_family = $rule{domain_family};
2399 if (my $defs = $proto_defs{$domain_family}{$protocol}) {
2400 merge_keywords(%rule, $defs->{keywords});
2401 my $module = netfilter_protocol_module($protocol);
2402 $rule{match}{$module} = 1;
2405 next;
2408 # port switches
2409 if ($keyword =~ /^[sd]port$/) {
2410 my $proto = $rule{protocol};
2411 error('To use sport or dport, you have to specify "proto tcp" or "proto udp" first')
2412 unless defined $proto and grep { /^(?:tcp|udp|udplite|dccp|sctp)$/ } to_array $proto;
2414 append_option(%rule, $keyword,
2415 getvalues(undef, allow_negation => 1));
2416 next;
2419 # default
2420 error("Unrecognized keyword: $keyword");
2423 # if the rule didn't reset the negated flag, it's not
2424 # supported
2425 error("Doesn't support negation: $keyword")
2426 if $negated;
2429 error('Missing "}" at end of file')
2430 if $lev > $base_level;
2432 # consistency check: check if they havn't forgotten
2433 # the ';' before the last statement
2434 error("Missing semicolon before end of file")
2435 if $rule{non_empty};
2438 sub execute_command {
2439 my ($command, $script) = @_;
2441 print LINES "$command\n"
2442 if $option{lines};
2443 return if $option{noexec};
2445 my $ret = system($command);
2446 unless ($ret == 0) {
2447 if ($? == -1) {
2448 print STDERR "failed to execute: $!\n";
2449 exit 1;
2450 } elsif ($? & 0x7f) {
2451 printf STDERR "child died with signal %d\n", $? & 0x7f;
2452 return 1;
2453 } else {
2454 print STDERR "(rule declared in $script->{filename}:$script->{line})\n"
2455 if defined $script;
2456 return $? >> 8;
2460 return;
2463 sub execute_slow($) {
2464 my $domain_info = shift;
2466 my $domain_cmd = $domain_info->{tools}{tables};
2468 my $status;
2469 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2470 my $table_cmd = "$domain_cmd -t $table";
2472 # reset chain policies
2473 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2474 next unless $chain_info->{builtin} or
2475 (not $table_info->{has_builtin} and
2476 is_netfilter_builtin_chain($table, $chain));
2477 $status ||= execute_command("$table_cmd -P $chain ACCEPT")
2478 unless $option{noflush};
2481 # clear
2482 unless ($option{noflush}) {
2483 $status ||= execute_command("$table_cmd -F");
2484 $status ||= execute_command("$table_cmd -X");
2487 next if $option{flush};
2489 # create chains / set policy
2490 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2491 if (is_netfilter_builtin_chain($table, $chain)) {
2492 if (exists $chain_info->{policy}) {
2493 $status ||= execute_command("$table_cmd -P $chain $chain_info->{policy}")
2494 unless $chain_info->{policy} eq 'ACCEPT';
2496 } else {
2497 if (exists $chain_info->{policy}) {
2498 $status ||= execute_command("$table_cmd -N $chain -P $chain_info->{policy}");
2500 else {
2501 $status ||= execute_command("$table_cmd -N $chain");
2506 # dump rules
2507 while (my ($chain, $chain_info) = each %{$table_info->{chains}}) {
2508 my $chain_cmd = "$table_cmd -A $chain";
2509 foreach my $rule (@{$chain_info->{rules}}) {
2510 $status ||= execute_command($chain_cmd . $rule->{rule});
2515 return $status;
2518 sub table_to_save($$) {
2519 my ($result_r, $table_info) = @_;
2521 foreach my $chain (sort keys %{$table_info->{chains}}) {
2522 my $chain_info = $table_info->{chains}{$chain};
2523 foreach my $rule (@{$chain_info->{rules}}) {
2524 $$result_r .= "-A $chain$rule->{rule}\n";
2529 sub rules_to_save($) {
2530 my ($domain_info) = @_;
2532 # convert this into an iptables-save text
2533 my $result = "# Generated by ferm $VERSION on " . localtime() . "\n";
2535 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2536 # select table
2537 $result .= '*' . $table . "\n";
2539 # create chains / set policy
2540 foreach my $chain (sort keys %{$table_info->{chains}}) {
2541 my $chain_info = $table_info->{chains}{$chain};
2542 my $policy = $option{flush} ? undef : $chain_info->{policy};
2543 unless (defined $policy) {
2544 if (is_netfilter_builtin_chain($table, $chain)) {
2545 $policy = 'ACCEPT';
2546 } else {
2547 next if $option{flush};
2548 $policy = '-';
2551 $result .= ":$chain $policy\ [0:0]\n";
2554 table_to_save(\$result, $table_info)
2555 unless $option{flush};
2557 # do it
2558 $result .= "COMMIT\n";
2561 return $result;
2564 sub restore_domain($$) {
2565 my ($domain_info, $save) = @_;
2567 my $path = $domain_info->{tools}{'tables-restore'};
2568 $path .= " --noflush" if $option{noflush};
2570 local *RESTORE;
2571 open RESTORE, "|$path"
2572 or die "Failed to run $path: $!\n";
2574 print RESTORE $save;
2576 close RESTORE
2577 or die "Failed to run $path\n";
2580 sub execute_fast($) {
2581 my $domain_info = shift;
2583 my $save = rules_to_save($domain_info);
2585 if ($option{lines}) {
2586 my $path = $domain_info->{tools}{'tables-restore'};
2587 $path .= " --noflush" if $option{noflush};
2588 print LINES "$path <<EOT\n"
2589 if $option{shell};
2590 print LINES $save;
2591 print LINES "EOT\n"
2592 if $option{shell};
2595 return if $option{noexec};
2597 eval {
2598 restore_domain($domain_info, $save);
2600 if ($@) {
2601 print STDERR $@;
2602 return 1;
2605 return;
2608 sub rollback() {
2609 my $error;
2610 while (my ($domain, $domain_info) = each %domains) {
2611 next unless $domain_info->{enabled};
2612 unless (defined $domain_info->{tools}{'tables-restore'}) {
2613 print STDERR "Cannot rollback domain '$domain' because there is no ${domain}tables-restore\n";
2614 next;
2617 my $reset = '';
2618 while (my ($table, $table_info) = each %{$domain_info->{tables}}) {
2619 my $reset_chain = '';
2620 foreach my $chain (keys %{$table_info->{chains}}) {
2621 next unless is_netfilter_builtin_chain($table, $chain);
2622 $reset_chain .= ":${chain} ACCEPT [0:0]\n";
2624 $reset .= "*${table}\n${reset_chain}COMMIT\n"
2625 if length $reset_chain;
2628 $reset .= $domain_info->{previous}
2629 if defined $domain_info->{previous};
2631 restore_domain($domain_info, $reset);
2634 print STDERR "\nFirewall rules rolled back.\n" unless $error;
2635 exit 1;
2638 sub alrm_handler {
2639 # do nothing, just interrupt a system call
2642 sub confirm_rules {
2643 $SIG{ALRM} = \&alrm_handler;
2645 alarm(5);
2647 print STDERR "\n"
2648 . "ferm has applied the new firewall rules.\n"
2649 . "Please type 'yes' to confirm:\n";
2650 STDERR->flush();
2652 alarm($option{timeout});
2654 my $line = '';
2655 STDIN->sysread($line, 3);
2657 eval {
2658 require POSIX;
2659 POSIX::tcflush(*STDIN, 2);
2661 print STDERR "$@" if $@;
2663 $SIG{ALRM} = 'DEFAULT';
2665 return $line eq 'yes';
2668 # end of ferm
2670 __END__
2672 =head1 NAME
2674 ferm - a firewall rule parser for linux
2676 =head1 SYNOPSIS
2678 B<ferm> I<options> I<inputfiles>
2680 =head1 OPTIONS
2682 -n, --noexec Do not execute the rules, just simulate
2683 -F, --flush Flush all netfilter tables managed by ferm
2684 -l, --lines Show all rules that were created
2685 -i, --interactive Interactive mode: revert if user does not confirm
2686 -t, --timeout s Define interactive mode timeout in seconds
2687 --remote Remote mode; ignore host specific configuration.
2688 This implies --noexec and --lines.
2689 -V, --version Show current version number
2690 -h, --help Look at this text
2691 --slow Slow mode, don't use iptables-restore
2692 --shell Generate a shell script which calls iptables-restore
2693 --domain {ip|ip6} Handle only the specified domain
2694 --def '$name=v' Override a variable
2696 =cut