Iptables: a little about the effect of REDIRECT, its limitations and scope


    This note describes the effect of REDIRECT in iptables, its limitations and scope.

    Iptables and REDIRECT


    The REDIRECT action is designed to redirect packets from one set of ports to another within the same system without leaving the host .

    REDIRECT only works 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 a 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 --dport 80 -j REDIRECT --to-port 3128

    Case


    Suppose you need to change the application port only by redirecting using iptables, without touching the daemon settings. Let the new port be 5555, and the application port 22. Thus, we need 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 --dport 5555 -j REDIRECT --to-port 22

    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 itself with iptables will not work, because packets with 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 OUTPUT chain of the nat table:

    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 via port 5555.

    REDIRECT and private port


    The meaning 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 mangle:

    iptables -t mangle -A PREROUTING -p tcp --dport 22 -j DROP

    Full 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

    Also popular now: