package password import ( "crypto/rand" "crypto/subtle" "encoding/base64" "errors" "fmt" "strconv" "strings" "golang.org/x/crypto/argon2" ) const ( argonTime = 2 argonMemory = 19456 argonThreads = 1 argonKeyLen = 32 argonSaltLen = 16 maxEncodedLen = 512 ) var ErrBusy = errors.New("password: derivation capacity exhausted") // All entry points share the same nonblocking, per-process derivation budget. // Legacy PHC strings can ask for 64 MiB per derivation; they get a separate // single slot so two upgrades cannot exceed the API memory limit. var ( derivations = make(chan struct{}, 2) legacyDerivations = make(chan struct{}, 1) ) type Verification struct { Match bool NeedsRehash bool } type parameters struct { memory uint32 time uint32 threads uint8 isLegacy bool salt [argonSaltLen]byte hash [argonKeyLen]byte } func Hash(plain string) (string, error) { if !acquire() { return "", ErrBusy } defer release() var salt [argonSaltLen]byte if _, err := rand.Read(salt[:]); err != nil { return "", fmt.Errorf("generate password salt: %w", err) } hash := argon2.IDKey([]byte(plain), salt[:], argonTime, argonMemory, argonThreads, argonKeyLen) return "$argon2id$v=19$m=19456,t=2,p=1$" + base64.RawStdEncoding.EncodeToString(salt[:]) + "$" + base64.RawStdEncoding.EncodeToString(hash), nil } func Verify(plain, encoded string) (Verification, error) { p, ok := parse(encoded) if !ok { return Verification{}, nil } if p.memory > argonMemory { if !acquireLegacy() { return Verification{}, ErrBusy } defer releaseLegacy() } else { if !acquire() { return Verification{}, ErrBusy } defer release() } actual := argon2.IDKey([]byte(plain), p.salt[:], p.time, p.memory, p.threads, argonKeyLen) if subtle.ConstantTimeCompare(actual, p.hash[:]) != 1 { return Verification{}, nil } obsolete := p.memory != argonMemory || p.time != argonTime || p.threads != argonThreads return Verification{Match: true, NeedsRehash: p.isLegacy || obsolete}, nil } // DummyVerify spends the same derivation budget as Verify for a caller that // cannot prove a match, so an unknown username is not cheaper than a known one. func DummyVerify(plain string) error { if !acquire() { return ErrBusy } defer release() var salt [argonSaltLen]byte _ = argon2.IDKey([]byte(plain), salt[:], argonTime, argonMemory, argonThreads, argonKeyLen) return nil } func acquire() bool { select { case derivations <- struct{}{}: return true default: return false } } func release() { <-derivations } func acquireLegacy() bool { select { case legacyDerivations <- struct{}{}: return true default: return false } } func releaseLegacy() { <-legacyDerivations } func parse(encoded string) (parameters, bool) { if len(encoded) > maxEncodedLen { return parameters{}, false } var p parameters var payload string switch { case strings.HasPrefix(encoded, "argon2id$"): p.memory, p.time, p.threads, p.isLegacy = 64*1024, 1, 4, true payload = strings.TrimPrefix(encoded, "argon2id$") case strings.HasPrefix(encoded, "$argon2id$v=19$"): body := strings.TrimPrefix(encoded, "$argon2id$v=19$") costs, rest, hasPayload := strings.Cut(body, "$") memoryPart, restCosts, hasMemory := strings.Cut(costs, ",") timePart, threadsPart, hasTime := strings.Cut(restCosts, ",") complete := hasPayload && hasMemory && hasTime if !complete { return parameters{}, false } memory, okMemory := cost(memoryPart, "m=", 64*1024) iterations, okTime := cost(timePart, "t=", 4) threads, okThreads := cost(threadsPart, "p=", 4) validCosts := okMemory && okTime && okThreads if !validCosts || threads > 4 || memory < 8*threads { return parameters{}, false } p.memory, p.time, p.threads = memory, iterations, uint8(threads) payload = rest default: return parameters{}, false } salt, hash, hasHash := strings.Cut(payload, "$") if !hasHash { return parameters{}, false } if len(salt) != 22 || len(hash) != 43 { return parameters{}, false } encoding := base64.RawStdEncoding.Strict() if n, err := encoding.Decode(p.salt[:], []byte(salt)); err != nil || n != argonSaltLen { return parameters{}, false } if n, err := encoding.Decode(p.hash[:], []byte(hash)); err != nil || n != argonKeyLen { return parameters{}, false } return p, true } func cost(encoded, prefix string, maximum uint32) (uint32, bool) { if !strings.HasPrefix(encoded, prefix) { return 0, false } value := strings.TrimPrefix(encoded, prefix) if len(value) == 0 || value[0] == '0' { return 0, false } for _, digit := range value { if digit < '0' || digit > '9' { return 0, false } } n, err := strconv.ParseUint(value, 10, 32) if err != nil || n == 0 || n > uint64(maximum) { return 0, false } return uint32(n), true }