RFC 8785 canonicalization emits duplicate object names and is not deterministic when keys differ only in encoding
Mantenedores costumam responder em até 1 dia
Ninguém assumiu esta issue ainda.
Avaliação
- Dificuldade
- 3/5
- Tempo estimado
- 1-2 dias
- Facilidade para iniciantes
- 55/100
Direção de pesquisa
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.
Escrita pelo modelo de indexação a partir do texto da issue.
Descrição
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
- Linguagem predominante
- Ruby
- Estrelas
- 787
- Forks
- 392
- Merge médio
- 6h 4min
- PRs com merge (30d)
- 22
Preparar o ambiente
Este projeto não oferece contêiner de desenvolvimento, Dockerfile nem guia de contribuição, então a configuração fica por sua conta: comece pelo README e veja nosso guia da primeira contribuição para os passos gerais.
Primeiros passos
- Leia a issue inteira e depois o guia de contribuição do projeto.
- Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
- Faça um fork do repositório e trabalhe em uma branch.
- Abra um pull request que referencie o número da issue.
Mais de ruby/json
-
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 76/100
Mantenedores costumam responder em até 1 dia
-
Dificuldade 4/5 3-5 dias Facilidade para iniciantes 55/100
Mantenedores costumam responder em até 1 dia
-
Audit excluded tests on JRuby and address differencesTalvez já em andamento @ojuschugh1 assumiu há 5 dias. Aberta
Dificuldade 4/5 3-5 dias Facilidade para iniciantes 48/100
ruby/json#1123 · 5 comentários ·
Mantenedores costumam responder em até 1 dia
-
Dificuldade 3/5 1-2 dias Facilidade para iniciantes 55/100
ruby/json#1041 · 7 comentários ·
Mantenedores costumam responder em até 1 dia
-
Output formatting differences between jRuby 10.0.0.1 and Ruby 3.4 when converting Float to JSON.Talvez já em andamento @headius assumiu há 460 dias. Abertajruby
ruby/json#817 · 3 comentários · 1 reação · 1 responsável ·
Mantenedores costumam responder em até 1 dia
Issues semelhantes
-
SecureRandom.alphanumeric can silently return an empty or wrong-length secret instead of raisingAberta
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 67/100
ruby/securerandom#92 ·
-
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 72/100
Mantenedores costumam responder em até 1 dia
-
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 85/100
open-feature/ruby-sdk-contrib#340 ·
Mantenedores costumam responder em até 1 dia
-
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 88/100
zold-io/wts.zold.io#651 ·
Mantenedores costumam responder em até 1 dia
-
good first issue help wanted
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 87/100
erkamyaman/rust-anything#788 ·
Mantenedores costumam responder em até 1 dia