snapshot of https://github.com/ory/kratos.git (master, 2026-09-15; blobs > 131072B omitted)
Some checks failed
CI / Run tests and lints (push) Failing after 29s
CI / Build CLI docs (push) Has been skipped
CI / Run Playwright end-to-end tests (mysql) (push) Failing after 3s
CI / Run Playwright end-to-end tests (postgres) (push) Failing after 2s
CI / Run Playwright end-to-end tests (sqlite) (push) Failing after 3s
CodeQL / Analyze (go) (push) Failing after 4s
CodeQL / Analyze (javascript) (push) Failing after 3s
Docker Image Scanners / scanners (push) Failing after 4s
Synchronize Issue Labels / Synchronize Issue Labels (push) Has been skipped
CI / Run end-to-end tests (postgres) (push) Failing after 19s
CI / Run end-to-end tests (sqlite) (push) Failing after 2s
CI / Run Playwright end-to-end tests (cockroach) (push) Failing after 2s
CI / Draft newsletter (push) Has been skipped
CI / Generate release (push) Has been skipped
CI / Pending approval Slack notification (push) Has been skipped
CI / Send newsletter (push) Has been skipped

This commit is contained in:
upstream-mirror
2026-09-15 21:19:12 +05:00
commit c60cc7ca75
8092 changed files with 394160 additions and 0 deletions

View File

