Java security is an overwhelming issue. For a truly secure application, you need to prevent hackers from entering the system, and you need to ensure that code safeguards security if a hacker does break in. Moreover, there is no room for error. If you anticipate and prevent hundreds of security vulnerabilities but overlook just one, a hacker can still wreak havoc on your system.
This article introduces some fundamental strategies for writing Java code that remains secure if a hacker manages to enter the system. Essentially, writing secure code requires a shift in thinking. Instead of worrying about whether code works correctly, you need to anticipate all of the ways that it can be exploited, then ensure that security is maintained in every possible worst case scenario. This, of course, is a monumental task, and there is no silver bullet for security. Several strategies for developing Java code that resists many common attacks are:
Rule 1: Avoid using inner classes
Java bytecode has no concept of inner classes, so the compiler translates inner classes into ordinary classes that are accessible to any code in the same package. An inner class gets access to the fields of the enclosing outer class - even if these fields are declared private - and the inner class is translated into a separate class. To let this separate class access the fields of the outer class, the compiler silently changes these fields' scope from private to package. As a result, when you use inner classes, not only is the inner class exposed, but the compiler is silently overruling your decision to make some fields private.
Note: If you really need to use inner classes, be sure to make all inner classes private.
Here is sample code that violates this rule:
package examples.rules.security;
public class AUIC {
private class AUIC2 { // VIOLATION
}
}
To correct this code, make the class AUIC2 a top-level class as follows:
public class AUICF {
}
class AUIC2 { // FIXED
}
Rule 2: Avoid comparing class objects by name
This rule prohibits comparing class objects with the getName() method. More than one class in a running JVM may have the same name. As a result, a hacker can create a class with malicious code and give it the same name as your class. When you compare classes by name, the comparison would not recognize this difference. When you compare classes by object equality, the difference would be detected.
Here is sample code that violates this rule:
package examples.rules.security;
public class CMP {
public boolean sameClass (Object o) {
Class thisClass = this.getClass();
Class otherClass = o.getClass();
return (thisClass.getName() == otherClass.getName()); //VIOLATION
}
}
To correct this code, modify it as follows to directly compare thisClass and otherClass for equality:
package examples.rules.security;
public class CMP {
public boolean sameClass (Object o) {
Class thisClass = this.getClass();
Class otherClass = o.getClass();
return (thisClass == otherClass); // FIXED
}
ยท}
Rule 3: Make your classes noncloneable
This rule requires that you make classes nonclone-able by defining a final method clone that will throw a java.lang.CloneNotSupportedException(). For example:
public final Object clone() throws java.lang.CloneNotSupportedException {
throw new java.lang.CloneNotSupportedException();
}
Java's object cloning mechanism can allow an attacker to manufacture new instances of classes that you define, without executing any of the class's constructors. Even if your class is not cloneable, the attacker can define a subclass of your class, make the subclass implement java.lang.Cloneable, then create new instances of your class by copying the memory images of existing objects. By defining the above clone method, you'll prevent such attacks.
Note: If you really need to make your classes cloneable, be sure to make your clone() method final.
Rule 4: Make your classes nonserializable
This rule requires that if you want to prevent access to the internal state of your objects, make your class nonserializable. If you don't, your objects can be serialized into readable byte arrays. As a result, hackers can view the objects' full internal state, including private fields and the internal states of referenced objects.
To make a class nonserializable, define the final method writeObject() that throws an IOException. For example:
private final void writeObject (ObjectInputStream in)
|| throws java.io.IOException {
throw new java.io.IOException ("Class cannot be serialized");
}
This method is declared final so that a subclass defined by a hacker adversary cannot override it.
Note: If you need to make a class serializable, follow these tips to safeguard security:
Rule 5: Do not depend on package scope
This rule prohibits classes with public or package-private access. An attacker can simply add another class to your package and then access package-private fields that were supposed to be hidden.
To correct violations of this rule, modify code so that it does not rely on package-level access. Give your classes, methods, and fields the most restricted access possible. If this is not an option, you might want to use package sealing, which can prevent hackers from adding classes to a package that is in a "sealed" JAR file. Package sealing is discussed at http://java.sun.com/j2se/1.3/docs/guide/extensions/spec.html#sealing.
Rule 6: Avoid returning references to mutable objects and, if necessary, clone the mutable object before returning a reference to it
Mutable objects are objects whose states can be changed. When you return a reference to a mutable object, the caller can change the state of that object; if that object is used in the class later on, it will be using a different state of the object, which would affect the internals of the class.
Note that arrays are mutable (even if array contents are not mutable), so don't return a reference to an internal array with sensitive data.
Here is sample code that violates this rule:
// fDate is a Date Field.
// The caller of this method can change the Date object and
// affect the internals of this class.
public Date getDate() {
return fDate;
}
To correct this code, modify it to return a defensive copy of the field as follows:
public Date getDate() {
return new Date(fDate.getTime());
}
Now, the caller of this method can change the returned Date object without affecting the internals of this class.
Rule 7: Make methods, fields, and classes private; if there's a reason one should not be private, document that reason
If a class, method, or variable is not private, hackers could use it as a potential entry point. If there is a good reason why a method, field, or class should not be private, it does not need to be private, but that reason should be clearly documented.
Rule 8: Make all classes and methods final; if there is a reason one should not be final, document that reason
If a class or method is not final, hackers could try to extend it in an unsafe way. If there is a good reason why a method or class should not be final, it does not need to be final, but that reason should be clearly documented.
Coding Defensively to Prevent Hackers from Moving Through the Code
Another way to boost code security is to code defensively by implementing defensive software firewalls and validating user/external inputs.
Defensive software firewalls have many uses, one of which is to ensure that any hacker who manages to access your code cannot move through critical code sections. A defensive software firewall is a point in the logical flow of a program where the validity of logical constraints is checked. If a constraint specified in a firewall is satisfied, execution proceeds. If the constraint is violated, the firewall triggers, generates an appropriate error message, and possibly takes damage-control actions (such as stopping execution) or diagnostic actions (such as turning on debugging information). Firewalls should not alter the execution flow of a program unless they are triggered, and they should have either no effect or a negligible effect on the performance of the production version.
Note that these firewalls are not related to the firewalls placed around Internet connections. The concept discussed here relates solely to code construction. If designed carefully, these firewalls serve the same purpose as physical firewalls: they can contain a dangerous event and prevent it from causing a complete disaster.
In Java, firewalls can be implemented by adding assertions that say that if the program reaches a critical point without executing the expected operations, the program should throw exceptions, shut down, or perform another defensive action. Hackers often access code from a path that you didn't know existed or did not expect to be taken. By using firewalls to check whether critical program points were reached in unexpected ways, you can identify many attempted security breaches and stop hackers from entering and manipulating your most critical code.
To implement these firewalls with assertions, first determine the critical points in your code, then add assertions so that when each critical point is reached, the call stack is checked to verify that the program reached that critical point by executing the expected sequence of operations. When a critical point is reached through an unexpected sequence of operations, the program should throw an exception and terminate. Once this firewall is implemented, you will have a barrier that prevents hackers from using "backdoor paths" to gain entry into your most critical code.
For example, the code in Listing 1 could be added to verify the call stack before modifying a field in the database. In this case, the assertTrue method is assumed to accept an error message and a boolean. If the boolean is false, the message with an exception will be reported and the program will terminate.
Another defensive coding strategy is to validate all user/external input. When security is an issue, you should always worry about external inputs. If users manage to submit the "right" inputs, they could gain access to program details you hoped to keep private, prompt the application to crash or enter an unstable state, or access and modify the database. These inputs could be created by hackers trying to design inputs that cause a security breach (for example, by applying a technique known as SQL injection, where hackers submit inputs designed to create a strategic SQL string, such as a string that disables password checking, a string that adds a new account, etc.). Moreover, these inputs could also be submitted by well-meaning users who entered information incorrectly (as a result of a typo or a copy/paste error) or who simply misunderstood what type or format of information they were supposed to add.
By validating all external inputs, you can identify improper or malicious inputs as they are submitted and then prevent the program from using those inputs. The performance impact and user inconvenience will be minimal, especially if you consider the potential impact and inconvenience of having the application unavailable or functioning incorrectly because a hacker designed and successfully submitted the "perfect" input.
User input validation could be performed with assertions, Design by Contract, or if statements. For example, say you have the following method that accepts a filename as input from a user, but does not verify whether the filename represents a valid file.
void method (String filename) {
System.exec("more " + filename);
}
If the user passes filename = "joe; /bin/rm -rf /*", the execution of that method could delete files. If the application runs as a regular user, the spawned process (rm -rf) inherits its privileges, which means that the user can remove only the files for which he or she has modify permissions. If the application runs as root, the spawned process will inherit root privileges and all files on the hard drive can be removed.
To prevent hackers from performing such disastrous deletions, this method should verify whether the entered filename represents a valid file. This verification could be implemented as a simple check using an if statement as follows:
void method (String filename){
if (new File(filename).exists()){
System.exec("more " + filename);
}
}
Expose and Correct as Many Bugs as Possible
Every bug that you are not aware of could present hackers with an opportunity to exploit your system. Each bug represents unexpected program behavior; if the program is not behaving as you expect, how can you rest assured that it is not providing hackers with a way to manipulate your code?
Java code that throws unexpected, uncaught runtime exceptions is especially ripe for security breaches. Imagine that when one of your methods receives an input that you did not expect, it throws an uncaught runtime exception that's thrown up several layers in your call stack before it's handled, and the handling code exposes some critical Java code. If a hacker can produce this exception (for example, by flooding that method with a wide variety and range of inputs), he or she can then learn about the critical code.
The best way to expose these types of problems is to perform what is known as "white-box testing" or "construction testing." This testing involves designing inputs that thoroughly exercise a class's public methods, then examines how the code handles the test inputs.
For example, if you wanted to check whether uncaught runtime exceptions could cause a class to expose critical code in methods you think are protected, you would flood the class's exposed methods with a wide variety of inputs to try to flush out all possible exceptions, examine how the class responds to each exception, and modify the code so that it does not throw dangerous exceptions.
If you find errors during the testing phase, you have the opportunity to fix the problem before an actual security breach occurs. In fact, this type of testing is best performed at the unit level because testing each unit (each class) in isolation is the best way to expose the maximum number of errors. Because unit testing brings you much closer to the errors, it helps you detect errors that application-level testing does not always find. Take a closer look at Figures 1 and 2 to see how unit testing does this.
Figure 1 shows a model of testing an application containing many units. The application is represented by the large oval, and the units it contains are represented by the smaller ovals; external arrows indicate inputs; starred regions show potential errors.
To find errors in this model, you modify inputs so that interactions between units force some units to hit the potential errors. This is incredibly difficult. Imagine standing at a pool table with a set of billiard balls in a triangle at the middle of the table, and having to use a cue ball to move the triangle's center ball into a particular pocket - with one stroke. This is how difficult it can be to design an input that finds an error within an application. As a result, if you rely only on application testing, you might never reach many of your application's units, let alone uncover the errors they contain.
As Figure 2 illustrates, testing at the unit level offers a more effective way to find errors. When you test one unit apart from all other units, reaching potential errors is much easier because you are much closer to those errors. The difficulty of reaching the potential errors when the unit is tested independently is comparable to the difficulty of hitting one billiard ball into a particular pocket with a single stroke.
To expose the maximum number of errors that pose security threats, you need to exercise the code as fully as possible. Unit-level testing is the ideal mechanism for doing this.
Design by Contract
Design by Contract (DbC) can be used to validate user inputs as well as to implement firewall-like restrictions that prevent hackers from moving through the application. DbC was designed to express and enforce contracts between a piece of code and its caller; these contracts specify what the callee expects and what the caller can expect.
Typically, DbC is implemented by expressing the code's implicit contracts in terms of assertions. Three types of conditions commonly used to create contracts are:
To learn more about DbC, see the following resources:
Conclusion
Following the strategies mentioned in this article will protect your Java code from many common security attacks. However, these strategies should be viewed as the beginning of a thorough security strategy, not as a security panacea. You need to anticipate and protect every possible security vulnerability because just one vulnerability can allow a skilled or lucky hacker to steal classified information or make your application unavailable. To ensure security, you need to learn how to identify and repair additional security vulnerabilities; some places to start are: