package userapi import ( "crypto/rand" "crypto/subtle" "encoding/base64" "errors" "fmt" "strings" "golang.org/x/crypto/argon2" ) // Argon2id parameters. These are OWASP's recommended settings for argon2id // (19 MiB, two passes, one lane): strong enough to make a stolen hash // expensive to attack, cheap enough that a login does not become a denial of // service against the server itself. // // The values are recorded in every hash, so raising them later is a matter // of changing these constants; old hashes keep verifying with the parameters // they were made with, and are rewritten the next time the password changes. const ( argonMemoryKiB = 19 * 1024 argonTime = 2 argonLanes = 1 argonSaltLen = 16 argonKeyLen = 32 ) // MaxPasswordLength caps a password at 512 bytes. Argon2id does not care how // long its input is, but accepting unbounded input means accepting unbounded // work in the hash function. const MaxPasswordLength = 512 // ErrPasswordTooLong is returned when a password exceeds MaxPasswordLength. var ErrPasswordTooLong = fmt.Errorf("password must be at most %d bytes", MaxPasswordLength) // ErrInvalidPasswordHash is returned when a stored hash cannot be parsed. It // means the row is corrupt, not that the password was wrong. var ErrInvalidPasswordHash = errors.New("stored password hash is malformed") // HashPassword returns an encoded argon2id hash in the PHC string format: // // $argon2id$v=19$m=19456,t=2,p=1$$ // // The format is the de facto standard for password hashes, so the parameters // travel with the hash and an operator can tell at a glance what a row was // written with. func HashPassword(password string) (string, error) { if len(password) > MaxPasswordLength { return "", ErrPasswordTooLong } salt := make([]byte, argonSaltLen) if _, err := rand.Read(salt); err != nil { return "", fmt.Errorf("generate password salt: %w", err) } key := argon2.IDKey([]byte(password), salt, argonTime, argonMemoryKiB, argonLanes, argonKeyLen) return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s", argon2.Version, argonMemoryKiB, argonTime, argonLanes, b64.EncodeToString(salt), b64.EncodeToString(key)), nil } // VerifyPassword reports whether password matches encoded. An unparseable // hash is an error rather than a mismatch, so a corrupt row shows up in the // logs instead of looking like a wrong password forever. func VerifyPassword(encoded, password string) (bool, error) { if len(password) > MaxPasswordLength { return false, ErrPasswordTooLong } params, salt, want, err := decodeHash(encoded) if err != nil { return false, err } got := argon2.IDKey([]byte(password), salt, params.time, params.memory, params.lanes, uint32(len(want))) return subtle.ConstantTimeCompare(got, want) == 1, nil } // b64 is the unpadded base64 the PHC format uses. var b64 = base64.RawStdEncoding type argonParams struct { memory uint32 time uint32 lanes uint8 } // decodeHash parses a PHC argon2id string. func decodeHash(encoded string) (argonParams, []byte, []byte, error) { // "", "argon2id", "v=19", "m=...,t=...,p=...", salt, hash parts := strings.Split(encoded, "$") if len(parts) != 6 || parts[0] != "" { return argonParams{}, nil, nil, ErrInvalidPasswordHash } if parts[1] != "argon2id" { return argonParams{}, nil, nil, fmt.Errorf("%w: unsupported algorithm %q", ErrInvalidPasswordHash, parts[1]) } var version int if _, err := fmt.Sscanf(parts[2], "v=%d", &version); err != nil { return argonParams{}, nil, nil, ErrInvalidPasswordHash } if version != argon2.Version { return argonParams{}, nil, nil, fmt.Errorf("%w: unsupported argon2 version %d", ErrInvalidPasswordHash, version) } var p argonParams if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &p.memory, &p.time, &p.lanes); err != nil { return argonParams{}, nil, nil, ErrInvalidPasswordHash } if p.memory == 0 || p.time == 0 || p.lanes == 0 { return argonParams{}, nil, nil, ErrInvalidPasswordHash } salt, err := b64.DecodeString(parts[4]) if err != nil || len(salt) == 0 { return argonParams{}, nil, nil, ErrInvalidPasswordHash } key, err := b64.DecodeString(parts[5]) if err != nil || len(key) == 0 { return argonParams{}, nil, nil, ErrInvalidPasswordHash } return p, salt, key, nil } // dummyPasswordHash is verified against when the named account does not // exist or has no password, so that a login attempt costs the same either // way. Without it, the time a rejection takes would tell an attacker which // user names are real. var dummyPasswordHash = func() string { hash, err := HashPassword("warp: this password hashes nothing") if err != nil { // HashPassword only fails on a short read from crypto/rand, which // at init time means the process cannot work at all. panic("userapi: cannot build the dummy password hash: " + err.Error()) } return hash }()