DEV Community

Cover image for How to prevent a potential remote code execution via SnakeYAML deserialization
Alex Yaroslavsky
Alex Yaroslavsky

Posted on

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

Top comments (0)