
Ruby's JSON.generate leaks arbitrary heap memory when null bytes are passed via JSON::State.space.
Ruby's `JSON::State` class exposes parameters like `space`, `indent`, `object_nl`, and `array_nl` to control generated JSON formatting. When `space` is initialized with null bytes (`"\0" * 1024`), the native C extension implementing the json gem does not sanitize the parameter before writing it as a separator into the output buffer.
The result: `JSON.generate` output includes arbitrary heap (the process's dynamic memory region — where Ruby stores live objects, strings, and internal structures) content. In the published example, the leak exposes real system paths (`mydata/scm/git/ruby/dist/lib/ruby/2.5.0/json/ext.rb`), internal code fragments (`psych/handlers/recorder.rb`, `Gem::Specification.new`), and whatever strings happen to reside in memory at that moment.
Root cause: a classic *C binding* bug. The native code treats `space` as an opaque string and dumps it directly to the buffer with no null byte check and no length validation.
This pattern surfaces across C bindings in multiple dynamic languages: Python, Ruby, Node.js with native addons. The real risk isn't just the visible stack trace — it's what *might* be in heap at request time: session tokens, API keys loaded as strings, in-memory database credentials.
If the endpoint calling `JSON.generate` accepts client-controlled format options (common in APIs offering pretty-print or custom indentation), this becomes a remote memory oracle. An attacker can vary the `\0` offset across multiple requests and reconstruct heap regions systematically.
The attack surface is wider than it looks: serialization libraries (JSON, YAML, MessagePack) with native bindings are all direct candidates for the same vector.
The core lesson: C bindings don't inherit the host language runtime's safety guarantees. Every parameter crossing the native boundary needs explicit validation on the Ruby side before the jump — the runtime won't cover you there.
Help more people discover BBLabs News.
Want to get news like this every day?
Browse all articles