Monday, August 3, 2009

SSL on Tomcat, JBoss and command line client

Talking about a secure website, the first thing that comes to mind is SSL. For almost all the sites today, we do encounter a section in the website where the address bar turns yellow with a lock indicating that the data being transfered is being encrypted. That section can be a login screen or a transaction screen etc. In this post i've tried to put some steps to achieve the goal of securing a HelloWorldServlet (not much useful but the technique for this or a complex one shall be same).
In order to start with the process of securing your site, we need a certificate. You shall be able to get a valid certificate from a Certification Authority like Thwate, Verisign and many more. Here I shall use a self-signed certificate but the process shall be quite similar for the ones from a Certification Authority (CA).
First of all we create a Keystore using the keytool available in a JRE installation. You can look for it in JDK\bin or JRE\bin directory.
keytool -genkey -alias rsatest -keyalg RSA -keystore test_store -validity 60
Keep in mind while creating the keystore that the answer to the first question i.e. What is your first and last name? should be either your domain address or machine name (It should be the name by which your machine shall be referred in URL when clients are making hits to it using an HttpsURLConnection). This is the CN (Common Name).
After answering a number of self explanatory questions and providing an appropriate password, you shall see a file names test_store in your present working directory folder.
In the next step, you can create a certificate that shall be required by the client application to communicate with this machine using SSL.
keytool -export -alias rsatest -file rsatest.cer -keystore test_store
After executing this command, you shall see a rsatest.cer file created.
In order to start tomcat in https mode in addition to its default http mode, we need to modify the server.xml in the TOMCAT_HOME\CONF folder.
Paste the snippet below in server.xml.
 <Connector port="8443" minSpareThreads="5" maxSpareThreads="75" enableLookups="true" 
  disableUploadTimeout="true" acceptCount="100" maxThreads="200" scheme="https" secure="true" 
  SSLEnabled="true" keystoreFile="c:/certs/test_store" keystorePass="password" clientAuth="false" sslProtocol="TLS"/>
Replace the location of keystoreFile and the keystorePass with appropriate values.
In case of JBoss the process is quite similar to that of Tomcat. We need to edit JBOSS_HOME\server\default\deploy\jboss-web.deployer\server.xml instead and paste the below give snippet.
 <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
     maxThreads="150" scheme="https" secure="true"
     clientAuth="false" strategy="ms"
     address="${jboss.bind.address}"
     keystoreFile="C:/certs/test_store"
     keystorePass="password"
     sslProtocol="TLS"/>
Which ever server you choose to modify, after you are done with saving the server.xml file start the server. You should be able to make hits to the server url with https protocol on an appropriate port (8443 in our case). Expect to see some warning like There is a problem with this website's security certificate. on IE or localhost:8443 uses an invalid security certificate. on firefox for the reasons explained very well on that screen. This happens as ours is a self-signed certificate and not issued by a trusted certificate authority that the machine or the browsers certificate stores posses. These self signed shall be good enough for internal use or testing but for internet use you should get the certs from a trusted certificate authority.
Well, we are ready with our server running in https mode. For example purposes I had developed a very simple HelloWorldServlet. I am able to access via https://localhost:8443/WebAppDemo/HelloWorldServlet
Before we write the client code, we need to get the cert that we generated earlier. As we are on the same machine, you can re-use the trust store (for practice purposes) but in real environment (on a different machine), you shall create a new trust store and import the cert into it using the command given below:
keytool -import -alias rsatest -file rsatest.cer -keystore cacerts
The same command is used to import any ROOT certificates or the certs provided by a website that you want to connect using your java program.
With the above command we created a new keystore and imported the certificate into it. The client code is very simple i.e. a usual HttpUrlConnection code. A small snippet from my test class HelloWorld.java is given below:
  URL url = new URL("https://localhost:8443/WebAppDemo/HelloWorldServlet");
  URLConnection connection = url.openConnection();
Rest code is simple IO reading from stream hence skipping it.
The important part is are the VM arguments. If you have written a stand alone application, you shall run it using the following command:
c:\>java -Djavax.net.ssl.trustStore=c:/certs/cacerts -Djavax.net.ssl.trustStorePassword=password HelloWorld
One very important point is that in the URL the server machine should be refered by the name used in the CN while creating the keystore. So you need to use the domain name of the machine as the CN. It won't work otherwise. In my example using localhost is a bad practice but I feel you get the point and modify your codes according to the situation. The IP of the machine should not be used as a CN, so you have to use the domain name or the machine name as the CN for the cert. The same domain name or machine name (used in CN) should be used when accessing the URL or else you will encounter host name verification failure.

Monday, February 23, 2009

Executing the code while JVM shuts down

A number of times we have encountered a situation where we want a particular piece of code to be executed when our application is exiting. More necessarily we need such a mechanism when we have developed a server and want the code to be executed for any System.exit(0) call or a CTRL + C key combination on the console. A shutdown hook is the way out for this problem. Writing it is very simple. All the code we need to be executed should be written in a Thread and its object should be registered with the Runtime of the JVM. The code is as below.
Runtime.getRuntime().addShutdownHook(new Thread() {
    public void run() {
        System.out.println("Executing the code while closing down.");
    }
});
A detailed explanation of the above method is provided in the Javadocs for the Runtime class.