@@ -0,0 +1,227 @@
package hasherx
import (
"context"
"crypto/subtle"
"encoding/base64"
"fmt"
"math"
"regexp"
"strings"
"github.com/pkg/errors"
"golang.org/x/crypto/argon2"
"golang.org/x/crypto/bcrypt"
"golang.org/x/crypto/pbkdf2"
)
var ErrUnknownHashAlgorithm = errors.New("unknown hash algorithm")
// Compare the given password with the given hash.
func Compare(ctx context.Context, password []byte, hash []byte) error {
switch {
case IsBcryptHash(hash):
return CompareBcrypt(ctx, password, hash)
case IsArgon2idHash(hash):
return CompareArgon2id(ctx, password, hash)
case IsArgon2iHash(hash):
return CompareArgon2i(ctx, password, hash)
case IsPbkdf2Hash(hash):
return ComparePbkdf2(ctx, password, hash)
default:
return errors.WithStack(ErrUnknownHashAlgorithm)
}
}
func CompareBcrypt(_ context.Context, password []byte, hash []byte) error {
if err := validateBcryptPasswordLength(password); err != nil {
return err
}
err := bcrypt.CompareHashAndPassword(hash, password)
if err != nil {
return err
}
return nil
}
func CompareArgon2id(_ context.Context, password []byte, hash []byte) error {
// Extract the parameters, salt and derived key from the encoded password
// hash.
p, salt, hash, err := decodeArgon2idHash(string(hash))
if err != nil {
return err
}
mem := uint64(p.Memory)
if mem > math.MaxUint32 {
return errors.WithStack(ErrInvalidHash)
}
// Derive the key from the other password using the same parameters.
otherHash := argon2.IDKey(password, salt, p.Iterations, uint32(mem), p.Parallelism, p.KeyLength)
// Check that the contents of the hashed passwords are identical. Note
// that we are using the subtle.ConstantTimeCompare() function for this
// to help prevent timing attacks.
if subtle.ConstantTimeCompare(hash, otherHash) == 1 {
return nil
}
return errors.WithStack(ErrMismatchedHashAndPassword)
}
func CompareArgon2i(_ context.Context, password []byte, hash []byte) error {
// Extract the parameters, salt and derived key from the encoded password
// hash.
p, salt, hash, err := decodeArgon2idHash(string(hash))
if err != nil {
return err
}
mem := uint64(p.Memory)
if mem > math.MaxUint32 {
return errors.WithStack(ErrInvalidHash)
}
// Derive the key from the other password using the same parameters.
otherHash := argon2.Key(password, salt, p.Iterations, uint32(mem), p.Parallelism, p.KeyLength)
// Check that the contents of the hashed passwords are identical. Note
// that we are using the subtle.ConstantTimeCompare() function for this
// to help prevent timing attacks.
if subtle.ConstantTimeCompare(hash, otherHash) == 1 {
return nil
}
return errors.WithStack(ErrMismatchedHashAndPassword)
}
func ComparePbkdf2(_ context.Context, password []byte, hash []byte) error {
// Extract the parameters, salt and derived key from the encoded password
// hash.
p, salt, hash, err := decodePbkdf2Hash(string(hash))
if err != nil {
return err
}
// Derive the key from the other password using the same parameters.
otherHash := pbkdf2.Key(password, salt, int(p.Iterations), int(p.KeyLength), getPseudorandomFunctionForPbkdf2(p.Algorithm))
// Check that the contents of the hashed passwords are identical. Note
// that we are using the subtle.ConstantTimeCompare() function for this
// to help prevent timing attacks.
if subtle.ConstantTimeCompare(hash, otherHash) == 1 {
return nil
}
return errors.WithStack(ErrMismatchedHashAndPassword)
}
var (
isBcryptHash = regexp.MustCompile(`^\$2[abzy]?\$`)
isArgon2idHash = regexp.MustCompile(`^\$argon2id\$`)
isArgon2iHash = regexp.MustCompile(`^\$argon2i\$`)
isPbkdf2Hash = regexp.MustCompile(`^\$pbkdf2-sha[0-9]{1,3}\$`)
)
func IsBcryptHash(hash []byte) bool {
return isBcryptHash.Match(hash)
}
func IsArgon2idHash(hash []byte) bool {
return isArgon2idHash.Match(hash)
}
func IsArgon2iHash(hash []byte) bool {
return isArgon2iHash.Match(hash)
}
func IsPbkdf2Hash(hash []byte) bool {
return isPbkdf2Hash.Match(hash)
}
func decodeArgon2idHash(encodedHash string) (p *Argon2Config, salt, hash []byte, err error) {
parts := strings.Split(encodedHash, "$")
if len(parts) != 6 {
return nil, nil, nil, ErrInvalidHash
}
var version int
_, err = fmt.Sscanf(parts[2], "v=%d", &version)
if err != nil {
return nil, nil, nil, err
}
if version != argon2.Version {
return nil, nil, nil, ErrIncompatibleVersion
}
p = new(Argon2Config)
_, err = fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &p.Memory, &p.Iterations, &p.Parallelism)
if err != nil {
return nil, nil, nil, err
}
salt, err = base64.RawStdEncoding.Strict().DecodeString(parts[4])
if err != nil {
return nil, nil, nil, err
}
saltLength := uint(len(salt))
if saltLength > math.MaxUint32 {
return nil, nil, nil, ErrInvalidHash
}
p.SaltLength = uint32(saltLength)
hash, err = base64.RawStdEncoding.Strict().DecodeString(parts[5])
if err != nil {
return nil, nil, nil, err
}
keyLength := uint(len(hash))
if keyLength > math.MaxUint32 {
return nil, nil, nil, ErrInvalidHash
}
p.KeyLength = uint32(keyLength)
return p, salt, hash, nil
}
// decodePbkdf2Hash decodes PBKDF2 encoded password hash.
// format: $pbkdf2-<digest>$i=<iterations>,l=<length>$<salt>$<hash>
func decodePbkdf2Hash(encodedHash string) (p *PBKDF2Config, salt, hash []byte, err error) {
parts := strings.Split(encodedHash, "$")
if len(parts) != 5 {
return nil, nil, nil, ErrInvalidHash
}
p = new(PBKDF2Config)
digestParts := strings.SplitN(parts[1], "-", 2)
if len(digestParts) != 2 {
return nil, nil, nil, ErrInvalidHash
}
p.Algorithm = digestParts[1]
_, err = fmt.Sscanf(parts[2], "i=%d,l=%d", &p.Iterations, &p.KeyLength)
if err != nil {
return nil, nil, nil, err
}
salt, err = base64.RawStdEncoding.Strict().DecodeString(parts[3])
if err != nil {
return nil, nil, nil, err
}
saltLength := uint(len(salt))
if saltLength > math.MaxUint32 {
return nil, nil, nil, ErrInvalidHash
}
p.SaltLength = uint32(saltLength)
hash, err = base64.RawStdEncoding.Strict().DecodeString(parts[4])
if err != nil {
return nil, nil, nil, err
}
keyLength := uint(len(hash))
if keyLength > math.MaxUint32 {
return nil, nil, nil, ErrInvalidHash
}
p.KeyLength = uint32(keyLength)
return p, salt, hash, nil
}

20
oryx/hasherx/hasher.go Normal file
View File

