Friday, December 14, 2007

JAVA SECURITY

Security is, perhaps, the most important and necessary assurance requirement to consider when deploying a system. Because computing systems assume more and more widespread business and mission-critical functionality each day, the cost associated with a breach of security is also increasing. Furthermore, because security problems are human-induced problems, the range of possible problems is as limitless as the human mind. Security, thus, becomes a crucial problem to solve.

The Basic Security Model

Figure Security depicts the basic security model that results from security problems and assurance-provisioning mechanisms. At the top of the diagram, a resource provider is shown offering some security-critical data or application resources. Such resources are security-critical because a malicious being, such as the hacker depicted at the bottom of the diagram, can corrupt, reference (that is, access), replace, delay access to, or deny access to such resources.




Figure Security : The basic security model.

A security service provider depicted on the left side of the diagram attempts to protect such resources from attack by providing protection services such as integrity, confidentiality, authorization and access, identity, authenticity, availability, non repudiation, and auditing-protection services. Such services attempt to thwart the hacker's best efforts.
The right side of the diagram shows the beneficiary of the security services. These services include the following:

§ Integrity Verification: The beneficiary has some verification that the data or application is accurate.
§ Confidentiality Preservation: The beneficiary has some assurance that confidentiality of the data or application has been preserved.
§ Authorization/Access Permission: Properly authorized permission to access security-critical data, application, or other resource has been provided.
§ Identity Verification: The beneficiary has some verification that the identity associated with the data or application source is who they say they are.
§ Authenticity Permission: Properly authenticated permission to access some data, application, or other resource has been provided.
§ Availability of Service: The beneficiary has access to the data, application, or other resource when it expects to have access.
§ Nonrepudiation Evidence: The beneficiary has some evidence regarding from whom the data or application comes or has some evidence that an intended receiver actually received data sent to it.
§ Auditing Evidence: The beneficiary has some evidence of security-critical operations that take place in the system.

Java and Security

Java is a language for the Web and is used to design Web pages. The first Web pages created using Java contained just images and text. However, this was an advancement from the traditional way of presenting information. You had access to a large repository of data that could be accessed through the hyperlinks on a page. The only drawback was that for executable programs, you had to refer to the server. The Web interface was so designed that you filled up data in a page and the data was transmitted to the server where it was acted on by an executable program. There were animations or puzzles that made a Web page more exciting; however, they could not be successful if they were placed on the server for execution. Moreover, if the concerned program was placed on the server, there was a long time interval between the submission of a customer query and the result of the query being displayed on the Web page. Wouldn't it be much easier and require less overhead if executable programs could be placed on the Web page itself? However, here comes the security factor. If programs are placed on Web pages, there is a risk of viruses being downloaded when you load the specified Web page in the browser or execute the program on your computer. Second, if the program was created using a specific platform that is not supported by your system, the main benefit of the Web being platform-independent whereby you can run programs on any client is lost.

AOP – Aspect Oriented Programming

AOP is a philosophy that is related to style of programming, first introduced by Gregor Kickzales in 1996. Like structured programming and Object-Oriented programming introduced a new approach for designing programs and a set of guidelines to make more readable and reusable code.

Aspect-oriented programming (AOP) better separates concerns than previous methodologies, thereby providing modularization of crosscutting concerns.

A concern is a particular goal, concept, or area of interest. In technology terms, a typical software system comprises several core and system-level concerns. For example, ATM processing system's core concern would process payments, while its system-level concerns would handle logging, transaction integrity, authentication, security, performance, and so on. To understand the spirit of AOP, you must understand the following issues:

Concerns Separation: referring the Law of Demeter, a project's efficiency increases if all the concerns are well modularized and if you only have to speak to your direct friends to make a modification of the program (this is a very old principle and the OOP gives some answers).

Crosscutting Concerns: in a complex system, there are always some concerns that are not easily modularized, especially common-interest concerns that, by essence, are used by several modules (i.e. several modules use/share a well-known service of a module -- such as a logging or a persistence service).

Dependencies inversion: the best way to avoid crosscutting is to NOT use the well-known services that crosscut. This is possible by reversing the dependencies (i.e. the well-known service shall use the other modules instead of the contrary). This dependency inversion is implemented by aspects.