Sunday, January 25, 2009

Remote debugging application on pocket pc running on j9

I assume that eclipse was used for the development of the application. Once the application is ready, It shall be copied over to the device that has j9 run time environment. The application can be deployed as a jar file or classes. In order to run the application, either command line needs to be used or we can create a link file with the following content:
255#"\Program Files\j9\bin\j9.exe" -jcl:ppro11  -cp "Test.jar" "trial.Test"
Assuming that the application is packed into a jar file and the trail.Test is the main class. Save the above file with a .lnk extension e.g. Test.lnk. Click on the Test.lnk file and see that the application launches properly.
Now in order to remote debug, check for the existence of j9dbg23.dll in your j9 bin directory. Modify the Test.lnk file to:
255#"\Program Files\j9\bin\j9w.exe" -jcl:ppro11 -debug:transport=dt_socket,server=y,address=4142 -cp "Test.jar" "trial.Test"
Once it is done, open the same project in eclipse.
  1. Open the Debug Configurations window (Run > Debug Configuration).
  2. Create a new Remote Java Application configuration and enter the details as follows:
  • Project -> Select your project.
  • Connection Type -> Standard (Socket Attach)
  • Connection Properties -> ip of the remote machine (pocket pc) and the debug port (4142 in our example case). This port is mentioned in the above created ".lnk" file, hence should be the same in this "Remote Java Application" debug configuration.
  • Run the application on the pocket pc by clicking on the Test.lnk file.
  • Click on the Debug button on the newly created "Remote Java Application" debug configuration.
You are ready to debug your application buy putting break points in appropriate code locations. This scenario has been tested with j9 on a Windows CE 4.2 environment. Should be the same for Windows Mobile and Linux environment (you'll get an .so instead of a .dll in j9 distribution).
The debugger can similiarly be attached even using netbeans.

Saturday, December 6, 2008

Fullscreen of Fedora10 installed on Vista using VirtualBox

Installing Fedora10 on Windows Vista using Virtual Box was very straight forward. I used a live disk or the iso initially and once the virtual machine booted up, I used the option of install to hard disk to avoid using the iso or the Live CD. The complex issue was that the screen size is too small i.e. the highest available resolution was 800 x 600. My Vista is using 1280 x 800, hence the Fedora on Virtual Box looked very small. I was able to make it full screen by following certain steps mentioned as below:
  • Run the Virtual Machine installed using VirtualBox. Go to the Devices menu and select the "Install Guest Addons . . ." option. Reboot the machine.
  • When the virtual machine is shutdown, you should be able to see that in the settings "CD/DVD-ROM" section will be configured for the "VBoxGuestAdditions.iso".
  • On the Virtual Machine startup, you shall be able to see this iso mounted and have icon on the desktop.
  • Before these Addons can be installed certain dependencies like make, gcc, kernel-headers and kernel-devel needs to be installed. These can be done using the following commands:
      • #] yum install make
      • #] yum install gcc-c++
      • #] yum install kernel-headers
      • #] yum install kernel-devel
  • When the dependencies are installed, we proceed installing the addons
      • #] cd /media/VBOXADDITIONS_2.0.6-39755/
      • #] sh ./VBoxLinuxAdditions-x86.run
  • Reboot the Virtual Machine. Now fire the commands to get the Display in the System > Administration menu.
      • #] yum install system-config-display
  • Now you can open the System > Administration > Display window. In the Hardware tab, select the VBoxVideo drivers in the Video Card configuration. Press OK two times and reboot the machine.
  • On restart, again open the Display window. If the desired resolution is not being displayed then you have to manually modify the /etc/X11/xorg.conf file.
  • Open the /etc/X11/xorg.conf file . Modify the Section "Screen". You need to add the Modes.
  •       Section "Screen"
             Identifier "Screen0"
             Device     "Videocard0"
             Monitor    "Monitor0"
             DefaultDepth     24
             SubSection "Display"
                 Viewport   0 0
                 Depth     24
                 Modes "1024x768"
             EndSubSection
          EndSection
  • Reboot the machine. On restart, you shall see the Virtual Machine will start with the new resolution. To have full screen press the host + F keys. By default the host key for Virtual Box is Right Control key.

Tuesday, November 11, 2008

Checking network connection using Java

At times it is required to check whether the machine is still connected to network or not. One way to find it using JDK1.6 by using the code is as below.
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
    NetworkInterface nic = interfaces.nextElement();
    System.out.print("Interface Name : [" + nic.getDisplayName() + "]");
    System.out.println(", Is connected : [" + nic.isUp() + "]");
}
Additionally several new useful methods such as isLoopBack(), isPointToPoint() and many more have been added in JDK 1.6 release. Refer to the Javadocs for more information on NetworkInterface class in java.net package.