Avoid Non Serializable Objects Stored
ID |
java.avoid_non_serializable_objects_stored |
Severity |
low |
Resource |
Risky Values |
Language |
Java |
Tags |
CWE:579, NIST.SP.800-53 |
Rationale
Serialization in Java is the process of converting an object into a byte stream, enabling it to be easily stored or transmitted. When non-serializable objects are stored in contexts that expect serialization, such as HTTP sessions, caching systems, or when attempting to persist them to disk, it can lead to runtime exceptions like java.io.NotSerializableException
. This undermines application stability and data integrity, and in some cases, could even cause security vulnerabilities, particularly if sensitive data is involved.
The Common Weakness Enumeration (CWE) 579 discusses risks associated with improper storage of non-serializable objects, emphasizing the importance of ensuring objects meet serialization requirements.
Below is an example where a non-serializable object is placed in a session context:
import javax.servlet.http.HttpSession;
public class SessionExample {
public void storeNonSerializableObject(HttpSession session, NonSerializableClass object) {
session.setAttribute("nonSerializableObject", object);
// This can lead to NotSerializableException
}
}
class NonSerializableClass {
private String data;
}
In this example, attempting to store NonSerializableClass
in a session attribute risks runtime exceptions because it’s not serializable.
Remediation
To resolve issues with non-serializable objects in Java, implement the following strategies:
-
Implement Serializable Interface: Ensure that classes intended for storage or transmission implement
java.io.Serializable
. This involves explicitly declaring the class as implementing the interface.import java.io.Serializable; import javax.servlet.http.HttpSession; public class SerializableExample { public void storeSerializableObject(HttpSession session, SerializableClass object) { session.setAttribute("serializableObject", object); } } class SerializableClass implements Serializable { private static final long serialVersionUID = 1L; private String data; }
-
Mark Non-Serializable Fields as Transient: If certain fields within a serializable class should not be serialized (e.g., sensitive information), mark them as
transient
to prevent serialization. -
Use Serialization Libraries: Leverage proven serialization libraries like Jackson or GSON that provide clear control over what gets serialized, especially for complex or legacy objects.
-
Testing and Validation: Conduct thorough testing to ensure that objects undergoing serialization and deserialization processes do not cause exceptions and maintain integrity during data exchanges.
By adhering to these practices, developers can ensure robust and secure handling of serializable objects in Java applications, promoting both reliability and data integrity across storage mediums and data transmissions.