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

未關閉 適合新手
#92 0 則留言 0 個 reaction 已指派 0 人 在 GitHub 檢視

還沒有人認領這個 Issue。

評估

難度
2/5
預估耗時
1-3 小時
新手友好度
67/100
Issue 類型
缺陷
描述清晰度
描述清楚
活躍度
活躍
技術堆疊
ruby
領域
backend, security

研究方向

從 lib/securerandom.rb:55 開始,追蹤英數字元實作及其共用的 choose 方法;在 Ruby 3.3 及更新版本中,也要檢查 Random::Formatter。為負長度和無效的 chars 值新增測試,包括檢查傳回的字串是否符合要求的長度。當無效輸入會引發例外,且有效輸入仍恰好傳回要求數量的字元時,即表示完成。

由索引模型根據 Issue 內容生成。

描述

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.
主要語言
Ruby
星號
76
分支
17
平均合併
42 分鐘
30 天內合併 PR
5

環境準備

這個專案沒有提供開發容器、Dockerfile 或貢獻指南,環境需要你自己搭建:先看它的 README,通用步驟見我們的新手貢獻指南。

從這裡開始

  1. 先讀完整個 Issue,再讀專案的貢獻指南。
  2. 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
  3. Fork 儲存庫,在一個分支上完成修改。
  4. 送出 Pull Request,並在描述裡引用這個 Issue 編號。

ruby/securerandom 的其他 Issue

查看 ruby/securerandom 的全部 Issue

相似的 Issue

更多 Ruby Issue

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。