Friday, August 31, 2007

Ten Aspects of Security to Improve Application Strength

When designing and developing applications, there are a lot of pieces to juggle at the outset, and when the complexities, priorities, and pressures of business are combined, quality application development easily can become something of an unreachable goal. As a final ingredient, the need for security in the application can further darken an already ominous undertaking. The situation is not hopeless, however, and both quality and security can be achieved by approaching applications logically and with a few guidelines driven from experience. This article provides a set of important pieces that can help application developers avoid critical mistakes as they relate to security within applications.

The first part discusses areas of security that relate to all applications where some of the most common mistakes are made:

1. Design time
2. Layers
3. Think like the enemy

The second part focuses on the application of security within the application where more technical weaknesses can be uncovered:

1. Authentication
2. Access control
3. Confidentiality/privacy
4. Encryption
5. Segregation of data and privileges
6. Error handling
7. Testing for security

Design Time

One of the largest mistakes application designers can make is to think of security as a bolt-on feature that always can be added at some later point, or upon request. Security affects all aspects of an application and needs to be looked at and considered from all angles, dimensions, and in all areas during design and development. Start thinking about security early when working on the initial ideas for an application. Consider the following questions:

1. What kind of data will the application be using and are there requirements for security such as authentication, access control, privacy, networking, and storage?
2. What kind of security-specific technologies and components will be needed? Look at the larger picture and where the application fits, including interoperability and standards such as Role Based Access Control, Public Key Cryptography, and SSL/TLS.
3. Are there any laws, regulations, and rules that govern the application, how it's used, or how data is handled? These often mandate auditing and logging, transactional components, and reporting.

Security needs to be woven into the application at all stages. To assure that this happens, some basic steps can be followed during the requirements gathering stage of application design:

1. Create a section dedicated to security in functional and design documents
2. Start with a list of questions and issues that relate to security. For example: "Do we need authentication here?" "What kind of users are expected to use this application?" "How do we want to handle bad input in module X?" "What effect does my application have on other systems and applications with which it interacts?"
3. As the functional requirements unfold, many of the questions can be answered. Repeat this cycle for the design phase.

Layers

Security should be thought of in layers. It is very easy to fall into the trap of perimeter-based security—only at the borders, such as the network via a firewall. The network is only one layer where security needs to be present. Any areas of interaction with external applications, users, and systems should also have security designed into them, as should the data handling inside an application.

A truly comprehensive model can be created by applying security to many layers of an application. Here is a model that roughly follows the well-known OSI layers for networking:

1. Physical Layer: Consider how controlling physical access to the system can add to or detract from the security of the application.
2. Network: Consider the interaction with the network that an application has, including the systems it interacts with, how network access is protected, and where.
3. Borders: The edges of the application, including its points of interaction with other applications, APIs, and libraries.
4. Presentation: The user interface of the application, such as a command line, a GUI, or Web browser.
5. Internal: The internals of the application, where data is consumed, rules are set, exceptions made, and memory manipulated.

Although these layers present a guideline, it is important to consider each application in its appropriate context by identifying the layers that reflect the application and its usage. Some applications will have more, or less, layers, and may differ from one application to the next.
Think Like The Enemy

When arriving at functionality and the corresponding design for an application, the most common mistake is to consider only ideal-world functionality. This is the act of defining functionality of an application exclusively by the best-case scenario of what you want users to do. Invariably, people will make mistakes and do things with an application that it was never meant to do—if the constraints of an application are not defined and handled, the effect can be severe. Other people will attempt to find vulnerabilities in any application by doing exactly that which one would not want them to do. Therefore, one can more easily be proactive during the design phase of an application by pondering the kinds of behavior and actions that are not desired and to implement functionality to prevent them from happening. Each of the aforementioned layers of an application will have well-known types of attacks that can be avoided and protected against.

It is also important to understand the risks surrounding an application. The best way to analyze risk is to put the application in context with its intended use—its relationship to other high- or low-risk applications and systems, and the data that it uses. Does the nature of the application, such as an e-commerce application, naturally make it a more appealing target, due to the plethora of important and sensitive information with which it works? Is the application known to interact with other systems, on which sensitive or critical material is located? Does the application itself constitute a critical piece of an organization's lifeblood? All of these aspects should be considered when evaluating the security of an application. If the application increases an organization's risk with its use, the appropriate attention needs to be given to the security in the application.
Authentication

When creating applications that have some form of user interaction, multiple system interaction, or any dealing with foreign components, it is probable that some form of authentication be used to protect the application. The most prevalent mistakes with authentication are to:

1. Have no authentication.
2. Define static and hard-coded authentication information.
3. Negate the effectiveness of having authentication with poor authentication management.

