Java SE API

ObjectInputFilter

Inspect class and graph metrics; use only as limited defense in depth.

Formal Syntax & Structure

java syntaxjava
ObjectInputFilter.Status checkInput(ObjectInputFilter.FilterInfo info)

Working Example

Example Snippetjava
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"); }    }}
Java Reference