Score:0

iptables rules confusion, nat PREROUTING

ma flag

Im struggling to understand exactly what these set of iptables rules do.

Does port 22 get the packet AND port 2222 gets a copy of it as well? Or does the packet get redirected to port 2222 skipping port 22? Can someone please explain to me what these set of rules do in detail? thanks in advance!

echo 1 > /proc/sys/net/ipv4/ip_forward
iptables -P FORWARD ACCEPT
iptables -A INPUT -p tcp --dport 2222 -j ACCEPT
iptables -t nat -A PREROUTING -p tcp --dport 22 -j REDIRECT --to-ports 2222
Score:2
za flag

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.

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.