How to prevent a potential remote code execution via SnakeYAML deserialization

trexinc

Alex Yaroslavsky

Posted on August 5, 2021

How to prevent a potential remote code execution via SnakeYAML deserialization

A popular java library for YAML parsing, SnakeYAML, has a well know vulnerability if used incorrectly to parse user generated YAMLs.

You can read about the vulnerability itself here:

The solutions for this problem that I have found on the net are either incorrect or unusable in real life. So I want to share here the solution that I have come up with.

It is quite simple:

  public static <T> T parseYamlSafe(String yaml, Constructor constructor) {
    Yaml yamlParser = new Yaml(new SafeConstructor());
    // the following line throws an exception
    // if constructors for non standard java types exist in yaml
    yamlParser.load(yaml);

    //if we got here, the YAML is safe to parse.
    yamlParser = new Yaml(constructor); 
    return yamlParser.load(yaml);
  }
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
trexinc
Alex Yaroslavsky

Posted on August 5, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related