ObjectInputFilter Deserialize Allowlist
Attach an ObjectInputFilter allowlist before readObject so only approved classes are rebuilt; anything else fails fast as InvalidClassException.
Code
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
Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.CSP Header BuilderBuild a Content-Security-Policy header from per-directive sources, skipping empty ones and rejecting a blanket wildcard.
FAQ
- What does ObjectInputFilter Deserialize Allowlist print when run?
- Run it as a complete program — the output lines carry labels such as `blocked:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.