Join our Newsletter — 33% off our NHI Course
Home› Guides› YAML Parsing Security Guide: Safe Loaders Across Python,…
Guide Application Security

YAML Parsing Security Guide: Safe Loaders Across Python, Java, Ruby and JavaScript

PDF for newsletter subscribers · free to read online

← All guides
By NHI Mgmt Group, under the editorial direction of Lalit Choda Updated 27 November 2026 14 min read
On this page

YAML looks like a configuration format, but most YAML libraries are also object deserialisers, and the wrong load call lets a document decide which classes your program builds. That single design choice has produced remote code execution findings in PyYAML, SnakeYAML, js-yaml and Ruby's Psych, and the safe defaults have changed several times across major versions. This guide gives developers and AppSec engineers the safe loader for each of the four most common ecosystems, explains how alias expansion turns a small file into a memory or CPU problem, and shows how to find and block unsafe calls in code review and CI. It goes deeper on YAML than the general Secure Deserialisation Guide and contains no exploit strings. Library facts were checked against each project's own source and changelog in November 2026; languages are listed alphabetically.

Key takeaways

  • Type tags are the danger, not the syntax. Language-specific tags such as Python and Ruby object tags or Java global tags let a document name a class to construct. Safe loaders refuse them; full and unsafe loaders do not.
  • Defaults depend on the version you run. PyYAML 6.0 requires an explicit Loader, Psych 4.0 made Psych.load safe, js-yaml 4.0 made load safe, and SnakeYAML 2.0 stopped allowing global tags by default. Older pinned versions keep the old, unsafe behaviour.
  • "Full" is not "safe". PyYAML's own documentation says FullLoader should not be used on untrusted data. Use safe_load, nothing in between.
  • Safe loaders still need resource limits. Anchors and aliases let a few hundred bytes expand into millions of nodes. SnakeYAML and the JavaScript libraries expose alias, depth and size limits; PyYAML and Psych need input size caps and alias rules in your code.
  • Enforce it with tooling. Bandit B506, RuboCop Security/YAMLLoad and CodeQL py/unsafe-deserialization catch most unsafe calls; pair them with dependency pinning so a downgrade cannot reopen the hole.

Why YAML parsing is risky

YAML 1.1 and 1.2 define tags that tell a parser what type a node should become. Common tags such as strings, integers, maps and sequences are harmless. The risk comes from language-specific tags that map a node to an arbitrary class or function in the host language. When the loader honours them, attacker-controlled YAML can instantiate classes with side effects in their constructors or setters, which is the classic CWE-502 pattern. MITRE defines CWE-502 as a product that "deserializes untrusted data without sufficiently ensuring that the resulting data will be valid", and its observed examples include an untrusted YAML deserialisation flaw in a data visualisation dashboard.

Two further risk classes apply even with a safe loader:

  • Resource exhaustion: anchors (&) and aliases (*) reference earlier nodes, so nested references expand exponentially when the result is walked or serialised. This is the YAML equivalent of the XML "billion laughs" attack (CWE-400 Uncontrolled Resource Consumption).
  • Parser differentials and type surprises: YAML 1.1 resolvers read no, off and yes as booleans and some unquoted values as numbers or dates, while YAML 1.2 core schemas do not. Two services parsing the same file with different libraries can disagree, which matters for policy files and allowlists. OWASP ASVS 5.0 V1.5.3 asks that parsers for the same data type parse consistently.

Where untrusted YAML reaches you in practice: uploaded configuration, CI pipeline definitions from forks, Kubernetes manifests and Helm values submitted by tenants, infrastructure-as-code from third parties, API endpoints that accept YAML bodies, and model or dataset metadata files pulled from public hubs. Treat any of these as untrusted unless their origin is authenticated.

Safe versus unsafe APIs at a glance