Existing Frameworks
Probably the most mature and fully featured framework available today is AspectJ. While AspectJ sets the standard that most frameworks follow, the architects took the unusual step of adding new keywords to the Java language in their implementation. Though the new syntax isn't too difficult to learn, it does mean that you will have to change your compiler, and potentially reconfigure your editor, in order to use the new syntax. In a large team this may not be feasible, as the whole team could be affected. The modification to the language also increases the learning curve for teams looking to introduce AOP into existing projects.
What we need is a framework that can be easily introduced without severely impacting the existing development and build process. There are several frameworks that fit the bill, such as JBoss AOP, Nanning, and Aspectwerkz (AW). For this article, I've chosen Aspectwerkz because it is probably the easiest framework to learn and integrate into your existing projects.
Aspectwerkz, created by Jonas Boner and Alexandre Vasseur, remains one of the quickest and most fully featured AOP frameworks available. While it may not boast all of the features of AspectJ, it is sufficiently complete to be of great use to most developers in many situations.
One of the most interesting features of Aspectwerkz is its ability to run in two different modes: online and offline. In online mode, AW is hooked into the low-level classloading mechanism part of the JVM, allowing it to intercept all classloading calls and transform the bytecode on the fly. AW provides many options to hook in, and a wrapper script can be used as a replacement for the bin/java command to automatically detect and set a working configuration depending on the Java version and JVM capabilities. This mode holds many benefits to developers, as it can be hooked into any classloader and weave classes at classload time, which means that your class files are not modified manually, but deployed as usual. However, it does require additional configuration of your application server, which may not be possible in some situations.
In offline mode, two phases are required to generate your classes. The first phase is the standard compilation using the javac tool that we all know and love. (In fact, most of us love it so much that we replaced it with an Ant task years ago.) The second phase is where things get interesting, we run the AWcompiler in offline mode and point it to the newly created class files. The compiler will then modify the bytecode of the classes to include your advice at the correct point-cuts, as defined in an XML file. The benefit of using the offline mode is that the classes will run in any JVM from version 1.3 and up. This is the mode that I will use in this article, as it requires no modifications to Tomcat and could be applied to most existing projects with only slight modification to the build process.

Tuesday, December 11, 2007

Servlet Event Listeners

Overview
First introduced as part of version 2.3 of the Servlet specification, application event listeners allow you to receive notifications of certain web application events. The primary goal of providing application events is to allow you to better manage resources at either the context or HTTP session level. For example, you can be notified when a web application has been created and is ready to handle requests and create a pool of objects to be used by servlets. Conversely, when the web application is terminated, you can gracefully destroy the object pool.

Four different types of listeners are defined by the specification:
ServletContextListener Allows notification of context lifecycle events (create and destroy)
ServletContextAttributesListener Allows notification of context attribute changes (add, modify, and remove)
HttpSessionListener Allows notification of HTTP session lifecycle events (create and destroy)
HttpSessionAttributesListeners Allows notification of HTTP session attribute changes (add, modify, and remove)

Each of these listener interfaces can be implemented by a listener object. The object is registered with the web application via entries in the deployment descriptor (web.xml). Next, we’ll take a look at simple examples of each type of listener as well as the corresponding configuration in web.xml.

ServletContextListener
Implementing the javax.servlet.ServletContextListener interface allows you to receive context lifecycle events. Note that there is a one-to-one relationship between a context and a web application, so it is safe to say that context lifecycle events can be viewed as web application lifecycle events as well.
The ServletContextListener is, in my opinion, the most powerful of the event listeners in that it allows you to manage resources that will be used by your web application, such as a JDBC connection pool. When you receive notification that the context has been created, you can create and initialize a pool of JDBC connections, and when the context is destroyed, you can properly tear it down.
Prior to the introduction of the ServletContextListener, many servlet developers would use a preloaded servlet to manage resources. The servlet would be preloaded when the web application started and its init() method would be called, which is where any resource initialization code would reside. When the web application was destroyed, the servlet destroy() method would be invoked and any resources would be destroyed as well. This is still a perfectly acceptable way to handle resources, but using the ServletContextListener is a much cleaner (and more elegant) way to handle context lifecycle events.
Let’s take a look at a simple implementation that simply outputs messages to the servlet log file when context events take place:

package com.omh.listeners;

import javax.servlet.ServletContextListener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContext;

