Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: More general compliant solution, using reflection

...

Code Block
bgColor#ccccff
languagejava
import java.io.*;
 
interface Whitelist {
  public boolean contains(String className);
}
 
class WhitelistedObjectInputStream extends ObjectInputStream {
  Whitelist whitelist;
 
  public WhitelistedObjectInputStream(InputStream inputStream) throws IOException {
    super(inputStream);
  }
 
  public void setWhitelist(Whitelist wl) {
    whitelist = wl;
  }
}
 
class import java.lang.reflect.*;
 
class OpenedFile implements Serializable {
  public String filename;
  public BufferedReader reader;

  public OpenedFile(String _filename) throws FileNotFoundException {
    filename = _filename;
    init();
  }
  private void init() throws FileNotFoundException {
      reader = new BufferedReader(new FileReader(filename));
  }
     
  private void writeObject(ObjectOutputStream out) throws IOException {
    out.writeUTF(filename);
  }

  private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
    boolean isWhitelisted = ((in instanceof WhitelistedObjectInputStream) &&
false;
    try {
        Object whitelist = in.getClass((WhitelistedObjectInputStream) in).whitelist.contains().getDeclaredField("whitelist").get(in);
        Method contains = whitelist.getClass().getMethod("contains", new Class[]{Object.class});
        isWhitelisted = contains.invoke(whitelist, this.getClass().getName()).equals(Boolean.TRUE);
    } catch (ReflectiveOperationException e) {}
    if (!isWhitelisted) {
      throw new SecurityException("Attempted to deserialize unexpected class.");
    }
    filename = in.readUTF();
    init();
  }
}

...