Warning
Deserialization of untrusted data is inherently dangerous and should be avoided. Untrusted data should be carefully validated according to the "Serialization and Deserialization" section of the Secure Coding Guidelines for Java SE. Serialization Filtering describes best practices for defensive use of serial filters.
The key to disabling deserialization attacks is to prevent instances of
arbitrary classes from being deserialized, thereby preventing the direct or
indirect execution of their methods.
ObjectInputFilter
describes how to use filters and
ObjectInputFilter.
describes how to configure the filter and filter factory.
Each stream has an optional deserialization filter
to check the classes and resource limits during deserialization.
The JVM-wide filter factory ensures that a filter can be set on every ObjectInputStream
and every object read from the stream can be checked.
The ObjectInputStream constructors invoke the filter factory
to select the initial filter which may be updated or replaced by setObjectInputFilter
.
If an ObjectInputStream has a filter, the ObjectInputFilter
can check that
the classes, array lengths, number of references in the stream, depth, and
number of bytes consumed from the input stream are allowed and
if not, can terminate deserialization.
ObjectOutputStream and ObjectInputStream can provide an application with persistent storage for graphs of objects when used with a FileOutputStream and FileInputStream respectively. ObjectInputStream is used to recover those objects previously serialized. Other uses include passing objects between hosts using a socket stream or for marshaling and unmarshaling arguments and parameters in a remote communication system.
ObjectInputStream ensures that the types of all objects in the graph created from the stream match the classes present in the Java Virtual Machine. Classes are loaded as required using the standard mechanisms.
Only objects that support the java.io.Serializable or java.io.Externalizable interface can be read from streams.
The method readObject
is used to read an object from the
stream. Java's safe casting should be used to get the desired type. In
Java, strings and arrays are objects and are treated as objects during
serialization. When read they need to be cast to the expected type.
Primitive data types can be read from the stream using the appropriate method on DataInput.
The default deserialization mechanism for objects restores the contents of each field to the value and type it had when it was written. Fields declared as transient or static are ignored by the deserialization process. References to other objects cause those objects to be read from the stream as necessary. Graphs of objects are restored correctly using a reference sharing mechanism. New objects are always allocated when deserializing, which prevents existing objects from being overwritten.
Reading an object is analogous to running the constructors of a new object. Memory is allocated for the object and initialized to zero (NULL). No-arg constructors are invoked for the non-serializable classes and then the fields of the serializable classes are restored from the stream starting with the serializable class closest to java.lang.object and finishing with the object's most specific class.
For example to read from a stream as written by the example in
ObjectOutputStream
:
try (FileInputStream fis = new FileInputStream("t.tmp"); ObjectInputStream ois = new ObjectInputStream(fis)) { String label = (String) ois.readObject(); LocalDateTime dateTime = (LocalDateTime) ois.readObject(); // Use label and dateTime } catch (Exception ex) { // handle exception }
Classes control how they are serialized by implementing either the java.io.Serializable or java.io.Externalizable interfaces.
Implementing the Serializable interface allows object serialization to save and restore the entire state of the object and it allows classes to evolve between the time the stream is written and the time it is read. It automatically traverses references between objects, saving and restoring entire graphs.
Serializable classes that require special handling during the serialization and deserialization process should implement methods with the following signatures:
private void writeObject(java.io.ObjectOutputStream stream) throws IOException; private void readObject(java.io.ObjectInputStream stream) throws IOException, ClassNotFoundException; private void readObjectNoData() throws ObjectStreamException;
The method name, modifiers, return type, and number and type of parameters must match exactly for the method to be used by serialization or deserialization. The methods should only be declared to throw checked exceptions consistent with these signatures.
The readObject method is responsible for reading and restoring the state of the object for its particular class using data written to the stream by the corresponding writeObject method. The method does not need to concern itself with the state belonging to its superclasses or subclasses. State is restored by reading data from the ObjectInputStream for the individual fields and making assignments to the appropriate fields of the object. Reading primitive data types is supported by DataInput.
Any attempt to read object data which exceeds the boundaries of the custom data written by the corresponding writeObject method will cause an OptionalDataException to be thrown with an eof field value of true. Non-object reads which exceed the end of the allotted data will reflect the end of data in the same way that they would indicate the end of the stream: bytewise reads will return -1 as the byte read or number of bytes read, and primitive reads will throw EOFExceptions. If there is no corresponding writeObject method, then the end of default serialized data marks the end of the allotted data.
Primitive and object read calls issued from within a readExternal method
behave in the same manner--if the stream is already positioned at the end of
data written by the corresponding writeExternal method, object reads will
throw OptionalDataExceptions with eof set to true, bytewise reads will
return -1, and primitive reads will throw EOFExceptions. Note that this
behavior does not hold for streams written with the old
ObjectStreamConstants.PROTOCOL_VERSION_1
protocol, in which the
end of data written by writeExternal methods is not demarcated, and hence
cannot be detected.
The readObjectNoData method is responsible for initializing the state of the object for its particular class in the event that the serialization stream does not list the given class as a superclass of the object being deserialized. This may occur in cases where the receiving party uses a different version of the deserialized instance's class than the sending party, and the receiver's version extends classes that are not extended by the sender's version. This may also occur if the serialization stream has been tampered; hence, readObjectNoData is useful for initializing deserialized objects properly despite a "hostile" or incomplete source stream.
Serialization does not read or assign values to the fields of any object that does not implement the java.io.Serializable interface. Subclasses of Objects that are not serializable can be serializable. In this case the non-serializable class must have a no-arg constructor to allow its fields to be initialized. In this case it is the responsibility of the subclass to save and restore the state of the non-serializable class. It is frequently the case that the fields of that class are accessible (public, package, or protected) or that there are get and set methods that can be used to restore the state.
Any exception that occurs while deserializing an object will be caught by the ObjectInputStream and abort the reading process.
Implementing the Externalizable interface allows the object to assume complete control over the contents and format of the object's serialized form. The methods of the Externalizable interface, writeExternal and readExternal, are called to save and restore the objects state. When implemented by a class they can write and read their own state using all of the methods of ObjectOutput and ObjectInput. It is the responsibility of the objects to handle any versioning that occurs.
Enum constants are deserialized differently than ordinary serializable or
externalizable objects. The serialized form of an enum constant consists
solely of its name; field values of the constant are not transmitted. To
deserialize an enum constant, ObjectInputStream reads the constant name from
the stream; the deserialized constant is then obtained by calling the static
method Enum.valueOf(Class, String)
with the enum constant's
base type and the received constant name as arguments. Like other
serializable or externalizable objects, enum constants can function as the
targets of back references appearing subsequently in the serialization
stream. The process by which enum constants are deserialized cannot be
customized: any class-specific readObject, readObjectNoData, and readResolve
methods defined by enum types are ignored during deserialization.
Similarly, any serialPersistentFields or serialVersionUID field declarations
are also ignored--all enum types have a fixed serialVersionUID of 0L.
Records are serialized differently than ordinary serializable or externalizable objects. During deserialization the record's canonical constructor is invoked to construct the record object. Certain serialization-related methods, such as readObject and writeObject, are ignored for serializable records. See Java Object Serialization Specification, Section 1.13, "Serialization of Records" for additional information.
java.io.DataInput
, java.io.ObjectOutputStream
, java.io.Serializable
, Java Object Serialization Specification, Section 3, "Object Input Classes"
Modifier and Type | Class and Description |
---|---|
private class | ObjectInputStream.
Input stream with two modes: in default mode, inputs data written in the same format as DataOutputStream; in "block data" mode, inputs data bracketed by block data markers (see object serialization specification for details). |
private static class | |
private class | ObjectInputStream.
Default GetField implementation. |
pack-priv static class | ObjectInputStream.
Hold a snapshot of values to be passed to an ObjectInputFilter. |
public abstract static class | ObjectInputStream.
Provide access to the persistent fields read from the input stream. |
private static class | ObjectInputStream.
Unsynchronized table which tracks wire handle to object mappings, as well as ClassNotFoundExceptions associated with deserialized objects. |
private static class | |
private static class | ObjectInputStream.
Input stream supporting single-byte peek operations. |
private static class | ObjectInputStream.
Prioritized list of callbacks to be performed once object graph has been completely deserialized. |
Modifier and Type | Field and Description |
---|---|
private final ObjectInputStream. | bin
filter stream for handling block data conversion |
private boolean | closed
whether stream is closed |
private SerialCallbackContext | curContext
Context during upcalls to class-defined readObject methods; holds object currently being deserialized and descriptor for current class. |
private boolean | defaultDataEnd
flag set when at end of field value block with no TC_ENDBLOCKDATA |
private long | depth
recursion depth |
private final boolean | enableOverride
if true, invoke readObjectOverride() instead of readObject() |
private boolean | enableResolve
if true, invoke resolveObject() |
private final ObjectInputStream. | handles
wire handle -> obj/exception map |
private static final int | NULL_HANDLE
handle value representing null |
private int | passHandle
scratch field for passing handle values up/down call stack |
private ObjectInputFilter | serialFilter
Filter of class descriptors and classes read from the stream; may be null. |
private boolean | streamFilterSet
True if the stream-specific filter has been set; initially false. |
private long | totalObjectRefs
Total number of references to any type of object, class, enum, proxy, etc. |
private static final Unsafe | |
private static final Object | unsharedMarker
marker for unshared objects in internal handle table |
private final ObjectInputStream. | vlist
validation callback list |
Access | Constructor and Description |
---|---|
public | ObjectInputStream(InputStream
input stream to read from in)Creates an ObjectInputStream that reads from the specified InputStream. |
protected | ObjectInputStream()
Provide a way for subclasses that are completely reimplementing ObjectInputStream to not have to allocate private data just used by this implementation of ObjectInputStream. |
Modifier and Type | Method and Description |
---|---|
private static Boolean | auditSubclass(Class<?> subcl)
Performs reflective checks on given subclass to verify that it doesn't override security-sensitive non-final methods. |
public int | Returns: the number of available bytes.Overrides java. Implements java. Returns the number of bytes that can be read without blocking. |
private void | checkArray(Class<?>
the array type arrayType, int the array length arrayLength)Checks the given array type and length to ensure that creation of such an array is permitted by this ObjectInputStream. |
private Object | checkResolve(Object obj)
If resolveObject has been enabled and given object does not have an exception associated with it, calls resolveObject to determine replacement for object, and updates handle table accordingly. |
private void | |
private static Object | |
public void | close()
Overrides java. Implements java. Closes the input stream. |
public void | defaultReadObject()
Read the non-static and non-transient fields of the current class from this stream. |
protected boolean | Returns: the previous setting before this method was invokedtrue for enabling use of enable)resolveObject for
every object being deserializedEnables the stream to do replacement of objects read from the stream. |
private void | filterCheck(Class<?>
the class; may be null clazz, int the array length requested; use arrayLength)-1 if not creating an arrayInvokes the deserialization filter if non-null. |
private void | |
public final ObjectInputFilter | Returns: the deserialization filter for the stream; may be nullReturns the deserialization filter for this stream. |
private void | handleReset()
If recursion depth is 0, clears internal data structures; otherwise, throws a StreamCorruptedException. |
private boolean | |
private static ClassLoader | latestUserDefinedLoader()
Returns the first non-null and non-platform class loader (not counting class loaders of generated reflection implementation classes) up the execution stack, or the platform class loader if only code from the bootstrap and platform class loader is on the stack. |
public int | Returns: the byte read, or -1 if the end of the stream is reached.Implements abstract java. Implements java. Reads a byte of data. |
public int | Returns: the total number of bytes read into the buffer, or-1 if there is no more data because the end of
the stream has been reached.the buffer into which the data is read buf, int the start offset in the destination array off, int buf the maximum number of bytes read len)Overrides java. Implements java. Reads into an array of bytes. |
private Object | readArray(boolean unshared)
Reads in and returns array object, or null if array class is unresolvable. |
public boolean | Returns: the boolean read.Implements java. Reads in a boolean. |
public byte | |
public char | |
private Class | |
private ObjectStreamClass | |
protected ObjectStreamClass | Returns: the class descriptor readRead a class descriptor from the serialization stream. |
public double | Returns: the 64-bit double read.Implements java. Reads a 64-bit double. |
private Enum | |
private void | readExternalData(Externalizable obj, ObjectStreamClass desc)
If obj is non-null, reads externalizable data by invoking readExternal() method of obj; otherwise, attempts to skip over externalizable data. |
private IOException | |
public ObjectInputStream. | Returns: theGetField object representing the persistent
fields of the object being deserializedReads the persistent fields from the stream and makes them available by name. |
public float | Returns: the 32-bit float read.Implements java. Reads a 32-bit float. |
public void | readFully(byte[]
the buffer into which the data is read buf)Implements java. Reads bytes, blocking until all bytes are read. |
public void | readFully(byte[]
the buffer into which the data is read buf, int the start offset into the data array off, int buf the maximum number of bytes to read len)Implements java. Reads bytes, blocking until all bytes are read. |
private Object | readHandle(boolean unshared)
Reads in object handle, sets passHandle to the read handle, and returns object associated with the handle. |
public int | |
public String | Returns: a String copy of the line.Implements java.
Deprecated
This method does not properly convert bytes to characters.
see DataInputStream for the details and alternatives.
Reads in a line that has been terminated by a \n, \r, \r\n or EOF. |
public long | |
private ObjectStreamClass | readNonProxyDesc(boolean unshared)
Reads in and returns class descriptor for a class that is not a dynamic proxy class. |
private Object | |
public final Object | |
private final Object | Returns: an object of the typethe type expected; either Object.class or String.class type)Internal method to read an object from the ObjectInputStream of the expected type. |
private Object | readObject0(Class<?>
a type expected to be deserialized; non-null type, boolean true if the object can not be a reference to a shared object, otherwise false unshared)Underlying readObject implementation. |
protected Object | Returns: the Object read from the stream.This method is called by trusted subclasses of ObjectInputStream that constructed ObjectInputStream using the protected no-arg constructor. |
private Object | readOrdinaryObject(boolean unshared)
Reads and returns "ordinary" (i.e., not a String, Class, ObjectStreamClass, array, or enum constant) object, or null if object's class is unresolvable (in which case a ClassNotFoundException will be associated with object's handle). |
private ObjectStreamClass | |
private Object | |
private void | readSerialData(Object obj, ObjectStreamClass desc)
Reads (or attempts to skip, if obj is null or is tagged with a ClassNotFoundException) instance data for each serializable class of object in stream, from superclass to subclass. |
public short | Returns: the 16-bit short read.Implements java. Reads a 16-bit short. |
protected void | readStreamHeader()
The readStreamHeader method is provided to allow subclasses to read and verify their own stream headers. |
private String | |
private String | |
pack-priv String | |
public Object | Returns: reference to deserialized objectReads an "unshared" object from the ObjectInputStream. |
public int | Returns: the 8-bit byte read.Implements java. Reads an unsigned 8-bit byte. |
public int | Returns: the 16-bit short read.Implements java. Reads an unsigned 16-bit short. |
public String | Returns: the String.Implements java. Reads a String in modified UTF-8 format. |
public void | registerValidation(ObjectInputValidation
the object to receive the validation callback. obj, int controls the order of callbacks; zero is a good default.
Use higher numbers to be called back earlier, lower numbers for
later callbacks. Within a priority, callbacks are processed in
no particular order. prio)Register an object to be validated before the graph is returned. |
protected Class | Returns: aClass object corresponding to desc an instance of class desc)ObjectStreamClass Load the local class equivalent of the specified stream class description. |
protected Object | Returns: the substituted objectobject to be substituted obj)This method will allow trusted subclasses of ObjectInputStream to substitute one object for another during deserialization. |
protected Class | Returns: a proxy class for the specified interfacesthe list of interface names that were
deserialized in the proxy class descriptor interfaces)Returns a proxy class that implements the interfaces named in a proxy class descriptor; subclasses may implement this method to read custom data from the stream along with the descriptors for dynamic proxy classes, allowing them to use an alternate loading mechanism for the interfaces and the proxy class. |
public final void | setObjectInputFilter(ObjectInputFilter
the filter, may be null filter)Set the deserialization filter for the stream. |
public int | Returns: the actual number of bytes skipped.the number of bytes to be skipped len)Implements java. Skips bytes. |
private void | |
private void | verifySubclass()
Verifies that this (possibly subclass) instance can be constructed without violating security constraints: the subclass must not override security-sensitive non-final methods, or else the "enableSubclassImplementation" SerializablePermission is checked. |