Java classes and methods may have invariants. An invariant is a property that is assumed to be true at certain points during program execution but is not formally specified as true. Invariants may be used in assert
statements or may be informally specified in comments.
Method invariants can include guarantees made about what the method can do, requirements about the state of the object when the method is invoked, or guarantees about the state of the object when the method completes. For example, a method of a Date
class might guarantee that 1 <= day_of_month <= 31
when the method exits.
Class invariants are guarantees made about the state of their objects' fields upon the completion of any of their methods. For example, classes whose member fields may not be modified once they have assumed a value are called immutable classes. An important consequence of immutability is that the invariants of instances of these classes are preserved throughout their lifetimes.
Similarly, classes can rely on invariants to properly implement their public interfaces. These invariants might relate to the state of member fields or the implementation of member methods. Generally, classes can rely on encapsulation to help maintain these invariants, for example, by making member fields private. However, encapsulation can be incompatible with extensibility. For example, a class designer might want a method to be publicly accessible yet rely on the particulars of its implementation when using it in another method within the class. In this case, overriding the method in a subclass can break the internal invariants of the class. Extensibility consequently carries with it two significant risks: a subclass can fail to satisfy the invariants promised to clients by its superclass, and it can break the internal invariants on which the superclass relies. For example, an immutable class that lacks the final
qualifier can be extended by a malicious subclass that can modify the state of the supposedly immutable object. Furthermore, a malicious subclass object can impersonate the immutable object while actually remaining mutable. Such malicious subclasses can violate program invariants on which clients depend, consequently introducing security vulnerabilities. Note that the same can be said for a benign subclass that mistakenly supports mutability. These risks relate to both benign and malicious development.
To mitigate these risks, by default classes should be declared final unless there is a definite need for the class to be extensible. In that case, developers must carefully design the class with extensibility in mind. As a specific instance of this recommendation, classes that are designed to be treated as immutable either must be declared final or must have all of their member methods and fields declared final or private.
In systems where code can come from mixed protection domains, some superclasses might want to permit extension by trusted subclasses while simultaneously preventing extension by untrusted code. Declaring such superclasses to be final is infeasible because it would prevent the required extension by trusted code. One commonly suggested approach is to place code at each point where the superclass can be instantiated to check that the class being instantiated is either the superclass itself or a trustworthy subclass. However, this approach is brittle and is safe only in Java SE 6 or higher (see OBJ11-J. Be wary of letting constructors throw exceptions for a full discussion of the issues involved).
Noncompliant Code Example (BigInteger
)
The java.math.BigInteger
class is itself an example of noncompliant code. It is nonfinal and consequently extendable, which can be a problem when operating on an instance of BigInteger
that was obtained from an untrusted client. For example, a malicious client could construct a spurious mutable BigInteger
instance by overriding BigInteger
's member functions [Bloch 2008].
The following code example demonstrates such an attack:
Code Block | ||
---|---|---|
| ||
// Malicious subclassing of java.math.BigInteger
class BigInteger extends java.math.BigInteger {
private byte[] ba;
public BigInteger(String str) {
super(str);
ba = (new java.math.BigInteger(str)).toByteArray( |
Wiki Markup |
---|
A nonfinal class or method that is not meant to be inherited can be overridden by an attacker if it is not declared as {{final}} \[3\]. |
Wiki Markup |
---|
If inheritance is to be limited to trusted implementations for a public, nonfinal class, then the class type should be confirmed before creating the instance at each place where an instance of the nonfinal class can be created. A SecurityManager check should be enforced on detecting a subclass (Chapter 6 of \[2\]). |
A nonfinal class can be subverted simply by declaring a malicious class that inherits from the nonfinal class, which implies that there is no need for reflection. However, reflection is necessary if the nonfinal class is private or otherwise inaccessible to the attacker.
Noncompliant Code Example
In this example, an attacker can easily create an instance and override methods of class BankOperation
. This example also assumes the absence of appropriate Security Manager checks.
Code Block | ||
---|---|---|
| ||
class BankOperation { //The account balance has already been retrieved from the database and stored in the foll variable private Integer balance = 5000; public BankOperation() { //invoke java.lang.Object.getClass to get class instance Class clazz = getClass(); //shows the class of the instantiated object System.out.println(clazz); } public void getBalance(BigInteger(byte[] ba) { System.out.println("The current balance is: $" + balance)super(ba); this.ba = ba; } } public //This class has been written by the attacker public class SubClass extends BankOperation {void setValue(byte[] ba) { this.ba = ba; } @Override public voidbyte[] getBalancetoByteArray() { //The attacker can change his account balance to any value he wants. Integer modifiedBalance = 0; //to read the new balance from the attacker InputStreamReader input = new InputStreamReader(System.in); Field balance=null; BufferedReader reader = new BufferedReader(input); System.out.print("Enter balance: "); try { modifiedBalance = Integer.parseInt(reader.readLine()); //this gets the private field from the superclass balance = this.getClass().getSuperclass().getDeclaredField("balance"); //this changes the accessibility so that field can now be accessed if (!Modifier.isPublic(balance.getModifiers())){ balance.setAccessible(true); } //retrieve the original balance System.out.println("Original Balance: $"+balance.get(this)); //change the balance balance.set(this, modifiedBalance); System.out.println("New Balance: $"+balance.get(this)); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] argsreturn ba; } } |
Unlike the benign BigInteger
class, this malicious BigInteger
class is clearly mutable because of the setValue()
method. Any code that receives an object of this class and assumes that the object is immutable will behave unexpectedly, as shown by the following code:
Code Block | ||
---|---|---|
| ||
BigInteger bi = new BigInteger("123");
bi.setValue((new BigInteger("246")).toByteArray());
System.out.println(new BigInteger(bi.toByteArray())); |
This code prints: "246", which shows that the value of the supposedly immutable BigInteger bi
has been changed.
OBJ01-J. Limit accessibility of fields points out that invariants cannot be enforced for mutable objects. TSM03-J. Do not publish partially initialized objects describes object construction and visibility issues specific to mutable objects, and CON50-J. Do not assume that declaring a reference volatile guarantees safe publication of the members of the referenced object and CON52-J. Document thread-safety and use annotations where applicable discuss some concurrency issues associated with mutable objects.
Violation of this recommendation can be mitigated by treating objects from untrusted sources as potentially malicious subclasses, as directed by OBJ06-J. Defensively copy mutable inputs and mutable internal components. Complying with that rule protects you from the consequences of violating this recommendation.
This example is particularly important because the BigInteger
type has several useful cryptographic applications.
Noncompliant Code Example (Security Manager)
This noncompliant code example proposes adding a security manager check in the constructor of the java.math.BigInteger
class. The security manager denies access when it detects that a subclass without the requisite permissions is attempting to instantiate the superclass [SCG 2009]. It also compares class types, in compliance with OBJ09-J. Compare classes and not class names. Note that this check does not prevent malicious extensions of BigInteger
; it instead prevents the creation of BigInteger
objects from untrusted code, which also prevents creation of objects of malicious extensions of BigInteger
.
Code Block | ||
---|---|---|
| ||
package java.math; // ... public class BigInteger { public BigInteger(String str) { securityManagerCheck(); // ... } // Check the permission needed to subclass BigInteger // throws a security exception if not allowed private void securityManagerCheck() { SubClass subclass = new SubClass(); subclass.getBalance();// ... } } |
Unfortunately, throwing an exception from the constructor of a nonfinal class is insecure because it allows a finalizer attack (see OBJ11-J. Be wary of letting constructors throw exceptions). Furthermore, since BigInteger
is Serializable
, an attacker could bypass the security check by deserializing a malicious instance of BigInteger
. For more information on proper deserialization, see the rule SER04-J. Do not allow serialization and deserialization to bypass the security manager.
Compliant Solution (Final)
This compliant solution limits the extensibility of the sensitive class by using the final
keywordprevents creation of malicious subclasses by declaring the immutable java.math.BigInteger
class to be final. Although this solution would be appropriate for locally maintained code, it cannot be used in the case of java.math.BigInteger
because it would require changing the Java SE API, which has already been published and must remain compatible with previous versions.
Code Block | ||
---|---|---|
| ||
package java.math; // ... final class BigInteger BankOperation{ // ... } |
In case the class needs to be extended, permissions should be checked in case a subclass is detected during construction so that malicious implementations are blocked.
Compliant Solution
Wiki Markup |
---|
Preferring static factory methods over {{public}} or {{protected}} constructors also helps limit class extensibility. \[[Bloch 08|java:AA. Java References#Bloch 08]\] |
Compliant Solution (Java SE 6, Public and Private Constructors)
This compliant solution invokes a security manager check as a side effect of computing the Boolean value passed to a private constructor (as seen in OBJ11-J. Be wary of letting constructors throw exceptions). The rules for order of evaluation require that the security manager check must execute before invocation of the private constructor. Consequently, the security manager check also executes before invocation of any superclass's constructor.
This solution prevents the finalizer attack; it applies to Java SE 6 and later versions, where throwing an exception before the java.lang.Object
constructor exits prevents execution of finalizers [SCG 2009].
Code Block | ||
---|---|---|
| ||
package java.math;
// ...
public class BigInteger {
public BigInteger(String str) {
this(str, check());
}
private BigInteger(String str, boolean dummy | ||
Code Block | ||
| ||
class BankOperation { public static void factoryMethod() { // ... Regular construction goes here } } |
Compliant Solution
A third solution is to provide a private
constructor.
Code Block | ||
---|---|---|
| ||
class BankOperation private static boolean check() { private BankOperationsecurityManagerCheck(); { // ...return true; } } |
Risk Assessment
Allowing a nonfinal class or method to be inherited without checking the class instances allows an attacker to exploit it.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
OBJ33-J | medium | likely | medium | P12 | L1 |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website
Reference:
Wiki Markup |
---|
\[[SCG 07|java:AA. Java References#SCG 07]\] Secure Coding Guidelines for the Java Programming Language
\[[Bloch 08|java:AA. Java References#Bloch 08]\] Item 1: "Consider static factory methods instead of constructors" |
Automated Detection
This recommendation is not checkable because it depends on factors that are unspecified in the code, including the invariants upon which the code relies and the necessity of designating a class as extensible, among others. However, simple statistical methods might be useful to find codebases that violate this recommendation by checking whether a given codebase contains a higher-than-average number of classes left nonfinal.
Related Guidelines
Guideline 4-5 / EXTEND-5: Limit the extensibility of classes and methods |
Bibliography
[API 2006] | Class |
Item 15: "Minimize mutability" Item 17, "Design and Document for Inheritance or Else Prohibit It" | |
Chapter 6, "Enforcing Security Policy" | |
[Lai 2008] | Java Insecurity, Accounting for Subtleties That Can Compromise Code |
Chapter 7, Rule 3, Make everything final, unless there's a good reason not to | |
[SCG 2009] | Guideline 4-5 / EXTEND-5: Limit the extensibility of classes and methods |
[Ware 2008] |
...
OBJ32-J. Do not allow partially initialized objects to be accessed 06. Object Orientation (OBJ) OBJ34-J. Compare classes and not class names