Serialization risks and safe parsing
What you will learn
Java native serialization can reconstruct object graphs, not just data fields. Deserializing arbitrary input can invoke behavior or consume excessive resources; avoid it at untrusted boundaries. ObjectInputFilter adds limited checks for legacy, trusted flows, not a proof of safety. Prefer explicit bounded structured parsing, validation and authorization.
- Explain why native deserialization has a larger risk surface than explicit data parsing.
- Apply a narrow filter to self-generated lab data and observe rejection.
- Validate a bounded data record and distinguish validity from permission.
Each example is a complete Main.java file. Use a fresh lab-owned directory: javac --release 21 -proc:none Main.java, then java Main. Use only generated test keys and fixed synthetic inputs. Never supply real credentials or arbitrary serialized data. The runner enforces a process deadline.
Read a self-generated record with a narrow filter
import java.io.*;import java.nio.charset.StandardCharsets;import java.security.*;import java.util.*;import javax.crypto.*;import javax.crypto.spec.GCMParameterSpec;import javax.net.ssl.*;public class Main { record Ticket(int count) implements Serializable { private static final long serialVersionUID = 1L; Ticket { if (count < 1 || count > 10) throw new IllegalArgumentException("count"); } } static byte[] localBytes(Object value) throws IOException { var buffer = new ByteArrayOutputStream(); try (var out = new ObjectOutputStream(buffer)) { out.writeObject(value); } return buffer.toByteArray(); } static Ticket readLocal(byte[] bytes) throws IOException, ClassNotFoundException { if (bytes.length > 1024) throw new IOException("size limit"); try (var in = new ObjectInputStream(new ByteArrayInputStream(bytes))) { in.setObjectInputFilter(info -> { if (info.depth() > 3 || info.references() > 8 || info.streamBytes() > 1024 || info.arrayLength() > 16) return ObjectInputFilter.Status.REJECTED; Class<?> type = info.serialClass(); if (type == null) return ObjectInputFilter.Status.UNDECIDED; return type == Ticket.class ? ObjectInputFilter.Status.ALLOWED : ObjectInputFilter.Status.REJECTED; }); Object value = in.readObject(); if (!(value instanceof Ticket ticket)) throw new InvalidObjectException("unexpected type"); return ticket; } } public static void main(String[] args) throws Exception { System.out.println(readLocal(localBytes(new Ticket(3))).count()); }}Expected output:
3The fixture creates and consumes its own known record. Its constructor enforces the count invariant.
Native serialization is not a wire-data default
ObjectOutputStream writes object representations; ObjectInputStream reconstructs them. The type graph and serialization hooks make reconstruction unlike reading plain text. A serialVersionUID is a compatibility marker, not a security guarantee. Do not accept native serialized objects from network requests, user uploads or arbitrary learner input. The first two examples only read bytes created immediately by the same reviewed fixture.
Filters are defense in depth
ObjectInputFilter can inspect encountered classes, graph depth, reference count, bytes read at filter invocations and array lengths. It is not invoked for every primitive or concrete String value; a filter cannot validate all field values, guarantee a safe class implementation, or serve as a sandbox. The outer byte cap is explicit, class policy is narrowly scoped, and the final type is checked. A reject result ends deserialization; undecided is not an allowlist verdict. Real legacy deployments need context-specific filters and a reviewed process-wide filter factory, separate budgets and an inventory of allowed classes. Do not treat this sample as a generic safe deserializer.
Explicit data and authorization
Prefer a maintained JSON or other structured parser configured with schema, size, depth and field constraints, without unsafe polymorphic type selection. The example uses a tiny two-field grammar rather than implementing CSV or JSON. Validate bytes before decoding and bound the read at the I/O boundary, not just after constructing a String; check syntax, numeric bounds and domain invariants. Derive the actor identity and tenant scope from trusted authentication context, not a submitted field. A syntactically valid order may still be unauthorized. Apply resource limits, redact secrets, review dependencies and reject invalid inputs before side effects.
Reject a different locally generated type
import java.io.*;import java.nio.charset.StandardCharsets;import java.security.*;import java.util.*;import javax.crypto.*;import javax.crypto.spec.GCMParameterSpec;import javax.net.ssl.*;public class Main { record Ticket(int count) implements Serializable { private static final long serialVersionUID = 1L; Ticket { if (count < 1 || count > 10) throw new IllegalArgumentException("count"); } } static byte[] localBytes(Object value) throws IOException { var buffer = new ByteArrayOutputStream(); try (var out = new ObjectOutputStream(buffer)) { out.writeObject(value); } return buffer.toByteArray(); } static Ticket readLocal(byte[] bytes) throws IOException, ClassNotFoundException { if (bytes.length > 1024) throw new IOException("size limit"); try (var in = new ObjectInputStream(new ByteArrayInputStream(bytes))) { in.setObjectInputFilter(info -> { if (info.depth() > 3 || info.references() > 8 || info.streamBytes() > 1024 || info.arrayLength() > 16) return ObjectInputFilter.Status.REJECTED; Class<?> type = info.serialClass(); if (type == null) return ObjectInputFilter.Status.UNDECIDED; return type == Ticket.class ? ObjectInputFilter.Status.ALLOWED : ObjectInputFilter.Status.REJECTED; }); Object value = in.readObject(); if (!(value instanceof Ticket ticket)) throw new InvalidObjectException("unexpected type"); return ticket; } } public static void main(String[] args) throws Exception { try { readLocal(localBytes(new int[]{1, 2})); throw new AssertionError(); } catch (InvalidClassException expected) { System.out.println("rejected"); } }}Expected output:
rejectedThe filter rejects the array class even though its size is small. This is a controlled benign local test, not an exploit payload.
Parse and authorize a bounded order
import java.io.*;import java.nio.charset.StandardCharsets;import java.security.*;import java.util.*;import javax.crypto.*;import javax.crypto.spec.GCMParameterSpec;import javax.net.ssl.*;public class Main { record Order(String sku, int quantity) { Order { if (!sku.matches("[A-Z]{2}[0-9]{2}") || quantity < 1 || quantity > 10) throw new IllegalArgumentException("invalid order"); } } static Order parse(String line) { if (line.length() > 32) throw new IllegalArgumentException("too long"); String[] parts = line.split(",", -1); if (parts.length != 2 || !parts[1].matches("[0-9]{1,2}")) throw new IllegalArgumentException("invalid fields"); return new Order(parts[0], Integer.parseInt(parts[1])); } static boolean authorized(String actorWarehouse, String orderWarehouse) { return actorWarehouse.equals(orderWarehouse); } public static void main(String[] args) throws Exception { Order order = parse("AB12,3"); System.out.println(order.sku() + ":" + order.quantity()); System.out.println(authorized("north", "south")); try { parse("AB12,99"); throw new AssertionError(); } catch (IllegalArgumentException expected) { System.out.println("invalid"); } }}Expected output:
AB12:3falseinvalidParsing succeeds for a valid order while the fictional actor is not authorized for a different warehouse. The quantity limit rejects invalid data.
Common mistakes
Avoid arbitrary ObjectInputStream input, broad allowlists, assuming the byte metric fires on every byte, allowing unsafe polymorphic deserialization, and treating valid input as authorized. Do not log raw submitted data or credentials.
Practice
Parse AB12,10 and check the same warehouse authorization. Reject AB12,0 and AB12,1,extra. Keep the existing size and field limits.
Expected output:
10trueinvalidinvalidCompare your answer with the manual practice criteria.
Official reading: ObjectInputFilter · ObjectInputStream. Java 25 execution remains unverified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Serialization risks and safe parsing — knowledge check
Original Java security questions.
Why avoid deserializing arbitrary native objects?
What can a filter inspect?
What does serialVersionUID mean?
When should a network size limit apply?
What does a valid order prove?