What are the security considerations for serialization?
The Java runtime environment has many features that contribute to security and robustness in a program. For example, the runtime environment enforces access permissions to private, protected, or "default" members. But when you serialize your objects, you are in effect removing them from the runtime environment, thereby exposing them to access that would normally not be allowed - e.g. anyone can come along and read the contents of a private variables from a serialized object. This is why it is important to consider security when you are designing your classes for serialization.
Java provides a number of mechanisms to protect your serialized code:
- The first is the obvious step that classes need to be explicitly declared as implementing Serializable or Externalizable - your class cannot be serialized without a concious decision on your part to make it so.
- Java provides a transient keyword which prevents a primitive type or object reference from being written to the stream. You may use this to control which information is sent out. For example, you may mark a private password field as transient so that it isn't written out - this prevents someone from coming along and reading your password directly from a serialized object.
- Serialization is a stream-oriented process, so you may apply any stream-based encryption to your serialized objects.
- Deserialization can't overwrite existing objects in memory - it can only create new objects.
- Loading classes for serialized objects is done through the normal class loader mechanism, therefore is protected by the usual Java security mechanisms.
The above is not a comprehensive list; more information on this subject may be found at: http://java.sun.com/security/seccodeguide.html and http://java.sun.com/products/jdk/1.2/docs/guide/serialization/spec/security.doc.html.