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 madePsych.loadsafe, js-yaml 4.0 madeloadsafe, 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
FullLoadershould not be used on untrusted data. Usesafe_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/YAMLLoadand CodeQLpy/unsafe-deserializationcatch 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,offandyesas 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 library | Unsafe on untrusted input | Safe choice | Version where defaults changed |
|---|---|---|---|
| Java: SnakeYAML | new Yaml() on 1.x; any Constructor with a permissive TagInspector on 2.x | new Yaml(new SafeConstructor(new LoaderOptions())), or binding to a declared root type with global tags left disabled | 2.0 (26 Feb 2023): global tags disabled by default |
| JavaScript: js-yaml | load on 3.x; adding the separate JavaScript types package on any version | load on 4.x and 5.x with the default CORE_SCHEMA | 4.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 classes | parse with the default core schema and default maxAliasCount | No unsafe tags in the default schema |
| Python: PyYAML | yaml.unsafe_load, yaml.load(..., Loader=yaml.Loader) or UnsafeLoader, FullLoader | yaml.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: Psych | Psych.unsafe_load, YAML.load on Psych 3 and earlier | YAML.safe_load with an explicit permitted_classes list; YAML.load on Psych 4 | Psych 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 field | Default | What it protects |
|---|---|---|
tagInspector | UnTrustedTagInspector (no custom classes) | Blocks global tags that name classes |
maxAliasesForCollections | 50 | Limits aliases for collections, the billion laughs pattern |
allowRecursiveKeys | false | Rejects keys that refer to themselves |
nestingDepthLimit | 50 | Caps nesting to avoid stack exhaustion |
codePointLimit | 3 MB (3 x 1024 x 1024 code points) | Caps document size; applied per document from 2.1 |
allowDuplicateKeys | true | Set to false for policy files so a later key cannot silently override an earlier one |
- Preferred pattern: build a
LoaderOptionsobject explicitly, keep the default tag inspector, setallowDuplicateKeysto false and lowercodePointLimitto the largest document you expect, then pass it toSafeConstructor. 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
TagInspectorthat 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
constructfunction that callsFunction,evalor a class lookup undoes the safe default. Review anywithTagsor schema extension in code review. - Resource options in js-yaml 5.x: the changelog adds
maxDepth(100),maxTotalMergeKeys(10,000) andmaxAliases(default -1, meaning unlimited) loader options, and 5.4.1 hard-limits merge sequence size to 100. SetmaxAliasesto a small number for untrusted input. The 4.3.0 and 3.15.0 releases backportedmaxTotalMergeKeysonly. - 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.stringifyor a deep clone. - The alternative yaml package: its documented
maxAliasCountoption 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 loader | What the project says | Use on untrusted input? |
|---|---|---|
BaseLoader | Loads the most basic YAML; all scalars become strings | Yes, 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 data | No |
UnsafeLoader / Loader (unsafe_load) | The original loader; easily exploitable with untrusted input | Never |
- Use the C loader safely:
yaml.load(stream, Loader=yaml.CSafeLoader)gives libyaml speed with safe semantics. Fall back toSafeLoaderif the C extension is missing. - Custom constructors: registering a constructor on
SafeLoaderwithadd_constructorchanges it for the whole process. SubclassSafeLoaderand 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.parsefor 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_loadexplicitly: it makes intent clear across Psych versions. Passpermitted_classesonly for value types you need, such asDate, and avoid permitting application classes. - Keep
aliases: false: it is the default forsafe_loadandload. Turning it on re-enables alias expansion, so pair it with an input size cap. - Files: use
YAML.safe_load_filerather thanload_fileon Psych 3, and avoidunsafe_load_filefor 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.
| Control | Java (SnakeYAML) | JavaScript (js-yaml / yaml) | Python (PyYAML) | Ruby (Psych) |
|---|---|---|---|---|
| Alias limit | maxAliasesForCollections (50) | maxAliases (-1 by default, set it) / maxAliasCount (100) | Application check on parse events | aliases: false (default) |
| Depth limit | nestingDepthLimit (50) | maxDepth (100) in js-yaml 4.2+ | Application check | Application check |
| Size limit | codePointLimit (3 MB) | Cap request or file size before load | Cap bytes read before parsing | Cap 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.
| Tool | Rule | What it flags |
|---|---|---|
| Bandit (Python) | B506 yaml_load | Unsafe 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/YAMLLoad | YAML.load calls; notes Psych 4 behaviour on Ruby 3.1+ |
| Dependency scanning (all) | SCA advisories | SnakeYAML 1.x, js-yaml 3.x, PyYAML below 5.4 and Psych 3 in the resolved tree |
- Inventory: grep for
unsafe_load,FullLoader,Loader=yaml.Loader,new Yaml(,TagInspector,YAML.loadand schema extensions, and list where each input comes from. - Fix by priority: internet-facing and multi-tenant inputs first, then CI and build inputs, then local-only tooling.
- 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.
- Pin and monitor: pin parser versions, alert on downgrades, and fuzz parsers that take untrusted input.
- 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
| Framework | Reference | Relevance |
|---|---|---|
| MITRE CWE | CWE-502, CWE-400 | Unsafe tags; alias and depth exhaustion |
| OWASP ASVS 5.0 | V1.5.2, V1.5.3 | Safe deserialisation with type allowlists; consistent parsing |
| NIST SP 800-53 Rev 5 | SI-10, SA-11, SI-2 | Input validation, developer testing, flaw remediation of parser versions |
| NIST CSF 2.0 | PR.PS, ID.RA | Secure 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.Loaderorunsafe_loadto make old files load. Fix the file instead. - Trusting FullLoader: it sounds safe and is the old default for
yaml.loadin 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),SafeConstructorwith explicitLoaderOptions(Java), and defaultloadon js-yaml 4 or later (JavaScript). - Remove
FullLoader,UnsafeLoader,unsafe_loadand 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
- MITRE: CWE-502 Deserialization of Untrusted Data
- OWASP: Deserialization Cheat Sheet
- OWASP: Application Security Verification Standard 5.0
- SnakeYAML: Changes
- js-yaml: Changelog
- js-yaml: Safety notes for untrusted input
- PyYAML: yaml.load(input) Deprecation
- Ruby: Ruby 3.1.0 Released (Psych 4.0)
Related NHI Mgmt Group resources: Secure Coding Guide · Secure Deserialisation Guide · Insecure Deserialisation Guide · Application Security Guide