#!/usr/local/bin/perl
# setup.cgi
# Setup an initial save file

require './firewall-lib.pl';
&ReadParse();

&lock_file($iptables_save_file);
if (defined(&unapply_iptables)) {
	&unapply_iptables();
	}
else {
	&backquote_logged("iptables-save >$iptables_save_file 2>&1");
	}
if ($in{'auto'}) {
	@tables = &get_iptables_save();
	if ($in{'auto'} == 1) {
		# Add a single rule to the nat table for masquerading
		$iface = $in{'iface1'} || $in{'iface1_other'};
		$iface || &error($text{'setup_eiface'});
		($table) = grep { $_->{'name'} eq 'nat' } @tables;
		push(@{$table->{'rules'}},
		     	{ 'chain' => 'POSTROUTING',
			  'o' => [ "", $iface ],
			  'j' => [ "", 'MASQUERADE' ] } );
		}
	elsif ($in{'auto'} == 2) {
		# Block all incoming traffic, except for established
		# connections, DNS replies and safe ICMP types
		$iface = $in{'iface2'} || $in{'iface2_other'};
		$iface || &error($text{'setup_eiface'});
		($table) = grep { $_->{'name'} eq 'filter' } @tables;
		$table->{'defaults'}->{'INPUT'} = 'DROP';
		push(@{$table->{'rules'}},
		     { 'chain' => 'INPUT',
		       'i' => [ "!", $iface ],
		       'j' => [ "", 'ACCEPT' ] },
		     { 'chain' => 'INPUT',
		       'm' => [ [ "", "tcp" ] ],
		       'p' => [ "", "tcp" ],
		       'tcp-flags' => [ "", "ACK", "ACK" ],
		       'j' => [ "", 'ACCEPT' ] },
		     { 'chain' => 'INPUT',
		       'm' => [ [ "", "state" ] ],
		       'state' => [ "", "ESTABLISHED" ],
		       'j' => [ "", 'ACCEPT' ] },
		     { 'chain' => 'INPUT',
		       'm' => [ [ "", "state" ] ],
		       'state' => [ "", "RELATED" ],
		       'j' => [ "", 'ACCEPT' ] },
		     { 'chain' => 'INPUT',
		       'm' => [ [ "", "udp" ] ],
		       'p' => [ "", "udp" ],
		       'sport' => [ "", 53 ],
		       'dport' => [ "", "1024:65535" ],
		       'j' => [ "", 'ACCEPT' ] },
		     { 'chain' => 'INPUT',
		       'm' => [ [ "", "icmp" ] ],
		       'p' => [ [ "", "icmp" ] ],
		       'icmp-type' => [ "", "echo-reply" ],
		       'j' => [ "", 'ACCEPT' ] },
		     { 'chain' => 'INPUT',
		       'm' => [ [ "", "icmp" ] ],
		       'p' => [ [ "", "icmp" ] ],
		       'icmp-type' => [ "", "destination-unreachable" ],
		       'j' => [ "", 'ACCEPT' ] },
		     { 'chain' => 'INPUT',
		       'm' => [ [ "", "icmp" ] ],
		       'p' => [ [ "", "icmp" ] ],
		       'icmp-type' => [ "", "source-quench" ],
		       'j' => [ "", 'ACCEPT' ] },
		     { 'chain' => 'INPUT',
		       'm' => [ [ "", "icmp" ] ],
		       'p' => [ [ "", "icmp" ] ],
		       'icmp-type' => [ "", "time-exceeded" ],
		       'j' => [ "", 'ACCEPT' ] },
		     { 'chain' => 'INPUT',
		       'm' => [ [ "", "icmp" ] ],
		       'p' => [ [ "", "icmp" ] ],
		       'icmp-type' => [ "", "parameter-problem" ],
		       'j' => [ "", 'ACCEPT' ] } );
		}
	&save_table($table);
	}

if ($in{'atboot'}) {
	&create_firewall_init();
	}
&unlock_file($iptables_save_file);

&webmin_log("setup");
&redirect("");


