This article describes the REDIRECT action in iptables, its limitations and scope.
Iptables and redirction
The REDIRECT action is designed to redirect packets from one set of ports to another within the same system,
without going beyond the host .
REDIRECT works only in the PREROUTING and OUTPUT chains of the nat table. Thus, the scope is reduced only to redirection from one port to another. Most often this is used for transparent proxy, when a client from the local network connects to port 80, and the gateway redirects packets to the local proxy port:
iptables -t nat -A PREROUTING -p tcp
Case
Suppose you only need to change the application port with a redirect using iptables, without touching the daemon settings. Let the new port be 5555, and the port of application 22. Thus, it is necessary to redirect from port 5555 to 22.
')
REDIRECT and remote client
The first step is obvious and will be the same as in the example above:
iptables -t nat -A PREROUTING -p tcp
However, the rule will work only for external clients and only when the application port is open.
REDIRECT and local client
The previous rule for the host with iptables will not work, because packets from localhost do not fall into the nat table. For the case to work on the local machine, you need to add a redirect to the nat table OUTPUT chain:
iptables -t nat -A OUTPUT -p tcp -s 127.0.0.1 --dport 5555 -j REDIRECT --to-ports 22
Now the local client can also connect to port 5555.
REDIRECT and closed port
The point of the case is to use the left port, and keep the application port closed, but if you execute the DROP rule in the INPUT chain on port 22, then 5555 will also stop responding. Actually, the trick is to open the application port in the INPUT chain, and drop it in the mangle:
iptables -t mangle -A PREROUTING -p tcp
Complete set of rules
Redirect with network and local access when the application port is closed:
iptables -t nat -A PREROUTING -p tcp --dport 5555 -j REDIRECT --to-port 22 iptables -t nat -A OUTPUT -p tcp -s 127.0.0.1 --dport 5555 -j REDIRECT --to-ports 22 iptables -A INPUT -p tcp --dport 5555 -j ACCEPT iptables -A INPUT -p tcp --dport 22 -j ACCEPT iptables -A INPUT -i lo -j ACCEPT iptables -t mangle -A PREROUTING -p tcp --dport 22 -j DROP iptables -P INPUT DROP