| | |

YAML 13 ๐Ÿ“„ Mitigating Billion Laughs and Entity Expansion DoS Attacks

โฑ๏ธ Estimated read: 12 min | |

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

StrategyMechanismExample
Collection alias limitCount collection alias resolutionsSymfony: 128 default
Expansion budgetCount resolved nodes or weightAPM: 5M weight
Input size capReject before parsedeer-flow: 500 KB
Event scanReject anchors/aliases at token layerLangAlpha
Depth limitBound nestingOpenAPI.NET: 64

Parser Limits (L4YAML)

LimitDefault
maxAliasExpansions10,000
maxResolvedNodes100,000
maxDepth100
maxInputBytes100 MB

Fail-Closed Requirements

RequirementDetail
Reject at parseBefore consumer sees the document
No partial dataError, not a truncated result
Walk the graphCount expansion weight, not just alias count
Guard placementBefore 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

PitfallWhy It HappensFix
safe_load returns successfully, consumer hangsDAG returned, expansion deferredGuard at parse, before consumer
Alias count guard bypassedNested aliases not counted per occurrenceCount expansion weight, not alias occurrences
Legitimate document rejectedFixed byte cap too lowScale cap to input size, or use expansion budget
Stored bomb persists after restartDocument in databaseReject 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

ItemValue
AttackNested aliases expand exponentially
safe_load limitationPrevents code execution, not alias expansion
Collection alias limitSymfony: 128 default
Expansion budgetAPM: 5M weight; OpenAPI.NET: 5M nodes
Input size capdeer-flow: 500 KB
Event scanReject anchors/aliases at token layer
Depth limitOpenAPI.NET: 64
Fail-closed requirementReject at parse, before consumer

Key takeaways:

  • safe_load is 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() or deepcopy will 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_ALIAS flag 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.

Was this helpful?


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!