From 2e1a9c61b84ef8abb7573bc4017c77806ffd9025 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sybren=20A=2E=20St=C3=BCvel?= Date: Fri, 15 Jul 2022 13:58:27 +0200 Subject: [PATCH] Manager: add SHA256 password hasher for worker auth Add a SHA256 password hasher for worker authentication. It's not used at the moment, but can be switched to for faster API queries. Note that switching will cause authentication errors on already-existing workers, which means they'll automatically re-register. This is mostly useful for debugging & profiling purposes. --- internal/manager/api_impl/worker_auth.go | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/internal/manager/api_impl/worker_auth.go b/internal/manager/api_impl/worker_auth.go index a5c2e9b7..c7d8beb6 100644 --- a/internal/manager/api_impl/worker_auth.go +++ b/internal/manager/api_impl/worker_auth.go @@ -4,6 +4,8 @@ package api_impl import ( "context" + "crypto/sha256" + "crypto/subtle" "errors" oapi_middle "github.com/deepmap/oapi-codegen/pkg/middleware" @@ -23,7 +25,7 @@ const ( var ( errAuthBad = errors.New("no such worker known") - passwordHasher = BCryptHasher{} + passwordHasher WorkerPasswordHasher = BCryptHasher{} ) type WorkerPasswordHasher interface { @@ -44,6 +46,22 @@ func (h BCryptHasher) CompareHashAndPassword(hashedPassword, password []byte) er return bcrypt.CompareHashAndPassword(hashedPassword, password) } +type SHA256Hasher struct{} + +func (h SHA256Hasher) hash(password []byte) []byte { + hasher := sha256.New() + return hasher.Sum(password) +} +func (h SHA256Hasher) GenerateHashedPassword(password []byte) ([]byte, error) { + return h.hash(password), nil +} +func (h SHA256Hasher) CompareHashAndPassword(hashedPassword, password []byte) error { + if subtle.ConstantTimeCompare(hashedPassword, h.hash(password)) != 1 { + return bcrypt.ErrMismatchedHashAndPassword + } + return nil +} + // OpenAPI authentication function for authing workers. // The worker will be fetched from the database and stored in the request context. func WorkerAuth(ctx context.Context, authInfo *openapi3filter.AuthenticationInput, persist PersistenceService) error {