Weak hashing for sensitive data

Weak hashing for sensitive data

Description

Password storage needs a hash that makes guessing expensive. Authenticating a download link needs a secret key. Unkeyed MD5 and SHA-1 are unsuitable for either purpose.

Potential impact

Leaked fast password hashes make guessing inexpensive. A link protected only by an unkeyed digest can be altered and still pass the check.

Remediation

Prefer Argon2id with a fresh random salt and adjustable cost for passwords. Alternatives include bcrypt, scrypt and PBKDF2-HMAC-SHA256. For PBKDF2-HMAC-SHA256 use at least 600,000 iterations and a random salt of at least 16 bytes. Tune the cost for your service. After a successful login with a legacy hash, rehash the password and save the algorithm and settings with it.

For links, use HMAC-SHA256 and protect the secret key. Use SHA-256, SHA-512 or SHA-3 when a collision-resistant unkeyed digest is appropriate.

Examples

Before

python
import hashlib

# Weak MD5/SHA-1 use for passwords and tokens

def store_password_md5(username: str, password: str) -> str:
    # BAD: fast MD5 password hashing without a salt
    digest = hashlib.md5(password.encode("utf-8")).hexdigest()
    return f"{username}:{digest}"

def sign_download_link_sha1(user_id: str, expires: int) -> str:
    # BAD: an unkeyed SHA-1 digest does not authenticate the data
    data = f"{user_id}:{expires}".encode()
    sig = hashlib.sha1(data).hexdigest()
    return f"{user_id}:{expires}:{sig}"

After

python
import os
import hmac
import base64
import hashlib
import secrets

# Password storage with PBKDF2-HMAC-SHA256

def hash_password(password: str) -> str:
    salt = os.urandom(16)
    iterations = 600_000
    dk = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, iterations)
    return f"pbkdf2_sha256${iterations}${base64.b64encode(salt).decode()}${base64.b64encode(dk).decode()}"

def verify_password(password: str, stored: str) -> bool:
    scheme, iters_s, b64_salt, b64_dk = stored.split("$")
    if scheme != "pbkdf2_sha256":
        return False
    salt = base64.b64decode(b64_salt)
    iterations = int(iters_s)
    true_dk = base64.b64decode(b64_dk)
    test_dk = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, iterations)
    return hmac.compare_digest(true_dk, test_dk)

# Integrity/authentication with HMAC-SHA256 (requires a secret key)

def sign_download_link(user_id: str, expires: int, secret_key: bytes) -> str:
    # Generate secret_key with secrets.token_bytes(32), for example, and store it securely
    msg = f"{user_id}:{expires}".encode()
    mac = hmac.new(secret_key, msg, hashlib.sha256).hexdigest()
    return f"{user_id}:{expires}:{mac}"

verify_password derives a value with the stored salt and iteration count and compares it with hmac.compare_digest. sign_download_link generates a MAC over the user ID and expiration time. The recipient still needs to check the MAC and expiry.

References