Language and libraryUnsafe on untrusted inputSafe choiceVersion where defaults changed
Java: SnakeYAMLnew Yaml() on 1.x; any Constructor with a permissive TagInspector on 2.xnew Yaml(new SafeConstructor(new LoaderOptions())), or binding to a declared root type with global tags left disabled2.0 (26 Feb 2023): global tags disabled by default
JavaScript: js-yamlload on 3.x; adding the separate JavaScript types package on any versionload on 4.x and 5.x with the default CORE_SCHEMA4.0.0 (3 Jan 2021): load safe by default; 5.0.0 removed the old safeLoad exports
JavaScript: yaml (eemeli)Custom tags that construct functions or classesparse with the default core schema and default maxAliasCountNo unsafe tags in the default schema
Python: PyYAMLyaml.unsafe_load, yaml.load(..., Loader=yaml.Loader) or UnsafeLoader, FullLoaderyaml.safe_load / yaml.safe_load_all (or Loader=yaml.CSafeLoader)5.1 (13 Mar 2019): loader warning; 5.4 (19 Jan 2021): Python object tags moved to UnsafeLoader; 6.0 (13 Oct 2021): Loader argument required
Ruby: PsychPsych.unsafe_load, YAML.load on Psych 3 and earlierYAML.safe_load with an explicit permitted_classes list; YAML.load on Psych 4Psych 4.0 (shipped with Ruby 3.1): load uses safe_load

Java

SnakeYAML is the YAML engine behind much of the Java ecosystem, including several configuration frameworks. OWASP's Deserialization Cheat Sheet states that SnakeYAML cannot be used safely unless SafeConstructor is used, which disables deserialisation of arbitrary classes. The project's changelog records that version 2.0 (26 February 2023) stopped allowing global tags by default, a backwards-incompatible change made to address CVE-2022-1471, and removed many deprecated methods.

In SnakeYAML 2.x the LoaderOptions class carries the security settings. Its source sets these defaults:

LoaderOptions fieldDefaultWhat it protects
tagInspectorUnTrustedTagInspector (no custom classes)Blocks global tags that name classes
maxAliasesForCollections50Limits aliases for collections, the billion laughs pattern
allowRecursiveKeysfalseRejects keys that refer to themselves
nestingDepthLimit50Caps nesting to avoid stack exhaustion
codePointLimit3 MB (3 x 1024 x 1024 code points)Caps document size; applied per document from 2.1
allowDuplicateKeystrueSet to false for policy files so a later key cannot silently override an earlier one
  • Preferred pattern: build a LoaderOptions object explicitly, keep the default tag inspector, set allowDuplicateKeys to false and lower codePointLimit to the largest document you expect, then pass it to SafeConstructor. Map the resulting maps and lists into your own record classes with validation.
  • If you must bind to classes: use a typed root (a constructor for one declared class) and, if tags are unavoidable, a custom TagInspector that allows a short, named list. Never return true for every tag.
  • Dependencies: many frameworks pull SnakeYAML transitively. Check the resolved version in your build tool's dependency tree; a 1.x copy reintroduces permissive defaults. Version 2.2 (27 August 2023) is the latest release listed on the project's changes page as of November 2026.

For broader Java guidance see the Oracle Java Secure Coding Guidelines Guide.

JavaScript

js-yaml 4.0.0 (3 January 2021) moved the JavaScript-specific tags for functions, regular expressions and undefined into a separate package and made load, loadAll and dump safe by default; the old safe* functions were removed. js-yaml 5.0.0 (20 June 2026) reduced the exported schemas: load uses CORE_SCHEMA without the merge key by default, and the deprecated safeLoad() exports were removed, so code still calling them fails at import.

  • Do not reintroduce unsafe tags: adding the JavaScript types package or custom tags with a construct function that calls Function, eval or a class lookup undoes the safe default. Review any withTags or schema extension in code review.
  • Resource options in js-yaml 5.x: the changelog adds maxDepth (100), maxTotalMergeKeys (10,000) and maxAliases (default -1, meaning unlimited) loader options, and 5.4.1 hard-limits merge sequence size to 100. Set maxAliases to a small number for untrusted input. The 4.3.0 and 3.15.0 releases backported maxTotalMergeKeys only.
  • The project's own safety notes: js-yaml's safety document recommends limiting input size, catching every exception and treating it as a rejected document, and counting nodes with a non-recursive walk before materialising the result with JSON.stringify or a deep clone.
  • The alternative yaml package: its documented maxAliasCount option defaults to 100 to prevent exponential entity expansion; 0 disallows all aliases, -1 disables the check. Leave it on.
  • Prototype keys: parse untrusted maps into objects without a prototype or into Map (js-yaml documents an alternate map tag for this) so keys such as __proto__ are data, not object structure.

See the TypeScript and JavaScript Secure Coding Guide for prototype pollution and input handling in general.

Python

PyYAML is the most common source of YAML deserialisation findings because its original yaml.load() constructed arbitrary Python objects. The project changelog and deprecation notice give the timeline: 5.1 (13 March 2019) deprecated plain yaml.load and added FullLoader and UnsafeLoader; 5.4 (19 January 2021) fixed CVE-2020-14343 by moving arbitrary Python tags to UnsafeLoader; 6.0 (13 October 2021) made the Loader argument mandatory. The 6.0.x line is current as of November 2026.

PyYAML loaderWhat the project saysUse on untrusted input?
BaseLoaderLoads the most basic YAML; all scalars become stringsYes, when you want strings only
SafeLoader (safe_load)Resolves only basic YAML tags; "known to be safe for untrusted input"Yes, the default choice
FullLoader (full_load)Resolves all tags except those known to be unsafe; the deprecation notice warns against untrusted dataNo
UnsafeLoader / Loader (unsafe_load)The original loader; easily exploitable with untrusted inputNever
  • Use the C loader safely: yaml.load(stream, Loader=yaml.CSafeLoader) gives libyaml speed with safe semantics. Fall back to SafeLoader if the C extension is missing.
  • Custom constructors: registering a constructor on SafeLoader with add_constructor changes it for the whole process. Subclass SafeLoader and register on the subclass, and never add constructors that import modules or call arbitrary callables.
  • No built-in alias limit: PyYAML's loaders do not expose an alias-count option, so cap input size before parsing and reject documents with anchors where your schema does not need them (check events from yaml.parse for alias events first).
  • Validate after parsing: pass the result through a schema validator or typed model so unexpected types fail fast.

Ruby

Ruby's YAML module is Psych. The Ruby 3.1.0 release notes state that Psych 4.0 changes Psych.load to use safe_load by default. In current Psych source, load calls safe_load with permitted_classes: [Symbol] and aliases: false, while unsafe_load keeps the old behaviour. Applications pinned to Psych 3, or Rails code that calls unsafe_load to "fix" an error after an upgrade, remain exposed.

  • Use YAML.safe_load explicitly: it makes intent clear across Psych versions. Pass permitted_classes only for value types you need, such as Date, and avoid permitting application classes.
  • Keep aliases: false: it is the default for safe_load and load. Turning it on re-enables alias expansion, so pair it with an input size cap.
  • Files: use YAML.safe_load_file rather than load_file on Psych 3, and avoid unsafe_load_file for anything outside your own repository.
  • Serialised columns and caches: YAML stored in databases or caches is only as trusted as every writer to that store. Prefer JSON for stored structures.

Resource exhaustion and alias bombs

A safe loader stops code execution but not exhaustion. An alias bomb defines an anchor, then a node that references it several times, then a node that references that node several times, and so on, so each level multiplies the size. Libraries can keep references shared while parsing, but the cost appears when the application walks, copies, validates or serialises the result. Deep nesting causes stack overflow, and very long keys or merge chains cause CPU spikes; js-yaml's 2026 changelog records several fixes of this kind.

ControlJava (SnakeYAML)JavaScript (js-yaml / yaml)Python (PyYAML)Ruby (Psych)
Alias limitmaxAliasesForCollections (50)maxAliases (-1 by default, set it) / maxAliasCount (100)Application check on parse eventsaliases: false (default)
Depth limitnestingDepthLimit (50)maxDepth (100) in js-yaml 4.2+Application checkApplication check
Size limitcodePointLimit (3 MB)Cap request or file size before loadCap bytes read before parsingCap bytes read before parsing

Add a wall-clock timeout or worker isolation for parsers in request paths, and enforce body size limits at the gateway as well as in code. NIST SP 800-53 SI-10 Information Input Validation covers both the validation and the limits.

Testing and linting

Unsafe YAML calls are easy to find statically because the dangerous function names are well known. Run these checks in CI and block merges on them.

