Sunday, August 15, 2010

Mixing Generic & Non-generic code in Java

Can you spot the error in the following code:

public class MixingGenerics{

public static void main(String[] args){
List<Integer> arr = new ArrayList<Integer>();
arr.add("String 1");
arr.add("String 2");

// add something more
addToList(arr);
}

public static void addToList(List arr){
arr.add(new Integer(1));
}
}

I’m sure you are able to point out the mistake that we are adding an Integer to an ArrayList of Strings. That’s definitely not done. But can you tell without compiling this code that we get an error at compile-time or at run-time ?

Unfortunately and even more surprisingly, this code doesn’t give any compilation error or runtime exception. Everything works fine and an Integer is added into your ArrayList (of Strings) !! Yes, you do get a compiler warning that says something about Type Safety of your code. We will get back to this point later on.

But first examine how is possible that you can actually store an Integer in a String Arraylist? Actually, it is an unfortunate outcome of mixing Generic & Non-generic code. The reason why we get no error is due to a property of Generics called Type-Erasure. We’ll get to it soon but first lets see when the previous code will throw an Error/Exception. This code will explode as soon as you would try and iterate the ArrayList of Strings, in which you have put an Integer unknowingly as shown below:

public class MixingGenerics{

public static void main(String[] args){
List<Integer> arr = new ArrayList<Integer>();
arr.add("String 1");
arr.add("String 2");

// add something more
addToList(arr);

// print the list
printMyList(arr);
}

public static void addToList(List arr){
arr.add(new Integer(1));
}

public static void printMyList(List<String> arr){
for(String s:arr){
System.out.println("String : "+s);
}
}
}

So we get a runtime exception now on iterating the list. It prints the first two strings and then throws ClassCastException as we are trying to cast an Integer into a String s. That’s okay but why does it allows you to add an Integer into List of Strings.

Type-Erasure

Generic code in Java exhibit a very important property: Type-erasure. What it means is that the so-called type-safe collection of yours (the generic collection here: ArrayList<String>) loses its type information at run-time and acts as if its just a List (like pre-Java 5 lists, the non-generic list). This has been made such so that we can integrate pre-Java 5 (the non-generic code) with newly written Generic code (Java 5 or later), but then while mixing them, you must be careful. Very careful indeed, else you could happen to write a code that will explode unpredictably.

So the answer to our question that why it allows an Integer to a list of Strings is because at runtime we only have a list, just like we had a list in pre-Java 5 days. Without generics, we had to take care while taking object out of the list and casting them but with Java 5 and above code, that casting is implicitly inserted by the compiler. So when we say

String s = arr.get(0) gets converted into String s = (String) arr.get(0)

Doing exactly the same with our list, it gives an error when we try and cast an Integer into a String and hence the error: java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String

Apart from giving the error, the compiler does his best and warns you when you are trying to mix Generic code with Non-Generic Code. If you are very sure about your code and do not want any compiler warning, then you can do by using following Annotation (valid with Java5+ code)

@SuppressWarnings("unchecked")
public static void addToList(List arr){
arr.add(new Integer(1));
}

This lets the compiler know that you are pretty sure about the code that you have written and do not give me any warnings with this method. Generally, it is not recommended to use such Annotations and if you really need to use one, you must do proper documentation of your code.

Any comments and corrections are welcome :-)

Thursday, July 15, 2010

JBoss – Basic & Digest Authentication

This blog entry is a replication of my previous blog entry: Tomcat – Container Managed Security. It is extending the same entry for JBoss, so I’m gonna skip all the introduction and straight-away get to work.

Basic Authentication

1. Open the login-config.xml file located at ${JBOSS_HOME}/server/${USER_PROFILE}/conf

This file sets up the configuration for the security domains available to applications running in the server. JBoss uses JAAS for the underlying security infrastructure, and JAAS interacts with a security store for authenticating credentials.

In simple words, we specify an application policy in this file, which tells the Login Module that we will use (Like Tomcat, here also we have plenty of options like LDAP, Database, Property Files etc for Login Modules). Basically, Login Module specifies the usernames, passwords and roles used for protecting your application. To start with, we will use UsersRolesLoginModule, which uses a property file to specify all the above mentioned information. Obviously, this isn’t secure and not really a choice for a system in production. Time to make changes:

Make changes in login-config.xml file : Add the following policy at the end of the file:

ApplicationPolicy

  • The "name" attribute on the "application-policy" element specifies the name of the security domain. This name is important because it is what will be used to tie the security domain to the web application later. We will mention it in application’s web.xml.
  • The "login-module" element specifies the login module that this domain will use.
  • The "module-option" elements specify some values to pass into the login module's "initialize" method. For UserRolesLoginModule, we will specify the property files for user information and role information. These paths are relative to the ${JBOSS_HOME}/server/${USER_PROFILE}/conf directory.

2. Open the ${jboss.dist}/server/${server.name}/conf/props and create 2 files:

  1. web-users.properties (user information)
  2. web-roles.properties (role information)

In web-users.properties property file, add

userNamePassword

In web-roles.properties, add

userRoleInfo

3. Open web.xml of your web application and make following changes -- add following security constraint:

