Module: Aspera::Secret::Strength

Defined in:
lib/aspera/secret/strength.rb

Overview

Estimate of the strength of a secret (e.g. a token), in bits: log2 of the number of guesses to find it

Uses gem zxcvbn if installed (dictionaries, l33t, dates...), else a built-in estimate, the lowest of:

  • alphabet: length x log2(size of character classes used)
  • Shannon: empirical entropy of characters (catches repeats)
  • patterns: repeats, sequences and keyboard rows cost 1 bit per character, words and years 2 bits per character Both under-estimate random secrets: a random secret of 32 bytes (e.g. openssl rand -hex 32) is far above any usual minimum.

Constant Summary collapse

DEFAULT_MIN_BITS =

Default minimum strength of tokens, in bits: random tokens of 32 bytes are far above

80

Class Method Summary collapse

Class Method Details

.assert_strong(secret, name:, min_bits: DEFAULT_MIN_BITS, type: ParameterError) ⇒ Object

Refuse an empty or weak secret: an empty one would often accept requests without secret

Parameters:

  • secret (String) —

    Secret to check

  • name (String) —

    Name of the parameter holding the secret, its minimum is in parameter <name>_min_bits

  • min_bits (Integer) (defaults to: DEFAULT_MIN_BITS) —

    Minimum estimated strength in bits, 0 checks only that the secret is not empty

  • type (Exception) (defaults to: ParameterError) —

    Exception to raise

Raises:

  • (Exception) —

    if the secret is empty or weaker than min_bits



48
49
50
51
52
53
54
# File 'lib/aspera/secret/strength.rb', line 48

def assert_strong(secret, name:, min_bits: DEFAULT_MIN_BITS, type: ParameterError)
  Aspera.assert(!secret.to_s.empty?, type: type) { "#{name} must not be empty" }
  strength = bits(secret)
  Aspera.assert(strength >= min_bits, type: type) do
    "#{name} is too weak: about #{strength.round} bits, minimum #{min_bits} (#{name}_min_bits). Generate one with: openssl rand -hex 32"
  end
end

.bits(secret) ⇒ Float

Returns Estimated strength in bits.

Parameters:

  • secret (String) —

    Secret to assess

Returns:

  • (Float) —

    Estimated strength in bits



36
37
38
39
40
# File 'lib/aspera/secret/strength.rb', line 36

def bits(secret)
  secret = secret.to_s
  return 0.0 if secret.empty?
  zxcvbn_bits(secret) || estimate_bits(secret)
end

.estimate_bits(secret) ⇒ Float

Built-in estimate, without dictionary

Parameters:

  • secret (String) —

    Secret to assess

Returns:

  • (Float) —

    Estimated strength in bits



59
60
61
62
63
# File 'lib/aspera/secret/strength.rb', line 59

def estimate_bits(secret)
  return 0.0 if secret.empty?
  bits_per_char = Math.log2(CHARACTER_CLASSES.sum { |regex, size| secret.match?(regex) ? size : 0 })
  [secret.size * bits_per_char, shannon_bits(secret), pattern_bits(secret, bits_per_char)].min
end