For example, the most commonly used authentication mechanism is the username and password. Although not the strongest form of authentication, it can be used safely to provide an adequate level of security, depending upon the context. There are, however, several ways to render username and password authentication very insecure:

1. Perform authentication in cleartext over the network.
2. Store the password in plaintext in a file or database.
3. Hard-code credentials into the application.
4. Create pre-defined/static special accounts.

Some ways to increase security for username/password authentication:

1. Utilize encryption for network-based authentication, such as SSL/TLS.
2. When storing passwords, store password hashes if there is no need to recover the plaintext of the original password. If recovery of the original password is desired, use encryption to securely store it (see the following section on encryption).
3. Mandate the use of longer passwords and a mixture of characters, including mixed-case alpha-numeric and special characters.

Access Control

The biggest mistake that an application designer can make is to ignore access control as a piece of required functionality. It is rare that every user or system that interacts with an application should have the same rights across that application. Some users may need access to particular pieces of data and not others; some systems should or should not be able to access the application. Access to specific components, functions, or modules within an application should also be controlled. Access control also is important for auditing and regulatory compliance. Some common ways of managing access control are:

1. Read, write and execute privileges: A file
2. Role-based access control: administrators, users
3. Host based access IP address, machine name
4. Object-level access control code object, multiple reader/single writer

Confidentiality/Privacy

Many applications use, manipulate, and consume sensitive data. The mistake often made here is to treat all data the same and fail to recognize the sensitive nature of some data types. Common examples of sensitive data includes:

1. Personal information about users: Includes names, addresses, phone numbers, ID numbers; Social Security, passport, and license numbers
2. Security information: Includes keys, passwords, tokens
3. Configuration information for the application
4. Financial information (e-commerce related): credit card and account numbers

Sensitive data can be segregated from other data within the application (see below), and the methods used to manipulate the data can be access controlled (above). When developing applications, especially in this day of increasing regulations and rules, it is even more important to research any regulations or procedures that may govern the application or its use. This is especially common in the financial, healthcare, energy, and other critical infrastructures.

Encryption

As with most security technologies, it is easy to render the security strength ineffective if used improperly. Encryption is an important component in most security architectures, but there are some complexities involved with its use. The following pieces need to be considered when using encryption:

1. The type of algorithm: symmetric or asymmetric
2. The generation of keys and keying material
3. The management of keys and keying material
4. The application's performance requirements

There are two types of encryption algorithms: asymmetric and symmetric. Asymmetric algorithms have separate keys for encryption and decryption, use longer key lengths, have slower performance, and have easier key distribution with somewhat difficult key management. Symmetric algorithms use a single key for encryption and decryption, typically have smaller key lengths, higher performance, and more complex key distribution with simpler key management. Choosing a type and algorithm is often done automatically depending on the technologies used. Unless implementing a new or proprietary protocol, the use of encryption is generally governed by an existing standard.

When using encryption, there are several pieces of information that affect its strength. This includes how the keys are generated and the sources of data used to start key generation. Initialization vectors used to seed keying material or encryption operations often rely on sources of randomness and entropy. What these sources are and how truly random they are can result in weaker keys and encryption that allows attackers to compromise the data. Often, the most reliable sources of randomness are hardware and many systems have built-in pseudo-random number generators (PRNG).

Once keys are generated, the next challenge is their management, which includes storage, distribution, revocation, and updates. The problem of key storage is fairly obvious, with the plethora of smart cards, USB tokens, and dongles readily available. Because the key used for decryption must be stored safely, the use of encryption can become useless if private keys are stored on globally accessible media, such as on a hard drive. The fun does not stop there, however. For symmetric encryption, where a single key is used for both encryption and decryption, that key must somehow be communicated to the parties that want to encrypt data. It is obviously not ideal to simply transmit the key via some common way (e-mail, a file, Instant Messaging, and so forth), because it can be compromised easily. For this reason, several schemes are used to exchange keys, including Diffie-Hellman key exchange, the use of Public Key cryptography to exchange keys, and other algorithms that allow for mutual calculation of keys. Finally, the management of keys can become tricky, especially for keys that are compromised or expire when used on data that persists for long periods of time. If keys are lost, stolen, or expired, new keys must be generated and the data that may have been encrypted with the old keys must then be decrypted and re-encrypted using the new keys.

Finally, the performance requirements of the application can affect which encryption technologies are used. Public key algorithms are computationally expensive and will result in dramatic decreases in performance and throughput. Symmetric ciphers have a higher degree of performance. A balance of the two can often be used—SSL/TLS is a perfect example. SSL/TLS most commonly runs in a mode that utilizes both public key and shared key encryption algorithms. The public key algorithm is used to exchange the shared key in a safe manner, and this shared key then is used for all of the bulk encryption operations that follow the session. It is also important to note that different algorithms perform differently.

