Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Increasing the accessibility of overridden or hidden methods permits a malicious subclass to offer wider access to the restricted method than was originally intended. Consequently, programs must override methods only when necessary and must declare methods final whenever possible to prevent malicious subclassing. When methods cannot be declared final, programs must refrain from increasing the accessibility of overridden methods.

The access modifier of an overriding or hiding method must provide at least as much access as the overridden or hidden method (The Java Language Specification, §8.4.8.3, "Requirements in Overriding and Hiding" [JLS 20052015]). The following are table lists the allowed accesses:

Overridden/Hidden Method Modifier

Overriding/Hiding Method Modifier

public

public

protected

protected or public

default

default or protected or public

private

Cannot be overridden

...

This noncompliant code example demonstrates how a malicious subclass Sub can both override the doLogic() method of the superclass and increase the accessibility of the overriding method. Any user of Sub can invoke the doLogic method because the base class Super defines it to be protected, consequently allowing class Sub to increase the accessibility of doLogic() by declaring its own version of the method to be public.

Code Block
bgColor#FFcccc
class Super {
  protected void doLogic() {
    System.out.println("Super invoked");
  }
}

public class Sub extends Super {
  public void doLogic() {
    System.out.println("Sub invoked");
    // Do sensitive operations
  }
}

...

MITRE CWE

CWE-487, Reliance on Package-Level Scope

Secure Coding Guidelines for the Java Programming LanguageSE, Version 35.0

Guideline 4-1 / EXTEND-1. : Limit the accessibility of classes, interfaces, methods, and fields

Bibliography

 

...