summaryrefslogtreecommitdiff
path: root/scripts/firewall/vyatta-firewall.pl
blob: 272fd8fa026b79ed73a58ca922b182af792eb13d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
#!/usr/bin/perl

use lib "/opt/vyatta/share/perl5";
use warnings;
use strict;

use Vyatta::Config;
use Vyatta::IpTables::Rule;
use Vyatta::IpTables::AddressFilter;
use Getopt::Long;

# Send output of shell commands to syslog for debugging and so that
# the user is not confused by it.  Log at debug level, which is supressed
# by default, so that we don't unnecessarily fill up the syslog file.
my $logger = 'logger -t firewall-cfg -p local0.debug --';

# Enable printing debug output to stdout.
my $debug_flag = 0;

# Enable sending debug output to syslog.
my $syslog_flag = 0;

my $fw_stateful_file = '/var/run/vyatta_fw_stateful';
my $fw_tree_file     = '/var/run/vyatta_fw_trees';

my (@updateints, @updaterules);
my ($setup, $teardown, $teardown_ok);

GetOptions("setup=s"           => \$setup, 
           "teardown=s"        => \$teardown,
           "teardown-ok=s"     => \$teardown_ok,
 	   "update-rules=s{2}" => \@updaterules,
	   "update-interfaces=s{5}" => \@updateints,
           "debug"             => \$debug_flag,
           "syslog"            => \$syslog_flag
);

# mapping from config node to iptables/ip6tables table
my %table_hash = ( 'name'        => 'filter',
		   'ipv6-name'   => 'filter',
                   'modify'      => 'mangle',
                   'ipv6-modify' => 'mangle' );

# mapping from config node to iptables command.  Note that this table
# has the same keys as %table hash, so a loop iterating through the 
# keys of %table_hash can use the same keys to find the value associated
# with the key in this table.
my %cmd_hash = ( 'name'        => 'iptables',
		 'ipv6-name'   => 'ip6tables',
		 'modify'      => 'iptables',
                 'ipv6-modify' => 'ip6tables');

# mapping from config node to IP version string.
my %ip_version_hash = ( 'name'        => 'ipv4',
                        'ipv6-name'   => 'ipv6',
                        'modify'      => 'ipv4',
                        'ipv6-modify' => 'ipv6');

# mapping from firewall tree to builtin chain for input
my %inhook_hash =  ( 'filter' => 'FORWARD',
	   	     'mangle' => 'PREROUTING' );

# mapping from firewall tree to builtin chain for output
my %outhook_hash = ( 'filter' => 'FORWARD',
	   	     'mangle' => 'POSTROUTING' );

# mapping from vyatta 'default-policy' to iptables jump target
my %policy_hash = ( 'drop'    => 'DROP',
                    'accept'  => 'RETURN' );

sub log_msg {
  my $message = shift;

  print "DEBUG: $message" if $debug_flag;
  system("$logger DEBUG: \"$message\"") if $syslog_flag;
}

sub other_table {
  my $this = shift;
  return (($this eq 'filter') ? 'mangle' : 'filter');
}

if (defined $setup) {
  setup_iptables($setup);
  exit 0;
}

my $update_zero_count = 0;
if (scalar(@updaterules) == 2) {
  update_rules(@updaterules);
  exit 0;
}

if ($#updateints == 4) {
  my ($action, $int_name, $direction, $chain, $tree) = @updateints;
  
  log_msg "updateints [$action][$int_name][$direction][$chain][$tree]\n";
  my ($table, $iptables_cmd) = (undef, undef);

  my $tree2     = chain_configured(1, $chain, $tree);
  $table        = $table_hash{$tree};
  $iptables_cmd = $cmd_hash{$tree};

  if ($action eq "update") {
    # make sure chain exists
    if (!defined($tree2)) {
      # require chain to be configured in "firewall" first
      print STDERR 'Firewall config error: ' .
                   "Rule set \"$chain\" is not configured\n";
      exit 1;
    }

    # do update action.
    update_ints(@updateints, $table, $iptables_cmd);
  } else {
    # delete
    update_ints(@updateints, $table, $iptables_cmd);
  }
  exit 0;
}