If performance is a factor for applications, the careful selection of encryption types and algorithms allows the application to meet performance requirements. Alternately, there are hardware components available to offload and increase performance of various encryption operations. These components come in many form factors and can be utilized by the application software.
Segregation of Data and Privileges

In conjunction with access control (above), how data is organized within the application can add or detract from its security. This flaw manifests itself when the application has no central mechanism for accessing sensitive data and when the management of sensitive data is distributed across many components and modules within the application. This distribution of sensitive data makes access control very difficult. It also allows for multiple points of vulnerability—each module or component that manages sensitive data becomes a potential target.

Applications that work with sensitive information can improve security by segregating access and management of that data to a protected module. This module can implement granular access controls and auditing functionality to assure access is granted only to those components that need it. Centralizing access to sensitive data also allows the application designer to more cleanly and logically organize functionality that may otherwise end up unmanageable when it is distributed across too many components.

The second aspect to isolation and segregation within applications concerns privilege. Most systems have some notion of privilege levels, especially when doing development on Windows and UNIX platforms—and many operations require elevated privileges to execute. Common mistakes in this area are:

1. Running the application in an elevated privilege level at all times (as the "root" user on UNIX or as one of the administrative accounts on Windows).
2. Failure to determine which actions truly require elevated privileges. Most operations within an application can be done without the need for elevated privileges.

One solution often used today is the separation of privileged actions. There are a few ways to accomplish this:

1. If possible, isolate privileged operations to initialization time to start with elevated privileges; then drop them once they are complete.
2. If elevated privileges are required at various points during the normal operation of an application, the privileged operations should be isolated from the non-privileged operations. Separate threads or processes then can be used to isolate and execute operations. Combined with the appropriate authentication and access control (above), privileged operations can be implemented and managed safely.

In short, it is vital to limit privileged functionality to a minimum and to keep sensitive data managed. Designing applications with this in mind can reduce the potential vulnerability and allow for better auditing within the application to determine when a problem has occurred.
Error Handling

Error handling is both an engineering and security challenge; how an application behaves individually and in conjunction with other applications can result in stronger or weaker security. An application that has defined constraints and safely handles error conditions can mean the difference between a resilient environment and one that crashes completely.

Error handling is an aspect of application design that is often forgotten or ignored. If a framework for handling errors is not designed, an application may end up with a different scheme for each developer who works on the project. Components of error handling can include:

1. Definition of error types: processing, runtime, security violations, program bugs/assertions.
2. Definition of severity levels: informational, warnings, catastrophic issues.
3. Logging and auditing: centralized auditing with modular logging components such as file, e-mail, and cell phone.
4. Defined responses to error types and levels: issue a warning, stop a component, restart a service, shut down the application, notify an administrator.

The design of an application's error handling capabilities is further strengthened when the functional requirements include negative scenarios; see the section on thinking like the enemy, above. Providing a framework for error handling creates more predictable and easily used applications. It resolves any difficulties that arise from individual developer styles and forces the designer to outline the constraints and limits within the application. A framework for error handling also provides greater clarity and understanding when anomalies do occur.
Testing for Security

One final aspect that people often fail to recognize is the importance of testing as it relates to security. Three components of testing for security are:

1. Functional verification
2. Constraint evaluation
3. Border cases and attacks

Functional verification is the most prevalent form of testing and is most often what is meant when people refer to testing applications. Just as one creates tests for their functional requirements, it is equally important to devise tests for those requirements established for undesired behavior and error conditions—the constraints and limits of the application. Each of the conditions and responses defined for the behavior of the application should be rung out and verified.

Border tests can be thought of in the following manner:

1. Testing interfaces to the application: APIs, network, and user—the physical borders.
2. Testing the borders of data processing: Multiple combinations of imperfect data that will be processed by the application. These can include valid ranges of data values, unexpected types, and randomly generated data.

There are a number of tools available to test an application's security. These include code analyzers, modeling tools, and stress testing tools such as fuzzers, which help identify many software vulnerabilities and coding issues.

The combination of testing that includes defined functionality and constraint evaluation, as well as stress testing that pushes the limits and boundaries of an application, help improve the security before it becomes deployed in critical environments.
Summary

Security in and of an application does not have to be an overwhelming task. By considering the security aspects of an application at all stages, as early as basic functional requirements, one can weave security into all areas of the application; doing so results in a cumulative and strong level of security strength, resiliency, and quality. Effort spent during the design phases looking at the various layers of the application and how one hopes people will and will not use the application sets the foundation for functionality that both meets the needs of users and withstands all anomalies that occur.

Proper application of security technologies such as authentication, access control, and encryption can assure a higher degree of safety in untrustworthy environments. An understanding of worst-case scenario events, handling errors, and compartmentalizing sensitive data and operations within the application can solidify the strength of an application. Finally, taking some time to test and verify constraints, functionality, and security will assure a level of confidence with the developers and users alike. Keep security in mind to create useful—and safe—applications.
About the Author

