Versions Compared

Key

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

...

Classes and class members should be given the minimum access possible so that malicious code has the least chance of manipulating the system. As far as possible, sensitive classes should avoid implementing interfaces. This is because only public methods are allowed to be declared within interfaces and these carry forward to the public API of the class. An exception is implementing an unmodifiable interface that exposes a public immutable view of a mutable object (SEC01-J. Provide sensitive mutable classes with unmodifiable wrappers). Additionally, be aware that even if a class's visibility is default, it can be susceptible to misuse if it exposes a public method.

...

In this noncompliant example, the class PublicClass is declared public. The member function getPoint as well as the (x, y) coordinates are also declared public. This gives world-access to the class members. A real world vulnerability, for example, can arise when a malicious applet attempts to access the credit card field of another object that is declared public. Note that a non-public class may is also be vulnerable if its members are declared public.

...

Code Block
bgColor#ccccff
final class PrivateClass {
  private int x;
  private int y;
	
  private void getPoint() { 
     System.out.println("(" + x + "," + y + ")");  
  }	
}

Noncompliant Code Example

This noncompliant code example overrides the finalize() method of the superclass and changes its accessibility from protected to public.

According to Sun's Secure Coding Guidelines [[SCG 07]]:

In addition, refrain from increasing the accessibility of an inherited method, as doing so may break assumptions made by the superclass. A class that overrides the protected java.lang.Object.finalize method and declares that method public, for example, enables hostile callers to finalize an instance of that class, and to call methods on that instance after it has been finalized. A superclass implementation unprepared to handle such a call sequence could throw runtime exceptions that leak private information, or that leave the object in an invalid state that compromises security. One noteworthy exception to this guideline pertains to classes that implement the java.lang.Cloneable interface. In these cases, the accessibility of the Object.clone method should be increased from protected to public.

Code Block
bgColor#FFcccc

final class SubClass extends Base {
  public void finalize() {
    // ...
  }
}

Compliant SOlution

This compliant solution correctly declares the finalize() method protected.

Code Block
bgColor#ccccff

final class SubClass extends Base {
  protected void finalize() {
    // ... 
  }
}

Risk Assessment

Granting unnecessary access weakens the security of Java applications.

...