DEV Community

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

Posted on

2 1

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)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay