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.
- Define static factory methods instead of public constructors.
- Support extensibility through delegation rather than inheritance.
- 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.
- Enforce checks at the beginning of each public and protected constructor.
- Enforce checks at the beginning of each factory method if a class declares public static factory methods.
- Enforce a check inside the readObject or readObjectNoData method of a serializable class.
- 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.
- Construction of a subclassable class can be prevented by throwing an exception before the object constructor completes.
- 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.