Chad Cook has spent over a dozen years in Information Security that include both product engineering and IT services. Chad has developed IT service security strategies, networks, and policies for organizations including BBN and GTE Internetworking, Infolibria, and the international security consulting firm, @stake/Symantec. He has architected and developed security technology for award-winning networking, security, and financial products sold worldwide, including core routers, edge devices, utility hosting systems, and Web services security devices and high-performance systems. Chad has nine patents applied for and pending on security analysis, modeling techniques, and encryption processing acceleration.

Currently, Chad is the VP of Information Security at Lime Group, a New York securities and brokerage organization, where he leads product architecture, infrastructure security, and compliance efforts. Prior to Lime Group, he designed and developed security risk management and threat modeling products as CTO at Black Dragon Software. Chad has held lead engineering and security positions developing products at BBN, GTE, and a number of small companies. Chad is an internationally published author on security topics having contributed to two books, Maximum Security, 3rd and 4th editions, has been featured in numerous articles and also has written articles for Symantec's SecurityFocus.com and numerous online publications.

10 Commandments for Java Developers

There are many standards and best practices for Java Developers out there. This article outlines ten most basic rules that every developer must adhere to and the disastrous outcomes that can follow if these rules are not followed.

1. Add comments to your code. – Everybody knows this, but somehow forgets to follow it. How many times have you "forgotten" to add comments? It is true that the comments do not literally contribute to the functionality of a program. But time and time again you return to the code that you wrote two weeks ago and, for the life of you, you cannot remember what it does! You are lucky if this uncommented code is actually yours. In those cases something may spark your memory. Unfortunately most of the time it is somebody else's, and many times the person is no longer with the company! There is a saying that goes "one hand washes the other." So let's be considerate to one another (and ourselves) and add comments to your code.

2. Do not complicate things. – I have done it before and I am sure all of you have. Developers tend to come up with complicated solutions for the simplest problems. We introduce EJBs into applications that have five users. We implement frameworks that an application just does not need. We add property files, object-oriented solutions, and threads to application that do not require such things. Why do we do it? Some of us just do not know any better, but some of us do it on purpose to learn something new, to make it interesting for ourselves. For those who do not know any better, I recommend reaching out to the more experienced programmers for advice. And to those of us that are willing to complicate the design of an application for personal gains, I suggest being more professional.

3. Keep in Mind – "Less is more" is not always better. – Code efficiency is a great thing, but in many situations writing less lines of code does not improve the efficiency of that code. Let me give you a "simple" example:

if(newStatusCode.equals("SD") && (sellOffDate == null ||
todayDate.compareTo(sellOffDate)<0>
todayDate.compareTo(lastUsedDate)>0)) ||
(newStatusCode.equals("OBS") && (OBSDate == null ||
todayDate.compareTo(OBSDate)<0))){
newStatusCode = "NYP";
}

How easy is it to figure out what this "if" condition is doing? Now imagine that whoever wrote this code, did not follow rule number 1 – Add comments to your code.

Wouldn't it be much easier if we could separate this condition into two separate if statements? Now, consider this revised code:

if(newStatusCode.equals("SD") && (sellOffDate == null ||
todayDate.compareTo(sellOffDate)<0>
todayDate.compareTo(lastUsedDate)>0))){
newStatusCode = "NYP";
}else
if(newStatusCode.equals("OBS") && (OBSDate == null ||
todayDate.compareTo(OBSDate)<0))
{
newStatusCode = "NYP";
}


Isn't it much more readable? Yes, we have repeating statements. Yes, we have one extra "IF" and two extra curly braces, but the code is much more readable and understandable!

4. No hard coding please. – Developers often forget or omit this rule on purpose because we are, as usual, crunched for time. But maybe if we had followed this rule, we would not have ended up in the situation that we are in. How long does it take to write one extra line of code that defines a static final variable?

Here is an example:

public class A {

public static final String S_CONSTANT_ABC = "ABC";

public boolean methodA(String sParam1){

if (A.S_CONSTANT_ABC.equalsIgnoreCase(sParam1)){
return true;
}
return false;
}
}

Now every time we need to compare literal "ABC" with some variable, we can reference A.S_CONSTANT_ABC instead of remembering what the actual code is. It is also much easier to modify this constant in one place rather then looking for it though out all of the code.

5. Do not invent your own frameworks. – There are literally thousands of frameworks out there and most of them are open-source. Many of these frameworks are superb solutions that have been used in thousands of applications. We need to keep up to date with the new frameworks, at least superficially. One of the best and most obvious examples of a superb widely used framework is Struts. This open source web framework is a perfect candidate to be used in web-based applications. Please do not come up with your own version of Struts, you will die trying. But you must remember rule number 3 – Do not complicate things. If the application that you are developing has 3 screens – please, do not use Struts, there isn't much "controlling" required for such an application.

