...
This noncompliant code example installs 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() {
// ...
}
}
|
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 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 | ||
---|---|---|
| ||
package java.math;
// ...
final class 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 | ||
---|---|---|
| ||
package java.math;
// ...
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;
}
}
|
...