@@ -0,0 +1,20 @@
package hasherx
import (
"context"
)
// Hasher provides methods for generating and comparing password hashes.
type Hasher interface {
// Generate returns a hash derived from the password or an error if the hash method failed.
Generate(ctx context.Context, password []byte) ([]byte, error)
// Understands returns whether the given hash can be understood by this hasher.
Understands(hash []byte) bool
}
type HashProvider interface {
Hasher() Hasher
}
const tracingComponent = "github.com/ory/kratos/hash"

View File

@@ -0,0 +1,118 @@
package hasherx
import (
"bytes"
"context"
"crypto/rand"
"encoding/base64"
"fmt"
"math"
"time"
"github.com/ory/x/otelx"
"github.com/inhies/go-bytesize"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"github.com/pkg/errors"
"golang.org/x/crypto/argon2"
)
var (
ErrInvalidHash = errors.New("the encoded hash is not in the correct format")
ErrIncompatibleVersion = errors.New("incompatible version of argon2")
ErrMismatchedHashAndPassword = errors.New("passwords do not match")
)
type (
// Argon2Config is the configuration for a Argon2 hasher.
Argon2Config struct {
// Memory is the amount of memory to use.
Memory bytesize.ByteSize `json:"memory"`
// Iterations is the number of iterations to use.
Iterations uint32 `json:"iterations"`
// Parallelism is the number of threads to use.
Parallelism uint8 `json:"parallelism"`
// SaltLength is the length of the salt to use.
SaltLength uint32 `json:"salt_length"`
// KeyLength is the length of the key to use.
KeyLength uint32 `json:"key_length"`
// ExpectedDuration is the expected duration of the hash.
ExpectedDuration time.Duration `json:"expected_duration"`
// ExpectedDeviation is the expected deviation of the hash.
ExpectedDeviation time.Duration `json:"expected_deviation"`
// DedicatedMemory is the amount of dedicated memory to use.
DedicatedMemory bytesize.ByteSize `json:"dedicated_memory"`
}
// Argon2 is a hasher that uses the Argon2 algorithm.
Argon2 struct {
c Argon2Configurator
}
// Argon2Configurator is a function that returns the Argon2 configuration.
Argon2Configurator interface {
HasherArgon2Config(ctx context.Context) *Argon2Config
}
)
func NewHasherArgon2(c Argon2Configurator) *Argon2 {
return &Argon2{c: c}
}
func toKB(mem bytesize.ByteSize) (uint32, error) {
kb := uint64(mem / bytesize.KB)
if kb > math.MaxUint32 {
return 0, errors.Errorf("memory %v is too large", mem)
}
return uint32(kb), nil
}
// Generate generates a hash for the given password.
func (h *Argon2) Generate(ctx context.Context, password []byte) (_ []byte, err error) {
ctx, span := otel.GetTracerProvider().Tracer(tracingComponent).Start(ctx, "hash.Argon2.Generate")
defer otelx.End(span, &err)
p := h.c.HasherArgon2Config(ctx)
span.SetAttributes(attribute.String("argon2.config", fmt.Sprintf("#%v", p)))
salt := make([]byte, p.SaltLength)
if _, err := rand.Read(salt); err != nil {
return nil, err
}
mem, err := toKB(p.Memory)
if err != nil {
return nil, err
}
// Pass the plaintext password, salt and parameters to the argon2.IDKey
// function. This will generate a hash of the password using the Argon2id
// variant.
hash := argon2.IDKey(password, salt, p.Iterations, mem, p.Parallelism, p.KeyLength)
var b bytes.Buffer
if _, err := fmt.Fprintf(
&b,
"$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
argon2.Version, mem, p.Iterations, p.Parallelism,
base64.RawStdEncoding.EncodeToString(salt),
base64.RawStdEncoding.EncodeToString(hash),
); err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
return nil, errors.WithStack(err)
}
return b.Bytes(), nil
}
// Understands checks if the given hash is in the correct format.
func (h *Argon2) Understands(hash []byte) bool {
return IsArgon2idHash(hash)
}

View File