6. Say no to Print lines and String Concatenations. – I know that for debugging purposes, developers like to add System.out.println everywhere we see fit. And we say to ourselves that we will delete these later. But we often forget to delete these lines of code or we do not want to delete them. We use System.out.println to test, why would we be touching the code after we have tested it? We might remove a line of code that we actually need! Just so that you do not underestimate the damage of System.out.println, consider the following code:

public class BadCode {
public static void calculationWithPrint(){
double someValue = 0D;
for (int i = 0; i <>
System.out.println(someValue = someValue + i);
}
}
public static void calculationWithOutPrint(){

double someValue = 0D;
for (int i = 0; i <>
someValue = someValue + i;
}

}
public static void main(String [] n) {
BadCode.calculationWithPrint();
BadCode.calculationWithOutPrint();
}
}

In the figure below, you can observe that method calculationWithOutPrint() takes 0.001204 seconds to run. In comparison, it takes a staggering 10.52 seconds to run the calculationWithPrint() method.

(If you would like to know how to produce a table like this, please read my article entitled "Java Profiling with WSAD" Java Profiling with WSAD )

The best way to avoid such CPU waste is to introduce a wrapper method that looks something like this:

public class BadCode {

public static final int DEBUG_MODE = 1;
public static final int PRODUCTION_MODE = 2;

public static void calculationWithPrint(int logMode){
double someValue = 0D;
for (int i = 0; i <>
someValue = someValue + i;
myPrintMethod(logMode, someValue);
}
}

public static void myPrintMethod(int logMode, double value) {
if (logMode > BadCode.DEBUG_MODE) { return; }
System.out.println(value);
}
public static void main(String [] n) {
BadCode.calculationWithPrint(BadCode.PRODUCTION_MODE);
}
}

String concatenation is another CPU waster. Consider example below:

public static void concatenateStrings(String startingString) {
for (int i = 0; i <>
startingString = startingString + startingString;
}
}

public static void concatenateStringsUsingStringBuffer(
String startingString) {
StringBuffer sb = new StringBuffer();
sb.append(startingString);
for (int i = 0; i <>
sb.append(sb.toString());
}
}

In the following figure you can see that the method that uses StringBuffer takes .01 seconds to execute where as the methods that use string concatenation takes .08 seconds to execute. The choice is obvious.

7. Pay attention to the GUI. – No matter how absurd it sounds; I repeatedly observe that GUI is as important to the business clients as functionality and performance. The GUI is an essential part of a successful application. Very often IT management tends to overlook the importance of GUI. Many organizations save money by not hiring web designers who have experience in design of "user-friendly" applications. Java developers have to rely on their own HTML skills and their limited knowledge in this area. I have seen too many applications that are "computer friendly" rather then "user friendly". Very rarely I have seen developers that are proficient in both software development and GUI development. If you are this unlucky Java developer who has been assigned to create an application interface, you should follow these three rules:

1. Do not reinvent the wheel. Look for existing applications that have similar interface requirements.
2. Create a prototype first. This is a very important step. The clients like to see what they are going to get. It is better for you also because you are going to get their input before you go all out and create an application interface that will leave the clients cold.
3. Put the user's hat on. In other words, inspect the application requirements from the user's perspective. For example, a summary screen can be created with paging and without. As a software developer, it might be temping for you to omit paging from the application because it is so much less complicated. But, from the client's perspective, it might not be the best solution because the summary results can hold hundreds of rows of data.

8. Always Prepare Document Requirements. – Every business requirement must be documented. This could be true in some fairy tale, but it is far from that in the real world. No matter how time-pressed your development is, no matter how tight the deadlines, you must always make sure that every business requirement is documented.

9. Unit-test. Unit-test. Unit-test. – I am not going to go into any details as to what is the best way to unit-test your code. I am just going to say that that it must be done. This is the most basic rule of programming. This is one rule that, above all, cannot be omitted. It would be great if your fellow developer could create and execute a test plan for your code, but if that is not possible, you must do it yourself. When creating a unit test plan, follow these basic rules:

1. Write the unit test before writing code for class it tests.
2. Capture code comments in unit tests.
3. Test all the public methods that perform an "interesting" function (that is, not getters and setters, unless they do their getting and setting in some unique way).

10. Remember – quality, not quantity. - Do not stay late (when you do not have to). I understand that sometimes production problems, urgent deadlines, and unexpected events might prevent us from leaving work on time. But, managers do not appreciate and reward their employees because they stay late on regular basis, they appreciate them because they do quality work. If you follow the rules that I outline above, you will find yourself producing less buggy and more maintainable code. That is the most important part of your job.

