Search code examples
iptables

Redirection using iptables


I have a server on cloud with following iptables.

iptables -A INPUT   -i  lo -j ACCEPT
iptables -A INPUT -p tcp --dport 80 -j ACCEPT 
iptables -A INPUT -p tcp --dport 443 -j ACCEPT 
iptables -A INPUT  -j DROP

iptables -A OUTPUT -o lo -j ACCEPT 
iptables -A OUTPUT -p tcp --sport 80 -m state --state RELATED,ESTABLISHED -j ACCEPT 
iptables -A OUTPUT -p tcp --sport 443 -m state --state RELATED,ESTABLISHED -j ACCEPT 
iptables -A OUTPUT -p tcp --sport 9200 -m state --state New,RELATED,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -j DROP

iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 2900 -j DNAT --to-destination 127.0.0.1:9200

What I have to add in other chains so that i can access my service on 2900 port.


Solution

  • Rules apply from the top down.

    6.2 Destination NAT

    This is done in the PREROUTING chain, just as the packet comes in; this means that anything else on the Linux box itself (routing, packet filtering) will see the packet going to its `real' destination

    So you want the PREROUTING line at the top, so the NAT happens first.

    Then an INPUT entry allowing incoming connections on your destination port, after NAT.

    Except, what's up with your INPUT rules not accepting RELATED and ESTABLISHED and your output rules setting specific source ports? Outbound traffic usually comes from random high ports.

    From https://serverfault.com/a/578781/57144 and https://serverfault.com/a/578787/57144 you want to explicitly say NEW connections for incoming ports, and should prefer fewer rules for performance (if applicable).

    iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 2900 -j DNAT --to-destination 127.0.0.1:9200
    
    iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT 
    iptables -A INPUT -i  lo -j ACCEPT
    iptables -A INPUT -p tcp -m state --state NEW -m tcp --dport 80 -j ACCEPT 
    iptables -A INPUT -p tcp -m state --state NEW -m tcp --dport 443 -j ACCEPT 
    iptables -A INPUT -p tcp -m state --state NEW -m tcp --dport 9200 -j ACCEPT 
    
    # or
    # iptables -A INPUT -p tcp -m state --state NEW -m tcp -m multiport --dports 80,443,9200 -j ACCEPT
    
    iptables -A INPUT  -j DROP