sub find_chain_rule {
  my ($iptables_cmd, $table, $chain, $search) = @_;
  
  my ($num, $chain2) = (undef, undef);
  my $cmd = "$iptables_cmd -t $table -L $chain -vn --line";
  my @lines = `$cmd 2> /dev/null | egrep ^[0-9]`;
  if (scalar(@lines) < 1) {
    system("$logger DEBUG: find_chain_rule: @_ = none \n") if $syslog_flag;
    return;
  }
  foreach my $line (@lines) {
    ($num, undef, undef, $chain2) = split /\s+/, $line;
    last if $chain2 eq $search;
    ($num, $chain2) = (undef, undef);
  }

  if ($syslog_flag) {
    my $tmp_num = $num ? $num : -1;
    system("$logger DEBUG: find_chain_rule: @_ = $tmp_num");
  }

  return $num if defined $num;
  return;
}

if (defined $teardown_ok) {
  my $rc = is_tree_in_use($teardown_ok);
  log_msg "teardown_ok($teardown_ok) = [$rc]\n";
  exit $rc;
}

if (defined $teardown) {
  my $table        = $table_hash{$teardown};
  my $iptables_cmd = $cmd_hash{$teardown};
  log_msg "teardown [$table][$iptables_cmd]\n";
  teardown_iptables($table, $iptables_cmd);

  # remove the conntrack setup.
  my $num;
  $num = find_chain_rule($iptables_cmd, 'raw', 'PREROUTING', 'FW_CONNTRACK');
  if (defined $num) {
    run_cmd("$iptables_cmd -t raw -D PREROUTING $num", 1, 1);
    run_cmd("$iptables_cmd -t raw -D OUTPUT $num", 1, 1);
    run_cmd("$iptables_cmd -t raw -F FW_CONNTRACK", 1, 1);
    run_cmd("$iptables_cmd -t raw -X FW_CONNTRACK", 1, 1);
  }
  exit 0;
}

help();
exit 1;

sub help {
  print "usage: vyatta-firewall.pl\n";
  print "\t--setup              setup Vyatta specific iptables settings\n";
  print "\t--update-rules       update iptables with the current firewall rules\n";
  print "\t--update-interfaces  update the rules applpied to interfaces\n";
  print "\t                     (<action> <interface> <direction> <chain name>)\n";
  print "\t--teardown           teardown all user rules and iptables settings\n";
  print "\n";
}

sub run_cmd {
  my ($cmd_to_run, $redirect_flag, $logger_flag) = @_;

  my $cmd_extras = '';
  
  print "DEBUG: Running: $cmd_to_run \n" if $debug_flag;
  
  system("$logger DEBUG: Running: $cmd_to_run") if $syslog_flag;
  
  $cmd_extras  = ' 2>&1' if $redirect_flag;
  $cmd_extras .= " | $logger" if $logger_flag;
  
  system("$cmd_to_run $cmd_extras");
}

sub read_refcnt_file {
    my ($refcnt_file) = @_;

    my @lines = ();
    if ( -e $refcnt_file) {
      open(my $FILE, '<', $refcnt_file) or die "Error: read $!";
      @lines = <$FILE>;
      close($FILE);
      chomp @lines;
    }
    return @lines;
}

sub write_refcnt_file {
    my ($refcnt_file, @lines) = @_;	    

    if (scalar(@lines) > 0) {
      open(my $FILE, '>', $refcnt_file) or die "Error: write $!";
      print $FILE join("\n", @lines), "\n";
      close($FILE);
    } else {
      system("rm $refcnt_file");
    }
}

sub add_refcnt {
  my ($file, $value) = @_;
    
  log_msg "add_refcnt($file, $value)\n";
  my @lines = read_refcnt_file($file);
  foreach my $line (@lines) {
    return if $line eq $value;
  }
  push @lines, $value;
  write_refcnt_file($file, @lines);
  return @lines; 
}

sub remove_refcnt {
  my ($file, $value) = @_;

  log_msg "remove_refcnt($file, $value)\n";
  my @lines = read_refcnt_file($file);
  my @new_lines = ();
  foreach my $line (@lines) {
    push @new_lines, $line if $line ne $value;
  }
  write_refcnt_file($file, @new_lines) if scalar(@lines) ne scalar(@new_lines);
  return @new_lines;
}

sub is_conntrack_enabled {
  my @lines = read_refcnt_file($fw_stateful_file);
  return 1 if scalar(@lines) > 0;
  return 0;
}