Securing Struts Applications

Most Web applications require certain aspects of the system to be secured in some manner. Security requirements are often specified at both the system and functional levels. System requirements may dictate, for example, that entry of sensitive information should be performed over a secure HTTP connection (HTTPS). On a higher level, functional requirements may dictate that only users with administrative privileges can access certain pages and menu items. From a developer's perspective, the critical task is to identify which of the requirements can be satisfied using standard security mechanisms, and which requirements require a customized security solution. Quite often, security requirements dictate some sort of customization. In some cases, you can use a combination of standard security mechanisms and customization to achieve the desired security policy.
Levels of Security

Security is a fairly broad topic and may encompass everything from encryption to personalization, depending on how 'security' is defined. This chapter focuses on the levels of security that you can implement to secure your Struts applications, beginning in this section with an overview of the various security levels. That is followed by sections that look in depth at using container-managed security and application-managed security, the two primary ways to secure your Struts applications.

* Transport-level security using HTTPS
* authentication and authorization
* Role-based access control
* Container-managed security
* Application-managed security

Some aspects of personalization will also be covered, specifically some techniques for hiding or displaying content based on a user's authorization.
Providing Secure Communications

Data can be securely transmitted by using HTTP over Secure Socket Layer (referred to as HTTPS). HTTPS secures data by encrypting the protocol at the transport level. In other words, the entire HTTP conversation between the client browser and the Web server is encrypted. Struts applications, like most Web applications, can send data over HTTPS without modification.

HTTPS does impact performance, however. There is an order of magnitude of performance penalty when using HTTPS. To reduce the impact on performance, it is common for applications to switch the protocol between HTTP and HTTPS. The typical scenario uses the HTTPS protocol for application login and submission of sensitive data. Once the data is entered, the protocol is switched back to HTTP. While on the surface this seems like a good approach, it leaves open a serious security hole whereby the user's session can be hijacked. Sensitive user information, such as a credit card number, may be stored in that session. A network snoop could use the session ID to spoof a valid user session. Due to this risk, container-managed security does not support protocol switching. However, if you need protocol switching and can accept the security risks, there are mechanisms for doing so that integrate with Struts.
Authentication and Authorization

Authentication is the process of proving to an application that you are who you say you are. For Web applications, this process is most commonly associated with entering a username and password. If you are registered as a user of the application and you provide a valid password, the application allows access to privileged features of the application. In contrast, if you cannot provide valid credentials, you are allowed access only to the public areas of the site. In fact, many Web applications may only allow authenticated access-with the only public page being the login screen. Authentication can be provided through custom coding for the application, or by using container-managed security services.

Authorization is how the application determines which aspects of the Web application you are allowed to access. Generally speaking, determining a user's authorization requires the user to first be authenticated. Once authenticated, application-provided or container-managed security can be used to determine a user's authorization.
Role-based Access Control

Role-based access control (RBAC) is a common scheme for implementing authorization. Users are assigned roles through a container-specific means. When a user is authenticated, the user's roles are associated with the HTTP request. Given this information, access to certain pages or user interface components can be allowed or disallowed based on the user's roles. In most cases, a user is allowed to have multiple roles. However, roles are typically flat; that is, there is no hierarchical relationship between roles.
Container- vs. Application-Managed Security

Servlet containers provide security as specified by the servlet specification. Container-managed security allows the developer to declaratively specify how authentication is to be performed and how authorization is to be granted. Container-managed security provides an easy, unobtrusive way of adding security to an application. This mechanism of implementing security provides the following benefits:

* It is declarative. Authentication and authorization are specified in the web.xml file. Container-specific details, such as the security realm, typically are configured in server-specific XML configuration files.

* It supports multiple authentication schemes, such as password authentication, FORM-based authentication, authentication using encrypted passwords, and authentication using client-side digital certificates.

* Using container-specific security realms, user data can be provided by a variety of stores, including flat files, relational databases, and Lightweight Directory Access Protocol (LDAP) servers.

* Redirects are handled automatically. In other words, the container determines when a user is accessing a protected URL, prompts for user credentials, and, if authenticated, redirects to the requested page. This is a powerful mechanism, particularly for applications that publish links to protected pages in e-mail communications.

Containers are, however, somewhat limiting because of the following:

* The implementation of container-managed security varies by container. An application using container-managed security generally requires modification at some level when ported from one application server to another.

* The login flow does not allow easy custom processing of login requests. In other words, additional processing cannot be performed in the authentication process.

* Authorization can only use a flat, role-based approach. Access to Web pages cannot be granted based on multiple factors, for example, a managerial level and a department number.

* FORM-based login forces a workflow that uses a separate page for login. This limits the flexibility of the application.