/**
* Simple example of implementing the application lifecycle
* event listener ServletContextListener
*/
public class MyContextListener
implements ServletContextListener
{
public void contextInitialized(ServletContextEvent event)
{
// Grab ahold of the ServletContext
ServletContext context = event.getServletContext();

context.log(context.getServletContextName() + " initialized");
}

public void contextDestroyed(ServletContextEvent event)
{
// Grab ahold of the ServletContext
ServletContext context = event.getServletContext();

context.log(context.getServletContextName() + " destroyed");
}
}
When a web application is started, a ServletContext is created as well. Once the ServletContext has been initialized, the servlet container checks its internal list of listeners. If any listeners implement javax.servlet.ServletContextListener, the contextInitialized() method will be invoked on that listener. A similar process is followed when the web application is destroyed. The following shows how our event listener is configured within web.xml:




com.omh.listeners.MyContextListener



Listeners are simply specified by adding a element with a corresponding entry that specifies the full package name of the class that implements one of the application event listeners. You can specify any number of listeners, and a single class can implement any number of the event listener interfaces. The order in which you specify event listeners in web.xml is important, because the servlet container will invoke the listeners in that same order when events occur. Note that when a context is destroyed, the listeners are invoked in reverse order. Remember that, in order to be fully portable, the elements in web.xml must appear in the same order as they appear in the XML grammar.

Using Tomcat 4.0, the servlet log file will contain the following messages after starting and then stopping the server:
Java Servlets Developer's Guide Listener Examples initialized

Java Servlets Developer's Guide Listener Examples destroyed
Note that you must specify a element within web.xml in order to get the web application name from getServletContextName(). If you don’t specify a , you will get the message “null initialized” instead.

ServletContextAttributeListener

Implementing the javax.servlet.ServletContextAttributeListener interface allows you to receive notification when attributes are added, modified, or removed from the ServletContext for a web application. Perhaps you have a very complex web application that stores state information in the ServletContext and you require notification of certain changes in state. Maybe you allow a servlet to cache information in the context, and have a background thread automatically destroy the cache after a certain amount of time (the thread can be started when the attribute is added). Whatever the reason, implementing the ServletContextAttributeListener gives you fine-grain control over these events.
Again, let’s take a look at an example that simply logs the context attribute events as they happen:
package com.omh.listeners;

import javax.servlet.ServletContextAttributeListener;
import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContext;

/**
* Simple example of implementing the application lifecycle
* event listener ServletContextAttributeListener
*/
public class MyContextAttributeListener
implements ServletContextAttributeListener
{
public void attributeAdded(ServletContextAttributeEvent event)
{
// Grab ahold of the ServletContext
ServletContext context = event.getServletContext();

String attributeName = event.getName();
Object attributeValue = event.getValue();

context.log("Add context attribute " +
attributeName + "=" + attributeValue);
}

public void attributeRemoved(ServletContextAttributeEvent event)
{
// Grab ahold of the ServletContext
ServletContext context = event.getServletContext();

String attributeName = event.getName();
Object attributeValue = event.getValue();

context.log("Remove context attribute " +
attributeName + "=" + attributeValue);
}

public void attributeReplaced(ServletContextAttributeEvent event)
{
// Grab ahold of the ServletContext
ServletContext context = event.getServletContext();

String attributeName = event.getName();
Object oldAttributeValue = event.getValue();
Object attributeValue =
context.getAttribute(attributeName);

context.log("Replace context attribute " +
attributeName + "=" + attributeValue +
" old value=" + oldAttributeValue);
}
}
To see the listener in action, you first need to configure it within web.xml
“”
““
““
com.omh.listeners.MyContextListener
“
“
“
“
“
“

and then create a simple servlet that uses context attributes:
package com.omh;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;

