Tuesday, April 26, 2011

Securing Tomcat with Apache Web Server mod_proxy

I wanted to enable SSL encryption to allow secure channels (https) to our tomcat server. There were 2 obvious ways to do this:

  1. Secure Tomcat directly
  2. Secure an Apache web server front-end that controls access to tomcat

Secure Tomcat directly

Securing tomcat directly is fairly straight-forward and is the easiest. But it does have some drawbacks. The major drawback for me was restricting access to other webapps running within the tomcat container. I had about 5 different webapps running, but I only wanted one to be publicly available. Now some will argue that you can restrict access by enforcing rules within the firewall, but I found that to be clunky. If you're interested in going this route, here is a link describing how to enable security for tomcat directly:
http://tomcat.apache.org/tomcat-5.5-doc/ssl-howto.html

Secure an Apache web server front-end

 I prefer using Apache web server as the front-end for many reasons which has been discussed to death. I'll note some of the more important reasons:
  • Apache can server static content much faster
  • Apache can run as a load balancer in front of a cluster of tomcat instances
  • Apache can handle SSL encryption for a cluster of tomcat instances
  • Apache has several modules that can easily be plugged in
For more reasons have a look at this article: http://wiki.apache.org/tomcat/FAQ/Connectors

In this instance I will be using Apache's mod_proxy module to redirect traffic to the tomcat server and use Apache to provide the SSL encryption.


To get an idea of how it works see the diagram below:




When a user visits our website using the default web port of 80, Apache will redirect the traffic to Tomcat on port 8080. Similarly, when browser is communicating on port 443 (https), apache will enable encryption and redirect traffic to tomcat on port 8443.




In my setup of Apache, I have 2 main configuration files:
  1. httpd.conf
  2. ssl.conf
httpd.conf contains the configuration for handling traffic running on port 80:

Listen 80
ProxyRequests Off
ProxyPreserveHost on
<VirtualHost _default_:80>

    ServerName your_company_domain_name
    ProxyPass /app http://localhost:8080/app
    ProxyPassReverse /app http://localhost:8080/app 
  
    RewriteEngine On
    RewriteRule ^(.*)/login$ https://%{SERVER_NAME}$1/login [L,R]      
</VirtualHost>

The ProxyPass and ProxyPassReverse is responsible for the redirection.
The RewriteEngine and RewriteRule is responsible for redirecting  any requrests for the login page on port 80 to the secure channel running on port 443.

ssl.conf contains the configuration for handling traffic running on port 443:
Listen 443
<VirtualHost _default_:443>
SSLEngine on
SSLProxyEngine on
SSLCertificateFile /etc/pki/tls/certs/your_company_certificate.pem
SSLCertificateKeyFile /etc/pki/tls/certs/your_company_private_key.pem
ServerName your_company_domain_name
ProxyPass /app http://localhost:8443/app
ProxyPassReverse /app http://localhost:8443/app
</VirtualHost>

The SSLCertificateFile and SSLCertificateKeyFile are responsible for enabling encryption and requires the private key as well as the certificate file provided by your certificate authority.
Just as before, the lines ProxyPass and ProxyPassReverse are responsible for the redirection of traffic from port 443 to tomcat on port 8443.

server.xml contains the tomcat configuration details
Server.xml
    <Connector port="8080" maxHttpHeaderSize="8192" maxThreads="150" minSpareThreads="25" maxSpareThreads="75" enableLookups="true" redirectPort="443" acceptCount="100" connectionTimeout="20000" disableUploadTimeout="true"/>  

    <Connector port="8443" maxHttpHeaderSize="8192" maxThreads="150" minSpareThreads="25" maxSpareThreads="75" enableLookups="true" acceptCount="100" connectionTimeout="20000" disableUploadTimeout="true"        
        scheme="https"
        secure="false" 
        SSLEnabled="false" 
        proxyPort="443"
        proxyName="your_company_domain_name"
     />

Importing certficates into keystore

keytool -import -alias auscert -keystore -trustcacerts -file


Extracting existing certificates and private keys from a keystore to be used in Apache in PEM format

Originally, I had setup encryption witin Tomcat rather than apache. When I wanted to  migrate the control of security from Tomcat to Apache, I was faced with the issue that each Tomcat and Apache expected the certificates in different formats. After much researching I found a tool that was helpful in extracting the private key and the certificate out of the keystore into the PEM format expected by Apache. The opensource tool can be downloaded here: http://sourceforge.net/projects/portecle