ToolRuleWhat it flags
Bandit (Python)B506 yaml_loadUnsafe use of yaml.load; suggests yaml.safe_load
CodeQL (Python)py/unsafe-deserialization (CWE-502)User-controlled data reaching a deserialiser, with data flow paths
RuboCop (Ruby)Security/YAMLLoadYAML.load calls; notes Psych 4 behaviour on Ruby 3.1+
Dependency scanning (all)SCA advisoriesSnakeYAML 1.x, js-yaml 3.x, PyYAML below 5.4 and Psych 3 in the resolved tree
  1. Inventory: grep for unsafe_load, FullLoader, Loader=yaml.Loader, new Yaml(, TagInspector, YAML.load and schema extensions, and list where each input comes from.
  2. Fix by priority: internet-facing and multi-tenant inputs first, then CI and build inputs, then local-only tooling.
  3. Add regression tests: unit tests that feed a document containing a language-specific tag and assert the loader raises an error, plus a nested alias document that must be rejected within a time budget. Keep these fixtures inert: unknown tag names are enough to prove rejection.
  4. Pin and monitor: pin parser versions, alert on downgrades, and fuzz parsers that take untrusted input.
  5. Roll back safely: if a safe loader breaks a legitimate file that used custom tags, convert the file to plain types or allow one named class; do not revert to the unsafe loader.

Metrics: count of unsafe YAML calls open in SAST (target zero on internet-facing code), percentage of repositories with the lint rule blocking, number of resolved SnakeYAML 1.x, js-yaml 3.x or pre-5.4 PyYAML copies, mean time to fix a new B506 or CodeQL finding, and the rate of rejected YAML documents at runtime (a sudden rise can indicate probing). Log parser exceptions with the source and size, never the full document. Probing of public endpoints maps to ATT&CK T1190 Exploit Public-Facing Application.

Framework mapping

FrameworkReferenceRelevance
MITRE CWECWE-502, CWE-400Unsafe tags; alias and depth exhaustion
OWASP ASVS 5.0V1.5.2, V1.5.3Safe deserialisation with type allowlists; consistent parsing
NIST SP 800-53 Rev 5SI-10, SA-11, SI-2Input validation, developer testing, flaw remediation of parser versions
NIST CSF 2.0PR.PS, ID.RASecure software practice; vulnerability identification

Common failure patterns

  • Switching to the unsafe loader to silence an error: after PyYAML 6.0 or Psych 4 upgrades, teams add Loader=yaml.Loader or unsafe_load to make old files load. Fix the file instead.
  • Trusting FullLoader: it sounds safe and is the old default for yaml.load in PyYAML 5.x, but the project warns against untrusted data.
  • A transitive SnakeYAML 1.x: the application uses 2.x directly but a plugin brings in 1.x, and the classpath picks the old one.
  • Permissive TagInspector: a lambda that returns true for all tags, written to make a migration compile, turns 2.x back into 1.x behaviour.
  • Safe loader, no limits: code execution is fixed but a small upload with nested aliases takes down a worker when the result is serialised to JSON.
  • Treating CI files as trusted: pipeline and manifest YAML from forks or tenants is attacker input; see the CI/CD Security Guide.

Practitioner checklist

  • Inventory every YAML parse call and classify its input as trusted or untrusted.
  • Use safe_load (Python, Ruby), SafeConstructor with explicit LoaderOptions (Java), and default load on js-yaml 4 or later (JavaScript).
  • Remove FullLoader, UnsafeLoader, unsafe_load and permissive tag inspectors from code that touches untrusted input.
  • Pin SnakeYAML 2.x, js-yaml 4 or later, PyYAML 6.0 or later and Psych 4 or later, and check the resolved dependency tree.
  • Set alias, depth and size limits, and add body size caps and timeouts in request paths.
  • Validate parsed data against a schema or typed model before use.
  • Enable Bandit B506, RuboCop Security/YAMLLoad and CodeQL deserialisation queries as blocking checks.
  • Add inert regression tests for tag rejection and alias limits.

Standards and references

Related NHI Mgmt Group resources: Secure Coding Guide · Secure Deserialisation Guide · Insecure Deserialisation Guide · Application Security Guide

PDF for subscribers

Take this guide with you

Every section, table and checklist in one PDF, with links to the sources and related guides. Subscribe to our weekly NHI & AI Identity Journal and we’ll email you a download link.

Free weekly newsletter

Subscribe to the NHI & AI Identity Journal

The latest on NHI and Agentic AI security – articles, research, breaches, news and events every week.

Bonus 33% off our NHI Course when you subscribe.

PDF Downloads for Newsletter Subscribers

Get the guide

Enter your details and we’ll email you a download link.

The full guide is free to read online. The PDF is a thank you for subscribing.

Fill in all fields marked * and tick both boxes to continue.