Monday, September 19, 2011

Using Nginx as a Reverse Proxy

http://www.ubuntugeek.com/using-nginx-as-a-reverse-proxy-to-get-the-most-out-of-your-vps.html
This how-to is going to assume that you already have a standard LAMP stack running, if not, there are plenty of tutorials and examples on how to get a LAMP stack running.

We have chosen to go with a standard Apache 2 installation using libapache2_mod_php5 over using Nginx (pronounced ‘Engine X’) with fastCGI. You may be thinking “that is preposterous, why not just use Nginx as your webserver and ditch Apache?” I hate fastCGI, I’ve never had very good luck with it and most importantly I know Apache. Also, when all Apache has to worry about is the dynamic content, in this case PHP, it is quite fast, and has a smaller memory footprint then normal Apache usage.

Using Nginx as a reverse proxy is great for a few reasons. Firstly it handles static content very well. It is able to handle the requests and serve static content much faster in our tests and this has cut our page load time in about half (using YSlow with a clear cache). The memory footprint of Nginx is very small so this extra speed increase is worth every megabyte, in this case .6 megabytes of our total ram on a 540 megabyte server. Secondly, it allows for quick and easy migration of your Apache services to another server. Through the config files you are able to specify an IP of your server and a port. If your apache server is taking a pounding it wouldn’t be difficult to move it to another server and just change the proxy IP to your now remote server.

Setting up Nginx is fairly straight forward. I will be showing the commands for an Ubuntu 8.04 installation but they should work for previous versions and other distributions (with a little tweaking).

Install Nginx

sudo apt-get install nginx
the following is essentially the config file we use for /etc/nginx/nginx.conf and is pretty similar to the default config for the installation. The only major thing I changed was adding gzip compression. I have personally set the level to 5 although it is adjustable. The higher you set this value the more CPU intensive it becomes.

user www-data;
worker_processes  2;
error_log  /var/log/nginx/error.log;
pid        /var/run/nginx.pid;
events {
    worker_connections  1024;
}
http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;
    access_log /var/log/nginx/access.log;