* Container-managed authentication requires changes to the application server's configuration that may not be allowed in a hosted environment.

These limitations can be overcome by using application-managed security. However, using application-managed security means that custom code must be designed and written. The decision of which approach to take should be driven by the requirements. While container-managed security is simpler to implement, it does restrict the flexibility of your security policy. One container's security implementation may be different from another's, making your application less portable. Also, container-managed security limits you to a specific login workflow that may not be what you want for your application.

Application-managed security, on the other hand, allows you to implement your security policy as needed at the price of requiring more custom code. Struts mitigates this problem by allowing for customized role processing via a custom request processor. Also, servlet filters can be used to apply across-the-board security policies. Cookies can be used to persist user login information between sessions. In addition, there are Struts extensions that permit finer-grained control of the use of HTTPS.

One last point: there is a somewhat hybrid approach that allows programmatic access to the methods that are usually only available when using container-managed security.

EJB Interview Questions

1. What is the need of Remote and Home interface? Why can't it be in one?

The main reason is because there is a clear division of roles and responsibilities between the two interfaces. The home interface is your way to communicate with the container, that is who is responsible of creating, locating even removing one or more beans. The remote interface is your link to the bean that will allow you to remotely access to all its methods and members. As you can see there are two distinct elements (the container and the beans) and you need two different interfaces for accessing to both of them.

2. Can I develop an Entity Bean without implementing the create () method in the home interface?

As per the specifications, there can be 'ZERO' or 'MORE' create () methods defined in an Entity Bean. In cases where create () method is not provided, the only way to access the bean is by knowing its primary key, and by acquiring a handle to it by using its corresponding finder method. In those cases, you can create an instance of a bean based on the data present in the table. All one needs to know is the primary key of that table. i.e. a set a columns that uniquely identify a single row in that table. Once this is known, one can use the 'getPrimaryKey ()' to get a remote reference to that bean, which can further be used to invoke business methods.

3. What is the difference between Context, InitialContext and Session Context? How they are used?

javax.naming.Context is an interface that provides methods for binding a name to an object. It's much like the RMI Naming.bind() method. javax.naming.InitialContext is a Context and provides implementation for methods available in the Context interface. Where as SessionContext is an EJBContext object that is provided by the EJB container to a SessionBean in order for the SessionBean to access the information and/or services or the container. There is EntityContext too which is also and EJBContext object that'll be provided to an EntityBean for the purpose of the EntityBean accessing the container details. In general, the EJBContext (SessionContext and EntityContext), AppletContext and ServletContext help the corresponding Java objects in knowing about its 'context' [environment in which they run], and to access particular information and/or service. Whereas, the javax.naming.Context is for the purpose of 'NAMING' [by the way of referring to] an object.

4. Why an onMessage call in Message-driven bean is always a separate transaction?

EJB 2.0 specification: "An onMessage call is always a separate transaction, because there is never a transaction in progress when the method is called." When a message arrives, it is passed to the Message Driven Bean through the onMessage() method, that is where the business logic goes.Since there is no guarantee when the method is called and when the message will be processed, is the container that is responsible of managing the environment, including transactions.

5. Why are ejbActivate() and ejbPassivate() included for stateless session bean even though they are never required as it is a nonconversational bean?

To have a consistent interface, so that there is no different interface that you need to implement for Stateful Session Bean and Stateless Session Bean.Both Stateless and Stateful Session Bean implement javax.ejb.SessionBean and this would not be possible if stateless session bean is to remove ejbActivate and ejbPassivate from the interface.

6. Static variables in EJB should not be relied upon as they may break in clusters.Why?

Static variables are only ok if they are final. If they are not final, they will break the cluster. What that means is that if you cluster your application server (spread it across several machines) each part of the cluster will run in its own JVM. Say a method on the EJB is invoked on cluster 1 (we will have two clusters - 1 and 2) that causes value of the static variable to be increased to 101. On the subsequent call to the same EJB from the same client, a cluster 2 may be invoked to handle the request. A value of the static variable in cluster 2 is still 100 because it was not increased yet and therefore your application ceases to be consistent. Therefore, static non-final variables are strongly discouraged in EJBs.

7. If I throw a custom ApplicationException from a business method in Entity bean which is participating in a transaction, would the transaction be rolled back by container?

EJB Transaction is automatically rolled back only when a SystemException (or a subtype of it) is thrown.Your ApplicationExceptions can extend from javax.ejb.EJBException, which is a sub class of RuntimeException. When a EJBException is encountered the container rolls back the transaction. EJB Specification does not mention anything about Application exceptions being sub-classes of EJBException.You can tell container to rollback the transaction, by using setRollBackOnly on SessionContext/EJBContext object as per type of bean you are using.

