My objective using iptables is to allow only incoming traffic to ports 80, 443, and 22 and only allow outgoing traffic for established connections. I also need to route traffic from ports 80 and 443 to 3128 and 3129 respectively which are the ports for squid (a proxy).
The issue I'm having is when the traffic is being routed to 3128 from 80 as far as iptables is concerned it seems to see it as incoming traffic to 3128. That means that in order to have things work I have had to add a rule to allow incoming traffic to port 3128 which is not what I want to do.
Here are the current rules I'm working with:
iptables -t nat -A PREROUTING -i eth0 -p tcp -m tcp --dport 80 -j REDIRECT --to-ports 3128
iptables -t nat -A PREROUTING -i eth0 -p tcp -m tcp --dport 443 -j REDIRECT --to-ports 3129
#Allow outgoing established tcp connections
iptables -A OUTPUT -o eth0 -m state --state ESTABLISHED,RELATED -j ACCEPT
#Allow new incoming connections to 22, 80, and 443
iptables -A INPUT -p tcp -i eth0 --dport 22 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A INPUT -p tcp -i eth0 --dport 80 -j ACCEPT
iptables -A INPUT -p tcp -i eth0 --dport 443 -j ACCEPT
iptables -A INPUT -p tcp -i eth0 --dport 3128 -j ACCEPT
#Drop everything else
iptables -A INPUT -i eth0 -p tcp -s 0.0.0.0/0 -j DROP
iptables -A OUTPUT -o eth0 -p tcp -d 0.0.0.0/0 -j DROP
So my question is whether there is a way to configure the rules so I don't have to explicitly allow connections to port 3128. I want to allow traffic to 3128, but only the traffic that is redirected from the prerouting rules. Sorry if that was a bit confusing or hard to understand, if anyone needs any clarification, please ask.
Exchange your PREROUTE rules for POSTROUTE rules.