iptables redirect 80 to 8080 but block public 8080 access

lazidar picture lazidar · Jun 16, 2012 · Viewed 15.2k times · Source

I have some iptables rules which redirect requests for port 80 onto our application server (GlassFish) at port 8080 (and also SSL ports too but I've left them out for simplicity).

Whilst what we have works fine (and I don't personally have an issue with it) port 8080 is also open to the outside world if someone wished to specify it in the url. It has been mandated that port 8080 should be closed off from access from the outside world and only 80 be open.

I don't wish to change the listener on the application server (as to use port 80 this appears to need elevated permissions for the user running the app server) and the listener on port 8080 needs to know the source IP of the packet as the application audits the requests to the application (i.e. we can't change the source IP address to a local one).

The current iptables config is below. Does anyone know if there is a way to block 8080 from the public internet whilst retaining the source IP in the packets redirected to from port 80?

Many thanks in advance.


    iptables -P INPUT ACCEPT
    iptables -P OUTPUT ACCEPT
    iptables -P FORWARD DROP

    # allow establishment of connections initialised by my outgoing packets
    iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT

    # accept anything on localhost
    iptables -A INPUT -i lo -j ACCEPT

    ################################################################
    #individual ports tcp 
    ################################################################
    iptables -A INPUT -p tcp --dport 80 -j ACCEPT
    iptables -A INPUT -p tcp --dport 8080 -j ACCEPT

    #drop everything else
    iptables -A INPUT -j DROP

    ################################################################
    #Redirection Rules
    ################################################################
    # redirection rules (allowing forwarding from localhost)
    iptables -t nat -A OUTPUT -o lo -p tcp --dport 80 -j REDIRECT --to-port 8080

    # redirection http
    iptables -t nat -A PREROUTING -p tcp -m tcp --dport 80 -j REDIRECT --to-ports 8080

Answer

Vince picture Vince · Jul 3, 2012

One way I've found to accomplish this is to use the MARK target in the mangle table's PREROUTING chain.

Add a rule to tag the packets you want to block:

iptables -t mangle -A PREROUTING -p tcp --dport 8080 -j MARK --set-mark 1

Then, before you allow port 8080 add this to DROP marked packets:

iptables -A INPUT -m mark --mark 1 -j DROP