LearnFrenzy
Sign in Take a free test

Serialization · Serialization Programs · Question 5

Block unexpected classes with an ObjectInputFilter in Java Solution, output & explanation

  • Program
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

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"));
        }
    }
}

Output Verified by compiling and running

good: [Order[id=O1, amount=499], Order[id=O2, amount=1299]]
rejected: true

The filter pattern lists allowed classes and ends with !* to reject everything else; limits such as maxdepth stop resource-exhaustion attacks.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links