// Package argon2id implements outbound.PasswordHasher with Argon2id (RFC 9106) // from golang.org/x/crypto/argon2 and the PHC string format. package argon2id import ( "context" "crypto/rand" "crypto/subtle" "encoding/base64" "errors" "fmt" "strconv" "strings" "golang.org/x/crypto/argon2" "golang.org/x/sync/semaphore" "lincodex/backend/internal/domain" "lincodex/backend/internal/port/outbound" ) // Parameters of new hashes: the second recommended option of RFC 9106, // section 4 (64 MiB, 3 passes, 4 lanes). It is stronger than the OWASP // Password Storage Cheat Sheet baseline (19 MiB, 2 passes, 1 lane). const ( recommendedMemoryKiB = 64 * 1024 recommendedIterations = 3 recommendedParallelism = 4 // RFC 9106 recommends a 128-bit salt and a 256-bit tag. saltBytes = 16 keyBytes = 32 ) // Bounds for stored hashes. Verify recomputes a hash with the parameters // stored in it, so a crafted or corrupted row must not be able to demand // unbounded memory or time. They leave room to raise the current parameters // and still verify older hashes until a login rehashes them. A stored hash // must also fit the memory budget of the hasher (see Hasher). const ( maxStoredMemoryKiB = 2 * recommendedMemoryKiB maxStoredIterations = 16 maxStoredParallelism = 16 // Argon2 needs at least 8 KiB per lane; x/crypto silently raises a lower // value, which no conforming encoder writes. minMemoryKiBPerLane = 8 // The salt and digest minimums match domain.NewPasswordHash. minStoredSaltBytes = 8 maxStoredSaltBytes = 64 minStoredKeyBytes = 16 maxStoredKeyBytes = 64 phcFieldCount = 6 phcParameterCount = 3 ) type parameters struct { memoryKiB uint32 iterations uint32 parallelism uint8 } func recommendedParameters() parameters { return parameters{ memoryKiB: recommendedMemoryKiB, iterations: recommendedIterations, parallelism: recommendedParallelism, } } // Hasher is safe for concurrent use. Derivations share a memory budget of // concurrency times the current memory parameter: each one holds its own // memory parameter in a weighted semaphore while it runs, so at most // concurrency current-parameter derivations run at once, and a stored hash // with a larger memory parameter takes a larger share. Other calls wait in // FIFO order until the budget frees up or their context ends; the queue is // bounded only by the callers' contexts, and request rate limiting belongs // to the HTTP layer. type Hasher struct { current parameters budgetKiB int64 memory *semaphore.Weighted // dummy has the current parameters, a random salt, and a random digest // that no password derives in practice. dummy domain.PasswordHash } var _ outbound.PasswordHasher = (*Hasher)(nil) // NewHasher returns a hasher with the RFC 9106 parameters and a memory // budget for concurrency derivations with those parameters. func NewHasher(concurrency int) (*Hasher, error) { return newHasher(recommendedParameters(), concurrency) } func newHasher(current parameters, concurrency int) (*Hasher, error) { if concurrency < 1 { return nil, errors.New("argon2id.newHasher - concurrency must be positive") } if violation := current.violation(); violation != "" { return nil, errors.New("argon2id.newHasher - " + violation) } salt, err := randomBytes(saltBytes) if err != nil { return nil, fmt.Errorf("argon2id.newHasher - generate dummy salt: %w", err) } digest, err := randomBytes(keyBytes) if err != nil { return nil, fmt.Errorf("argon2id.newHasher - generate dummy digest: %w", err) } dummy, err := domain.NewPasswordHash(encodePHC(current, salt, digest)) if err != nil { return nil, fmt.Errorf("argon2id.newHasher - encode dummy hash: %w", err) } budgetKiB := int64(concurrency) * int64(current.memoryKiB) return &Hasher{ current: current, budgetKiB: budgetKiB, memory: semaphore.NewWeighted(budgetKiB), dummy: dummy, }, nil } // Hash derives a 32-byte key with a fresh 16-byte salt from crypto/rand. func (hasher *Hasher) Hash(ctx context.Context, password domain.Password) (domain.PasswordHash, error) { if password.IsZero() { return domain.PasswordHash{}, fmt.Errorf("Hasher.Hash - password must be built by a domain constructor: %w", domain.ErrInvalidPassword) } salt, err := randomBytes(saltBytes) if err != nil { return domain.PasswordHash{}, fmt.Errorf("Hasher.Hash - generate salt: %w", err) } key, err := hasher.derive(ctx, password, hasher.current, salt, keyBytes) if err != nil { return domain.PasswordHash{}, fmt.Errorf("Hasher.Hash - derive key: %w", err) } hash, err := domain.NewPasswordHash(encodePHC(hasher.current, salt, key)) if err != nil { return domain.PasswordHash{}, fmt.Errorf("Hasher.Hash - encode hash: %w", err) } return hash, nil } // Verify recomputes the key with the salt, parameters, and key length stored // in the hash and compares it in constant time. func (hasher *Hasher) Verify(ctx context.Context, password domain.Password, stored domain.PasswordHash) (bool, error) { if password.IsZero() { return false, fmt.Errorf("Hasher.Verify - password must be built by a domain constructor: %w", domain.ErrInvalidPassword) } decoded, err := parsePHC(stored.PHC()) if err != nil { return false, fmt.Errorf("Hasher.Verify - parse stored hash: %w", err) } // The semaphore would block until the context ends on a weight above its // size, so such a hash is refused up front. if int64(decoded.parameters.memoryKiB) > hasher.budgetKiB { return false, corruptHash("Hasher.Verify", "memory exceeds the hashing budget") } keyLength := uint32(len(decoded.key)) //nolint:gosec // parsePHC bounds the digest to 64 bytes. key, err := hasher.derive(ctx, password, decoded.parameters, decoded.salt, keyLength) if err != nil { return false, fmt.Errorf("Hasher.Verify - derive key: %w", err) } if subtle.ConstantTimeCompare(key, decoded.key) != 1 { return false, fmt.Errorf("Hasher.Verify - compare keys: %w", outbound.ErrPasswordMismatch) } needsRehash := decoded.parameters != hasher.current || len(decoded.salt) != saltBytes || len(decoded.key) != keyBytes return needsRehash, nil } // VerifyDummy runs Verify against the dummy hash, so it parses, waits for a // slot, derives, and compares exactly as a real verification does. func (hasher *Hasher) VerifyDummy(ctx context.Context, password domain.Password) error { _, err := hasher.Verify(ctx, password, hasher.dummy) if err != nil { return fmt.Errorf("Hasher.VerifyDummy - verify dummy hash: %w", err) } // Unreachable in practice (a 2^-256 chance); fail closed all the same. return fmt.Errorf("Hasher.VerifyDummy - dummy hash matched: %w", outbound.ErrPasswordMismatch) } func (hasher *Hasher) derive(ctx context.Context, password domain.Password, params parameters, salt []byte, keyLength uint32) ([]byte, error) { weight := int64(params.memoryKiB) if err := hasher.acquire(ctx, weight); err != nil { return nil, err } defer hasher.memory.Release(weight) secret := []byte(password.Reveal()) // Best effort: this clears only the byte copy handed to Argon2. The // normalized string inside domain.Password cannot be wiped in Go and stays // in memory until the garbage collector reuses it. defer clear(secret) return argon2.IDKey(secret, salt, params.iterations, params.memoryKiB, params.parallelism, keyLength), nil } // acquire checks the context first, because Acquire may succeed on an ended // context when the budget is free. func (hasher *Hasher) acquire(ctx context.Context, weight int64) error { if err := ctx.Err(); err != nil { return fmt.Errorf("Hasher.acquire - context ended before hashing: %w", err) } if err := hasher.memory.Acquire(ctx, weight); err != nil { return fmt.Errorf("Hasher.acquire - wait for hashing memory: %w", err) } return nil } func randomBytes(size int) ([]byte, error) { buffer := make([]byte, size) if _, err := rand.Read(buffer); err != nil { return nil, fmt.Errorf("argon2id.randomBytes - read random bytes: %w", err) } return buffer, nil } // encodePHC writes $argon2id$v=19$m=,t=,p=$$ // with unpadded standard base64, the format of the reference implementation. func encodePHC(params parameters, salt, key []byte) string { return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s", argon2.Version, params.memoryKiB, params.iterations, params.parallelism, base64.RawStdEncoding.EncodeToString(salt), base64.RawStdEncoding.EncodeToString(key)) } type decodedHash struct { parameters parameters salt []byte key []byte } // parsePHC accepts only what encodePHC writes: Argon2id version 19, the // parameters in the order m, t, p as decimals without leading zeros, and // unpadded standard base64. Every failure wraps outbound.ErrPasswordHashCorrupt, // and through it domain.ErrInvalidPasswordHash, and never quotes the input. func parsePHC(encoded string) (decodedHash, error) { fields := strings.Split(encoded, "$") if len(fields) != phcFieldCount || fields[0] != "" || fields[1] != "argon2id" { return decodedHash{}, corruptHash("argon2id.parsePHC", "hash must be an Argon2id PHC string") } if fields[2] != "v="+strconv.Itoa(argon2.Version) { return decodedHash{}, corruptHash("argon2id.parsePHC", "hash must use Argon2 version 19") } params, err := parseParameters(fields[3]) if err != nil { return decodedHash{}, err } salt, err := base64.RawStdEncoding.Strict().DecodeString(fields[4]) if err != nil || len(salt) < minStoredSaltBytes || len(salt) > maxStoredSaltBytes { return decodedHash{}, corruptHash("argon2id.parsePHC", "salt must be unpadded base64 of 8 to 64 bytes") } key, err := base64.RawStdEncoding.Strict().DecodeString(fields[5]) if err != nil || len(key) < minStoredKeyBytes || len(key) > maxStoredKeyBytes { return decodedHash{}, corruptHash("argon2id.parsePHC", "digest must be unpadded base64 of 16 to 64 bytes") } return decodedHash{parameters: params, salt: salt, key: key}, nil } func parseParameters(field string) (parameters, error) { values := strings.Split(field, ",") if len(values) != phcParameterCount { return parameters{}, corruptHash("argon2id.parseParameters", "parameters must be m, t, and p") } memory, memoryOK := parseParameter(values[0], "m=", 32) iterations, iterationsOK := parseParameter(values[1], "t=", 32) parallelism, parallelismOK := parseParameter(values[2], "p=", 8) if !memoryOK || !iterationsOK || !parallelismOK { return parameters{}, corruptHash("argon2id.parseParameters", "parameters must be m, t, and p as decimals without leading zeros") } params := parameters{ memoryKiB: uint32(memory), //nolint:gosec // ParseUint limited the value to 32 bits. iterations: uint32(iterations), //nolint:gosec // ParseUint limited the value to 32 bits. parallelism: uint8(parallelism), //nolint:gosec // ParseUint limited the value to 8 bits. } if violation := params.violation(); violation != "" { return parameters{}, corruptHash("argon2id.parseParameters", violation) } return params, nil } // parseParameter reads one "" value that fits bitSize bits. func parseParameter(value, prefix string, bitSize int) (uint64, bool) { digits, found := strings.CutPrefix(value, prefix) if !found || digits == "" || digits[0] == '0' { return 0, false } number, err := strconv.ParseUint(digits, 10, bitSize) return number, err == nil } // violation returns the stored-hash bound that params break, or "". The // current parameters must pass it too, so every new hash stays verifiable. func (params parameters) violation() string { switch { case params.parallelism < 1 || params.parallelism > maxStoredParallelism: return "parallelism must be between 1 and 16" case params.iterations < 1 || params.iterations > maxStoredIterations: return "iterations must be between 1 and 16" case params.memoryKiB < minMemoryKiBPerLane*uint32(params.parallelism) || params.memoryKiB > maxStoredMemoryKiB: return "memory must be between 8 KiB per lane and 128 MiB" default: return "" } } func corruptHash(location, reason string) error { return fmt.Errorf("%s - %s: %w", location, reason, outbound.ErrPasswordHashCorrupt) }