predictable-token

A token built from values anyone can guess.

Group
Code
Runs
Runs under ur scan: ur scan --rule predictable-token
Level
warning
Reads
Every file
Fix
None: the safe form depends on what the value is meant to be

Why

A token sent to a user to prove who they are, such as a password reset link's, is a digest of values anyone can learn or guess, such as an email address, an id, or the time, with no secret or random part, so anyone can compute the token of any account and use it. Make tokens with SecureRandom.urlsafe_base64, or sign them with a secret, as Rails' generates_token_for does.

The fix, as Ur suggests it: make the token random.

For agents

Never build a token from a digest of an email, id, or time alone; make it random or sign it with a secret.

Example

app/controllers/password_resets_controller.rb
class PasswordResetsController < ApplicationController
  private

  def reset_token(user)
    Digest::MD5.hexdigest("#{user.id}-#{user.email}")
  end
end
What Ur prints
$ ur scan --rule predictable-token
warning[predictable-token]: a token is `Digest::MD5.hexdigest` of values anyone can guess, with no secret or random part, so anyone can make it
  --> ./app/controllers/password_resets_controller.rb:5:5 method `reset_token`
  = hint: make the token random
  = see: CWE-640: Weak Password Recovery Mechanism for Forgotten Password, MITRE (2024-11-19), https://cwe.mitre.org/data/definitions/640.html
scanned 1 file (no framework recognized)
  predictable-token: 1 high, 0 medium
1 finding and 0 of medium confidence

Try it in the playground →

Source

CWE-640: Weak Password Recovery Mechanism for Forgotten Password, MITRE (2024-11-19).