4 # ferm, a firewall setup program that makes firewall rules easy!
6 # Copyright (C) 2001-2012 Max Kellermann, Auke Kok
8 # Bug reports and patches for this program may be sent to the GitHub
9 # repository: L<https://github.com/MaxKellermann/ferm>
12 # This tool allows you to import an existing firewall configuration
16 # This program is free software; you can redistribute it and/or modify
17 # it under the terms of the GNU General Public License as published by
18 # the Free Software Foundation; either version 2 of the License, or
19 # (at your option) any later version.
21 # This program is distributed in the hope that it will be useful,
22 # but WITHOUT ANY WARRANTY; without even the implied warranty of
23 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 # GNU General Public License for more details.
26 # You should have received a copy of the GNU General Public License
27 # along with this program; if not, write to the Free Software
28 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
39 # find the main "ferm" program
41 if ($0 =~ /^(.*)\//) {
47 # Perl 5.24 requires this prefix or else it will only look in @INC
48 $ferm = "./$ferm" unless $ferm =~ /^\
//;
50 # import its module tables
53 # delete conflicting symbols
54 delete $main::{$_} for qw(merge_keywords parse_option);
57 use vars
qw(%aliases);
69 use vars qw($indent $table $chain @rules $domain $next_domain);
75 return $_ unless /[^-\w.:\/]/s or length == 0;
81 return ferm_escape($a) unless ref $a;
82 return ferm_escape($a->[0]) if @$a == 1;
83 return '(' . join(' ', map { ferm_escape($_) } @$a) . ')';
87 # write a line of tokens, with indent handling
89 # don't add space before semicolon
90 my $comma = $_[-1] eq ';' ? pop : '';
91 # begins with closing curly braces -> decrease indent
92 $indent -= 4 if $_[0] =~ /^}/;
97 # ends with opening curly braces -> increase indent
98 $indent += 4 if $_[-1] =~ /{$/;
101 sub module_match_count {
102 my ($module, $rules) = @_;
105 last unless $_->{mod}{$module};
113 return @{$b->{match}} > 0 &&
114 (Dumper($a->{match}[0]) eq Dumper($b->{match}[0]));
117 sub prefix_match_count {
118 my ($prefix, $rules) = @_;
121 last unless prefix_matches($prefix, $_);
127 sub is_merging_array_member {
129 return defined $value &&
131 ref $value eq 'ARRAY');
134 sub array_matches($$) {
135 my ($rule1, $rule2) = @_;
136 return if @{$rule1->{match}} == 0 or @{$rule2->{match}} == 0;
137 return unless is_merging_array_member($rule1->{match}[0][1]);
138 return unless is_merging_array_member($rule2->{match}[0][1]);
139 return unless @{$rule2->{match}} > 0;
140 return unless $rule1->{match}[0][0] eq $rule2->{match}[0][0];
143 $r1{match} = [ @{$r1{match}} ];
144 $r2{match} = [ @{$r2{match}} ];
147 return Dumper(\%r1) eq Dumper(\%r2);
150 sub array_match_count($\@) {
151 my ($first, $rules) = @_;
152 return 0 unless @{$first->{match}} > 0;
155 last unless array_matches($first, $_);
164 # try to find a common prefix and put rules in a block:
165 # saddr 1.2.3.4 proto tcp dport ssh ACCEPT;
166 # saddr 5.6.7.8 proto tcp dport ssh DROP;
168 # proto tcp dport ssh {
169 # saddr 1.2.3.4 ACCEPT;
170 # saddr 5.6.7.8 DROP;
174 if (@{$rule->{match}} > 0) {
175 my $match_count = prefix_match_count($rule, \@_);
177 if ($match_count > 0) {
178 my $match = $rule->{match}[0];
179 my @matching = ( $rule, splice(@_, 0, $match_count) );
180 map { shift @{$_->{match}} } @matching;
182 my @block = optimize(@matching);
186 unshift @{$rule->{match}}, $match;
205 # try to combine rules with arrays:
206 # saddr 1.2.3.4 proto tcp ACCEPT;
207 # saddr 5.6.7.8 proto tcp ACCEPT;
209 # saddr (1.2.3.4 5.6.7.8) proto tcp ACCEPT;
212 my $match_count = array_match_count($rule, @_);
214 if ($match_count > 0) {
215 my $option = $rule->{match}[0][0];
216 my @matching = ( $rule, splice(@_, 0, $match_count) );
218 (ref $_ and ref $_ eq 'ARRAY') ? @$_ : $_
223 $rule->{match}[0][1] = \@params;
233 my ($line, $key, $value) = @_;
235 if (ref($value) and ref($value) eq 'pre_negated') {
237 $value = $value->[0];
242 if (ref($value) and ref($value) eq 'negated') {
244 $value = $value->[0];
247 if (ref($value) and ref($value) eq 'params') {
249 push @$line, format_array($_);
251 } elsif (defined $value) {
252 push @$line, format_array($value);
257 # optimize and write a list of rules
259 my @r = @_ ? @_ : @rules;
262 foreach my $rule (@r) {
264 # assemble the line, match stuff first, then target parameters
265 if (exists $rule->{match}) {
266 foreach (@{$rule->{match}}) {
267 flush_option(\@line, @$_);
271 if (exists $rule->{jump}) {
272 if (is_netfilter_core_target($rule->{jump}) ||
273 is_netfilter_module_target('ip', $rule->{jump})) {
274 push @line, $rule->{jump};
276 flush_option(\@line, 'jump', $rule->{jump});
278 } elsif (exists $rule->{goto}) {
279 flush_option(\@line, 'goto', $rule->{goto});
280 } elsif (not exists $rule->{block}) {
284 if (exists $rule->{target}) {
285 foreach (@{$rule->{target}}) {
286 flush_option(\@line, @$_);
290 if (exists $rule->{block}) {
291 # this rule begins a block created in &optimize
292 write_line(@line, '{');
293 flush(@{$rule->{block}});
297 write_line(@line, ';');
305 write_line '}' if defined $chain;
306 write_line '}' if defined $table;
307 write_line '}' if defined $domain;
317 while (s/^\s*"([^"]*)"//s || s/^\s*(!)// || s/^\s*(\S+)//s) {
323 sub fetch_token($\@) {
324 my ($option, $tokens) = @_;
325 die "not enough arguments for option '$option' in line $."
330 sub fetch_negated(\@) {
332 @$tokens > 0 && $tokens->[0] eq '!' && shift @$tokens;
335 sub merge_keywords(\%$) {
336 my ($rule, $keywords) = @_;
337 while (my ($name, $def) = each %$keywords) {
338 $rule->{keywords}{$name} = $def;
342 sub parse_def_option($\%$\@) {
343 my ($option, $def, $negated, $tokens) = @_;
345 my $params = $def->{params};
348 $negated = 1 if fetch_negated(@$tokens);
350 unless (defined $params) {
352 } elsif (ref $params && ref $params eq 'CODE') {
353 # XXX we assume this is ipt_multiport
354 $value = [ split /,/, fetch_token($option, @$tokens) ];
355 } elsif ($params eq 'm') {
356 $value = bless [ fetch_token($option, @$tokens) ], 'multi';
357 } elsif ($params =~ /^[a-z]/) {
358 die if @$tokens < length($params);
361 foreach my $p (split(//, $params)) {
363 push @params, shift @$tokens;
364 } elsif ($p eq 'c') {
365 push @params, [ split /,/, shift @$tokens ];
371 $value = @params == 1
373 : bless \@params, 'params';
374 } elsif ($params == 1) {
375 $value = fetch_token($option, @$tokens);
377 $value = bless [ map {
378 fetch_token($option, @$tokens)
379 } (1..$params) ], 'multi';
382 $value = bless [ $value ], exists $def->{pre_negation} ? 'pre_negated' : 'negated'
388 sub parse_option(\%$$\@) {
389 my ($line, $option, $pre_negated, $tokens) = @_;
391 my $cur = $line->{cur};
392 die unless defined $cur;
394 $option = $aliases{$option} if exists $aliases{$option};
395 $option = 'destination-ports' if $option eq 'dports';
396 $option = 'source-ports' if $option eq 'sports';
398 if ($option eq 'protocol') {
399 my %def = ( params => 1 );
400 my $value = parse_def_option($option, %def, $pre_negated, @$tokens);
401 $line->{proto} = $value;
402 push @$cur, [ 'protocol', $value ];
404 my $module = netfilter_canonical_protocol($value);
405 if (exists $proto_defs{ip}{$module}) {
406 merge_keywords(%$line, $proto_defs{ip}{$module}{keywords});
409 if ($value =~ /^(?:tcp|udp|udplite|dccp|sctp)$/) {
414 $line->{keywords}{sport} = { name => 'sport', %def };
415 $line->{keywords}{dport} = { name => 'dport', %def };
418 } elsif ($option eq 'match') {
420 my $param = shift @$tokens;
421 $line->{mod}{$param} = 1;
422 # we don't need this module if the protocol with the
423 # same name is already specified
424 push @$cur, [ 'mod', $param ]
425 unless exists $line->{proto} and
426 ($line->{proto} eq $param or
427 $line->{proto} =~ /^(ipv6-icmp|icmpv6)$/s and $param eq 'icmp6');
429 my $module = $param eq 'icmp6' ? 'icmpv6' : $param;
430 if (exists $match_defs{ip}{$module}) {
431 merge_keywords(%$line, $match_defs{ip}{$module}{keywords});
432 } elsif (exists $proto_defs{ip}{$module}) {
433 merge_keywords(%$line, $proto_defs{ip}{$module}{keywords});
436 if ($param =~ /^(?:tcp|udp|udplite|dccp|sctp)$/) {
441 $line->{keywords}{sport} = { name => 'sport', %def };
442 $line->{keywords}{dport} = { name => 'dport', %def };
444 } elsif (exists $line->{keywords}{$option}) {
445 my $def = $line->{keywords}{$option};
446 my $value = parse_def_option($option, %$def, $pre_negated, @$tokens);
448 if (ref $value and ref $value eq 'multi' and
449 @{$line->{cur}} > 0 and $line->{cur}[-1][0] eq $option and
450 ref $line->{cur}[-1][1] eq 'multi') {
451 # merge multiple "--u32" into a ferm array
452 push @{$line->{cur}[-1][1]}, @$value;
457 push @{$line->{cur}}, [ $def->{ferm_name} || $def->{name}, $value ];
458 } elsif ($option eq 'jump') {
460 my $target = shift @$tokens;
461 # store the target in $line->{jump}
462 $line->{jump} = $target;
463 # what now follows is target parameters; set $cur
465 $line->{cur} = $line->{target} = [];
467 $line->{keywords} = {};
468 merge_keywords(%$line, $target_defs{ip}{$target}{keywords})
469 if exists $target_defs{ip}{$target};
470 } elsif ($option eq 'goto') {
472 my $target = shift @$tokens;
473 # store the target in $line->{jump}
474 $line->{goto} = $target;
476 die "option '$option' in line $. not understood\n";
479 die "option '$option' in line $. cannot be negated\n"
483 if (grep { $_ eq '-h' || $_ eq '--help' } @ARGV) {
485 Pod::Usage::pod2usage(-exitstatus => 0,
489 if (@ARGV == 0 && -t STDIN) {
490 open STDIN, "iptables-save|"
491 or die "Failed run to iptables-save: $!";
492 } elsif (grep { /^-./ } @ARGV) {
494 Pod::Usage::pod2usage(-exitstatus => 1,
498 print "# ferm rules generated by import-ferm\n";
499 print "# http://ferm.foo-projects.org/\n";
501 $next_domain = $ENV{FERM_DOMAIN} || 'ip';
509 $next_domain = $1 if /^#.*\b(ip|ip6)tables(?:-save)\b/;
510 } elsif (/^\*(\w+)$/) {
513 if (keys %policies > 0) {
514 while (my ($chain, $policy) = each %policies) {
515 write_line('chain', $chain, 'policy', $policy, ';');
520 unless (defined $domain and $domain eq $next_domain) {
522 $domain = $next_domain;
523 write_line 'domain', $domain, '{';
526 write_line('}') if defined $table;
528 write_line('table', $table, '{');
529 } elsif (/^:(\S+)\s+-\s+/) {
531 die unless defined $table;
532 write_line("chain $1;");
533 } elsif (/^:(\S+)\s+(\w+)\s+/) {
535 die unless defined $table;
537 } elsif (s/^-A (\S+)\s+//) {
539 unless (defined $chain) {
542 write_line('chain', $chain, '{');
543 } elsif ($1 ne $chain) {
547 write_line('chain', $chain, '{');
550 if (exists $policies{$chain}) {
551 write_line('policy', $policies{$chain}, ';');
552 delete $policies{$chain};
555 my @tokens = tokenize($_);
558 $line{keywords} = {};
559 merge_keywords(%line, $match_defs{ip}{''}{keywords});
561 # separate 'match' parameters from 'target' parameters; $cur
562 # points to the current position
563 $line{cur} = $line{match} = [];
565 local $_ = shift @tokens;
566 if (/^-(\w)$/ || /^--(\S+)$/) {
567 parse_option(%line, $1, undef, @tokens);
568 } elsif ($_ eq '!') {
571 /^-(\w)$/ || /^--(\S+)$/
572 or die "option expected in line $.\n";
573 parse_option(%line, $1, 1, @tokens);
575 print STDERR "warning: unknown token '$_' in line $.\n";
580 } elsif ($_ =~ /^COMMIT/) {
583 if (defined $chain) {
588 print STDERR "line $. was not understood, ignoring it\n";
592 if (keys %policies > 0) {
593 while (my ($chain, $policy) = each %policies) {
594 write_line('chain', $chain, 'policy', $policy, ';');
598 flush_domain if defined $domain;
600 die unless $indent == 0;
606 import-ferm - import existing firewall rules into ferm
610 B<import-ferm> > ferm.conf
612 iptables-save | B<import-ferm> > ferm.conf
614 B<import-ferm> I<inputfile> > ferm.conf
618 This script helps you with porting an existing IPv4 firewall
619 configuration to ferm. It reads a file generated with
620 B<iptables-save>, and tries to suggest a ferm configuration file.
622 If no input file was specified on the command line, B<import-ferm>
623 runs F<iptables-save>.
627 iptables-save older than 1.3 is unable to write valid saves - this is
628 not a bug in B<import-ferm>.