Create an allow-list ObjectInputFilter that accepts only Order records, ArrayList and java.base classes; show that a valid stream loads while a stream containing an unexpected serializable class is rejected with InvalidClassException.
Solution
Main.java
import java.io.*;
import java.util.ArrayList;
import java.util.List;
record Order(String id, int amount) implements Serializable { }
class Gadget implements Serializable { // stands in for a class an attacker might smuggle in
private static final long serialVersionUID = 1L;
String command = "rm -rf /";
}
public class Main {
static byte[] save(Object o) throws IOException {
ByteArrayOutputStream b = new ByteArrayOutputStream();
try (ObjectOutputStream out = new ObjectOutputStream(b)) { out.writeObject(o); }
return b.toByteArray();
}
static Object safeLoad(byte[] data) throws IOException, ClassNotFoundException {
ObjectInputFilter filter = ObjectInputFilter.Config.createFilter("Order;java.util.ArrayList;java.base/*;maxdepth=5;!*");
try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(data))) {
in.setObjectInputFilter(filter);
return in.readObject();
}
}
public static void main(String[] args) throws Exception {
ArrayList<Object> good = new ArrayList<>(List.of(new Order("O1", 499), new Order("O2", 1299)));
System.out.println("good: " + safeLoad(save(good)));
ArrayList<Object> evil = new ArrayList<>(List.of(new Order("O3", 99), new Gadget()));
try {
safeLoad(save(evil));
} catch (InvalidClassException e) {
System.out.println("rejected: " + e.getMessage().contains("REJECTED"));
}
}
}
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!