RFC 8785 canonicalization emits duplicate object names and is not deterministic when keys differ only in encoding

未關閉
#1,153 0 則留言 0 個 reaction 已指派 0 人 在 GitHub 檢視

維護者通常 1 天內回覆

還沒有人認領這個 Issue。

評估

難度
3/5
預估耗時
1-2 天
新手友好度
55/100
Issue 類型
缺陷
描述清晰度
描述清楚
活躍度
活躍
技術堆疊
ruby
領域
backend, security

研究方向

Start with the duplicate-key check and sort in lib/json/ext.rb:153-164, then read the generator encoding path in generator.c:899-935 and the existing RFC 8785 duplicate-key test mentioned in the issue. Reproduce with the UTF-8 and ISO-8859-1 keys from the proof of concept. Done means those keys are rejected as duplicates, invalid UTF-8 round trips are rejected, and canonical output is deterministic.

由索引模型根據 Issue 內容生成。

描述

About

Title: RFC 8785 canonicalization emits duplicate object names and is not deterministic when keys differ only in encoding
Repository: ruby/json
Location: lib/json/ext.rb:160
Severity: High
Impacted versions: 3.1.0, 3.2.0

Summary

rfc8785: true is supposed to implement RFC 8785 (JCS), whose entire purpose is to turn a
JSON document into one fixed byte string so that hashes and signatures over it are
repeatable (RFC 8785 section 1). The implementation sorts object members with
k.encode(Encoding::UTF_16) (lib/json/ext.rb:164) but decides whether two keys are
duplicates before that transcoding, from hash.transform_keys(&:to_s)
(lib/json/ext.rb:153-162). Keys are only converted to UTF-8 later, by the C generator
itself (ensure_valid_encoding/convert_invalid_encoding, generator.c:899-935).

Two Ruby strings that denote the same Unicode character but carry different encodings are
different Hash keys - the two bytes C3 A9 tagged UTF-8 and the single byte E9 tagged
ISO-8859-1 both denote U+00E9 - so transform_keys keeps both, the size check never
fires, and both produce identical UTF-16 sort keys. The canonicalizer therefore prints
both members under the same JSON name, and their relative order is whatever the sort
leaves in place (Hash insertion order in practice). Canonicalising a hash that maps U+00E9
to the value user and then to the value admin returns an object carrying that name twice,
user first; the reversed hash returns admin first: the same document, two different
canonical byte strings, and an output that is not even valid JSON - this project's own
parser rejects it with a duplicate-key error.

That violates RFC 8785 section 3.1 (JSON objects MUST NOT exhibit duplicate property
names, and string data must be expressible as Unicode) and RFC 7493 (I-JSON) section 2.3,
which defines duplicates after character processing. Recommendation: compare the
post-transcoding key bytes (i.e. deduplicate with Ext.coerce_key/an explicit UTF-8
conversion instead of the raw transform_keys(&:to_s) result) and reject keys that do not
round-trip through UTF-8, so the sort proc can never see two keys whose UTF-16 forms are
equal.

Impact

