Security Considerations with Externalizable
What you'll learn: You'll understand the unique security risks that arise when manually controlling deserialization through Externalizable and how to validate data during readExternal.
The Security Challenge
When you implement Externalizable, you take full responsibility for reading raw data from a stream and reconstructing your object. Unlike default serialization, there's no built-in validation—whatever bytes arrive, your readExternal method processes them. This is like receiving packages without a security scanner: malicious or corrupted data can slip through if you don't check it yourself.
Why Externalizable Creates Risk
Manual deserialization means attackers can craft malicious byte streams to exploit your code. They might:
- Send values outside expected ranges (negative sizes, extreme numbers)
- Inject null references where objects are required
- Provide corrupted object data that violates invariants
- Attempt to exhaust memory with enormous length values
Your readExternal method blindly reads what it's told to read—no questions asked.
Validation Strategies in readExternal
Always validate data immediately after reading it:
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
String username = (String) in.readObject();
int age = in.readInt();
// Validate immediately
if (username == null || username.isEmpty()) {
throw new InvalidObjectException("Username cannot be null or empty");
}
if (age < 0 || age > 150) {
throw new InvalidObjectException("Age must be between 0 and 150");
}
this.username = username;
this.age = age;
}
Check for null, range boundaries, string lengths, collection sizes—anything that could violate your class's contract. Throw InvalidObjectException (from java.io) for validation failures.
Defense in Depth
Never trust deserialized data. Think of readExternal as a border checkpoint: inspect everything before letting it into your object's state.
Key Takeaway: With Externalizable, you must manually validate all deserialized data in readExternal to prevent malicious or corrupted streams from creating invalid objects—always check nulls, ranges, and invariants before assigning to fields.