Although serialization allows an object's state to be saved as a sequence of bytes and then reconstituted at a later time, it provides no mechanism to protect the serialized data. An attacker who gains access to the serialized data can use it to discover sensitive information and to determine implementation details of the objects. An attacker can also modify the serialized data in an attempt to compromise the system when the malicious data is deserialized. Consequently, sensitive data that is serialized is potentially exposed, without regard to the access qualifiers (such as the private
keyword) that were used in the original code. Moreover, the security manager cannot guarantee the integrity of the deserialized data.
Examples of sensitive data that should never be serialized include cryptographic keys, digital certificates, and classes that may hold references to sensitive data at the time of serialization.
This rule is meant to prevent the unintentional serialization of sensitive information. SER02-J. Sign then seal objects before sending them outside a trust boundary applies to the intentional serialization of sensitive information.
Noncompliant Code Example
The data members of class Point
are private. Assuming the coordinates are sensitive, their presence in the data stream would expose them to malicious tampering.
public class Point implements Serializable { private double x; private double y; public Point(double x, double y) { this.x = x; this.y = y; } public Point() { // No-argument constructor } } public class Coordinates extends Point { public static void main(String[] args) { FileOutputStream fout = null; try { Point p = new Point(5, 2); fout = new FileOutputStream("point.ser"); ObjectOutputStream oout = new ObjectOutputStream(fout); oout.writeObject(p); } catch (Throwable t) { // Forward to handler } finally { if (fout != null) { try { fout.close(); } catch (IOException x) { // Handle error } } } } }
In the absence of sensitive data, classes can be serialized by simply implementing the java.io.Serializable
interface. By doing so, the class indicates that no security issues may result from the object's serialization. Note that any derived subclasses also inherit this interface and are consequently serializable. This approach is inappropriate for any class that contains sensitive data.
Compliant Solution
When serializing a class that contains sensitive data, programs must ensure that sensitive data is omitted from the serialized form. This includes suppressing both serialization of data members that contain sensitive data and serialization of references to nonserializable or sensitive objects.
This compliant solution both avoids the possibility of incorrect serialization and protects sensitive data members from accidental serialization by declaring the relevant members as transient so that they are omitted from the list of fields to be serialized by the default serialization mechanism.
public class Point implements Serializable { private transient double x; // Declared transient private transient double y; // Declared transient public Point(double x, double y) { this.x = x; this.y = y; } public Point() { // No-argument constructor } } public class Coordinates extends Point { public static void main(String[] args) { FileOutputStream fout = null; try { Point p = new Point(5,2); fout = new FileOutputStream("point.ser"); ObjectOutputStream oout = new ObjectOutputStream(fout); oout.writeObject(p); oout.close(); } catch (Exception e) { // Forward to handler } finally { if (fout != null) { try { fout.close(); } catch (IOException x) { // Handle error } } } } }
Other compliant solutions include
- Developing custom implementations of the
writeObject()
,writeReplace()
, andwriteExternal()
methods that prevent sensitive fields from being written to the serialized stream. - Defining the
serialPersistentFields
array field and ensuring that sensitive fields are omitted from the array (see SER00-J. Enable serialization compatibility during class evolution).
Noncompliant Code Example
Serialization can be used maliciously, for example, to return multiple instances of a singleton class object. In this noncompliant code example (based on [Bloch 2005]), a subclass SensitiveClass
inadvertently becomes serializable because it extends the java.lang.Number
class, which implements Serializable
:
public class SensitiveClass extends Number { // ... Implement abstract methods, such as Number.doubleValue()⦠private static final SensitiveClass INSTANCE = new SensitiveClass(); public static SensitiveClass getInstance() { return INSTANCE; } private SensitiveClass() { // Perform security checks and parameter validation } private int balance = 1000; protected int getBalance() { return balance; } } class Malicious { public static void main(String[] args) { SensitiveClass sc = (SensitiveClass) deepCopy(SensitiveClass.getInstance()); // Prints false; indicates new instance System.out.println(sc == SensitiveClass.getInstance()); System.out.println("Balance = " + sc.getBalance()); } // This method should not be used in production code static public Object deepCopy(Object obj) { try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); new ObjectOutputStream(bos).writeObject(obj); ByteArrayInputStream bin = new ByteArrayInputStream(bos.toByteArray()); return new ObjectInputStream(bin).readObject(); } catch (Exception e) { throw new IllegalArgumentException(e); } } }
See MSC07-J. Prevent multiple instantiations of singleton objects for more information about singleton classes.
Compliant Solution
Extending a class or interface that implements Serializable
should be avoided whenever possible. For instance, a nonserializable class could contain an instance of a serializable class and delegate method calls to the serializable class.
When extension of a serializable class by an unserializable class is necessary, inappropriate serialization of the subclass can be prohibited by throwing NotSerializableException
from custom writeObject()
, readObject()
, and readObjectNoData()
methods, defined in the nonserializable subclass. These custom methods must be declared private (see SER01-J. Do not deviate from the proper signatures of serialization methods for more information).
class SensitiveClass extends Number { // ... private final Object writeObject(java.io.ObjectOutputStream out) throws NotSerializableException { throw new NotSerializableException(); } private final Object readObject(java.io.ObjectInputStream in) throws NotSerializableException { throw new NotSerializableException(); } private final Object readObjectNoData(java.io.ObjectInputStream in) throws NotSerializableException { throw new NotSerializableException(); } }
It is still possible for an attacker to obtain uninitialized instances of SensitiveClass
by catching NotSerializableException
or by using a finalizer attack (see OBJ11-J. Be wary of letting constructors throw exceptions for more information). Consequently, an unserializable class that extends a serializable class must always validate its invariants before executing any methods. That is, any object of such a class must inspect its fields, its actual type (to prevent it being a malicious subclass), and any invariants it possesses (such as being a malicious second object of a singleton class).
Exceptions
SER03-J-EX0: Sensitive data that has been properly encrypted may be serialized.
Risk Assessment
If sensitive data can be serialized, it may be transmitted over an insecure connection, stored in an insecure location, or disclosed inappropriately.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
SER03-J | Medium | Likely | High | P6 | L2 |
Automated Detection
Tool | Version | Checker | Description |
---|---|---|---|
CodeSonar | 8.1p0 | JAVA.CLASS.SER.ND | Serialization Not Disabled (Java) |
Coverity | 7.5 | UNSAFE_DESERIALIZATION | Implemented |
Parasoft Jtest | 2024.1 | CERT.SER03.SIF | Inspect instance fields of serializable objects to make sure they will not expose sensitive information |
Related Guidelines
CWE-499, Serializable Class Containing Sensitive Data | |
Guideline 8-2 / SERIAL-2: Guard sensitive data during serialization |
Bibliography
Puzzle 83, "Dyslexic monotheism" | |
Item 1, "Enforce the Singleton Property with a Private Constructor" | |
Section 2.4, "Serialization" | |
[Sun 2006] | Serialization Specification, A.4, Preventing Serialization of Sensitive Data |
15 Comments
Dhruv Mohindra
David Svoboda
Right now, those methods would be pretty trivial, as there are (currently) no useful fields to serialize.
Fixed
Fixed
Added a link. The singleton rule is MSC11-J.
Masaki Kubo
sounds a bit strange for an exception considering the fact that the title of this rule is "Do not serialize unencrypted, sensitive data". The exception condition would be considered as a compliant solution.
David Svoboda
We tried to avoid discussing good vs. bad encryption in our Java guidelines. It is a huge topic, and we considered it outside our scope. The compliant solutions here solve the problem by preventing data from being serialized, rather than encrypting the data before serialization.
I'll agree that the exception is somewhat redundant by the scope of the rule as you note. I just think it is better to include the xception than to omit it (and have people wonder what to do if their data is encrypted).
Masaki Kubo
I understood the situation. Thanks for the clarification.
Thomas Hawtin
With respect to the last compliant solution, it doesn't generally make a great deal of sense to have a readResolve method on a subclassable class. Also, private methods and implicitly final, so adding final to a private method looks as if it is doing something but isn't.
If you subclass a serialisable class, then the subclass is serialisable. You might not allow the fields to be initialised but you can't stop deserialisation (other than by having a serialPersistentFields (spelt correctly) containing an array containing a null element, but that isn't really documented and so may change at any time).
David Svoboda
I s/readResolve()/readObject()/ in the last CS. That strikes me as a less confusing solution anyway. Also pointed out that readObject must be final or private.
Not sure I understand your latter paragraph. Throwing an exception in readResolve() does effectively prevents serialization. A caller could catch the exception and continue with a partially-initialized
SensitiveClass
object...is that what you meant? IIRC one of our other serialization rules addresses that issue.Thomas Hawtin
readResolve or readObject throwing doesn't absolutely prevent deserialisation because a reference can be retrieved from the deserialisation of the base class (or a finaliser in a non-final class). Also as the example is subclassable, readObjectNoData could be used instead of readObejct.
I guess for serialisation writeReplace throwing may work (assuming not subclassed). But really, avoid such inheritance.
David Svoboda
Try the last CS now, which summarizes our discussion.
I'm tempted to just take it out and declare that sensitive unserializable classes should never extend serializable ones. Even as it is, the ability for attackers to create a 'zombie' sensitive class is a big problem which seems unsolvable.
Yozo TODA
I'd like to make clear the intention of the last sentence of the last CS,
what should we validate here?
validating if the instance is of the intended class (not a malicious subclass)?
David Svoboda
Validating the instance. Which includes the possibility of malicious subclasses. I've tweaked the paragraph to be clearer on this point.
Andre
With compliant code "by throwing
NotSerializableException
from customwriteObject()
,readObject()
, andreadObjectNoData()" the Malicious class still able to run deepCopy and gain access to getBalance?
David Svoboda
Sort of. As written, the
deepCopy()
would fail with aNotSerializableException
. It's trivial to modifydeepCopy()
to catch the exception and return the uninitializedSensitiveClass
. You can then callgetBalance()
on it, but you'll get an uninitialized value out of it (probably 0). I madebalance
a private field, which makes the code safer, as well as more realistic.Finally remember the last paragraph of the last compliant solution:
Andre
"deepCopy() will fail with a
NotSerializableException"
But executing these code, deepCopy() does not fail.
public
class
SensitiveClass
extends
Number {
// ..implement abstract methods, such as Number.doubleValue()â¦
private
static
final
SensitiveClass INSTANCE =
new
SensitiveClass();
public
static
SensitiveClass getInstance() {
return
INSTANCE;
}
private
SensitiveClass() {
// Perform security checks and parameter validation
}
private
int
balance =
1000
;
protected
int
getBalance() {
return
balance;
}
@Override
public int intValue() {
// TODO Auto-generated method stub
return 0;
}
@Override
public long longValue() {
// TODO Auto-generated method stub
return 0;
}
@Override
public float floatValue() {
// TODO Auto-generated method stub
return 0;
}
@Override
public double doubleValue() {
// TODO Auto-generated method stub
return 0;
}
protected
final
Object writeObject(java.io.ObjectOutputStream out)
throws
NotSerializableException {
throw
new
NotSerializableException();
}
protected
final
Object readObject(java.io.ObjectInputStream in)
throws
NotSerializableException {
throw
new
NotSerializableException();
}
protected
final
Object readObjectNoData(java.io.ObjectInputStream in)
throws
NotSerializableException {
throw
new
NotSerializableException();
}
}
class
Malicious {
public
static
void
main(String[] args) {
SensitiveClass sc =
(SensitiveClass) deepCopy(SensitiveClass.getInstance());
// Prints false; indicates new instance
System.out.println(sc == SensitiveClass.getInstance());
System.out.println(
"Balance = "
+ sc.getBalance());
}
// This method should not be used in production code
static
public
Object deepCopy(Object obj) {
try
{
ByteArrayOutputStream bos =
new
ByteArrayOutputStream();
new
ObjectOutputStream(bos).writeObject(obj);
ByteArrayInputStream bin =
new
ByteArrayInputStream(bos.toByteArray());
return
new
ObjectInputStream(bin).readObject();
}
catch
(Exception e) {
throw
new
IllegalArgumentException(e);
}
}
}
David Svoboda
Oops, the *Object() methods need to be private. I fixed the compliant solution.