securityConstraints

4. Open jboss-web.xml of your web application and add following line inside the <jboss-web> element:

JAASSettigns

This element tells JBoss to connect the web application to the "webPasswordProtection" security domain (application policy) we defined in the login-config.xml file earlier. JBoss exposes security domains via JNDI by pre-pending "java:/jaas/" to the name element in the application-policy element in the login-config.xml file.

Voila!! You are done now. Just restart the JBoss Server and your authentication should work fine.

DIGEST Authentication

Having already said that this basic authentication is not recommended for production purposes, we will try using a different authentication mechanism : Digest Passwords. We will save the passwords in a digest (hashed) form in the properties file instead of saving them in clear-text form. Make following changes:

1. Change in login-config.xml file

Digest

2. Find the new hashed password using built-in RFC2617Digest class:

digestpassword

The RFC2617Digest class is present in jbosssx.jar which is present in ${JBOSS_HOME}/server/default/lib directory. So this jar file must be on your classpath when you execute the above command. If it is not so, then use –cp option of java tool to set CLASSPATH as done above. The generated password is b63289befb5c9bb0509eed20b253e985. Note that the arguments passed to this class are

  1. User Name
  2. Realm Name
  3. Password

in that order. Now is the time to store this hashed password in your web-users.properties file.

3. Change web-users.properties file as follows:

digestpass

Now, just restart JBoss to see the effect. And it is more secure than Basic authentication as you are not transmitting the password over the wire.

Sunday, June 27, 2010

SSL Configuration in Tomcat

Today, we are going to learn about how to setup SSL on your Tomcat so that you can access your application on HTTPS instead of HTTP and provide a secure interface to your clients. But before going into that, lets understand the basic difference between HTTP & HTTPS.

Introduction to HTTPS

HTTPS (HyperText Transfer Protocol Secure) combines HTTP protocol with SSL (Secure Sockets Layer) or TLS (Transport Layer Security) and offers a secure channel to browse the web so that you can trust the connection to send sensitive information like payment transactions details or your bank account details. The difference between the two clearly shows in the address bar where you can see “https://” instead of “http://”. Also HTTPS uses port 443 as the default port, whereas HTTP uses port 80 as the default port for communication.

Using HTTPS, the two-way communication that occurs between your web browser and the host server is now secure and encrypted. This means that the data being sent is encrypted by one side, transmitted, then decrypted by the other side before processing.

When a web browser initially attempts to contact a web server over a secure connection, it is presented with a “certificate” (set of credentials), as a proof of the site is who what it claims to be. These certificates are signed (digitally verified) by certain authorities like VeriSign and typically purchased by the web server. Remember that you need to buy a certificate for each port on which you want a secure connection. For this blog entry, we will sign our own certificate and make other changes to Tomcat configuration so that it starts accepting connection on port 443 using HTTPS protocol.

But before we begin setting up SSL on Tomcat, its very important to iterate that this is valid only if you are using Tomcat as a stand-alone web server, the other possibility being Microsoft IIS or Apache Server serving as the main interface to the outside world and Tomcat is serving as the JSP/Servlet Container at the backend, communicating with one of these servers. In that case, you have to make SSL configuration changes in IIS or Apache, while Tomcat will continue to work normally sending cleartext responses (no encryption at Tomcat level).

Creating a Certificate

Fortunately, Java provides us with a utility (keytool) which can be used to create a self-signed certificate. This is not validated by any authority, hence not suitable for production use. But it can certainly be used for development purposes. So, lets  create a certificate from scratch for our application:

Type in the following command and enter details(credentials) about your organization that users of your site/application would see in the certificate given to them when they use it. The default password for Tomcat is “changeit” (all in lower-case). It would be asked when you type the following command to generate your self signed certificate:

>> keytool –genkey –alias –tomcat –keyalg RSA

Note, you must enter the password (as told above) and then all the credentials as shown below:

newCertificate

After doing this correctly, a .keystore file will be generated in your home folder (in the home folder of the user who did this). This is the certificate your tomcat would use and present to any user who visit the secure site.

Configuring Tomcat

Now, we make changes in Tomcat configuration to reflect this change. Tomcat uses 2 different implementations for SSL: Apache Portable Runtime (APR) implementation and JSSE Connector implementation, provided by default with JRE (Java Runtime). Most of the users (like me) do not have APR installed by default, so following steps are valid for JSSE implementation

We now open server.xml present in $CATALINA_HOME/conf. An example <Connector> element for SSL is included by default in most server.xml that comes with Tomcat. It looks something like this:

SSLconnector

All you have to do is to uncomment this connector and add to it the location of your certificate (.keystore) that we generated and the password we used to generate it. So finally the entry for the connector looks like:

NewConnector

Also, make sure that the Non-SSL Connector (the default one) which accepts connection on 8080, should have a redirectPort attribute set to 8443 or to the port that you specified for SSL Connection in the connector above. The entry looks like:NonSSLConnector

That’s all you need to do to make sure that Tomcat starts accepting secure connections on 8443 and redirects users who attempt to access a secure page with http to https. For more details regarding each attribute of the connector, you can refer Java HTTP Connector configuration reference.