@@ -0,0 +1,68 @@
package hasherx
import (
"context"
"github.com/pkg/errors"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"golang.org/x/crypto/bcrypt"
"github.com/ory/x/otelx"
)
// ErrBcryptPasswordLengthReached is returned when the password is longer than 72 bytes.
var ErrBcryptPasswordLengthReached = errors.Errorf("passwords are limited to a maximum length of 72 characters")
type (
// Bcrypt is a hasher that uses the bcrypt algorithm.
Bcrypt struct {
c BCryptConfigurator
}
// BCryptConfig is the configuration for the bcrypt hasher.
BCryptConfig struct {
Cost uint32 `json:"cost"`
}
// BCryptConfigurator is the interface that must be implemented by a configuration provider for the bcrypt hasher.
BCryptConfigurator interface {
HasherBcryptConfig(ctx context.Context) *BCryptConfig
}
)
func NewHasherBcrypt(c BCryptConfigurator) *Bcrypt {
return &Bcrypt{c: c}
}
// Generate generates a hash for the given password.
func (h *Bcrypt) Generate(ctx context.Context, password []byte) (hash []byte, err error) {
ctx, span := otel.GetTracerProvider().Tracer(tracingComponent).Start(ctx, "hash.Bcrypt.Generate")
defer otelx.End(span, &err)
if err := validateBcryptPasswordLength(password); err != nil {
return nil, err
}
cost := int(h.c.HasherBcryptConfig(ctx).Cost)
span.SetAttributes(attribute.Int("bcrypt.cost", cost))
hash, err = bcrypt.GenerateFromPassword(password, cost)
if err != nil {
return nil, err
}
return hash, nil
}
func validateBcryptPasswordLength(password []byte) error {
// Bcrypt truncates the password to the first 72 bytes, following the OpenBSD implementation,
// so if password is longer than 72 bytes, function returns an error
// See https://en.wikipedia.org/wiki/Bcrypt#User_input
if len(password) > 72 {
return ErrBcryptPasswordLengthReached
}
return nil
}
// Understands checks if the given hash is in the correct format.
func (h *Bcrypt) Understands(hash []byte) bool {
return IsBcryptHash(hash)
}

View File

@@ -0,0 +1,103 @@
package hasherx
import (
"bytes"
"context"
"crypto/rand"
"crypto/sha1" // #nosec G505 - compatibility for imported passwords
"crypto/sha256"
"crypto/sha512"
"encoding/base64"
"fmt"
"hash"
"github.com/pkg/errors"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/codes"
"golang.org/x/crypto/pbkdf2"
"golang.org/x/crypto/sha3"
"github.com/ory/x/otelx"
)
type (
// PBKDF2 is a PBKDF2 hasher.
PBKDF2 struct {
c PBKDF2Configurator
}
// PBKDF2Config is the configuration for a PBKDF2 hasher.
PBKDF2Config struct {
// Algorithm can be one of sha1, sha224, sha256, sha384, sha512
Algorithm string
// Iterations is the number of iterations to use.
Iterations uint32
// KeyLength is the length of the salt.
SaltLength uint32
// KeyLength is the length of the key.
KeyLength uint32
}
// PBKDF2Configurator is a configurator for a PBKDF2 hasher.
PBKDF2Configurator interface {
HasherPBKDF2Config(ctx context.Context) *PBKDF2Config
}
)
// NewHasherPBKDF2 creates a new PBKDF2 hasher.
func NewHasherPBKDF2(c PBKDF2Configurator) *PBKDF2 {
return &PBKDF2{c: c}
}
// Generate generates a hash for the given password.
func (h *PBKDF2) Generate(ctx context.Context, password []byte) (hash []byte, err error) {
ctx, span := otel.GetTracerProvider().Tracer("").Start(ctx, "hash.PBKDF2.Generate")
defer otelx.End(span, &err)
conf := h.c.HasherPBKDF2Config(ctx)
salt := make([]byte, conf.SaltLength)
if _, err := rand.Read(salt); err != nil {
return nil, err
}
key := pbkdf2.Key(password, salt, int(conf.Iterations), int(conf.KeyLength), getPseudorandomFunctionForPbkdf2(conf.Algorithm))
var b bytes.Buffer
if _, err := fmt.Fprintf(
&b,
"$pbkdf2-%s$i=%d,l=%d$%s$%s",
conf.Algorithm,
conf.Iterations,
conf.KeyLength,
base64.RawStdEncoding.EncodeToString(salt),
base64.RawStdEncoding.EncodeToString(key),
); err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
return nil, errors.WithStack(err)
}
return b.Bytes(), nil
}
// Understands checks if the given hash is in the correct format.
func (h *PBKDF2) Understands(hash []byte) bool {
return IsPbkdf2Hash(hash)
}
func getPseudorandomFunctionForPbkdf2(alg string) func() hash.Hash {
switch alg {
case "sha1":
return sha1.New
case "sha224":
return sha3.New224
case "sha256":
return sha256.New
case "sha384":
return sha3.New384
case "sha512":
return sha512.New
default:
return sha256.New
}
}