The first cost is signature confusion. A service that signs the canonical bytes of a
document - JWS/JOSE payloads signed without base64url, verifiable credentials, webhook and
API request signatures, signed audit records - signs a byte string that is not an
unambiguous document. Two parties can build the'same' Hash in a different order (or read
the same data in a different encoding) and get different canonical bytes, so an untampered
document fails verification: a remotely triggerable denial of service against any signing
or verification endpoint, since the attacker only has to supply the second copy of a key.
And when the canonical form is consumed by a last-wins parser, the signed bytes read back
as a different document than the one the producer hashed - the producer's Hash says
user, while Ruby JSON.parse(..., allow_duplicate_key: true), Python's json.loads,
jq and JavaScript's JSON.parse all return admin. That is a value override inside
bytes that a signature was supposed to cover, and RFC 7159 section 4 (shipped in this
repository's references/) warns that duplicate names make receiver behaviour
unpredictable.

The second cost is determinism and content addressing in general. JCS output is commonly
used as a content hash for de-duplication, idempotency keys, ETags, cache keys and
on-chain/anchored digests; two runs over the same logical document yielding different
bytes silently breaks all of those (double-processing, cache misses, mismatched
idempotency records), and the duplicate members make the output unusable by any strict
consumer, including this library's own parser. Because the failure is silent - no
exception, just a wrong byte string - it can persist in stored signatures and digests long
before anyone notices.

Mitigations

Detect duplicates by comparing the actual transcoded key bytes (e.g. Ext.coerce_key /
encode to UTF-8) instead of transform_keys(&:to_s); reject keys that do not round-trip
through UTF-8; upgrade to a patched json whose rfc8785 path deduplicates on the
post-transcoding keys. Workaround: pass a converter block to JSON::Coder
(JSON::Coder.new(rfc8785: true) { |o, *| o.to_s} raises JSON::GeneratorError for the
Latin-1 key), or normalise all keys to valid UTF-8 before canonicalising.

Examples
example 1

Signing and verifying a webhook: the sender builds the payload Hash from its own UTF-8
data, the receiver rebuilds it from an events table whose connection is tagged ISO-8859-1,
and each computes HMAC(secret, JSON.generate(doc, rfc8785: true)). The two canonical
byte strings differ (the two members carrying the same name appear in opposite order), so
every legitimate event fails verification with the project's standard signing recipe.

example 2

A gateway that keeps a canonical-form digest for replay protection: a document containing
a Latin-1 key canonicalizes differently on two replicas that built the Hash in a different
order, so a replayed request is accepted (or a fresh one is rejected) - the classic'same
signed bytes, two interpretations' problem also seen in XML signature wrapping.

example 3

A document signed over its canonical form where the producer's in-memory Hash maps é to
user and the downstream last-wins consumer (Node/Python/jq/Ruby with
allow_duplicate_key: true) maps é to admin - the attacker's value is what the
consumer authorizes, while the signature covers the producer's value.

example 4

RFC 7493 section 2.3 makes the rule explicit - duplicates are names that are identical
sequences of Unicode characters after processing escapes - and this project's own test
suite already expects duplicate detection for a String key 1 plus an Integer key 1 under
rfc8785, showing that rejecting collisions (rather than printing them) is the intended
behaviour; only transcoding-induced collisions slip through.

Proof of concept
#!/usr/bin/env ruby
# frozen_string_literal: true
#
# PoC: RFC 8785 (JCS) canonicalisation is neither injective nor deterministic
#
# lib/json/ext.rb:160 detects duplicate object keys from the *pre-transcode*
# `hash.transform_keys(&:to_s)` result.  Two distinct Ruby String keys that only
# become equal once the generator transcodes them to UTF-8 (the same character
# held as UTF-8 and as ISO-8859-1) therefore slip through.  The canonicaliser
# then sorts by `k.encode(Encoding::UTF_16)` and emits both as the same key.
#
# Consequences, all demonstrated below on the real generator:
#   * canonical bytes depend on Hash insertion order (JCS requires identical
#     bytes for identical documents) -> signatures over the canonical form are
#     not reproducible;
#   * the canonical form contains duplicate object keys, so it is not a valid
#     unambiguous JSON document: a strict parser rejects it and a last-wins
#     parser silently drops one of the values, letting a consumer read a
#     different document than the one that was signed.

lib = File.expand_path("lib", Dir.pwd)
lib = File.expand_path("../lib", __dir__) unless File.directory?(lib)
$LOAD_PATH.unshift(lib)
require "json"
require "digest"

puts "json gem #{JSON::VERSION}  (generator: #{JSON.generator})"

utf8_e   = "\xC3\xA9".b.force_encoding("UTF-8")   # U+00E9 in UTF-8
latin1_e = "\xE9".b.force_encoding("ISO-8859-1")  # U+00E9 in Latin-1

# Two documents holding the very same (key, value) pairs, only the insertion
# order of the two colliding keys differs.
forward = { utf8_e => "user", latin1_e => "admin" }
reverse = { latin1_e => "admin", utf8_e => "user" }
puts "same pairs, only order differs: #{forward.to_a.sort_by(&:inspect) == reverse.to_a.sort_by(&:inspect)}"

c1 = JSON.generate(forward, rfc8785: true)
c2 = JSON.generate(reverse, rfc8785: true)
puts "\n[>] canonical(forward) = #{c1.inspect}"
puts "[>] canonical(reverse) = #{c2.inspect}"
puts "[!] deterministic?     = #{c1 == c2}   (JCS requires true)"

# The canonical byte string is not a valid unambiguous JSON document.
begin
  JSON.parse(c1)
rescue JSON::ParserError => e
  puts "[!] strict JSON parse of canonical bytes: #{e.class}: #{e.message}"
end
last_wins = JSON.parse(c1, allow_duplicate_key: true)
puts "[!] last-wins consumer reads: #{last_wins.inspect}"
puts "[!] producer Hash reads 'é' as: #{forward[utf8_e].inspect}" \
     "  (does not match the consumer -> signed bytes are ambiguous)"

# A signing scheme built on JCS: the signature is over the canonical bytes.
secret = "top-secret-hmac-key"
sign = ->(doc) { Digest::SHA256.hexdigest(secret + JSON.generate(doc, rfc8785: true)) }
s1 = sign.call(forward)
s2 = sign.call(reverse)
puts "\n[>] sig(forward) = #{s1[0, 32]}"
puts "[>] sig(reverse) = #{s2[0, 32]}"
puts "[!] signature over the 'same' document reproducible? #{s1 == s2}"

puts "\nRESULT: #{c1 != c2 ? 'VULNERABLE' : 'not vulnerable'}"
stdout
json gem 3.2.0  (generator: JSON::Ext::Generator)
same pairs, only order differs: true

[>] canonical(forward) = "{\"é\":\"user\",\"é\":\"admin\"}"
[>] canonical(reverse) = "{\"é\":\"admin\",\"é\":\"user\"}"
[!] deterministic?     = false   (JCS requires true)
[!] strict JSON parse of canonical bytes: JSON::ParserError: duplicate key "é" at line 1 column 1
[!] last-wins consumer reads: {"é" => "admin"}
[!] producer Hash reads 'é' as: "user"  (does not match the consumer -> signed bytes are ambiguous)

[>] sig(forward) = 67f181b98399b0cc1a4cd86ccf52b66b
[>] sig(reverse) = 0258a5858cdaec5ceb11651022da9c0f
[!] signature over the 'same' document reproducible? false

RESULT: VULNERABLE
主要語言
Ruby
星號
787
分支
392
平均合併
6 小時 4 分鐘
30 天內合併 PR
22

環境準備

這個專案沒有提供開發容器、Dockerfile 或貢獻指南,環境需要你自己搭建:先看它的 README,通用步驟見我們的新手貢獻指南。

從這裡開始

  1. 先讀完整個 Issue,再讀專案的貢獻指南。
  2. 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
  3. Fork 儲存庫,在一個分支上完成修改。
  4. 送出 Pull Request,並在描述裡引用這個 Issue 編號。

ruby/json 的其他 Issue

查看 ruby/json 的全部 Issue

相似的 Issue

更多 Ruby Issue

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。