Go ahead, try it out and feel the magic that Tomcat provides you. :-) Please post any bugs, queries and corrections as comments.

Saturday, May 29, 2010

Tomcat – Container Managed Security

If you are a web developer, then I will not think twice before saying that you must have used Tomcat knowingly or unknowingly for deploying your web applications.

For me, Tomcat is a pretty basic web server, which mainly serves as a JSP/Servlet Container. Today, we explore some basic security features that are provided by the container itself. There are different ways in which this authentication can be provided. In this blog entry, we will try to understand and implement Basic & Form-based Authentication using MemoryRealm.

What’s a Realm?

According to the Tomcat specification, a Realm is a "database" of usernames and passwords that identify valid users of a web application (or set of web applications), plus an enumeration of the list of roles associated with each valid user. Obviously, there are many ways to specify the valid username-password combinations and the associated roles. We will use something known as MemoryRealm, which uses a file: tomcat-users.xml to specify this database.

Steps to Enable Authentication

  1. Change the configuration file (server.xml) of the Tomcat Server to specify the realm that you will use
  2. Change the tomcat-users.xml file to list the valid username-passwords and the associated roles
  3. Change the deployment descriptor (web.xml) for your web application to reflect security constraints needed by the application.

Step1: Change server.xml of Tomcat

The default server.xml has the UserDatabaseRealm enabled as shown below:

 serverXml

Note: This can change depending on the versions of the Tomcat, but for Tomcat 5.5 and Tomcat 6, it is the default one. We change it to use MemoryRealm by commenting the previous line and adding the following declaration as shown below:

serverXmlChanged

Step2: Change tomcat-users.xml of Tomcat

The default tomcat-users.xml file, which is present at $CATALINA_HOME/conf/tomcat-users.xml  where $CATALINA_HOME is the directory in which your Tomcat server is installed, looks like:

tomcatUsers

To this, add your own role and associate with it, some valid combination of username and password as done below:

tomcatUsersChanged

Step3: Change web.xml of your web application

So far, we have made changes in the Tomcat server itself, its time we must modify our application to reflect the security constraints that we want. To do so, we add the following to our web.xml file:

a) Security Constraints as per the need

securityConstraint

Here, We specify that in order to access any URL in our application which comes after http://{context_App}/jsp/…  should be password-protected. Also, we associate a role with it, so users associated with that role can only access these URLs now.

b) Declaring the Security Role

securityRole

c) Specifying the Type of Authentication

basicAuthntication

We tell Tomcat that we want to use BASIC authentication for our web application and the realm that we will use will use your tomcat-users.xml file. 

That’s it. All you need to do now, is to restart Tomcat and check whether this works or not. Obviously you need to create a basic web application to deploy onto the Tomcat , for which you have specified the security constraints. You can download my test web application here. (Provide a Link)…………………

This was pretty basic stuff, but it has several limitations. For one, this is not suitable for production environments and we must use FORM-based authentication instead of BASIC. Secondly, it is not a good practice to use clear-text passwords in tomcat-users.xml file. We can save the encrypted password (encrypted by any algorithm like SHA, MD2, MD5 etc) supported by the realm.

Changes to overcome limitations

1. Use Digested Passwords

Obviously, storing passwords in clear-text readable format in tomcat-users.xml cannot be considered safe or practical. In a production environment, it is essential to use some encryption to provide security. Tomcat provides us with several digest algorithms (SHA, MD2, MD5 etc) supported by MessageDigest class. To enable it, change the realm declaration in server.xml of Tomcat to the following:

memoryRealmMD5

Also, change the password you specified in tomcat-users.xml to the encrypted version of the original password, by using RealmBase class. You can find this class in catalina.jar in $CATALINA_HOME/lib directory. Use it as follows: RealmBase.digest(“password”, “MD5”, null) . Now, restart your Tomcat and test your authentication.

2. Use FORM-based Authentication

Since using BASIC authentication, you have very little control over the authentication/login method used by Tomcat and it is not considered practical for production environment. So we demonstrate another way: FORM-based authentication. The whole setup remains same, only you can provide your own custom login and error pages (with your company logo and whatever you want) instead of just popping up a window (as done by Tomcat in BASIC mode)

We will change the <login-config> element declared in your application’s web.xml as follows:

form-login-config

We will now add login.jsp and error.jsp to our application. login.jsp is used to authenticate the user: hence it would provide a form while error.jsp is the page to which user is redirected in case of an error: invalid username-password.

login.jsp will have at least a login field with name as “j_username” and password field with name as “j_password”. This must be same so that tomcat can identify the password and login fields in the form. Also the action of the form must be “j_security_check”. You can find the link to download the whole project at the end. My authentication page looks like this, which I believe is much better and safer than basic mode.

authenticate

Still, we have one limitation:

Any changes made to the file: tomcat-users.xml will be reflected only when the Tomcat server is restarted. So, if you add a new username-password combination to it, you must restart Tomcat in order to have its effect. We can also overcome this limitation by specifying the username-password and roles in a database table and using a JDBCRealm instead of MemoryRealm. You can download entire project from here.