Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: changed CS into NCE

...

At all points that the class can be instantiated, there must be checks to ensure that the instance being created has the same type as the class. If the type is found to be that of a subclass , instead of the non-final public superclass's type, a security manager check must be performed to ensure that malicious classes cannot misuse the class.

The use of reflection is necessary if to exploit the non-final class if it has members that are declared private or are otherwise inaccessible to the attacker. Declaring the class or its methods final prohibits this level of access.

...

In this noncompliant code example, a malicious class can extend the public non-final class, NonFinal. As a result, it can call any of its accessible instance methods and access its protected fields.

Code Block
bgColor#FFcccc
public class NonFinal {
  public NonFinal() {
    // ...   
  }
}

...

Noncompliant Code Example

Wiki Markup
This noncompliant compliantcode solutionexample installs a security manager check in the constructor of the non-final class. Access is denied if the security manager detects that a subclass without the requisite permissions, is trying to instantiate the superclass. \[[SCG 07|java:AA. Java References#SCG 07]\]

Code Block
bgColor#ccccff#FFcccc
public class NonFinal {
  public NonFinal() {
    // Invoke java.lang.Object.getClass to get class instance
    Class c = getClass();
    // Confirm class type
    if (c != NonFinal.class) {
      // Check the permission needed to subclass NonFinal
      securityManagerCheck(); // throws a security exception if not allowed
    }
  // ...   
  }
}

However, throwing an exception from the constructor is a non-final class is insecure because it allows a finalizer attack (see OBJ04-J. Do not allow partially initialized objects to be accessed).

This noncompliant code example complies with OBJ06-J. Compare classes and not class names because it compares It is critical to compare the class types and not the class names (OBJ06-J. Compare classes and not class names).class names.

Compliant Solution

Irrespective of whether it is a trusted instance or an untrusted one, install a security manager check using the technique described in OBJ04-J. Do not allow partially initialized objects to be accessed.

Code Block
bgColor#ccccff

public class NonFinal {
  public NonFinal() {
    this(securityManagerCheck()); // throws a security exception if not allowed
    // ...
  }
  
  private NonFinal(boolean securityManagerCheck) {
    // No statements required	  
  }

  private static boolean securityManagerCheck() {
    // Perform security check	  
  }
}

Risk Assessment

Allowing 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.

...