To extract the private key from JKS keystore, use this:
http://www.softpedia.com/get/Security/Security-Related/KeyTool-IUI.shtml
Select Export -> Keystore's entry -> Private key
When identifying the Target files, remember to choose 'Private key and certificates' and 'PEM Encoded'
And the rest is self explantory


Remove passphrase from key

openssl rsa -in private_key.pem -out private_key_no_passphrase.pem


Here are some articles describing the problem in more detail:
http://techsk.blogspot.com/2009/01/exporting-tomcat-keys-to-apache-httpd.html
http://pnkumaresh.wordpress.com/2010/11/12/exporting-tomcat-ssl-keys-to-apache-httpd/

Verification

To verify that the certificates are properly installed use the following command:

keytool -printcert -sslserver servername

References:

http://tomcat.apache.org/tomcat-6.0-doc/config/http.html
http://thejavamonkey.blogspot.com/2008/07/using-apache-httpd-server-as-secure.html
http://www.mooreds.com/wordpress/archives/223
http://www.customware.net/repository/display/GREENHOUSE/2009/06/13/Reverse+Proxy+with+Apache+mod_proxy
https://confluence.sakaiproject.org/display/DOC/Sakai+Admin+Guide+-+Advanced+Tomcat++%28and+Apache%29+Configuration

Monday, March 7, 2011

Dynamically positioning a signature in iText

After much tinkering, I've been able to find a way to dynamically populate a signature image to the bottom of a PDF as follows:


            PdfReader reader = new PdfReader(...);

            PdfStamper stp = PdfStamper.createSignature(reader, os, '\0'); 
            PdfSignatureAppearance sap = stp.getSignatureAppearance();
            sap.setCrypto(key, chain, null, PdfSignatureAppearance.SELF_SIGNED);
            sap.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED);
                
            
            Image image = Image.getInstance(imageBytes);
            sap.setRender(PdfSignatureAppearance.SignatureRenderGraphicAndDescription);
            sap.setSignatureGraphic(image);
            sap.setAcro6Layers(true);
            sap.setImage(null);
            
            int page = reader.getNumberOfPages();

            Rectangle pageSize = reader.getPageSize(page);

            int verticalPosition = (int)(pageSize.getBottom() + 70);
            int signatureEnd = (int) verticalPosition + 50;
            position = new Rectangle(50, verticalPosition, 250, signatureEnd);                        
            
            sap.setVisibleSignature(position, page, null);

Tuesday, March 1, 2011

I had this unusual problem with Data Tables (http://datatables.net) where the table was being pushed down leaving a blank space above the table. I've shown the problem below:

I've highlighted the blank space in red to make it more visible.

After spending some time and using the webdeveloper firefox plugin, I narrowed it down to a CSS properties called float and clear

To see these properties in action, here is a simple website demonstrating how these properties work:
http://www.quackit.com/css/properties/css_clear.cfm

Looking back at the image above, you can see that the tables were being pushed down to the bottom of menus on the left hand side. Its important to notice this as we shall soon see why. This is the CSS definition for the menus:

#sidebar {
    float: left;    width: 150px;
    margin-right: 0px;
    margin-bottom: 20px;
    margin-left: 0px;
    /*padding-top: 20px;*/
    
    background-image: url(../images/menutop_owr3.gif);
    background-repeat: no-repeat;
    background-position: top;
}

The important property to note, is that the menus are being floated to the left.

Now looking at the CSS applied to Data Tables I was using the demo_table_jui.css which had the following definitions:

.dataTables_wrapper {
    position: relative;
    min-height: 302px;
    _height: 302px;
    clear: both;}
table.display {
 margin: 0 auto;
 width: 100%;
 clear: both;
 border-collapse: collapse;
} 

The clear property meant that any floating elements on either the right or left should be cleared, resulting in the tables being pushed down. To resolve the issue, I simply had to remove this property from the definitions as follows:


.dataTables_wrapper {
    position: relative;
    min-height: 302px;
    _height: 302px;
    /*clear: both;*/
table.display {
 margin: 0 auto;
 width: 100%;
 /*clear: both;*/
 border-collapse: collapse;
} 

And now the tables are displayed without the ugly gap: