...
For instance, 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 resultTo prevent misuse, 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.
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.
...
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 that receives an untrusted, non-final nonfinal input argument must beware that other methods or threads might concurrently 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-objectssubobjects, which that can still be modified by other methods or threads. Some methods go further and perform a deep copy of the input object. This Although this mitigates the problem of modifiable sub-objectssubobjects, but the method could still receive as an argument a mutable object that extends the input object class and provides inadequate copy functionality.
Noncompliant Code Example (BigInteger
)
...
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 int value; public BigInteger(String str) { super(str); value = Integer.parseInt(str); } public void setValue(int value) { this.value = value; } @Override public java.math.BigInteger modPow( java.math.BigInteger exponent, java.math.BigInteger m) { this.value = ((int) (Math.pow(this.doubleValue(), exponent.doubleValue()))) exponent.doubleValue()))) % m.intValue(); return this; } } |
This malicious BigInteger
class is clearly mutable because of the setValue()
method. Furthermore, the modPow()
method is subject to precision loss. (See rules " NUM00-J. Detect or prevent integer overflow, " " NUM08-J. Check floating-point inputs for exceptional values, " " NUM12-J. Ensure conversions of numeric types to narrower types do not result in lost or misinterpreted data, " and "NUM13-J. Avoid loss of precision 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 behaviorbehave unexpectedly. This is particularly important because the BigInteger.modPow()
method has several useful cryptographic applications.
...
Wiki Markup |
---|
This noncompliant code example installs a security manager check in the constructor of the {{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|AA. Bibliography#SCG 09]\]. It also compares class types, in compliance with rule "[OBJ09-J. Compare classes and not class names]." |
Code Block | ||
---|---|---|
| ||
public class BigInteger { public BigInteger(String str) { Class c = getClass(); // java.lang.Object.getClass(), which is final //Class Confirmc class type= getClass(); // Confirm class type if (c != NonFinaljava.math.BigInteger.class) { // Check the permission needed to subclass NonFinalBigInteger securityManagerCheck(); // throws a security exception if not allowed securityManagerCheck(); } // ... } } |
Unfortunately, throwing an exception from the constructor of a non-final class is insecure because it allows a finalizer attack. (See rule OBJ11-J. Be wary of letting constructors throw exceptions.)
...
Compliant Solution (Class Sanitization)
Wiki Markup |
---|
WhenThe instances of non-finalnonfinal classes are obtained from untrusted sources, such instances must be used with care because their method callsmethods 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) { // 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; } |
The rules "Rules OBJ06-J. Defensively copy mutable inputs and mutable internal components" and "OBJ04-J. Provide mutable classes with copy functionality to allow passing instances to untrusted code safely" discuss defensive copying in great depth.
...
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 rule 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. 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).
...
Code Block | ||
---|---|---|
| ||
public class BigInteger { public BigInteger(String str) { // throws a security exception if not allowed this(str, check(this.getClass())); // throws a security exception if not allowed } private BigInteger(String str, boolean securityManagerCheck) { // regular construction goes here } private static boolean check(Class c) { // Confirm class type if (c != java.math.BigInteger.class) { // Check the permission needed to subclass BigInteger securityManagerCheck(); // throws a security exception if not allowed } securityManagerCheck(); } 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.
...
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 a method other than someMethod()
.
Compliant Solution (Final)
...
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 nonfinal class or method to be inherited without checking the class instance allows a malicious subclass to misuse the privileges of the class.
...
Secure Coding Guidelines for the Java Programming Language, Version 3.0 | Guideline 1-2. Limit the extensibility of classes and methods |
...
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="8a3f6cdd64704535-006b496a-41df4eb7-85e4be93-aebd8d6a4248540df33f4f99"><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="8f87f27e9a2ed05c-288ce7a0-41b14089-b0be8cfc-18384770f272565a9cd35bf8"><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="1a794e2b72720043-eb6c175f-453e40d5-b29b9435-7537651b80592b58a2511775"><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="f3198cf951deac69-1f07cd9c-4490418c-9fe89a2e-2c94dc6155811de26abd795b"><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="0c9b3663d8f81c99-5e762466-4f8547f8-8bd9b427-6fd5e00832926ea10ce84157"><ac:plain-text-body><![CDATA[ | [[McGraw 1999 | AA. Bibliography#McGraw 99]] | Chapter Seven, Rule 3: "Make Everything Final, Unless There. Make everything final, unless there's a Good Reason Not To" 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="8da2ff420dc85509-922d1329-4ff44a26-8fd78628-19d311a65cae2e940999169f"><ac:plain-text-body><![CDATA[ | [[Ware 2008 | AA. Bibliography#Ware 08]] | ]]></ac:plain-text-body></ac:structured-macro> |
...