iptables rules confusion, nat PREROUTING
No. Only the local process listening on port 2222
will receive the packet. If it replies, the reverse translation will take place, and outgoing reply
packet will be out from port 22
.
Fourth rule will make any encountered packets destined to port 22
to be re-routed to your local port 2222
, even if they weren't meant to be for this machine. Since you don't have any other match criteria, it'll be so for anyone, except for connections outgoing from this machine.
In effect, this intercepts any pass-through SSH traffic. If somebody is set this system as their gateway and try to connect to any SSH service outside the LAN, they'll end up connecting to your service running on port 2222
instead. If they were already established the trust (have the real server's key in the known_hosts
file, or it is is properly published with DNSSEC), their attempt will be rejected by their client with the proper warning about ongoing man-in-the-middle attack (which this rule essentially looks like).
Please, consult the Netfilter packet flow diagram.
By the way, you don't need to enable ip forwarding in this case, because the packet don't need be forwarded (even if it has to be forwarded if there was no REDIRECT
rule). And you don't need do to anything with the FORWARD
chain, because it isn't traversed. So first and second commands are redundant. After the nat
table, the packet is re-targeted to the local machine; when routing decision takes place, the packet is sent to the INPUT
chain. This is where you can control this packet, and the packet there will be already translated to the port 2222
, so rule in your third command is correct.