YAML 13 ๐ Mitigating Billion Laughs and Entity Expansion DoS Attacks
The “Billion Laughs” attack is a denial-of-service technique that exploits YAML’s anchor and alias features. A small document defines an anchor on a collection, aliases it repeatedly, and nests those aliases so that the resolved structure grows exponentially. Symfony’s advisory describes the mechanism precisely: aliases that reference collections can themselves point to other collections containing aliases, and “a small input can blow up into a multi-gigabyte structure and exhaust memory” . The attack is not a parser bug; it is a feature working as designed. Mitigation requires bounding the expansion, not disabling aliases.
This chapter covers the mitigation strategies that parsers and applications implement: collection alias limits, total expansion budgets, input size caps, and the fail-closed patterns that reject a bomb before it materializes. It explains why safe_load alone does not prevent the attack, how different ecosystems implement the limits, and the layered defense that combines parser configuration with application-level guards. The sections that follow walk through the alias-limit approach, the expansion-budget approach, and the input-validation patterns that stop the attack at the boundary.
Key point: safe_load prevents code execution but still resolves aliases; mitigating Billion Laughs requires bounding alias expansion (collection count, total node weight, or input size) and failing closed before the structure materializes.
Why safe loading does not stop the attack
The resolution problem. yaml.safe_load restricts parsing to plain data types, which prevents arbitrary object construction. It does not restrict alias resolution. An alias that references a collection still resolves to that collection, and nested aliases still expand exponentially. The Microsoft APM red-team analysis documents this directly: the original assumption that safe_load was safe “because it resolves aliases to shared references (a DAG), making parse cost linear in the document text” was disproved. The shared-reference DAG is “a LATENT bomb that detonates in any consumer that materializes it”โstr(), deepcopy, or re-serialization hangs for minutes on a sub-kilobyte manifest .
The materialization problem. A parser that returns a DAG of shared references has not allocated the expanded structure yet. The bomb detonates when a downstream consumer walks the structure and produces a flat representation. The parser’s memory is small; the consumer’s memory is not. This is why the mitigation must either reject the document at parse time or ensure that no downstream consumer can be induced to materialize the expansion.
The event-loop problem. HedgeDoc’s CVE-2026-58486 shows the worst case. A ten-level alias bomb blocked the single Node.js event loop for roughly 235 seconds per request, causing concurrent requests to hang and the instance to become unavailable. The note was stored in the database, so the impact survived process restarts until the note was removed . A parser-level limit that rejects the document at first parse prevents the stored bomb from ever being parsed again.
a. Collection alias limits and expansion budgets
The most common mitigation is a limit on collection alias resolutions. Symfony’s fix, following the SnakeYAML model, counts collection alias resolutions in a shared state object with a default limit of 128. Scalar aliases remain unrestricted because they cannot drive exponential growth. The limit is configurable, and a PARSE_EXCEPTION_ON_ALIAS flag rejects all aliases outright for fully untrusted input .
// Symfony: limit collection aliases to 128 (default)
$parser = new Parser(128);
// Reject all aliases for fully untrusted input
Yaml::parse($input, Yaml::PARSE_EXCEPTION_ON_ALIAS);
The expansion-budget approach counts total resolved nodes rather than alias occurrences. OmegaConf’s default limit is 10,000 expanded YAML nodes, and it also rejects a document larger than 1,000 expanded nodes if aliases make it more than 100 times larger than the unexpanded document . Microsoft’s APM uses a 5,000,000 expansion-weight budget and fails closed with yaml.YAMLError the instant the per-occurrence expansion weight crosses the cap, before any consumer can re-expand the DAG .
The OpenAPI.NET fix illustrates the materialization trap. SharpYaml parses YAML into a DAG where aliases share nodes, so the parsed graph stays small. The explosion happens in YamlConverter.ToJsonNode, which must materialize each alias occurrence as an independent copy because JsonNode is single-parent. The fix adds a conversion budget: a maximum materialized node count of 5,000,000 and a nesting depth of 64, throwing a diagnostic error instead of allowing OOM .
b. Input size caps and layered defense
A size cap is the simplest guard and the least precise. It rejects documents above a fixed byte threshold before parsing, which bounds the worst case without requiring parser-level configuration. Microsoft’s deer-flow project caps YAML content at 500 KB and refuses to parse above that threshold, specifically to prevent alias-bomb DoS . The cap is bluntโit rejects legitimate large documentsโbut it is impossible to bypass with a clever payload.
The layered defense combines multiple limits, each covering a different attack surface. L4YAML’s ParserLimits structure groups four families: alias limits (depth, expansion count, resolved nodes), structural limits (nesting depth, collection size, scalar bytes), document limits (document count, anchor count, input size), and tag security (core schema only, language tags rejected) . The presets map to use cases: strict for untrusted input, default for general use, permissive for trusted input, and unlimited for testing .
The Go go-yaml limit plugin implements the same layering: DepthValue(n) sets a maximum nesting depth, AliasValue(n) sets an alias expansion count threshold, and AliasNone() disables alias checking for trusted input . The plugin architecture means the limits are opt-in, and the default loader has conservative limits.
c. The fail-closed pattern
The critical property of a mitigation is that it fails closed. A rejected document must not be partially parsed, cached, or passed to a consumer that will materialize it. The APM loader fails closed with yaml.YAMLError, and every consumer of load_yaml treats that error as an empty result or an exit code, never as a partial document . The OpenAPI.NET reader converts the budget breach into a diagnostic error with Document = null, consistent with its existing error handling .
The guard placement matters as much as the guard itself. The APM red-team analysis notes that a parse-time guard is necessary because a downstream str() or deepcopy can detonate a DAG that the parser returned successfully. The guard must walk the composed node graph and reject the document before any consumer sees it . A guard that only checks the input size or the alias count at the top level can be bypassed by a payload that is small at the top and explosive below.
The event-scan pattern is the strictest form. A parser can scan the token stream for ANCHOR and ALIAS events without composing them, and reject any document containing them if aliases are not needed. Microsoft’s LangAlpha project uses yaml.parse() to scan frontmatter and reject any anchor or alias before safe_load runs, because “events never compose, so the scan itself cannot expand” . This is the safest approach for applications that do not need aliases at all: reject them at the event layer, and the question of expansion limits becomes moot.
Complete Example Session
# ============================================
# PART 1: THE VULNERABLE PATTERN
# ============================================
import yaml
# A small bomb: 9-way nesting, exponential expansion
bomb = """
a: &a ["x","x","x","x","x","x","x","x","x"]
b: &b [*a,*a,*a,*a,*a,*a,*a,*a,*a]
c: &c [*b,*b,*b,*b,*b,*b,*b,*b,*b]
d: &d [*c,*c,*c,*c,*c,*c,*c,*c,*c]
"""
# safe_load parses it successfully (no code execution)
# The DAG is small. The bomb detonates in the consumer.
data = yaml.safe_load(bomb)
# str(data) or deepcopy(data) now expands to millions of nodes
# ============================================
# PART 2: THE COLLECTION ALIAS LIMIT (SYMFONY MODEL)
# ============================================
# Symfony counts collection alias resolutions, default 128
# Scalar aliases unrestricted (no exponential growth)
# PARSE_EXCEPTION_ON_ALIAS rejects all aliases
# ============================================
# PART 3: THE EXPANSION BUDGET (APM MODEL)
# ============================================
# Walk the composed node graph, count per-occurrence weight
# Fail closed when weight exceeds budget (e.g., 5M)
# Reject before any consumer can materialize the DAG
# ============================================
# PART 4: THE EVENT-SCAN GUARD
# ============================================
# Scan token events for ANCHOR/ALIAS without composing
# Reject any document containing them
# Events never compose, so the scan cannot expand
# ============================================
# PART 5: THE LAYERED DEFENSE
# ============================================
# 1. Input size cap (e.g., 500 KB)
# 2. Event scan for aliases (reject if not needed)
# 3. Collection alias limit (if aliases needed)
# 4. Expansion budget (total resolved nodes)
# 5. Depth limit (nesting)
The parts covered the vulnerable pattern, the collection alias limit, the expansion budget, the event-scan guard, and the layered defense.
Quick Reference
Mitigation Strategies
| Strategy | Mechanism | Example |
|---|---|---|
| Collection alias limit | Count collection alias resolutions | Symfony: 128 default |
| Expansion budget | Count resolved nodes or weight | APM: 5M weight |
| Input size cap | Reject before parse | deer-flow: 500 KB |
| Event scan | Reject anchors/aliases at token layer | LangAlpha |
| Depth limit | Bound nesting | OpenAPI.NET: 64 |
Parser Limits (L4YAML)
| Limit | Default |
|---|---|
maxAliasExpansions | 10,000 |
maxResolvedNodes | 100,000 |
maxDepth | 100 |
maxInputBytes | 100 MB |
Fail-Closed Requirements
| Requirement | Detail |
|---|---|
| Reject at parse | Before consumer sees the document |
| No partial data | Error, not a truncated result |
| Walk the graph | Count expansion weight, not just alias count |
| Guard placement | Before any str(), deepcopy(), or re-serialize |
Best Practices
โ Do This:
# Reject aliases if the application does not need them
# (event scan before safe_load) # โ
# Use a parser with collection alias limits
# (Symfony 128 default, configurable) # โ
# Cap input size as a first line of defense
if len(content) > 500_000: return None # โ
# Fail closed on any YAML error
try: data = load_yaml(content)
except yaml.YAMLError: data = None # โ
โ Don’t Do This:
# Assume safe_load prevents alias bombs
data = yaml.safe_load(bomb) # DAG is small, consumer explodes # โ
# Pass the DAG to a consumer that materializes it
str(yaml.safe_load(bomb)) # hangs # โ
# Only check alias count at top level
# (nested aliases bypass the count) # โ
# Trust a document because it is small
# (a sub-kilobyte bomb expands to gigabytes) # โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
safe_load returns successfully, consumer hangs | DAG returned, expansion deferred | Guard at parse, before consumer |
| Alias count guard bypassed | Nested aliases not counted per occurrence | Count expansion weight, not alias occurrences |
| Legitimate document rejected | Fixed byte cap too low | Scale cap to input size, or use expansion budget |
| Stored bomb persists after restart | Document in database | Reject at write time, not read time |
Real-World Examples
1. Symfony collection limit
new Parser(128); // max collection aliases
2. Symfony alias rejection
Yaml::parse($input, Yaml::PARSE_EXCEPTION_ON_ALIAS);
3. APM expansion budget
# Walk composed node graph, fail closed at 5M weight
4. OpenAPI.NET conversion budget
YamlConverter.MaxNodeCount = 5_000_000;
YamlConverter.MaxDepth = 64;
5. OmegaConf node limit
OmegaConf.load("config.yaml", max_yaml_expanded_nodes=10_000);
6. Go-yaml depth limit
limit.New(limit.DepthValue(50))
7. Event-scan guard
for event in yaml.parse(content):
if isinstance(event, (yaml.AnchorEvent, yaml.AliasEvent)):
raise ValueError("Aliases not allowed")
8. Input size cap
if len(content) > 500_000: return None
9. L4YAML strict preset
parseYamlSafe input .strict // web APIs
10. Fail-closed error handling
except yaml.YAMLError: data = None # never partial
Visual
The Attack Mechanism
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ BILLION LAUGHS โ
โ โ
โ a: &a [x,x,x,x,x,x,x,x,x] 9 nodes โ
โ b: &b [*a,*a,*a,*a,*a,*a,*a,*a,*a] 81 nodes โ
โ c: &c [*b,*b,*b,*b,*b,*b,*b,*b,*b] 729 nodes โ
โ d: &d [*c,*c,*c,*c,*c,*c,*c,*c,*c] 6,561 nodes โ
โ โ
โ A few hundred bytes โ megabytes at depth 8 โ
โ safe_load resolves the DAG; the consumer explodes โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The Two-Phase Problem
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ PHASE 1: PARSE โ
โ safe_load โ DAG of shared references โ
โ Memory: small โ
โ โ
โ PHASE 2: MATERIALIZE โ
โ str() / deepcopy / serialize โ
โ Memory: exponential โ
โ โ
โ The guard must be in phase 1, before phase 2 starts โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Layered Defense
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ LAYER 1: INPUT SIZE CAP โ
โ Reject > 500 KB before parsing โ
โ โ โ
โ โผ โ
โ LAYER 2: EVENT SCAN โ
โ Reject anchors/aliases at token layer โ
โ โ โ
โ โผ โ
โ LAYER 3: COLLECTION ALIAS LIMIT โ
โ Count collection alias resolutions (128) โ
โ โ โ
โ โผ โ
โ LAYER 4: EXPANSION BUDGET โ
โ Count resolved nodes/weight (5M) โ
โ โ โ
โ โผ โ
โ LAYER 5: DEPTH LIMIT โ
โ Bound nesting (64-100) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Fail-Closed Flow
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ GUARD DETECTS BOMB โ
โ โ โ
โ โผ โ
โ Raise YAMLError / Diagnostic error โ
โ โ โ
โ โผ โ
โ Consumer receives error, not partial data โ
โ โ โ
โ โผ โ
โ Empty result / exit code / 400 response โ
โ โ
โ Never: partial document, cached DAG, re-serialization โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| Attack | Nested aliases expand exponentially |
safe_load limitation | Prevents code execution, not alias expansion |
| Collection alias limit | Symfony: 128 default |
| Expansion budget | APM: 5M weight; OpenAPI.NET: 5M nodes |
| Input size cap | deer-flow: 500 KB |
| Event scan | Reject anchors/aliases at token layer |
| Depth limit | OpenAPI.NET: 64 |
| Fail-closed requirement | Reject at parse, before consumer |
Key takeaways:
safe_loadis not a Billion Laughs mitigation. It prevents arbitrary object construction, but it still resolves aliases. The DAG it returns is small; the expansion happens when a consumer materializes it .- The guard must be at parse time, before the consumer. A DAG that reaches
str()ordeepcopywill expand. The fix walks the composed node graph and fails closed before any consumer sees the document . - Collection alias limits are the standard mitigation. Symfony’s 128-limit follows the SnakeYAML model, and scalar aliases remain unrestricted because they cannot drive exponential growth .
- Expansion budgets catch what alias counts miss. A value-heavy bombโone large string aliased thousands of timesโpasses a node-count guard but still explodes. Weighting string leaves by length and scaling the cap to input size closes the gap .
- Rejecting aliases entirely is the safest option for untrusted input. The
PARSE_EXCEPTION_ON_ALIASflag and the event-scan pattern reject the document before any composition, which makes the question of expansion limits moot .
Remember: The Billion Laughs attack is not a parser bug; it is a feature working as designed. The parser resolves aliases, and the consumer materializes them. The mitigation is to bound the expansion before the consumer sees the data, and the bound must fail closed. Use a collection alias limit, an expansion budget, or an input size capโor reject aliases entirely if the application does not need them. The bomb is small; the explosion is deferred; the guard must be placed in the phase where the deferral happens.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!