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
...
The java.math.BigInteger
class is itself an example of noncompliant code. It 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].
The following code example demonstrates such an attack.
...
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]. It also compares class types, in compliance with rule 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
.
...
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 | ||
---|---|---|
| ||
public class BigInteger { public BigInteger(String str) { this(str, check()); } private BigInteger(String str, boolean dummy) { // regular construction goes here } private static boolean check() { securityManagerCheck(); return true; } } |
...
Secure Coding Guidelines for the Java Programming Language, Version 3.0 | Guideline 1-2. Limit the extensibility of classes and methods |
Bibliography
[API 2006] | Class BigInteger |
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 Seven, Rule 3. Make everything final, unless there's a good reason not to | |
...
Rule 05: Object Orientation (OBJ) Rule 05: Object Orientation (OBJ) OBJ01-J. Declare data members as private and provide accessible wrapper methods