Thursday, May 30, 2013

Setup Tomcat 7 port redirects


*This guide is for a CentOS 6 (or Red Hat derivatives) server that has Tomcat 7. No Apache or any other web servers are installed. (Just Tomcat)

*Must be as root

Redirect traffic from 80 to 8080:
"iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-ports 8080"
"iptables -t nat -A OUTPUT -p tcp --dport 80 -lo -j REDIRECT --to-port 8080"

Redirect traffic from 443 to 8443:

"iptables -t nat -A PREROUTING -p tcp --dport 443 -j REDIRECT --to-ports 8443"
"iptables -t nat -A OUTPUT -p tcp --dport 443 -lo -j REDIRECT --to-port 8443"

Then save your changes
"/sbin/service iptables save"

You can verify the changes, if you look in the config file for iptables:
"vi /etc/sysconfig/iptables"

Now in Tomcat 7 "server.xml" a minor configuration must be set. Here is the configuration for Tomcat to work with port 8080.
<Connector compression="on" connectiontimeout="20000" connector="" port="8080" protocol="HTTP/1.1" redirectport="443"/>

redirectPort must be set to 443. This option is used if your Java web application has the restriction of only allowing secured connection. Thus if Tomcat receives a request for that application on port 8080 Tomcat will reply by redirecting the request to port 443. Which means that the Tomcat server must have configuration set to work with SSL.
Here is the configuration for Tomcat to work with SSL 
<Connector clientauth="false" compression="on" keystorefile="YOUR KEYSTORE FILE LOCATION" keystorepass="KEYSTORE PASSWORD" maxthreads="200" port="8443" protocol="HTTP/1.1" scheme="https" secure="true" sslenabled="true" sslprotocol="TLS"/>

You might ask why is Tomcat listening on 8443 and 8080 when the traffic will be on 80 and  443? Well that's where Iptables comes into play. All traffic that comes in at port 80/443 will be redirected to 8080/8443 respectively.

Besides making the installation of the Tomcat server a little easier and a step in the right direction in setting it up as a production server.  Having the ability to run Tomcat with a restricted user instead of root is a good start for securing your server. Security is very important now a days, if things can be simple and still be secure then DO IT!

No comments: