JSON Poisoning

Difficulty: Intermediate

Question

What is JSON poisoning? Explain how duplicate keys, prototype pollution and oversized payloads can be used to attack an API.

Answer

JSON poisoning is a loose term for attacks that craft a JSON payload so that it is parsed or processed in a way the developer did not expect. The main variants are duplicate keys that different parsers interpret differently, special keys like __proto__ that pollute JavaScript object prototypes, and huge or deeply nested payloads that exhaust memory or CPU. The defences are strict parsing, schema validation with unknown keys rejected, safe merging, and size and depth limits.

Duplicate keys and parser differentials

RFC 8259 says object names SHOULD be unique but does not require it, and leaves behaviour for duplicates unspecified. In practice:

  • JavaScript JSON.parse, Python json, and many others keep the last value.
  • Some parsers keep the first value, and some strict ones reject the document.

This matters when two components parse the same request. Suppose an API gateway validates {"amount": 100, "amount": 100000} and sees the first value, but the payment service reads the last. The check passes on ₹100 while the service processes ₹1,00,000. The same applies between a WAF and the backend, or between a signature check and the business logic. Research by Bishop Fox in 2021 found such inconsistencies across dozens of popular JSON parsers.

Prototype pollution in JavaScript

JSON.parse('{"__proto__": {"isAdmin": true}}') creates an object with an own property literally named __proto__. That is harmless on its own, but if the result is passed to a naive recursive merge or set(obj, path, value) helper, the merge writes into Object.prototype. Now every object in the process has isAdmin === true, which can bypass authorization checks or, with the right gadget, lead to RCE. Older versions of lodash merge, defaultsDeep and many small utilities were affected. constructor.prototype is an alternative path to the same target.

Resource exhaustion

  • Large bodies: a 500 MB JSON body forces the server to buffer and parse it. Express's express.json() defaults to a 100 kb limit; keep a limit everywhere.
  • Deep nesting: [[[[...]]]] thousands of levels deep can overflow recursive parsers or later recursive code.
  • Huge numbers: very long integer strings cost CPU to convert. Python 3.11+ limits int conversion to 4,300 digits by default for this reason (CVE-2020-10735). JavaScript silently loses precision above 2^53 - 1, so 9007199254740993 becomes 9007199254740992, which can corrupt IDs.

How to defend

  1. Validate every body against a strict schema (Zod .strict(), JSON Schema with additionalProperties: false, Pydantic with extra='forbid').
  2. Reject duplicate keys where it matters, or make sure every layer uses the same parser.
  3. Never deep-merge untrusted objects into existing ones. Block __proto__, constructor and prototype keys, use Object.create(null) or Map for dictionaries, and keep libraries patched. Node's --disable-proto=delete flag removes the __proto__ accessor.
  4. Set body size limits at the load balancer and the framework, and limit nesting depth.
  5. Send large IDs and money values as strings, or amounts as integer paise, to avoid float and precision issues.
Duplicate key parser differential. Two services read the same bytes and see different amounts.
  1. Attacker → API gateway: amount: 100 and amount: 100000 in one body
  2. API gateway → API gateway: First-wins parser checks 100, passes
  3. API gateway → Payment service: Forwards the original raw body
  4. Payment service → Payment service: Last-wins parser reads 100000

Code examples

Duplicate keys and prototype pollution in Node.js

// 1. Duplicate keys: last one wins in JSON.parse
console.log(JSON.parse('{"amount": 100, "amount": 100000}').amount);

// 2. Naive deep merge pollutes Object.prototype
function merge(target, src) {
  for (const key in src) {
    if (typeof src[key] === 'object' && src[key] !== null) {
      target[key] ??= {};
      merge(target[key], src[key]);
    } else target[key] = src[key];
  }
  return target;
}
const body = JSON.parse('{"__proto__": {"isAdmin": true}}');
merge({}, body);
console.log({}.isAdmin);

// Fix: skip dangerous keys (or use a vetted library / Map)
const BAD = new Set(['__proto__', 'constructor', 'prototype']);
const safeKeys = (o) => Object.keys(o).filter((k) => !BAD.has(k));

// 3. Precision loss on big integers
console.log(JSON.parse('{"id": 9007199254740993}').id);

target['__proto__'] resolves to Object.prototype, so the merge writes isAdmin onto every object. Filtering keys and using strict schemas prevents both tricks.

Strict schema plus body limit

import express from 'express';
import { z } from 'zod';

const app = express();
app.use(express.json({ limit: '20kb', strict: true }));

const Payment = z.object({
  orderId: z.string().uuid(),
  amountPaise: z.number().int().positive().max(10_000_000),
}).strict(); // unknown keys such as __proto__ are rejected

app.post('/pay', (req, res) => {
  const r = Payment.safeParse(req.body);
  if (!r.success) return res.status(400).json(r.error.flatten());
  res.json({ ok: true });
});

The size limit stops oversized payloads before parsing, and .strict() rejects any field not in the schema, including prototype keys.

Key points

  • RFC 8259 leaves duplicate-key behaviour unspecified; parsers disagree
  • Parser differentials between gateway and backend can bypass validation
  • __proto__ keys plus a naive deep merge cause prototype pollution
  • Limit body size and nesting depth; express.json defaults to 100kb
  • Use strict schemas that reject unknown keys

Common follow-up questions

  • How can prototype pollution escalate to remote code execution?
  • Why should monetary amounts and large IDs be sent as strings or integers in paise?
  • How would you ensure a gateway and backend parse JSON identically?
  • What does Object.create(null) protect against?

Interview tips

  • Clarify that 'JSON poisoning' covers several attacks, then walk through each briefly
  • The gateway versus backend duplicate-key example is memorable and shows systems thinking
  • Show you know the JavaScript-specific angle: __proto__, deep merge and 2^53 precision

Concepts covered

JSON Duplicate Keys, Parser Differentials, Prototype Pollution, JSON DoS, Schema Validation

More Web Security (OWASP, JWT, XSS, CSRF) questions