#! /bin/sh

trusthost='192.168.0.20'
internal_ip='192.168.0.0/24'

my_internet_ip='1.2.3.4'
my_internal_ip='192.168.0.1'

proxy_port='3128'

echo 1 > /proc/sys/net/ipv4/ip_forward

##############
#Flush & Reset
##############
iptables -F
iptables -t nat -F
iptables -X

##############
#Deafult Rule
##############
iptables -P INPUT DROP
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

iptables -P OUTPUT ACCEPT

iptables -P FORWARD DROP
iptables -A FORWARD -i eth1 -o eth0 -s $internal_ip -j ACCEPT
iptables -A FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT

#########
#loopback
#########
iptables -A INPUT -i lo -j ACCEPT
iptables -A OUTPUT -o lo -j ACCEPT
#######################
#ICMP trusthost->myhost
#######################
iptables -A INPUT -p icmp --icmp-type echo-request -s $trusthost -d $my_internal_ip -j ACCEPT
iptables -A OUTPUT -p icmp --icmp-type echo-reply  -s $my_internal_ip -d $trusthost -j ACCEPT
#######################
#ICMP myhost->trusthost
#######################
iptables -A OUTPUT -p icmp --icmp-type echo-request -s $my_internal_ip -d $trusthost -j ACCEPT
iptables -A INPUT -p icmp --icmp-type echo-reply -s $trusthost -d $my_internal_ip -j ACCEPT
#######################
#ssh trusthost-> myhost
#######################
iptables -A INPUT -p tcp ! --syn -m state --state NEW -j DROP
iptables -A INPUT -p tcp -m state --state NEW,ESTABLISHED,RELATED -s $trusthost -d $my_internal_ip --dport 22 -j ACCEPT
iptables -A OUTPUT -p tcp -s $my_internal_ip --sport 22 -d $trusthost -j ACCEPT
#########################
#Proxy trusthost-> myhost
#########################
iptables -A INPUT -p tcp -m state --state NEW,ESTABLISHED,RELATED -s $internal_ip -d $my_internal_ip --dport $proxy_port -j ACCEPT
iptables -A OUTPUT -p tcp -s $my_internal_ip --sport $proxy_port -d $internal_ip -j ACCEPT

#################
#SNAT(masquerade)
#################
iptables -t nat -A POSTROUTING -o eth0 -s $internal_ip -j MASQUERADE

####################
#Transparently proxy
####################
iptables -t nat -A PREROUTING -i eth1  -s ! $my_internal_ip -p tcp --dport 80 -j DNAT --to-destination $my_internal_ip:$proxy_port
#iptables -t nat -A PREROUTING -i eth1 -p tcp --dport 80 -j REDIRECT --to-port $proxy_port

################################################
#Outgoing packet should be real internet Address
################################################
iptables -A OUTPUT -o eth0 -d 10.0.0.0/8 -j DROP
iptables -A OUTPUT -o eth0 -d 176.16.0.0/12 -j DROP
iptables -A OUTPUT -o eth0 -d 192.168.0.0/16 -j DROP
iptables -A OUTPUT -o eth0 -d 127.0.0.0/8 -j DROP

#########
#logging
#########
iptables -N LOGGING
iptables -A LOGGING -j LOG --log-level warning --log-prefix "DROP:" -m limit
iptables -A LOGGING -j DROP
iptables -A INPUT -j LOGGING
iptables -A FORWARD -j LOGGING