sub is_tree_in_use {
  my ($tree) = @_;

  my @lines = read_refcnt_file($fw_tree_file);
  my %tree_hash;
  foreach my $line (@lines) {
    if ($line =~ /^([^\.]+)\.([^\.]+)$/) {
      my ($tmp_tree, $tmp_chain) = ($1, $2);
      $tree_hash{$tmp_tree}++;
    } else {
      die "Error: unexpected format [$line]\n";
    }
  }
  my $rc;
  $rc = $tree_hash{$tree} ? 1 : 0;
  log_msg "is_tree_in_use($tree) = $rc\n";
  return $rc;
}


sub update_rules {
  my ($tree, $name) = @_;	        # name, modify, ipv6-name or ipv6-modify
  my $table = $table_hash{$tree};	# "filter" or "mangle"
  my $iptables_cmd = $cmd_hash{$tree};  # "iptables" or "ip6tables"
  my $config = new Vyatta::Config;
  my %nodes = ();

  log_msg "update_rules: $tree $name $table $iptables_cmd\n";

  $config->setLevel("firewall $tree");

  %nodes = $config->listNodeStatus();
  if ((scalar (keys %nodes)) == 0) {
    # I don't think we should be able to get here now
    # that end node is moved down from the firewall node.
    log_msg "update_rules: no nodes at this level \n";

    # no names. teardown the user chains and return.
    $update_zero_count += 1;
    teardown_iptables($table, $iptables_cmd);
    return;
  }
  
  # by default, nothing needs to be tracked.
  my $chain_stateful = 0;

  $config->setLevel("firewall $tree $name");
  my $policy = $config->returnValue('default-policy');
  $policy = 'drop' if ! defined $policy;
  my $old_policy = $config->returnOrigValue('default-policy');
  log_msg "update_rules: [$name] = [$nodes{$name}], policy [$policy]\n";

  if ($nodes{$name} eq 'static') {
    # not changed. check if stateful.
    log_msg "$tree $name = static\n";
    $config->setLevel("firewall $tree $name rule");
    my @rules = $config->listOrigNodes();
    foreach (sort numerically @rules) {
      my $node = new Vyatta::IpTables::Rule;
      $node->setupOrig("firewall $tree $name rule $_");
      $node->set_ip_version($ip_version_hash{$tree});
      if ($node->is_stateful()) {
        $chain_stateful = 1;
      }
    }
  } elsif ($nodes{$name} eq 'added') {
    log_msg "$tree $name = added\n";
    # create the chain
    my $ctree = chain_configured(2, $name, $tree);
    if (defined($ctree)) {
      # chain name must be unique in both trees
      printf STDERR 'Firewall config error: '
          . "Rule set name \"$name\" already used in \"$ctree\"\n";
      exit 1;
    }
    setup_chain($table, "$name", $iptables_cmd, $policy);
    add_refcnt($fw_tree_file, "$tree.$name");
    # handle the rules below.
  } elsif ($nodes{$name} eq 'deleted') {

    log_msg "$tree $name = deleted\n";

    # delete the chain
    if (chain_referenced($table, $name, $iptables_cmd)) {
      # disallow deleting a chain if it's still referenced
      print STDERR 'Firewall config error: '
          . "Cannot delete rule set \"$name\" (still in use)\n";
      exit 1;
    }
    delete_chain($table, "$name", $iptables_cmd);
    remove_refcnt($fw_tree_file, "$tree.$name");
    goto end_of_rules;
  } elsif ($nodes{$name} eq 'changed') {
    log_msg "$tree $name = changed\n";
    # handle the rules below.
  }

  # set our config level to rule and get the rule numbers 
  $config->setLevel("firewall $tree $name rule");

  # Let's find the status of the rule nodes
  my %rulehash = ();
  %rulehash = $config->listNodeStatus();
  if ((scalar (keys %rulehash)) == 0) {
    # no rules. flush the user rules.
    # note that this clears the counters on the default DROP rule.
    # we could delete rule one by one if those are important.
    run_cmd("$iptables_cmd -t $table -F $name", 1, 1);
    set_default_policy($table, $name, $iptables_cmd, $policy);
    next;
  }
  
  my $iptablesrule = 1;
  foreach my $rule (sort numerically keys %rulehash) {
    if ("$rulehash{$rule}" eq 'static') {
      my $node = new Vyatta::IpTables::Rule;
      $node->setupOrig("firewall $tree $name rule $rule");
      $node->set_ip_version($ip_version_hash{$tree});
      if ($node->is_stateful()) {
        $chain_stateful = 1;
      }
      my $ipt_rules = $node->get_num_ipt_rules();
      $iptablesrule += $ipt_rules;
    } elsif ("$rulehash{$rule}" eq 'added') {
      # create a new iptables object of the current rule
      my $node = new Vyatta::IpTables::Rule;
      $node->setup("firewall $tree $name rule $rule");
      $node->set_ip_version($ip_version_hash{$tree});
      if ($node->is_stateful()) {
        $chain_stateful = 1;
      }
      
      my ($err_str, @rule_strs) = $node->rule();
      if (defined($err_str)) {
        print STDERR "Firewall config error: $err_str\n";
        exit 1;
      }
      foreach (@rule_strs) {
        if (!defined) {
          last;
        }
          
        run_cmd("$iptables_cmd -t $table --insert $name $iptablesrule $_", 
                0, 0);
        die "$iptables_cmd error: $! - $_" if ($? >> 8);
        $iptablesrule++;
      }
    } elsif ("$rulehash{$rule}" eq 'changed') {
      # create a new iptables object of the current rule
      my $oldnode = new Vyatta::IpTables::Rule;
      $oldnode->setupOrig("firewall $tree $name rule $rule");
      $oldnode->set_ip_version($ip_version_hash{$tree});
      my $node = new Vyatta::IpTables::Rule;
      $node->setup("firewall $tree $name rule $rule");
      $node->set_ip_version($ip_version_hash{$tree});
      if ($node->is_stateful()) {
        $chain_stateful = 1;
      }
      
      my ($err_str, @rule_strs) = $node->rule();
      if (defined($err_str)) {
        print STDERR "Firewall config error: $err_str\n";
        exit 1;
      }
      
      my $ipt_rules = $oldnode->get_num_ipt_rules();
      for (1 .. $ipt_rules) {
        run_cmd("$iptables_cmd -t $table --delete $name $iptablesrule", 0,
                0);
        die "$iptables_cmd error: $! - $rule" if ($? >> 8);
      }
      
      foreach (@rule_strs) {
        if (!defined) {
          last;
        }
        run_cmd("$iptables_cmd -t $table --insert $name $iptablesrule $_", 
                0, 0);
        die "$iptables_cmd error: $! - " , join(' ', @rule_strs) if ($? >> 8);
        $iptablesrule++;
      }
    } elsif ("$rulehash{$rule}" eq 'deleted') {
      my $node = new Vyatta::IpTables::Rule;
      $node->setupOrig("firewall $tree $name rule $rule");
      $node->set_ip_version($ip_version_hash{$tree});
      
      my $ipt_rules = $node->get_num_ipt_rules();
      for (1 .. $ipt_rules) {
        run_cmd("$iptables_cmd -t $table --delete $name $iptablesrule", 
                0, 0);
        die "$iptables_cmd error: $! - $rule" if ($? >> 8);
      }
    }
  } # foreach rule
    
  if (defined $old_policy and $policy ne $old_policy) {
    change_default_policy($table, $name, $iptables_cmd, $policy);
  }

end_of_rules:

  #
  # check if conntrack needs to be enabled/disabled
  #
  my $global_stateful = is_conntrack_enabled();
  log_msg "stateful [$tree][$name] = [$global_stateful][$chain_stateful]\n";
  if ($chain_stateful) {
    add_refcnt($fw_stateful_file, "$tree.$name");
    enable_fw_conntrack($iptables_cmd) if ! $global_stateful;
  } else {
    remove_refcnt($fw_stateful_file, "$tree.$name");
    disable_fw_conntrack($iptables_cmd) if ! is_conntrack_enabled();
  }
}