/**
* Simple servlet for testing a ServletContextAttributeListener
*/
public class TestContextAttributes
extends HttpServlet
{
public void doGet(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException, IOException
{
resp.setContentType("text/html");

// Get an output stream that takes into account
// the proper character encoding
PrintWriter out = resp.getWriter();

// Get the context
ServletContext context = getServletContext();

// Set, modify, and delete an attribute
String name = "com.omh.name";

out.println("Setting " + name + " to Bob
");
context.setAttribute(name, "Bob");
out.println("Setting " + name + " to Larry
");
context.setAttribute(name, "Larry");
out.println("Removing " + name);
context.removeAttribute(name);
}
}
Note that the context attribute name I’m using includes my class package name. This is a good idea for two reasons. First, using the package name will greatly reduce the chance that another application will use the same name. Second, it helps you debug problems, because the name will contain the package name of the code that put it there.

Requesting this servlet will cause something like the following to be logged to the servlet log file:
Add context attribute com.omh.name=Bob
Replace context attribute com.omh.name=Larry old value=Bob
Remove context attribute com.omh.name=Larry

Basics of Filters : Servlet Filters ( Your First Filter )

Overview

Filters are a powerful feature first introduced in version 2.3 of the Servlet API. Filters allow you to write a software component that can then be placed into the request and response flow of a servlet or group of servlets. A filter is not a servlet; filters do not typically create a response to a request but, rather, either modify or inspect the request to a servlet or response from a servlet. Note that you not only can configure filters to act upon servlet requests, but can also apply them to the access of any resource (such as static files).

Like servlets, filters have a specification-defined lifecycle:

§ Filters are initialized by calling their init() method. The init() method is supplied with a FilterConfig object that allows the filter to access initialization parameters as well as reference to the ServletContext.
§ The doFilter() method of the filter is invoked during the request processing of a resource. It is in the doFilter() method that you can inspect the request, modify request headers, modify the response, or skip the processing of the underlying resource altogether.
§ The destroy() method is called when the filter is destroyed.


So what types of filters can you create? The servlet specification gives the following list of suggestions:

§ Authentication filters

§ Logging and auditing filters The first filter you will create in this chapter will log the access of a servlet and supply the elapsed execution time.
§ Image conversion filters Filters can very easily modify the output of a request, such as converting a JPEG image into GIF format.
§ Data compression filters Tomcat supplies the code for a compression filter (named CompressionFilter).
§ Tokenizing filters WML (Wireless Markup Language) is a perfect example of tokenizing; a tokenizing compiler converts tags into a single byte token in an effort to compress the response.
§ Filters that trigger resource access events You may want to log the fact that certain resources are being requested.
§ XSLT filters The last example in this chapter will illustrate the power of using filters to translate XML output into any number of target clients using XSL templates.

What makes a filter a filter?

You must implement the javax.servlet.Filter interface, which includes the init(), doFilter(), and destroy() lifecycle events, and then configure the filter within a web application to place itself into the process chain of a resource request.

Your First Filter

Let’s take a look at a very simple filter that will log the execution time of any requested resource:
package com.omh.filters;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

/**
* Simple filter for measuring servlet response times
*/
public class ResponseTimerFilter
implements Filter
{
protected FilterConfig config;

public void init(FilterConfig config)
throws ServletException
{
// Save the config object
this.config = config;
}

public void destroy()
{
}

public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain)
throws ServletException, IOException
{
// Save the start time
long startTime = System.currentTimeMillis();

// Invoke the next filter/servlet in the chain
chain.doFilter(request, response);

// Capture the elapsed time
long elapsed = System.currentTimeMillis() - startTime;

// Figure out what was requested. If we are not
// processing an HTTP request just default the
// name to servlet
String name = "servlet";
if (request instanceof HttpServletRequest)
{
name = ((HttpServletRequest) request).getRequestURI();
}

// Output the time
config.getServletContext().log(name +
" took " + elapsed + " ms");
}
}


The init() method simply saves a reference to the FilterConfig object (since we’ll use it later to access the ServletContext log() method). There is nothing to do in destroy(), since we don’t have anything to gracefully tear down when the servlet container is done with the filter, but we must provide an empty implementation in order to fully implement the Filter interface.
The doFilter() method is where all the action is found. For our simple ResponseTimeFilter, all we do is save the current clock time, call the next filter in the chain (which will ultimately invoke the requested servlet or resource), and log the elapsed time of the request.

After requesting any resource, the servlet container log file will contain something like the following:
2001-10-28 16:41:07 /jsdg-filters/Properties took 110 ms

In this case, I requested the Properties servlet using Tomcat 4.0. Note that we did nothing to modify the flow or content of the request or response, but this is certainly possible using filters (as we’ll see next).

To notify the servlet container that you have a filter, you must add a filter definition and filter mapping to web.xml:

Timing Filter
com.omh.filters.ResponseTimerFilter



Timing Filter
/*

The element defines the name and fully qualified class name of the filter, while defines a URL pattern that, when matched, will have the corresponding filter placed in its execution stream. A single servlet name can be specified instead, which we’ll use in the last example in the chapter. When using filters that overlap (meaning that more than one filter will be placed in the request chain), the filters will be applied in the same order in which they appear in web.xml.