Why reading untrusted data is dangerous
40 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)Deserialization is safe only when you trust where the bytes came from. Untrusted input is any data that someone outside your control could have written or changed: an uploaded file, a network message, a cookie, a request body. Java's readObject should never read it.
Deserialization can run code
Reading an object runs code. While readObject rebuilds objects, it calls methods such as readObject in the classes named in the bytes. Those can be any serializable classes on your program's class path, including JDK and library classes you never meant to read.
Example 1 · Code runs before your cast can check anything
import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.Serializable;
class Marks implements Serializable { private static final long serialVersionUID = 1L; String student; int marks;
Marks(String student, int marks) { this.student = student; this.marks = marks; }}
class AuditNote implements Serializable { private static final long serialVersionUID = 1L; String text = "note";
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); System.out.println(" AuditNote.readObject runs while reading"); }}
public class ReadingRunsCodeDemo { public static void main(String[] args) throws IOException, ClassNotFoundException { // The program expects Marks, but the bytes it receives hold an AuditNote ByteArrayOutputStream buffer = new ByteArrayOutputStream(); try (ObjectOutputStream out = new ObjectOutputStream(buffer)) { out.writeObject(new AuditNote()); }
System.out.println("Reading what should be Marks:"); try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray()))) { Object obj = in.readObject(); // code inside AuditNote has already run System.out.println(" readObject returned " + obj.getClass().getSimpleName()); Marks m = (Marks) obj; // the check comes too late System.out.println(m.student); } catch (ClassCastException e) { System.out.println(" Cast failed, but only after AuditNote's code ran"); } }}Reading what should be Marks: AuditNote.readObject runs while reading readObject returned AuditNote Cast failed, but only after AuditNote's code ran
What this code does
- The program expects
Marks, but the bytes hold anAuditNote. ItsreadObjectmethod runs while reading, beforereadObjecteven returns. - The cast to
Marksthen fails, but the other class's code has already run. Checking the type afterwards cannot undo that. AuditNotehere only prints a line; the lesson is about when code runs, which is why the defence must act before classes are read.
The bytes choose which classes are read, so an attacker who controls the bytes can make the program run code in classes that are already there, with effects the program never intended. Security teams call such a combination of existing classes a gadget chain. You do not need the details: the point is that the danger exists before your code even looks at the result. Your cast and your checks come after readObject returns, which is too late. The defence has to stop unwanted classes before they are read.
Huge or deep data that stops a program
Bytes can describe data that is far too big: an array with millions of slots, or objects nested thousands of levels deep. Reading it can use up memory or overflow the stack. This is a denial-of-service problem.
Example 2 · Limits reject data that is too deep
import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InvalidClassException;import java.io.ObjectInputFilter;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.Serializable;
class Node implements Serializable { private static final long serialVersionUID = 1L; int value; Node next;
Node(int value, Node next) { this.value = value; this.next = next; }}
public class DepthLimitDemo { static byte[] chainOf(int length) throws IOException { Node head = null; for (int i = length; i >= 1; i--) { head = new Node(i, head); } ByteArrayOutputStream buffer = new ByteArrayOutputStream(); try (ObjectOutputStream out = new ObjectOutputStream(buffer)) { out.writeObject(head); } return buffer.toByteArray(); }
static void load(String label, byte[] bytes) throws IOException, ClassNotFoundException { ObjectInputFilter limits = ObjectInputFilter.Config.createFilter("maxdepth=50;maxbytes=100000;Node;!*"); try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes))) { in.setObjectInputFilter(limits); Node head = (Node) in.readObject(); System.out.println(label + ": loaded, first value " + head.value); } catch (InvalidClassException e) { System.out.println(label + ": rejected (" + e.getMessage() + ")"); } }
public static void main(String[] args) throws IOException, ClassNotFoundException { load("10 nodes", chainOf(10)); load("300 nodes", chainOf(300)); }}10 nodes: loaded, first value 1 300 nodes: rejected (filter status: REJECTED)
What this code does
- Each
Nodepoints to the next, so a chain of 300 nodes is 300 levels deep when it is read. - The filter allows only
Nodeand setsmaxdepth=50, so the short chain loads and the long one is rejected with "filter status: REJECTED". - Limits stop huge or deep data before it can use up memory or overflow the stack.
The program stops and the service stops working for everyone, even though no unwanted code ran.
The defence is a limit. A filter can refuse a stream that is too deep (maxdepth), has too many objects (maxrefs), uses too many bytes (maxbytes) or has too long an array (maxarray). When a limit is broken, readObject throws InvalidClassException with the message "filter status: REJECTED".
ObjectInputFilter to allow only known classes
ObjectInputFilter (Java 9+) lets you decide which classes a stream may contain. Set one with in.setObjectInputFilter(filter) before the first readObject; setting it later throws IllegalStateException.
java -Djdk.serialFilter="Marks;java.util.ArrayList;java.lang.*;maxdepth=20;!*" ReportAppTo set one filter for the whole program without changing code, start Java with the jdk.serialFilter system property, as shown below.
Example 3 · An allow-list with ObjectInputFilter
import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InvalidClassException;import java.io.ObjectInputFilter;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.Serializable;import java.util.ArrayList;import java.util.List;
record Marks(String student, int marks) implements Serializable {}
class AuditNote implements Serializable { private static final long serialVersionUID = 1L; String text = "note";}
public class AllowListDemo { static byte[] toBytes(Object obj) throws IOException { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); try (ObjectOutputStream out = new ObjectOutputStream(buffer)) { out.writeObject(obj); } return buffer.toByteArray(); }
static void load(String label, byte[] bytes, String pattern) throws IOException, ClassNotFoundException { ObjectInputFilter filter = ObjectInputFilter.Config.createFilter(pattern); try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes))) { in.setObjectInputFilter(filter); // set before the first readObject Object obj = in.readObject(); System.out.println(label + ": loaded " + obj); } catch (InvalidClassException e) { System.out.println(label + ": rejected (" + e.getMessage() + ")"); } }
public static void main(String[] args) throws IOException, ClassNotFoundException { String onlyMarks = "Marks;java.lang.*;!*"; // allow Marks and java.lang, reject the rest
load("one Marks", toBytes(new Marks("Aditi", 88)), onlyMarks); load("an AuditNote", toBytes(new AuditNote()), onlyMarks);
List<Marks> list = new ArrayList<>(List.of(new Marks("Aditi", 88), new Marks("Bala", 74))); load("list, old filter", toBytes(list), onlyMarks); load("list, new filter", toBytes(list), "Marks;java.lang.*;java.util.ArrayList;!*"); }}one Marks: loaded Marks[student=Aditi, marks=88] an AuditNote: rejected (filter status: REJECTED) list, old filter: rejected (filter status: REJECTED) list, new filter: loaded [Marks[student=Aditi, marks=88], Marks[student=Bala, marks=74]]
What this code does
- The pattern
Marks;java.lang.*;!*allowsMarksandjava.langclasses and rejects everything else, so theAuditNotestream is refused. - The list of marks is refused too, because
java.util.ArrayListis not on the list. Adding it to the pattern fixes that. - The filter is set before the first
readObject, so unlisted classes are never read at all.
Build a filter from a pattern with ObjectInputFilter.Config.createFilter("..."). The pattern is a list separated by ;. A class name allows that class, java.lang.* allows a package, a leading ! rejects, and the final !* rejects everything not listed. This is an allow-list: only what you name can be read. Limits such as maxdepth=20 go in the same pattern.
- Prefer an allow-list (
...;!*) to a list of classes to block: new dangerous classes are found over time. - Collections need their own entries, such as
java.util.ArrayList. - Combine the filter with a validating
readObjector a record's compact constructor for the values.
The rule: never deserialize untrusted input
Filters reduce the risk, but the safest rule is simple: never use readObject on data from outside your trust boundary. A trust boundary is the line between data your program made itself and data anyone else could have touched.
Example 4 · Text data: read only what you expect
import java.util.ArrayList;import java.util.List;
record Marks(String student, int marks) { Marks { if (student == null || student.isBlank()) { throw new IllegalArgumentException("name is missing"); } if (marks < 0 || marks > 100) { throw new IllegalArgumentException("marks must be 0-100, got " + marks); } }}
public class TextLineDemo { // Text received from another app: only names and numbers, never class names static final String RECEIVED = "Aditi,88\nBala,74\nChetan,250\nDeepa\nEsha,91";
public static void main(String[] args) { List<Marks> good = new ArrayList<>(); int lineNo = 0; for (String line : RECEIVED.split("\n")) { lineNo++; String[] parts = line.split(","); try { if (parts.length != 2) { throw new IllegalArgumentException("expected 2 values, got " + parts.length); } good.add(new Marks(parts[0].trim(), Integer.parseInt(parts[1].trim()))); } catch (IllegalArgumentException e) { // NumberFormatException is a subclass System.out.println("Line " + lineNo + " skipped: " + e.getMessage()); } } System.out.println("Loaded " + good.size() + " rows: " + good); }}Line 3 skipped: marks must be 0-100, got 250 Line 4 skipped: expected 2 values, got 1 Loaded 3 rows: [Marks[student=Aditi, marks=88], Marks[student=Bala, marks=74], Marks[student=Esha, marks=91]]
What this code does
- The data from the other app is plain text lines. The program splits each line and builds
Markswith its own constructor, so it never reads a class name from the data. - Bad lines (marks 250, a missing value) are reported and skipped by the record's checks and the column count check.
- This is the usual choice across a trust boundary; the next lesson compares text formats in more detail.
For anything crossing that line, use a plain data format such as CSV or JSON. Your code reads only names and numbers, never class names, and builds objects through your own constructors with your own checks. Keep Java serialization, if at all, for data your own program wrote and stored somewhere only it can change.
Next step
Check your understanding
12 quick questions