# returns the "tree" in which the chain is configured; undef if not configured.
# mode: 0: check if the chain is configured in any tree.
#       1: check if it is configured in the specified tree.
#       2: check if it is configured in any "other" tree.
sub chain_configured {
  my ($mode, $chain, $tree) = @_;
  
  my $config = new Vyatta::Config;
  my %chains = ();
  log_msg "chain_configured($mode, $chain, $tree)\n";
  foreach (keys %table_hash) {
    next if ($mode == 1 && $_ ne $tree);
    next if ($mode == 2 && $_ eq $tree);
 
    $config->setLevel("firewall $_");
    %chains = $config->listNodeStatus();

    if (grep(/^$chain$/, (keys %chains))) {
      if ($chains{$chain} ne "deleted") {
        log_msg "found $_\n";
        return $_;
      }
    }
  }
  log_msg "not found\n";
  return; # undef
}

sub update_ints {
  my ($action, $int_name, $direction, $chain, $tree, $table, $iptables_cmd) = @_;
  my $interface = undef;
 
  log_msg "update_ints: @_ \n";

  if (! defined $action || ! defined $int_name || ! defined $direction
      || ! defined $chain || ! defined $table || ! defined $iptables_cmd) {
    return -1;
  }

  if ($action ne 'delete' && $table eq 'mangle' && $direction =~ /^local/) {
    print STDERR 'Firewall config error: ' .
                 "\"Modify\" rule set \"$chain\" cannot be used for " .
                 "\"local\"\n";
    exit 1;
  }

  $_ = $direction;
  my $dir_str = $direction;

  CASE: {
    /^in/    && do {
             $direction = 'VYATTA_IN_HOOK';
             $interface = "--in-interface $int_name";
             last CASE;
             };

    /^out/   && do {   
             $direction = 'VYATTA_OUT_HOOK';
             $interface = "--out-interface $int_name";
             last CASE;
             };

    /^local/ && do {
             # mangle disallowed above
             $direction = "INPUT";
             $interface = "--in-interface $int_name";
             last CASE;
             };
    }

  # In the update case, we want to see if the new rule will replace one
  # that is already in the table.  In the delete case, we need to find
  # the rule in the table that we need to delete.  Either way, we
  # start by listing the rules rules already in the table.
  my $grep = "egrep ^[0-9] | grep $int_name";
  my @lines
    = `$iptables_cmd -t $table -L $direction -n -v --line-numbers | $grep`;
  my ($cmd, $num, $oldchain, $in, $out, $ignore)
    = (undef, undef, undef, undef, undef, undef);

  foreach (@lines) {
    # Parse the line representing one rule in the table.  Note that
    # there is a slight difference in output format between the "iptables"
    # and "ip6tables" comands.  The "iptables" command displays "--" in
    # the "opt" column, while the "ip6tables" command leaves that
    # column blank.
    if ($iptables_cmd eq "iptables") {
      ($num, $ignore, $ignore, $oldchain, $ignore, $ignore, $in, $out,
       $ignore, $ignore) = split /\s+/;
    } else {
      ($num, $ignore, $ignore, $oldchain, $ignore,  $in, $out,
       $ignore, $ignore) = split /\s+/;
    }

    # Look for a matching rule...
    if (($dir_str eq 'in' && $in eq $int_name) 
        || ($dir_str eq 'out' && $out eq $int_name)
        || ($dir_str eq 'local' && $in eq $int_name)) {
      # found a matching rule
      if ($action eq 'update') {
        # replace old rule
        $action = 'replace';
        $cmd = "--replace $direction $num $interface --jump $chain";
      } else {
        # delete old rule
        $cmd = "--delete $direction $num";
      }
      last;
    }
  }

  if (!defined($cmd)) {
    # no matching rule
    if ($action eq 'update') {
      # add new rule.
      # there is a post-fw rule at the end. insert at the front.      
      $cmd = "--insert $direction 1 $interface --jump $chain";
    } else {
      # delete non-existent rule!
      # not an error. rule may be in the other table.
    }
  }

  # no match. do nothing.
  return 0 if (!defined($cmd));

  run_cmd("$iptables_cmd -t $table $cmd", 0, 0);
  exit 1 if ($? >> 8);
 
  # the following delete_chain is probably no longer necessary since we
  # now disallow deleting a chain when it's still referenced
  if ($action eq 'replace' || $action eq 'delete') {
    if (!defined(chain_configured(1, $oldchain, $tree))) {
      if (!chain_referenced($table, $oldchain, $iptables_cmd)) {
        delete_chain($table, $oldchain, $iptables_cmd);
      }
    }
  }
  return 0;
}