server_names_hash_bucket_size 64;
    sendfile        on;
    tcp_nopush     on;
    #keepalive_timeout  0;
    keepalive_timeout  65;
    tcp_nodelay        on;
 gzip              on;
  gzip_comp_level   5;
  gzip_http_version 1.0;
  gzip_min_length   0;
  gzip_types        text/plain text/html text/css image/x-icon
 application/x-javascript;
  gzip_vary         on;
  include /etc/nginx/conf.d/*.conf;
  include /etc/nginx/sites-enabled/*;
You are going to want to make sure that the line “include /etc/nginx/conf.d/*.conf;” is included in this config. This is where you will store the default proxy information.

We will now configure the default proxy. Create the file proxy.conf in the /etc/nginx/conf.d/ folder with the following contents.

proxy_redirect          off;
proxy_set_header        Host            $host;
proxy_set_header        X-Real-IP       $remote_addr;
proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
client_max_body_size    10m;
client_body_buffer_size 128k;
client_header_buffer_size 64k;
proxy_connect_timeout   90;
proxy_send_timeout      90;
proxy_read_timeout      90;
proxy_buffer_size   16k;
proxy_buffers       32   16k;
proxy_busy_buffers_size 64k;
The only thing you may want to change is the buffer sizes. We had to increase our proxy_buffer_size and a few others, from the default, to allow for larger cookies that were choking Nginx. With that being said you may want to decrease the buffers a bit, just do some testing. If the buffers are not working for your content Nginx will throw a 50x error.

Finally, we will configure the various hosts. To save yourself some time, and possible a headache you should always keep your static assets in one folder, while subdividing them by type in containing folders. For example static->images, static->js, static->css. This will greatly simplify your Nginx installation and I’ve found your code.

Now we will edit (with your favorite CLI editor) /etc/nginx/sites-available/default.

server {
 listen   80;
 server_name  example.com;
 access_log  /var/www/example.com/log/nginx.access.log;
 error_log  /var/www/example.com/log/nginx_error.log debug;
 
 #set your default location
 location / {
  proxy_pass         http://127.0.0.1:8080/;
 }
 
 #I had a problem accessing phpmyadmin with an Nginx reverse
 #proxy without adding this location
 location /phpmyadmin {
  proxy_pass         http://127.0.0.1:8080/phpmyadmin;
  allow 1.1.1.1;
  deny all;
 }
 #set your static folder location without the proxy pass so Nginx
 #will server those files. We also set expires max to add an
 #expires to have the client cache the files.  You will
 #have to  #set a version on your css and js files to prevent
 #the user who has cached files from not receiving new versions.
 location /static {
  root   /var/www/example.com/htdocs/;
  expires     max;
  }
  #error_page  404  /404.html;
  # redirect server error pages to the static page /50x.html
 #
 error_page   500 502 503 504  /50x.html;
 location = /50x.html {
  root   /var/www/nginx-default;
 }
}
#If you have a subdomain you need to add a new server if you
#want Nginx to server the static files. Our subdomain only
#serves static files so we have not set up a proxy_pass
server {
 listen 80;
 server_name subdomain.example.com;
 error_page 500 502 503 504 /50x.html;
 location = /50x.html {
  root /var/www/nginx-default;
 }
 access_log /var/www/subdomain.example.com/log/nginx.access.log;
 error_log /var/www/subdomain.example.com/log/nginx.error.log;
 index index.html;
 location / {
  expires     max;
  root /var/www/subdomain.example.com/htdocs/;
 }
}
Finally we need to make some quick changes to Apache and we’ll finally have everything running. Edit the file /etc/apache2/ports.conf.

You’ll want to change the listen line to 127.0.0.1:8080. This will prevent apache from receiving requests from outside, but you should be blocking port 8080 anyways! The port we’ve set is 8080 but whatever you set in the Nginx configs is what you should use.

NameVirtualHost *
Listen 127.0.0.1:8080
Lastly, if you don’t want all your apache logs to show 127.0.0.1 for who is accessing your files or your application uses IP’s to track sessions you need to install libapache2-mod-rpaf. It is painless just issue the command below.

sudo apt-get install libapache2-mod-rpaf
reload or restart both Apache2 and Nginx.

/etc/init.d/apache2 restart
/etc/init.d/nginx restart
To see if it is working open a page on your website, if you don’t see any errors that is a good start. You can then check the logs of Apache and Nginx. Your Apache logs should only contain the php requests and your Nginx logs should contain all of your assets. Your Apache logs should also have HTTP 1.0 request when they go through the reverse proxy.
-------------------------

A couple of clarifying questions would be helpful before jumping into the fray:
1. I’m not seeing any declarations of the types of static files that Nginx would handle in your examples unless it is the “application/octet-stream” or the fact that you are gzipping the static files and that is where they are declared.
2. You mention it a wise choice to organize static files together in structures like
“/static-folder/static-file.img-type”
Is this “required” for Nginx or simply “better”? And either way, does this imply that if Nginx is to serve those files, they have to be located there versus where a CMS might place them (for instance, WordPress placing uploaded images into the wp-content/uploads/ directory)?
Thanks again. Looking forward to your thoughts on the above.
---
Here is the thing, the two are directly related which is why I said it is important to have a static folder.
location /static {
root /var/www/example.com/htdocs/;
expires max;
}
These few lines tell Nginx that everything in the static folder it should handle by finding in the /var/www/example.com/htdocs/ folder. So anything coming into such as /static/css/style.css will be handled by Nginx because it is missing the proxy_pass command for this folder. Where as example.com/index.php will be passed to Apache.
This really works out well because if you only wanted Nginx to server your user uploaded images you would just have the location /wp-content/uploads/ command and apache would be passed everything else. I would definitely recommend having Nginx handle your css and js as we’ve seen great performance increases using this technique.
Overall it took me about 15-20 minutes to get setup and running.
---------------------------
I find the following configuration lines more useful instead of keeping my status files separate from dynamic in different folders:
Instead the following lines simply detect the static files file extensions and only proxy pass onto apache for php scripts:
server { # simple reverse-proxy
listen 80;
server_name domain2.com http://www.domain2.com;
access_log logs/domain2.access.log main;
# serve static files
location ~ ^/(images|javascript|js|css|flash|media|static)/ {
root /var/www/htdocs;
expires 30d;
}
# pass requests for dynamic content to apache
location / {
proxy_pass http://127.0.0.1:8080;
include /etc/nginx/proxy.conf;
}
}
NOTE: I make nginx and apache root and docroots point to the same file dir:
Of course, both approaches work, just preference really.
-----------------
NginX+PHP-FPM
http://interfacelab.com/nginx-php-fpm-apc-awesome/
Nginx vs. Lighttpd
http://hostingfu.com/article/nginx-vs-lighttpd-for-a-small-vps

Friday, September 16, 2011

Securing an Apache Web server with SELinux

http://searchenterpriselinux.techtarget.com/tip/Securing-an-Apache-Web-server-with-SELinux

The chances of having your Web servers  hacked are real, but SELinux can be used to make sure that your website doesn’t suffer real damage.
You can use SELinux types to create an exact definition of what a service can do and where it can do it. By default, the httpd_sys_content type is set to /var/www, which defines that the httpd process is allowed to work from this directory. If a hacker breaches the Apache Web server and tries to write somewhere else—like the default /tmp to Red Hat and similar Linux distributions such as Fedora and CentOS. But you need to know what you’re dealing with. If you configure Apache to serve content in the /data directory, SELinux would prevent that by default too.
Because of the complications that these default settings may introduce, many Linux administrators disable SELinux. And while it’s true that disabling SELinux makes it easier to provide service on your server, it also increases security risks.
Managing SELinux Settings for ApacheManaging SELinux settings for services like Apache is not hard. The problem is that there are no easy graphical tools that allow you to do a quick setup. But by applying just three commands, you can configure it.
To set the file type on the directory that you want to give your service access to, you must first determine which file system type to use. To do that, type ls –ldZ on the default directory that your service uses.
For Apache, you would use ls –ldZ /var/www. You’ll notice that in this cases, the –Z option gives additional file properties, and the –t option is the one that matters. This process defines the current file system type to which the Apache environment is set (httpd_sys_content_t). This also is the file type that you need to set as your new document root.
There are two commands that you can use for setting your content type: with chcon you can make a temporary change—which disappears after a reboot—and with semanage, followed by restorecon, you can make the changes permanent.
The semanage command may seem complicated, but it’s actually quite simple because you need to change only the type you want to use and the target directory. In the example below, there are just two parameters you would need to change. The following shows that the rest of the example command can remain exactly as it is:
semanage fcontext -a -t httpd_sys_content_t /web(/.*)/?
After using semanage to set the default file type, use the restorecon command to make sure that it is applied.. In the example above, where the file type for the directory /web is changed to allow Apache to server files from that directory, run the following command to apply the changes:
restorecon -R -v /web
At this point, Apache will be able to serve files from the new nondefault document root directory.
Managing Booleans for SELinuxAnother aspect of SELinux that youneed to manage are the SELinux Booleans. These are binary values that switch certain functions on or off. Booleans are available for many services. Use the getsebool –a command to get an overview of all the existing Booleans . This command normally gives a long list of settings that you can apply.
To find all Booleans for the service you want to configure, pipe the output of getsebool –a through grep. For instance, use getsebool –a | grep http to find all Booleans that match the string http. Even without having a clear understanding of each Boolean, you’ll often find out by just looking at their names what they are supposed to be doing.
Use getsebool –a to find out which SELinux Booleans are available to modify behavior of your services:
[root@bia Desktop]# getsebool -a | grep http
allow_httpd_anon_write --> off
allow_httpd_mod_auth_ntlm_winbind --> off
allow_httpd_mod_auth_pam --> off
allow_httpd_sys_script_anon_write --> off
httpd_builtin_scripting --> on
httpd_can_check_spam --> off
httpd_can_network_connect --> off
httpd_can_network_connect_cobbler --> off
httpd_can_network_connect_db --> off
httpd_can_network_relay --> off
httpd_can_sendmail --> off
httpd_dbus_avahi --> on
httpd_enable_cgi --> on
httpd_enable_ftp_server --> off
httpd_enable_homedirs --> off
httpd_execmem --> off
httpd_read_user_content --> off
httpd_setrlimit --> off
httpd_ssi_exec --> off
httpd_tmp_exec --> off
httpd_tty_comm --> on
httpd_unified --> on
httpd_use_cifs --> off
httpd_use_gpg --> off
httpd_use_nfs --> off

After learning which Booleans you want to use, apply them using setsebool -P. If you want to allow Apache to use nfs, use setsebool -P http_use_nfs on. For a complete list of all Booleans that are available, consult the httpd_selinux man page, which explains Apache specific file labels as well as Booleans.

Wednesday, September 14, 2011

Secure Linux Distributions

http://www.serverwatch.com/server-trends/10-secure-linux-distributions-you-need-know-about.html

  1. Astaro Security Appliance - Formerly known as Astaro Security Linux, the Astaro Security Appliances come in three flavors: Hardware, software and virtual. In the virtual appliance category, Astaro offers appliances built specifically for network security, mail security, Web security and Web application security. Its virtual appliances hold the VMware Ready certfication.
    The network security virtual appliance, for example, includes a configurable firewall, intrusion protection, DoS attack protection, NAT tools, VPN, IPSec Remote Access, LDAP authentication integration, and bandwidth control. Sophos recently acquired Astaro to create one of the world's leading security companies. Sophos boasts over 100 million worldwide business users in more than 150 countries.
  2. BackTrack Linux - BackTrack Linux is the highest rated and most acclaimed Linux security distribution. BackTrack is not a business desktop or server system but is a security-oriented system built solely for the purpose of network and computer penetration testing. BackTrack can be run from a bootable DVD, a thumbdrive or a hard disk. BackTrack Linux is a specialized distribution created to assist security professionals in performing security audits on target networks. But, with BackTrack Linux, you don't have to be a seasoned security professional to use it -- even security newcomers will find BackTrack easy to setup, use, and update. You can download BackTrack as an ISO image or as a VMware virtual machine.
  3. IPFire - IPFire is a firewall distribution that is small, highly secure and easy to use. IPFire developers and maintainers are experienced security professionals. Like BackTrack, IPFire enjoys widespread adoption and an active user community. IPFire has its own special packaging system called Pakfire. The Pakfire system is unique to IPFire and delivers all updates and new packages via encrypted transfer and digital signatures. IPFire also features easy addon installation. Addons include Samba, NFS, mail services, anti-virus, multimedia applications, VoIP applications, intrusion detection, network tools, security tools, backup tools and dozens of other applications.
  4. Lightweight Portable Security - The Lightweight Portable Security (LPS) distribution boots a thin Linux system from a CD or USB flash drive. It isn't meant to be run from a local hard disk. The intended use for LPS-Public version is to allow safe, public, general-purpose Web browsing and LPS-Remote Access is only for accessing internal networks. Since the system allows no traces of activity or browsing history, administrators must pay strict attention to limit where LPS users may browse by means of filtering through a proxy server. Users should reboot between sessions to clear any potential malware or browser hijacking that took place during previous sessions. LPS provides secure browsing during banking transactions or other security-sensitive sessions.
  5. Live Hacking DVD - This live DVD distribution is exactly what it sounds like: An ethical hacker's playground (workbench). There is also a CD version (Live Hacking CD). The DVD comes with a fully graphical desktop interface (GNOME) and the CD version is command line only. The CD version is as powerful as its graphical counterpart because most of the hacker tools are command line. The Live Hacking system requirements are minimal. You can use an old Pentium III or IV class system and as little as 512 MB RAM, although the developers recommend 1 GB RAM. To download and use the Live Hacking distribution, you must accept the Terms and Conditions which state that the tools are for ethical hacking only.
  6. EnGarde Secure Linux - EnGarde Linux is a Linux server distribution that is secure and perfect for use as an Internet server. It features intrusion detection, simple administration, secure network services, built-in alerts, Web services, DNS services, firewall, mail services and access to the Guardian Digital Support Network (GDSN). The GDSN provides free access to all system and security updates. EnGarde Regularly scheduled updates the first Tuesday of every month. Try before you buy with a downloadable live CD version of EnGarde.
  7. NetSecL - NetSecL is an OpenSUSE-based distribution that features GrSecurity, chroot hardening, auditing, and includes penetration testing software. It is versatile enough to be used as a desktop, server, or ethical hacking system. It is a live DVD but you can also install it to a hard disk. GrSecurity is an independent suite of security enhancements used by ISPs, hosting companies, and projects like NetSecL. Other tools included with NetSecL are Amap, Ettercap, Hydra, Kismet, Nessus, Nmap, Metasploit, and PADS.
  8. SmoothWall Express - The SmoothWall Open Source project began in 2000 and continues to be an excellent business firewall solution. SmoothWall Express (SWX) is a security-hardened GNU/Linux operating system with a simple to use web interface. The primary goals of the SWX project are to create and maintain a simple firewall system, support a variety of hardware, work with multiple connection methods, run on inexpensive and commodity hardware, develop a supportive user community and support the project via the commercial venture SmoothWall Limited. SmoothWall Limited manufactures several different SmoothWall hardware security appliances suitable for networks of all sizes.
  9. Openwall GNU/Linux - Openwall GNU/Linux (OWL) is a small, security-enhanced distribution suitable for virtual appliances, hardware appliances, and physical servers. OWL is binary compatible with Red Hat Enterprise Linux. OWL is also a distribution used by many security professionals for security penetration testing and password cracking. Openwall also develops other security products such as the famous John the Ripper password crack utility, phpass, passwdqc, and tcb.
  10. Vyatta - Vyatta is a commercial security appliance vendor delivering appliances for every network class including cloud architectures. Included in Vyatta's product line-up is the Vyatta virtual network appliance. Vyatta virtual appliances work in VMware, Xen, XenServer, and KVM environments. The virtual security appliance includes a stateful firewall, IPSec and SSL-based VPN, intrusion detection, filtering, dynamic routing and router-based services such as NAT, DHCP and is IPv6-ready.

psad: Intrusion Detection and Log Analysis with iptableshttp://www.cipherdyne.org/psad/index.html

Thursday, September 8, 2011

Setting Up SSL on Tomcat

http://techtracer.com/2007/09/12/setting-up-ssl-on-tomcat-in-3-easy-steps/

Setting up SSL on Tomcat is easy and you don’t have to do much for converting your web application to work with the https protocol. But however, the problem you would find to set up SSL is the documentation available over the web. The documentation source is available on the Apache site but it starts off good and ends with a lot of confusion. Especially I was confused on the OpenSSL part where it says to use OpenSSL.
It might be good in a production environment to use OpenSSL but if you just want to test out SSL with Tomcat alone then it is more than enough to just have your JDK and Tomcat setups. So I would make you walk through the same steps which I did while getting SSL up and running and building a secured web app within a matter of minutes.
The things which I have used to setup SSL consists of:
  • JDK 1.6
  • Tomcat 6
Even though I have used the latest version I don’t see any problems which you might face in carrying out the same set of steps for JDK 1.5 which I am about to explain. JDK comes shipped with a keytool executable which is required to generate a keystore. The keytool can be found in the earlier version of JDK too. The 3 steps which would make you to get started with setting up SSL are:
  1. Generating the Keystore file
  2. Configuring Tomcat for using the Keystore file
  3. Configuring your web application to work with SSL
Let’s get this party started now.
1. Generating the KeyStore file
The keystore file is the one which would store the details of the certificates necessary to make the protocol secured. Certificates contain the information as to who is the source from which you are receiving the application data and to authenticate whether it is the intended party or not. To make this keystore you would have to use the keytool. So open command prompt in Windows or the shell in Linux and type:
cd %JAVA_HOME%/bin on Windows
cd $JAVA_HOME/bin on Linux
You would land up in the Java bin directory. Now time to run the keytool command. You have to provide some parameters to the command as follows :

keytool -genkey -alias techtracer -keypass ttadmin -keystore techtracer.bin -storepass ttadmin

The highlighted words are the ones which you would have to change according to your requirements. But keep one thing in mind that both the keypass and storepass passwords should be the same. The .bin file is actually your keystore file. It would now start a questionnaire. So fill in the relevant details accordingly. Look below for a reference as to what to answer for the questions.

What is your first and last name?
[Unknown]: nitin pai
What is the name of your organizational unit?
[Unknown]: home
What is the name of your organization?
[Unknown]: techtracer
What is the name of your City or Locality?
[Unknown]: mumbai
What is the name of your State or Province?
[Unknown]: maharashtra
What is the two-letter country code for this unit?
[Unknown]: IN
Is CN=nitin pai, OU=home, O=techtracer, L=mumbai, ST=maharashtra, C=IN correct?
[no]: yes
The command would then conclude. It would make a .bin file with the name you had provided inside the bin directory itself. In my case it was techtracer.bin which was located in
C:\Program Files\Java\jdk1.6.0_02\bin\
Put the .bin file in the webapps directory of Tomcat. This is required to avoid the need to give an absolute path of the file in the next step.
2. Configuring Tomcat for using the Keystore file
Here we would be making some changes to the server.xml file inside tomcat to tell it to use the keystore which was created in the earlier step for configuring SSL. Open the file server.xml which can be found as:
<CATALINA_HOME>/conf/server.xml
Now you have to modify it. Find the Connector element which has port=”8443″ and uncomment it if already not done. Add two lines. The highlighted lines are the newly added ones.

<Connector port=”8443″
maxThreads=”150″ minSpareThreads=”25″ maxSpareThreads=”75″
enableLookups=”true” disableUploadTimeout=”true”
acceptCount=”100″ debug=”0″ scheme=”https” secure=”true”
clientAuth=”false” sslProtocol=”TLS”
keystoreFile=”../webapps/techtracer.bin”
keystorePass=”ttadmin” />

You can notice that I have given the path to the keystoreFile property as relative to tomcat bin directory because the startup command will look for the .bin file. Now all you have to do is start your server and check the working of SSL by pointing your browser to the URL to:
https://localhost:8443/
Now that you have your tomcat running in the SSL mode you are ready to deploy an application to test its working. You must note that still your tomcat can run in normal mode too at the same time i.e on port 8080 with http. So it is but obvious that any application deployed to the server will be running on http and https at the same time. This is something that we don’t want. We want our application to run only in the secured mode.
3. Configuring your web application to work with SSL
In order to do this for our test, take any application which has already been deployed successfully in Tomcat and first access it through http and https to see if it works fine. If yes, then open the web.xml of that application and just add this XML fragment before web-app ends i.e </web-app>

<security-constraint>
<web-resource-collection>
<web-resource-name>securedapp</web-resource-name>
<url-pattern>/*</url-pattern>
</web-resource-collection>
<user-data-constraint>
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>
</security-constraint>
Explanation of the fragment is beyond the scope of this tutorial but all you should notice is that the /* indicates that now, any resource in your application can be accessed only with https be it Servlets or JSP’s. The term CONFIDENTIAL is the term which tells the server to make the application work on SSL. If you want to turn the SSL mode for this application off then just turn don’t delete the fragment. Just put the value as NONE instead of CONFIDENTIAL. That’s it!
Conclusion
These were the 3 easy steps in which you can make Tomcat to work in the SSL mode and also it tells you how easily you can turn the SSL mode on and off. If you find any difficulty or are not clear on any of the above steps feel free to drop in your queries. If you like this tutorial it would be nice of you to drop in a comment of appreciation or feedback as to how this tutorial can be improved.


http://oldbytes.posterous.com/create-a-ssl-keystore-for-a-tomcat-server-usi

Create a SSL keystore for a Tomcat server using Openssl


An SSL certificate was required for one of our customers. The SSL certificate was to be used with a Tomcat server, but I decided to give the customer the flexibility to re-use this certificate on a different webserver if needed. This meant I used openssl to generate the certificate and then created a pkcs12 keystore.

  • Create the private key and certificate request
    • Create the certificate key
    • # openssl genrsa -des3 -out customercert.key 2048
    • Remove the passphrase from the key
    • # openssl rsa -in customercert.key -out customercert.key.new
      # mv customercert.key.new customercert.key

    • Create the Certificate request
    • # openssl req -new -key customercert.key -out customercert.csr
  • Create the Keystore file for use with tomcat and keytool
I had some trouble getting this to work. This is a very simple procedure when working with certs signed by GoDaddy, but certs from Verisign needed some extra hand-holding. There is some information on how to do this is found at http://conshell.net/wiki/index.php/OpenSSLtoKeytoolConversiontips.
I did not follow the instructions on this site. I ended up creating a keystore in the pkcs12 format instead of the default jks format. This site above does have instructions for converting a pkcs12 keystore to a jks format, if you require. The signed certificate was downloaded to clients.adaptivetcr.com.cer. The Secure Site with EV Root bundle was downloaded to intermediate.crt. When I first attempted to create the keystore file, I received the error below
openssl pkcs12 -export -chain -CAfile intermediate.crt -in customercert.cer -inkey customercert.key -out customercert.keystore -name tomcat -passout pass:changeit
Error unable to get issuer certificate getting chain.


Now the interesting thing about this error is that if you attempt a openssl verify using both cert file and intermediate.crt, it does not complain and gives the “OK” message. After a bit of testing, I found that you need to make a new CAfile to be used, that combines the cacerts file from the openssl distribution and the intermediate.crt file.
#
cat intermediate.crt /etc/ssl/certs/ca-certificates.crt > allcacerts.crt

or:

# cat ica.cer rca.cer /etc/pki/tls/certs/ca-bundle.crt > allcacerts.crt

#
openssl pkcs12 -export -chain -CAfile allcacerts.crt -in customercert.cer -inkey customercert.key -out customercert.keystore -name tomcat -passout pass:changeit

This successfully created the keystore file. You can look at the contents of the keystore by running
keytool -list -keystore customercert.keystore -storetype pkcs12 -v

Notes:
When using MS cert server generate the cert, put both ica and rca cert in the allcacerts.crt
shell> keytool -certreq -keyalg RSA -alias tomcat -file certreq.txt

Get cert from CA.
shell> keytool -import -alias tomcat -file
------
http://www.entrust.net/knowledge-base/technote.cfm?tn=6557

TN 6557 - How do I move my certificate from Apache to Tomcat?
Question:
How do I move my certificate from Apache to Tomcat?
Answer:
Since Jakarta Tomcat 5.x or higher supports the use of PKCS#12 or PFX keystores, you can use OpenSSL to convert the format of your Apache private key and SSL certificate.

Note: Only Tomcat 5 and later support keystores in PKCS#12 format.
Complete the following procedure to move your certificate from Apache to Tomcat.

To move your certificate from Apache to Tomcat:
1. At a command prompt or terminal session, type the following:
openssl pkcs12 -export -in mycert.crt -inkey <mykey.key> -out <mycert.p12> -name tomcat -CAfile <Entrust_SSL_CA.cer> -caname root -chain

Where:
<mykey.key> is your current private key.
<mycert.p12> is your current openssl certificate
<Entrust_SSL_CA.cer> is the Entrust Secure Server Root CA available for download at the following URL https://www.entrust.net/downloads/root_index.cfm

The exported keystore will be in <mycert.p12>
2. Specify in Tomcat that the keystore is in PKCS#12 format by inserting keystoreType="pkcs12" in the ssl configuration.


# openssl genrsa -des3 -out myserver.key.tmp 2048
# openssl rsa -in myserver.key.tmp -out myserver.key
# openssl req -new -key myserver.key -out myserver.csr

# cat ica.cer rca.cer /etc/pki/tls/certs/ca-bundle.crt > allcacerts.crt
# openssl pkcs12 -export -chain -CAfile allcacerts.crt -in myserver.b64.cer -inkey myserver.key -out myserver.p12 -name tomcat -passout pass:mypassword
where myserver.b64.cer is a Base64 encoded X.509 certificates (PEM).
The portion of tomcat server.xml :

<Connector port="443" protocol="HTTP/1.1" SSLEnabled="true"
maxThreads="150" scheme="https" secure="true"
keystoreFile="//myserver.p12" keystorePass="mypassword" keystoreType="pkcs12"
clientAuth="false" sslProtocol="TLS" />

Verify ssl cert
# openssl s_client -showcerts -connect myserver:443 (or 636 for ldap default port)
Copy from the "-----BEGIN CERTIFICATE-----" to the "-----END CERTIFICATE-----" , and save it to <mycert.pem> file
# keytool -printcert -file <mycert.pem>
http://shib.kuleuven.be/docs/ssl_commands.shtml
http://www.sslshopper.com/article-most-common-openssl-commands.html