ObjectInputFilter Deserialize Allowlist

Attach an ObjectInputFilter allowlist before readObject so only approved classes are rebuilt; anything else fails fast as InvalidClassException.

JavaSecurity Boundaries

Code

snippet
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InvalidClassException;
import java.io.ObjectInputFilter;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class DeserializeGate {

    record Point(int x, int y) implements Serializable {}
    record Size(int width, int height) implements Serializable {}

    static byte[] freeze(Object payload) throws Exception {
        try (ByteArrayOutputStream bytes = new ByteArrayOutputStream();
             ObjectOutputStream out = new ObjectOutputStream(bytes)) {
            out.writeObject(payload);
            return bytes.toByteArray();
        }
    }

    static Object thaw(byte[] blob, ObjectInputFilter filter) throws Exception {
        try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(blob))) {
            in.setObjectInputFilter(filter);   // 白名单在 readObject 之前挂上(JDK 9+)
            return in.readObject();
        }
    }

    public static void main(String[] args) throws Exception {
        byte[] pointBlob = freeze(new Point(3, 4));
        byte[] sizeBlob = freeze(new Size(800, 600));

        // 只放行本类的 Point;java.base/* 放行基础类型与 String;!* 拒绝其余一切
        ObjectInputFilter allowPoint = ObjectInputFilter.Config.createFilter(
                "DeserializeGate$Point;java.base/*;!*");

        System.out.println(thaw(pointBlob, allowPoint));

        try {
            thaw(sizeBlob, allowPoint);
        } catch (InvalidClassException e) {
            System.out.println("blocked: " + e.getMessage());
        }
    }
}

How the snippet works

The working surface is the classes DeserializeGate, Point and Size — everything else is wiring.

Resources live in the try header, so closing is compiler-generated and exception-safe.

Applying it

Running the file prints labeled results such as blocked: — each operation’s effect is visible in the output.

Statements that matter

return bytes.toByteArray();
return in.readObject();

Interactive Tools for This Topic

FAQ

What does ObjectInputFilter Deserialize Allowlist print when run?
Run it as a complete program — the output lines carry labels such as `blocked:`.