Port redirection with iptables to localhost / blocking the destination port
I like to forward all traffic coming to 80 to be redirected to 8000.
I used
iptables -tnat -A PREROUTING -p tcp -m tcp --dport 80 -j REDIRECT --to-ports 8000
But then port 8000 is still open to public.
I tried -DNAT:
iptables -t nat -A PREROUTING -p tcp --dport 80 -j DNAT --to-destination 127.0.0.1:8000
But this does not work at all. /proc/sys/net/ipv4/ip_forward is set to 1.
There are no other rules configured.
Please help me out :)
--
edit:
In answer to the question below: Here is exaclty, what I want to achieve:
I have a service running at port 8000 which can be seen as a webserver. It should be accessible via port 80 from outside, but not via port 8000. The internal network does not matter: may be restricted or not.
I understand, that REDIRECT does not drop packets directly addressed to port 8000, but if I would drop all packets to 8000 in INPUT chain, then the redirected packets are dropped also.
iptables -A INPUT -p tcp -m tcp --dport 8000 -j DROP
Cannot work for me.
Is there a way to drop packets with destination port 8000, that have not been redirected via my PREROUTING chain?
Adding a source ip via -s does not help, right? because the source IP does not change at redirection.
Answer
Based on the accepted answer I could solve it this way:
iptables -tmangle -A PREROUTING -p tcp -m tcp --dport 8000 -j MARK --set-mark 1
iptables -A INPUT -m mark --mark 1 -j DROP
Solution 1:
Set mark in the packet you redirect. Then allow the marked packs before the blocked packs. see iptables -j MARK -h
to mark a packet and iptables -m mark -h
to match a pack