Java Security   «Prev  Next»

Constructing Sensitive Objects

List of Guidelines

Let us take a look add the guideline and notes relating to constructing sensitive objects, including serialization and deserialization.

Guideline 1:

Avoid exposing constructors of sensitive classes. Construction of classes can be more carefully controlled if constructors are not exposed.
  1. Define static factory methods instead of public constructors.
  2. Support extensibility through delegation rather than inheritance.
  3. Implicit constructors through serialization and clone should be avoided.

Guideline 2:

Prevent the unauthorized construction of sensitive classes.
Important Points: A security sensitive class needs to prevent callers from modifying or circumventing SecurityManager access controls. Any instance of ClassLoader, for example, has the power to define classes with arbitrary security permissions. Enforce a SecurityManager check at all points where that class can be instantiated.
  1. Enforce checks at the beginning of each public and protected constructor.
  2. Enforce checks at the beginning of each factory method if a class declares public static factory methods.
  3. Enforce a check inside the readObject or readObjectNoData method of a serializable class.
  4. Enforce a check inside the clone method of a cloneable class.

Guideline 3:

Defend against partially initialized instances of non-final classes.
Important Points: When a constructor in a non-final class throws an exception, attackers might be able to gain access to this partially initialized instance. Ensure that a non final class remains totally unusable, until its constructor completes successfully.
  1. Construction of a subclassable class can be prevented by throwing an exception before the object constructor completes.
  2. Any security sensitive uses of such classes should check the state of an initialization flag.

Guideline 4:

Prevent constructors from calling methods that can be overridden.
Important Points: Constructors that call overridable methods give attackers a reference to ‘this’ (the object being constructed ) before the object has been fully initialized.

Guideline 5:

Defend against cloning of non-final classes. Important Notes: A non-final class may be subclassed buy a class that also implements java.lang.Cloneable. The result is that the base class can be unexpectedly cloned. The clone will be a shallow copy. The twins will share referenced objects but have different fields and separate intrinsic locks.