Duplicate-key detection in JSON generation is bypassed by keys that collide only after UTF-8 transcoding (JSON smuggling)
維護者通常 1 天內回覆
還沒有人認領這個 Issue。
評估
研究方向
Start in ext/json/ext/generator/generator.c around lines 899–935 and 1017–1069, then read JSON.on_mixed_keys_hash in lib/json/common.rb:112 to trace key conversion and duplicate checks. Reproduce with the UTF-8 and ISO-8859-1 string keys from the report, and inspect existing assert_duplicate_key tests and the 3.2.0 CHANGES.md entry. Done means generation rejects keys that collide after UTF-8 transcoding, including the reported String subclass case.
由索引模型根據 Issue 內容生成。
描述
About
Title: Duplicate-key detection in JSON generation is bypassed by keys that collide only after UTF-8 transcoding (JSON smuggling)
Repository: ruby/json
Location: ext/json/ext/generator/generator.c:1040
Severity: Medium
Impacted versions: 3.0.0, 3.1.0, 3.2.0
Summary
json made allow_duplicate_key: false the default for generation in 3.0.0 (duplicated
keys are now rejected by default), and 3.2.0 added detection for collisions between a
String/Symbol key and a non-String key such as a String key 1 together with an Integer key 1.
The C generator implements that check by comparing Ruby types: json_object_i
records the first key's type and only calls back into Ruby (JSON.on_mixed_keys_hash,
lib/json/common.rb:112) when a later key has a different type (generator.c:1017-1069).
on_mixed_keys_hash then stringifies every key and raises JSON::GeneratorError when two
of them coincide. But when every key is a plain T_STRING, the callback is never reached,
and the generator only converts keys to UTF-8 afterwards, in
ensure_valid_encoding/convert_invalid_encoding (generator.c:899-935).
So two Ruby string keys that are distinct objects but become the same JSON member name
after the generator's own transcoding are never compared: the UTF-8 bytes C3 A9 tagged
UTF-8 and the single byte E9 tagged ISO-8859-1 (both U+00E9), and equally the UTF-16BE
form, are kept as separate Hash entries, and the generator prints the member name twice
with the two different values. The same happens with a String subclass whose #to_s
differs from its content when it follows a plain String key (both are T_STRING). This
was confirmed on 3.0.0, 3.1.0 and 3.2.0; the TruffleRuby backend happens to catch the
subclass case because it compares key classes, while JRuby's HashKeyTracker is
type-based like the C extension and does not. JSON::Coder with or without a converter
block is affected the same way; only the rfc8785 path with a converter rejects the
Latin-1 key.
RFC 7493 (I-JSON) section 2.3 defines duplicate names as names that are identical
sequences of Unicode characters, i.e. after the transcoding the generator performs, so
this is a gap in the guard rather than an exotic input. Recommendation: deduplicate on the
transcoded key bytes (validate/normalise keys to UTF-8 first, as Ext.coerce_key already
does for the rfc8785 path) and do not compare only key classes.
Impact
The cost is JSON/parameter smuggling across a trust boundary. A Ruby component that relies
on the default allow_duplicate_key: false check to guarantee that the documents it
forwards are unambiguous will emit a document with two members of the same name, and the
receiver - JavaScript JSON.parse, Python json.loads, jq, or ruby/json itself with
allow_duplicate_key: true - silently keeps the last one. The producer and the consumer
therefore disagree about the document: in the proof of concept the Ruby Hash maps the
accented name to user while the backend maps it to admin, so an attacker who can get a
second copy of a key into the document overrides the legitimate value that the producer
validated, checked or logged. Strict consumers (this library's parser among them) instead
reject the message, which is a second, availability-only outcome of the same bug.
The severity is bounded by the precondition: unlike a plain String/Symbol duplicate pair,
the collision requires the Hash to hold two distinct Ruby keys that only coincide after
transcoding (different encodings of the same character) or a String subclass with a
surprising #to_s. That means attacker-controlled keys can only reach the sink through
application code that builds hash keys from differently-encoded sources - a Latin-1
CSV/XML/DB import merged with UTF-8 request parameters, for instance - and the override
only materialises if the downstream consumer resolves duplicates last-wins. When both
conditions are met the impact is high (integrity/authorisation decisions made on a value
the producer never saw), which is why this is still worth fixing: the documented default
check is the thing applications trust to prevent exactly that, and it fails silently.
Mitigations
Normalise and validate keys to well-formed UTF-8 before building hashes, and do not rely
on allow_duplicate_key: false as a security boundary. Reject non-String/non-Symbol keys
and String subclasses via a whitelist before serialisation. Upgrade to a json release
whose generator compares the transcoded key bytes rather than the Ruby key types.
Examples
example 1
A Ruby gateway that validates a document and forwards JSON.generate(document) to a Node
or Python backend. With one member name supplied twice, once as UTF-8 and once as
ISO-8859-1, the guard does not fire; the wire bytes carry the same name twice, user first
and admin second, and the backend resolves the role to admin - verified with Node,
Python and jq, while the Ruby side still reads user.
example 2
The same input against a WAF/policy engine or a signature verifier that parses the body
itself: parsers disagree about duplicate members (RFC 7159 section 4, in this repository's
references/, notes that some report the last pair, some error out, some report all
pairs), so the component that inspects the request and the component that acts on it can
reach different conclusions from one body.
example 3
A String subclass key with an overridden #to_s (for example a normalising key class,
or a class that returns a redacted value from to_s) placed after a plain String key
produces the same duplicated member: a Hash holding the String key x plus a
ShadowedString key whose to_s returns x serialises to two members named x because
both keys are T_STRING and are never compared.
example 4
The project's own test suite frames this as a supported guarantee - assert_duplicate_key
cases for a String key 1 plus an Integer key 1 and for a Symbol key plus an Integer key,
and the 3.2.0 CHANGES.md entry about fixing JSON.generate not detecting duplicate keys
such as those - so applications that adopted allow_duplicate_key: false did so on the
documented promise that colliding keys are rejected.
Proof of concept
#!/usr/bin/env ruby
# frozen_string_literal: true
#
# PoC: JSON duplicate-key detection bypass (allow_duplicate_key: false) -> JSON smuggling
#
# ruby/json 3.2.0 documents `allow_duplicate_key: false` (the default) as a
# guard that raises JSON::GeneratorError when two hash keys would serialise to
# the same JSON object key. The C generator implements that guard by comparing
# only the *Ruby types* of the keys (`arg->first_key_type`), so it never notices
# two String keys that become identical only *after* the generator transcodes
# them to UTF-8, nor a String subclass whose #to_s differs from its content.
# Resolve the repo under test whether run from the repo root or from tmp/poc.
lib = File.expand_path("lib", Dir.pwd)
lib = File.expand_path("../lib", __dir__) unless File.directory?(lib)
$LOAD_PATH.unshift(lib)
require "json"
puts "json gem #{JSON::VERSION} (generator: #{JSON.generator})"
# --- The victim gateway: it believes JSON.generate's default options reject
# --- duplicate keys before it forwards the document to its backend.
def guarded_forward(document)
wire = JSON.generate(document) # allow_duplicate_key: false (the default)
# The backend is a normal JSON consumer: last duplicate key wins.
backend_view = JSON.parse(wire, allow_duplicate_key: true)
[wire, backend_view]
end
# --- Baseline: the guard works when it can see the collision.
baseline = { "\xC3\xA9".b.force_encoding("UTF-8") => "user", :"\u00e9" => "admin" }
begin
guarded_forward(baseline)
puts "[-] baseline unexpectedly passed the guard"
rescue JSON::GeneratorError => e
puts "[+] baseline rejected by the guard as designed: #{e.message}"
end
# --- Attack A: same logical key "é", but the second copy is delivered in
# --- ISO-8859-1 (a legacy system / header / form field). Ruby treats it as a
# --- distinct Hash key; the generator transcodes both to UTF-8 "é".
utf8_e = "\xC3\xA9".b.force_encoding("UTF-8") # U+00E9, UTF-8
latin1_e = "\xE9".b.force_encoding("ISO-8859-1") # U+00E9, Latin-1
attack = { utf8_e => "user", latin1_e => "admin" }
puts "\n[>] attack keys are distinct Ruby objects: #{attack.keys.uniq.size == 2} " \
"(encodings #{attack.keys.map(&:encoding).inspect})"
wire, backend_view = guarded_forward(attack)
puts "[!] duplicate-key guard did NOT raise"
puts "[!] forwarded wire bytes : #{wire.inspect}"
puts "[!] backend (last-wins) : #{backend_view.inspect}"
puts "[!] smuggled value : #{backend_view[utf8_e].inspect} <-- attacker overrode 'user'"
# --- Attack B: a String subclass whose #to_s differs from its content.
class ShadowedString < String
def to_s
"x"
end
end
sub_attack = { "x" => "user", ShadowedString.new("y") => "admin" }
wire2, view2 = guarded_forward(sub_attack)
puts "\n[!] subclass bypass wire : #{wire2.inspect}"
puts "[!] backend (last-wins) : #{view2.inspect} <-- attacker overrode 'user'"
puts "\nRESULT: #{backend_view[utf8_e] == 'admin' && view2['x'] == 'admin' ? 'VULNERABLE' : 'not vulnerable'}"
stdout
json gem 3.2.0 (generator: JSON::Ext::Generator)
[+] baseline rejected by the guard as designed: detected duplicate key "é" in {"é" => "user", é: "admin"}
[>] attack keys are distinct Ruby objects: true (encodings [#<Encoding:UTF-8>, #<Encoding:ISO-8859-1>])
[!] duplicate-key guard did NOT raise
[!] forwarded wire bytes : "{\"é\":\"user\",\"é\":\"admin\"}"
[!] backend (last-wins) : {"é" => "admin"}
[!] smuggled value : "admin" <-- attacker overrode 'user'
[!] subclass bypass wire : "{\"x\":\"user\",\"x\":\"admin\"}"
[!] backend (last-wins) : {"x" => "admin"} <-- attacker overrode 'user'
RESULT: VULNERABLE
- 主要語言
- Ruby
- 星號
- 787
- 分支
- 392
- 平均合併
- 6 小時 4 分鐘
- 30 天內合併 PR
- 22
環境準備
這個專案沒有提供開發容器、Dockerfile 或貢獻指南,環境需要你自己搭建:先看它的 README,通用步驟見我們的新手貢獻指南。
從這裡開始
- 先讀完整個 Issue,再讀專案的貢獻指南。
- 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
- Fork 儲存庫,在一個分支上完成修改。
- 送出 Pull Request,並在描述裡引用這個 Issue 編號。
ruby/json 的其他 Issue
-
難度 2/5 1-3 小時 新手友好度 76/100
維護者通常 1 天內回覆
-
難度 3/5 1-2 天 新手友好度 55/100
維護者通常 1 天內回覆
-
Audit excluded tests on JRuby and address differences可能已有人在做 @ojuschugh1 於 5 天前認領。 未關閉
難度 4/5 3-5 天 新手友好度 48/100
維護者通常 1 天內回覆
-
難度 3/5 1-2 天 新手友好度 55/100
維護者通常 1 天內回覆
-
Output formatting differences between jRuby 10.0.0.1 and Ruby 3.4 when converting Float to JSON.可能已有人在做 @headius 於 460 天前認領。 未關閉jruby
ruby/json#817 · 3 則留言 · 1 個 reaction · 已指派 1 人 ·
維護者通常 1 天內回覆
相似的 Issue
-
SecureRandom.alphanumeric can silently return an empty or wrong-length secret instead of raising未關閉
難度 2/5 1-3 小時 新手友好度 67/100
ruby/securerandom#92 ·
-
難度 2/5 1-3 小時 新手友好度 72/100
維護者通常 1 天內回覆
-
難度 2/5 1-3 小時 新手友好度 85/100
open-feature/ruby-sdk-contrib#340 ·
維護者通常 1 天內回覆
-
難度 2/5 1-3 小時 新手友好度 88/100
zold-io/wts.zold.io#651 ·
維護者通常 1 天內回覆
-
good first issue help wanted
難度 2/5 1-3 小時 新手友好度 87/100
erkamyaman/rust-anything#788 ·
維護者通常 1 天內回覆