Pages

Friday, January 5, 2018

Forwarding ports 80 to 8080 or 443 to 8443 with iptables firewall

It is something I often do. So I make here a note for myself.

If you want that the user access you website via the standard http port 80 or https 443 you have few options:

  • use Appache server to forward request to your server, which will slow down your webapplication
  • run your server as root, which might be unsecure
  • use iptable service to forward the traffic arriving to the standard ports to the ports that are listened to by the server application (e.g. Tomcat, Wildfly)

It is seems to me that the option with iptables is the most straightforward. There are several ways to configure the firewall on CentOS. I use a shortcut way:

  • Edit file /etc/sysconfig/iptables as root so that it includes *nat section with the prerouting commands:
    *filter
    :FORWARD ACCEPT [0:0]
    :INPUT DROP [0:0]
    :OUTPUT ACCEPT [0:0]
    -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
    -A INPUT -p icmp -j ACCEPT
    -A INPUT -i lo -j ACCEPT
    -A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT
    -A INPUT -m state --state NEW -m tcp -p tcp --dport 8080 -j ACCEPT
    -A INPUT -m state --state NEW -m tcp -p tcp --dport 8443 -j ACCEPT
    -A INPUT -m state --state NEW -m tcp -p tcp --dport 3306 -j ACCEPT
    -A INPUT -m state --state NEW -m tcp -p tcp --dport 5666 -j ACCEPT
    -A INPUT -p icmp --icmp-type any -j ACCEPT
    -A INPUT -j REJECT --reject-with icmp-host-prohibited
    -A FORWARD -j REJECT --reject-with icmp-host-prohibited
    COMMIT
    
    *nat
    -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-ports 8080
    -A PREROUTING -p tcp --dport 443 -j REDIRECT --to-ports 8443
    COMMIT
    
    Those setting also block the incomming traffic except to ports like 22, 8080.
  • Restart iptables service:
    service iptables restart

Now you can access you web application without adding :8080 to the host address.

No comments:

Post a Comment