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 Many methods offer invariants, which can be any or all of the guarantees made about what the method can do, requirements about the required state of the object when the method is invoked, or guarantees about the state of the object when the method completes. For instance, the %
operator, which computes the remainder of a number, provides the invariant that
0 <= abs(a % b) <= abs(b), for all integers a, b where b != 0
example, a method of a Date
class might guarantee that 1 <= day_of_month <= 31
when the method exits.
Class invariants Many classes also offer invariants, which are guarantees made about the state of their objects' fields upon the completion of any of all their methods. For instanceexample, 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.
A fundamental principle of object-oriented design is that a subclass that extends a superclass must preserve the invariants provided by the superclass. Unfortunately, design principles fail to constrain attackers, who can (and do) construct malicious classes that extend benign classes and provide methods that deliberately violate the invariants of the benign classes.
For instanceSimilarly, 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. FurtherFurthermore, the a malicious subclass object can impersonate the immutable object while actually remaining mutable. Such malicious subclasses can then violate program invariants on which clients depend, consequently introducing security vulnerabilities.
As a result, classes with invariants on which other code depends should be declared final, thereby preventing malicious subclasses from subverting their invariants. Furthermore, immutable classes must be declared final.
. 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 Superclasses must permit extension by trusted subclasses while simultaneously preventing extension by untrusted code. Consequently, declaring Declaring such superclasses to be final is infeasible because it would prevent the required extension by trusted code. Such problems require careful design for inheritance. Consider two classes belonging to different protection domains: one is malicious and extends the other, which is trusted. Consider an object of the malicious subclass with a fully qualified invocation of a method defined by the trusted superclass, not overridden by the malicious class. In this case, the trusted superclass's permissions are examined to execute the method, and, as a result, the malicious object gets the method invoked inside the protection domain of the trusted superclass \[[Gong 2003|AA. Bibliography#Gong 03]\]. One commonly suggested solution approach is to place code at each point where the superclass can be instantiated to ensure check that the instance being created has the same type as the superclass. When the type is found to be that of a subclass rather than the superclass's type, the checking code performs a security manager check to ensure that malicious classes cannot misuse the superclass. This approach is insecure because it allows a malicious class to add a finalizer and obtain a partially initialized instance of the superclass. This attack is detailed in rule "OBJ05-J. Prevent access to partially initialized objects." Wiki Markup
For non-final classes, the method that performs the security manager check must be invoked as an argument to a private constructor to ensure that the security check is performed before any superclass's constructor can exit.
When the parent class has members that are declared private or are otherwise inaccessible to the attacker, the attacker must use reflection to exploit those members of the parent class. Declaring the parent class or its methods final prohibits this level of access.
A method which receives an untrusted, non-final input argument must beware that other methods or threads might modify the input object. Some methods attempt to prevent modification by making a local copy of the input object. This is insufficient because a shallow copy of an object can still allow it to refer to mutable sub-objects, which can still be modified by other methods or threads. Some methods go further and perform a deep copy of the input object. This mitigates the problem of modifiable sub-objects, but the method could still receive as an argument a mutable object that extends the input object class.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
)
This noncompliant code example uses the {{The Wiki Markup java.math.BigInteger
}} class. This class is non-final and consequently extendable. This 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|AA. Bibliography#Bloch 08]\ 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 | ||
---|---|---|
| ||
BigInteger msg = new BigInteger("123"); msg = msg.modPow(exp, m); // Always returns 1 // Malicious subclassing of java.math.BigInteger class BigInteger extends java.math.BigInteger { private intbyte[] valueba; public BigInteger(String str) { super(str); valueba = Integer.parseInt( str (new java.math.BigInteger(str)).toByteArray(); } public setValueBigInteger(intbyte[] valueba) { super(ba); this.valueba = valueba; } public @Override public java.math.BigInteger modPow(java.math.BigInteger exponent, java.math.BigInteger mvoid setValue(byte[] ba) { this.valueba = ((int) (Math.pow( this.value, exponent))) % m; ba; } @Override public byte[] toByteArray() { return thisba; } } |
This 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 Furthermore, the modPow()
method is subject to precision loss. (See rules "NUM00-J. Detect or prevent integer overflow," "NUM11-J. Check floating-point inputs for exceptional values," "NUM15-J. Ensure conversions of numeric types to narrower types do not result in lost or misinterpreted data," and "NUM17-J. Beware of precision loss when converting primitive integers to floating-point" for more information.) Any code that receives an object of this class and assumes that the object is immutable will have unexpected behavior. This is particularly important because the BigInteger.modPow()
method has several useful cryptographic applications.
Noncompliant Code Example (Security Manager)
...
This noncompliant code example installs proposes adding a security manager check in the constructor of the {{BigInteger}} 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 2007|AA. Bibliography#SCG 07]\2009]. It also compares class types, in compliance with rule "[OBJ06with OBJ09-J. Compare classes and not class names|OBJ12-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) { Class c = getClass();securityManagerCheck(); // java.lang.Object.getClass(), which is final // Confirm class type if (c != NonFinal.class) { } // Check the permission needed to subclass NonFinalBigInteger securityManagerCheck(); // throws a security exception if not allowed private void }securityManagerCheck() { // ... } } |
Unfortunately, throwing an exception from the constructor of a non-final nonfinal class is insecure because it allows a finalizer attack . (See rule "OBJ05-J. Prevent access to partially initialized objects.")(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 prevents 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 | ||
---|---|---|
| ||
final class BigInteger { package java.math; // ... } |
Compliant Solution (Class Sanitization)
Wiki Markup |
---|
When instances of non-final classes are obtained from untrusted sources, such instances must be used with care because their method calls might be overridden by malicious methods. This potential vulnerability can be mitigated by making defensive copies of the acquired instances prior to use. This compliant solution demonstrates this technique for a {{BigInteger}} argument \[[Bloch 2008|AA. Bibliography#Bloch 08]\]. |
Code Block | ||
---|---|---|
| ||
public static BigInteger safeInstance(BigInteger val) final class BigInteger { // create a defensive copy if it is not java.math.BigInteger if (val.getClass() != java.math.BigInteger.class) return new BigInteger(val.toByteArray()); return val; } |
...
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 Boolean value passed to a private constructor (as seen in rule "OBJ05OBJ11-J. Prevent access to partially initialized objects"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. Note that the security manager check is made without regard to whether the object under construction has the type of the parent class or the type of a subclass (whether trusted or not).unmigrated-wiki-markup
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|AA. Bibliography#SCG 09]\].
Code Block | ||
---|---|---|
| ||
package java.math; // ... public class BigInteger { public BigInteger(String str) { this( str, check( this.getClass())); // throws a security exception if not allowed } private BigInteger(String str, boolean securityManagerCheckdummy) { // regularRegular construction goes here } private static boolean check(Class c) { // Confirm class type if (c != BigInteger.class) { // Check the permission needed to subclass BigInteger securityManagerCheck(); // throws a security exception if not allowed } return true; } } |
Noncompliant Code Example (Data-Driven Execution)
Code in privileged blocks should be as simple as possible, both to improve reliability and also to ease security audits. Invocation of overridable methods permits modification of the code that is executed in the privileged context without modification of previously audited classes. Furthermore, calling overridable methods disperses the code over multiple classes, making it harder to determine which code must be audited. Malicious subclasses cannot directly exploit this issue because privileges are dropped as soon as unprivileged code is executed. Nevertheless, maintainers of the subclasses might unintentionally violate the requirements of the base class. For example, even when the base class's overridable method is thread-safe, a subclass might provide an implementation that lacks this property, leading to security vulnerabilities.
This noncompliant code example invokes an overridable getMethodName()
method in the privileged block using the reflection mechanism.
Code Block | ||
---|---|---|
| ||
public class MethodInvoker {
public void invokeMethod() {
AccessController.doPrivileged(new PrivilegedAction<Object>() {
public Object run() {
try {
Class<?> thisClass = MethodInvoker.class;
String methodName = getMethodName();
Method method = thisClass.getMethod(methodName, null);
method.invoke(new MethodInvoker(), null);
} catch (Throwable t) {
// Forward to handler
}
return null;
}
});
}
String getMethodName() {
return "someMethod";
}
public void someMethod() {
// ...
}
// Other methods
}
|
A subclass can override getMethodName()
to return a string other than someMethod
. If an object of such a subclass runs invokeMethod()
, control flow will divert to some method other than someMethod
.
Compliant Solution (Final)
This compliant solution declares the getMethodName()
method final so that it cannot be overridden.
Code Block | ||
---|---|---|
| ||
final String getMethodName() {
// ...
}
|
Alternative approaches that prevent overriding of the getMethodName()
method include declaring it as private or declaring the enclosing class as final.
Compliant Solution (Disallow Polymorphism)
This compliant solution specifically invokes the correct getMethodName()
, preventing diversion of control flow.
Code Block | ||
---|---|---|
| ||
public void invokeMethod() {
AccessController.doPrivileged(new PrivilegedAction<Object>() {
public Object run() {
try {
Class<?> thisClass = MethodInvoker.class;
String methodName = MethodInvoker.this.getMethodName();
Method method = thisClass.getMethod(methodName, null);
method.invoke(new MethodInvoker(), null);
} catch (Throwable t) {
// Forward to handler
}
return null;
}
});
}
|
Risk Assessment
Permitting a non-final class or method to be inherited without checking the class instance allows a malicious subclass to misuse the privileges of the class.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
OBJ00-J | medium | likely | medium | P12 | L1 |
Bibliography
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="688ea60c-4a1b-4172-bf2e-7c9081876cda"><ac:plain-text-body><![CDATA[ | [[API 2006 | AA. Bibliography#API 06]] | Class BigInteger | ]]></ac:plain-text-body></ac:structured-macro> |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="3f9a902e-85d4-4b9b-84a3-30e49b9d07a6"><ac:plain-text-body><![CDATA[ | [[Bloch 2008 | AA. Bibliography#Bloch 08]] | Item 1: "Consider static factory methods instead of constructors" | ]]></ac:plain-text-body></ac:structured-macro> |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="809d0c8c-8200-48c8-9783-24c501d2c923"><ac:plain-text-body><![CDATA[ | [[Gong 2003 | AA. Bibliography#Gong 03]] | Chapter 6: "Enforcing Security Policy" | ]]></ac:plain-text-body></ac:structured-macro> |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="e5ddb139-7167-41e6-900b-4578a30d0367"><ac:plain-text-body><![CDATA[ | [[Lai 2008 | AA. Bibliography#Lai 08]] | Java Insecurity: Accounting for Subtleties That Can Compromise Code | ]]></ac:plain-text-body></ac:structured-macro> |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="216ff6f6-6f49-4bb1-9bc8-97ed21c10527"><ac:plain-text-body><![CDATA[ | [[McGraw 1999 | AA. Bibliography#McGraw 99]] | Chapter Seven Rule 3: "Make Everything Final, Unless There's a Good Reason Not To" | ]]></ac:plain-text-body></ac:structured-macro> |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="d68634cb-48f9-48e9-ba08-66149e372c14"><ac:plain-text-body><![CDATA[ | [[SCG 2007 | AA. Bibliography#SCG 07]] | Guideline 1-2 "Limit the extensibility of classes and methods" | ]]></ac:plain-text-body></ac:structured-macro> |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="daa574cb-77c8-48f8-9ab8-a820bdec1e6e"><ac:plain-text-body><![CDATA[ | [[SCG 2009 | AA. Bibliography#SCG 09]] | Secure Coding Guidelines for the Java Programming Language, version 3.0 | ]]></ac:plain-text-body></ac:structured-macro> |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="393b89db-295e-403b-8db7-b38944d178ff"><ac:plain-text-body><![CDATA[ | [[Ware 2008 | AA. Bibliography#Ware 08]] | ]]></ac:plain-text-body></ac:structured-macro> |
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] |
...
04. Object Orientation (OBJ) 04. Object Orientation (OBJ) OBJ01-J. Declare data members as private and provide accessible wrapper methods