#!/usr/bin/perl

use warnings;
use strict;
use IPC::Open3;
use File::Temp qw/ tempfile /;
use File::Copy;

use Config::Merge('My::Config' => '/etc/firewall/conf');
use My::Config;

my $user = shift;
help() unless ($user);
help(1) unless ( getpwnam($user) );
whitelist($user);

sub whitelist {
    my $user = shift;
    my @existing_users = get_whitelisted_users();
    if ( ! grep { /$user/ } @existing_users ) {
        push @existing_users, $user;
    }
    fix_firewall(@existing_users);
    write_whitelisted_users(@existing_users);
}

sub write_whitelisted_users {
    my @users = @_;
    my $config_dir = My::Config::object->{config_dir};
    my ($fh, $tempfile) = tempfile();
    eval {
        print $fh "$_\n" foreach (@users);
        close $fh;
    };
    if ($@) {
        print "Failed to write new whitelist!\n";
        exit 1;
    }
    move $tempfile, "$config_dir/outbound_whitelist";
}

sub get_whitelisted_users {
    my $config_dir = My::Config::object->{config_dir};
    return unless ( -f "$config_dir/outbound_whitelist" ); 
    open my $fh, '<', "$config_dir/outbound_whitelist";
    chomp(my @users = <$fh>);
    close $fh;
    foreach my $user (@users) {
        if ( ! getpwnam($user) ) {
            @users = grep { $_ ne $user } @users;
        }
    }
    return @users;
}

sub get_existing_chain {
    my ($chld_in, $chld_out, $chld_err);
    my $pid = open3($chld_in, $chld_out, $chld_err, '/sbin/iptables', '-n', '-L',  'outbound-attack', '--line-numbers');
    waitpid($pid, 0);
    my @out = <$chld_out>;
    close $chld_in;
    close $chld_out;
    chomp @out;
    my $chld_exit = $? >> 8;
    if ( $chld_exit == 0 ) {
        return @out;
    }
    else {
        print @out;
        exit 1;
    }
}

# finds the first DROP in the outbound-attack chain. this is where we want to INSERT whitelist rules
sub get_insert_mark {
    my @chain_lines = get_existing_chain();
    foreach (@chain_lines) {
        /^(\d+)\s+(\w+)\s+.+/;
        next unless $1;
        return $1 if ($2 eq 'DROP');
    }
}



sub fix_firewall {
    my @users = @_;
    my @chain_lines = get_existing_chain();
    my $insert_mark = get_insert_mark();
    foreach my $line ( @chain_lines ) {
        next unless ( $line =~ /owner UID match (\d+)/ );
        my $name = getpwuid( $1 );
        @users = grep { $_ ne $name } @users; # remove a user from the list if they already have a rule
    }
    foreach $user (@users) {
        my ($chld_in, $chld_out, $chld_err);
        my $pid = open3($chld_in, $chld_out, $chld_err, 
            '/sbin/iptables', '-I', 'outbound-attack', $insert_mark, '-m', 'owner', '--uid-owner', $user, '-j', 'RETURN',
            '-m', 'comment', '--comment', $user);
        waitpid($pid, 0);
        close $chld_in;
        close $chld_out;
        my $chld_exit = $? >> 8;
        if ( $chld_exit == 0 ) {
            return 1;
        }
        else {
            die "Failed to add iptables rule for $user";
        }
    }
}

sub help {
    my $stat = shift;
    print "Err: User doesn't exist\n" if ( $stat == 1 );
    print "whitelist_outbound <username>\n";
    print "- Adds <username> to whitelist for outbound dport 80\n\n";
    exit 1;
}