sub enable_fw_conntrack {
  # potentially we can add rules in the FW_CONNTRACK chain to provide
  # finer-grained control over which packets are tracked.
  my $iptables_cmd = shift;
  log_msg("enable_fw_conntrack($iptables_cmd)\n");
  run_cmd("$iptables_cmd -t raw -R FW_CONNTRACK 1 -j ACCEPT", 1, 1);
}

sub disable_fw_conntrack {
  my $iptables_cmd = shift;
  log_msg("disable_fw_conntrack\($iptables_cmd\)\n");
  run_cmd("$iptables_cmd -t raw -R FW_CONNTRACK 1 -j RETURN", 1, 1);
}


sub teardown_iptables {
  my ($table, $iptables_cmd) = @_;
  log_msg "teardown_iptables executing: $iptables_cmd -L -n -t $table\n";
  my @chains = `$iptables_cmd -L -n -t $table`;
  my $chain;

  # $chain is going to look like this...
  # Chain inbound (0 references)
  foreach my $chain (@chains) {
    # chains start with Chain 
    if ($chain =~ s/^Chain//) {
      # make sure this is a user chain by looking at "references".
      # make sure this is not a hook.
      if (($chain =~ /references/) && !($chain =~ /VYATTA_\w+_HOOK/)) {
	($chain) = split /\(/, $chain;
        $chain =~ s/\s//g;
        delete_chain($table, "$chain", $iptables_cmd);
      }
    }
  }

  # remove VYATTA_(IN|OUT)_HOOK
  my $ihook = $inhook_hash{$table};
  my $num = find_chain_rule($iptables_cmd, $table, $ihook, 'VYATTA_IN_HOOK');
  if (defined $num) {
    run_cmd("$iptables_cmd -t $table -D $ihook $num", 1, 1);
    run_cmd("$iptables_cmd -t $table -F VYATTA_IN_HOOK", 1, 1);
    run_cmd("$iptables_cmd -t $table -X VYATTA_IN_HOOK", 1, 1);
  }
  my $ohook = $outhook_hash{$table};
  $num = find_chain_rule($iptables_cmd, $table, $ohook, 'VYATTA_OUT_HOOK');
  if (defined $num) {
    run_cmd("$iptables_cmd -t $table -D $ohook $num", 1, 1);
    run_cmd("$iptables_cmd -t $table -F VYATTA_OUT_HOOK", 1, 1);
    run_cmd("$iptables_cmd -t $table -X VYATTA_OUT_HOOK", 1, 1);
  }
}

sub setup_iptables {
  my $iptables_cmd = shift;

  log_msg "setup_iptables [$iptables_cmd]\n";
  foreach my $table (qw(filter mangle)) {
    $update_zero_count += 1;
    #teardown_iptables($table, $iptables_cmd);
    my $ihook = $inhook_hash{$table};
    my $ohook = $outhook_hash{$table};
    # add VYATTA_(IN|OUT)_HOOK
    my $num = find_chain_rule($iptables_cmd, $table, $ohook, 'VYATTA_OUT_HOOK');
    if (! defined $num) {
      run_cmd("$iptables_cmd -t $table -N VYATTA_OUT_HOOK", 1, 1);
      run_cmd("$iptables_cmd -t $table -I $ohook 1 -j VYATTA_OUT_HOOK", 1, 1);
      run_cmd("$iptables_cmd -t $table -N VYATTA_IN_HOOK", 1, 1);
      run_cmd("$iptables_cmd -t $table -I $ihook 1 -j VYATTA_IN_HOOK", 1, 1);
    }
  }

  # by default, nothing is tracked (the last rule in raw/PREROUTING).
  my $cnt = count_iptables_rules('raw', 'FW_CONNTRACK', $iptables_cmd);
  if ($cnt == 0) {
    run_cmd("$iptables_cmd -t raw -N FW_CONNTRACK", 1 , 1);
    run_cmd("$iptables_cmd -t raw -A FW_CONNTRACK -j RETURN", 1, 1);
    run_cmd("$iptables_cmd -t raw -I PREROUTING 1 -j FW_CONNTRACK", 1, 1);
    run_cmd("$iptables_cmd -t raw -I OUTPUT 1 -j FW_CONNTRACK", 1, 1);
  } else {
    log_msg "FW_CONNTRACK exists $cnt\n";
  }
  return 0;
}

sub add_default_drop_rule {
  my ($table, $chain, $iptables_cmd) = @_;
  log_msg("add_default_drop_rule($iptables_cmd, $table, $chain)\n");
  my $comment = "-m comment --comment \"$chain-1025\"";
  run_cmd("$iptables_cmd -t $table -A $chain $comment -j DROP", 1, 1);
}

sub set_default_policy {
  my ($table, $chain, $iptables_cmd, $policy) = @_;

  $policy = 'drop' if ! defined $policy;
  log_msg("set_default_policy($iptables_cmd, $table, $chain, $policy)\n");
  my $target = $policy_hash{$policy};
  my $comment = "-m comment --comment \"$chain-1025 default-policy $policy\"";
  run_cmd("$iptables_cmd -t $table -A $chain $comment -j $target", 1, 1);
}

sub count_iptables_rules {
  my ($table, $chain, $iptables_cmd) = @_;
  my $cmd = "$iptables_cmd -t $table -L $chain -n --line";
  my @lines = `$cmd 2> /dev/null`;
  my $cnt = 0;
  foreach my $line (@lines) {
    $cnt++ if $line =~ /^\d/;
  }
  return $cnt;
}

sub change_default_policy {
  my ($table, $chain, $iptables_cmd, $policy) = @_;
  
  $policy = 'drop' if ! defined $policy;
  log_msg("change_default_policy($iptables_cmd, $table, $chain, $policy)\n");
  my $target = $policy_hash{$policy};
  my $comment = "-m comment --comment \"$chain-1025 default-policy $policy\"";
  my $default_rule = count_iptables_rules($table, $chain, $iptables_cmd);
  run_cmd("$iptables_cmd -t $table -A $chain $comment -j $target", 1, 1);
  run_cmd("$iptables_cmd -t $table -D $chain $default_rule", 1, 1);
}

sub setup_chain {
  my ($table, $chain, $iptables_cmd, $policy) = @_;

  my $configured = `$iptables_cmd -t $table -n -L $chain 2>&1 | head -1`;

  $_ = $configured;
  if (!/^Chain $chain/) {
    run_cmd("$iptables_cmd -t $table --new-chain $chain", 0, 0);
    die "iptables error: $table $chain --new-chain: $!" if ($? >> 8);
    set_default_policy($table, $chain, $iptables_cmd, $policy);
  }
}

sub chain_referenced {
  my ($table, $chain, $iptables_cmd) = @_;

  my $cmd = "$iptables_cmd -t $table -n -L $chain";
  my $line = `$cmd 2>/dev/null |head -n1`;
  chomp $line;
  my $found = 0;
  if ($line =~ m/^Chain $chain \((\d+) references\)$/) {
    if ($1 > 0) {
      $found = 1;
    }
  }
  log_msg "chain_referenced [$cmd] = $found\n";
  return $found;
}

sub chain_referenced_count {
  my ($table, $chain, $iptables_cmd) = @_;

  log_msg "chain_referenced_count: $iptables_cmd -t $table -n -L $chain\n";

  my $cmd = "$iptables_cmd -t $table -n -L $chain";
  my $line = `$iptables_cmd -t $table -n -L $chain 2>/dev/null |head -n1`;
  chomp $line;
  if ($line =~ m/^Chain $chain \((\d+) references\)$/) {
    return $1;
  }
  return;
}

sub delete_chain {
  my ($table, $chain, $iptables_cmd) = @_;
  
  log_msg "delete_chain: $iptables_cmd -t $table -n -L $chain\n";

  my $configured = `$iptables_cmd -t $table -n -L $chain 2>&1 | head -1`;

  if ($configured =~ /^Chain $chain/) {
    run_cmd("$iptables_cmd -t $table --flush $chain", 0, 0);
    die "$iptables_cmd error: $table $chain --flush: $!" if ($? >> 8);
    if (!chain_referenced($table, $chain, $iptables_cmd)) {
      run_cmd("$iptables_cmd -t $table --delete-chain $chain", 0, 0);
      die "$iptables_cmd error: $table $chain --delete-chain: $!" if ($? >> 8);
    } else {
      add_default_drop_rule($table, $chain, $iptables_cmd);
    }
  }
}

sub numerically { $a <=> $b; }

# Local Variables:
# mode: perl
# indent-tabs-mode: nil
# perl-indent-level: 2
# End: