Final IpTables Script

For your reference here is the final and full /etc/network/iptables script to transparently redirect all outbound HTTP and HTTPS traffic to Squid instance running on Ubuntu 16 gateway machine. This script is based on the excellect Ars Technica article https://arstechnica.com/gadgets/2016/04/the-ars-guide-to-building-a-linux-router-from-scratch.

*nat
:PREROUTING ACCEPT [0:0]
:INPUT ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
:POSTROUTING ACCEPT [0:0]


# ens32 is WAN interface
# ens33 is LAN interface
-A POSTROUTING -o ens32 -j MASQUERADE

# redirect HTTP to locally installed Squid instance
-A PREROUTING -i ens33 -p tcp --dport 80 -j REDIRECT --to-ports 3126

# redirect HTTPS to locally installed Squid instance
-A PREROUTING -i ens33 -p tcp --dport 443 -j REDIRECT --to-ports 3127

COMMIT

*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]

# Service rules
-A INPUT -s 127.0.0.0/8 -d 127.0.0.0/8 -i lo -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -m state --state ESTABLISHED -j ACCEPT

# enable traceroute rejections to get sent out
-A INPUT -p udp -m udp --dport 33434:33523 -j REJECT --reject-with icmp-port-unreachable
-A INPUT -i ens33 -p tcp --dport 53 -j ACCEPT
-A INPUT -i ens33 -p udp --dport 53 -j ACCEPT

# ssh accept from LAN and WAN
-A INPUT -i ens33 -p tcp --dport 22 -j ACCEPT
-A INPUT -i ens32 -p tcp --dport 22 -j ACCEPT

# DHCP client requests - accept from LAN
-A INPUT -i ens33 -p udp --dport 67:68 -j ACCEPT

# accept traffic to Web UI of Web Safety on port 8000
-A INPUT -i ens33 -p tcp --dport 8000 -j ACCEPT

# accept traffic to redirected ports 3126, 3127 and proxy port 3128
-A INPUT -i ens33 -p tcp --dport 3126 -j ACCEPT
-A INPUT -i ens33 -p tcp --dport 3127 -j ACCEPT
-A INPUT -i ens33 -p tcp --dport 3128 -j ACCEPT

# drop all other input traffic
-A INPUT -j DROP

# Forwarding rules

# forward packets along established/related connections
-A FORWARD -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT

# forward from LAN to WAN
-A FORWARD -i ens33 -o ens32 -j ACCEPT

# drop all other forwarded traffic
-A FORWARD -j DROP

COMMIT