8. Does Stateful Session bean support instance pooling?

Stateful Session Bean conceptually doesn't have instance pooling.

9. Can I map more than one table in a CMP?

no, you cannot map more than one table to a single CMP Entity Bean. CMP has been, in fact, designed to map a single table.

10. Can I invoke Runtime.gc() in an EJB?

You shouldn't. What will happen depends on the implementation, but the call will most likely be ignored.

11. Can a Session Bean be defined without ejbCreate() method?

The ejbCreate() methods is part of the bean's lifecycle, so, the compiler will not return an error because there is no ejbCreate() method. However, the J2EE spec is explicit: The home interface of a Stateless Session Bean must have a single create() method with no arguments, while the session bean class must contain exactly one ejbCreate() method, also without arguments.Stateful Session Beans can have arguments (more than one create method)

12. How to implement an entity bean which the PrimaryKey is an autonumeric field

The EJB 2 Spec (10.8.3 - Special case: Unknown primary key class) says that in cases where the PrimaryKeys are generated automatically by the underlying database, the bean provider must declare the findByPrimaryKey method to return java.lang.Object and specify the Primary Key Class as java.lang.Object in the Deployment Descriptor. When defining the Primary Key for the Enterprise Bean, the Deployer using the Container Provider's tools will typically add additional container-managed fields to the concrete subclass of the entity bean class. In this case, the Container must generate the Primary Key value when the entity bean instance is created (and before ejbPostCreate is invoked on the instance.)

13. What is clustering?

Clustering is grouping machines together to transparantly provide enterprise services. Clustering is an essential piece to solving the needs for today's large websites.The client does not know the difference between approaching one server or approaching a cluster of servers.

14. Is it possible to share an HttpSession between a JSP and EJB? What happens when I change a value in the HttpSession from inside an EJB?

You can pass the HttpSession as parameter to an EJB method, only if all objects in session are serializable. This has to be consider as "passed-by-value", that means that it's read-only in the EJB. If anything is altered from inside the EJB, it won't be reflected back to the HttpSession of the Servlet Container.

If my session bean with single method insert record into 2 entity beans, how can know that the process is done in same transaction (the attributes for these beans are Required)?

If your session bean is using bean-managed transactions, you can ensure that the calls are handled in the same transaction by : javax.transaction.UserTransaction tran= null;try{tran=ctx.getUserTransaction();tran.begin();myBeanHome1.create(....); myBeanHome2.create(...);tran.commit();}catch(...){}You may want to check if you're already running in a transaction by calling tran.getStatus().

15. When should I adopt BMP and when I should use CMP?

You can use CMP and BMP beans in the same application... obviously, a bean can be BMP or CMP, not both at the same time (they are mutually exclusive). There is a common approach that is normally used and considered a good one. You should start developing CMP beans, unless you require some kind of special bean, like multi-tables, that cannot be completely realized with a single bean. Then, when you realize that you need something more or that you would prefer handling the persistence (performanbce issue are the most common reason), you can change the bean from a CMP to a BMP.

Generic features of Java6

* XML processing and Web services: A host of cutting edge XML specifications have been incorporated into this Java release, including the Streaming API for XML (StAX), the Java API for XML Binding (JAXB) 2.0, amd the Java API for XML-based Web Services (JAX-WS) 2.0. The SDK also has built-in support for enhanced Web services metadata and APIs for processing XML digital signatures.

* Annotations-based programming: Annotations, a mechanism for embedding meta data into Java source code, were introduced in J2SE 5.0. In Java 6, the annotations model has been expanded to include new built-in annotation types and annotation processing APIs.


* Application client APIs: Several new APIs have been added to the SDK to support application client operations, including a long-awaited GIF image writer, the ability to access helper applications registered in the native desktop, native support for fast flash screen display, and support for system tray icons. Swing components have improved drag-and-drop capability and support for multi-threaded programming.


* JDBC 4.0: Some of the highlights of this updated specification include updated SQL and XML support, automatic driver loading, improved connection management, close association with JDBC RowSet implementations, and built-in annotations to make it easier for applications to manipulate data.


* Java compiler APIs: In response to a long-standing request from many Java tool vendors, Java SE 6 will includes a set of compiler APIs that allow a Java program to call a Java compiler and retrieve and examine the compiler's output in a structured fashion.


* Internationalization: Client processing updates allow for improved internationalization support, such as pluggable locales that allow existing Java Runtime Environments to be extended to support custom locales, APIs that transform Unicode strings into different canonical forms, and improvements to the ResourceBundle class. This release of the SDK will also support internationalized Internet domain names and URIs.


* Other features: A variety of other enhancements have been incorporated into Java SE 6, including masked command-line password entry, a framework for connecting to external scripting engines, and bidirectional variants of several Collections classes.