Restrict concurrent password hashes (#5437)

* internal/auth/password: add resizable pool

The resizable pool wraps the permit pool with a mutex
to allow it to be resized at runtime.

* internal/auth/password: add concurrency limit

The default concurrency limit is 1, and it can be
set using the SetHashingPermits function.

* internal/cmd/config: allow configuring hashing limits

The new concurrent_password_hash_workers configuration
value can be used to loosen the constraints on the
userpass auth method hashing operation.

* internal/cmd: set password hashing constraints

Sets the password hashing concurrency constraints on
startup and config reload.

* CHANGELOG: add notice about password concurrency limit
This commit is contained in:
Johan Brandhorst-Satzkorn authored and GitHub committed 2025-01-22 13:31:42 -08:00
1 parent aad833fe09
commit 40cb9f5c9e
11 files changed
+457 -10

No files matched your search

+29 -1
View File
@@ -17,6 +17,26 @@ import (
"google.golang.org/protobuf/proto"
)
// hashingPermitPool is the global permit pool used to restrict concurrent
// password hashing. It can be resized with SetHashingPermits.
var hashingPermitPool *resizablePermitPool
func init() {
hashingPermitPool = newResizablePermitPool(1)
}
// SetHashingPermits sets the number of concurrent password hashing operations permitted.
func SetHashingPermits(n int) error {
const op = "password.SetHashingPermits"
if n <= 0 {
return errors.New(context.Background(), errors.InvalidParameter, op, "n must be greater than 0")
}
if err := hashingPermitPool.SetPermits(n); err != nil {
return err
}
return nil
}
// Argon2Configuration is a configuration for using the argon2id key
// derivation function. It is owned by an AuthMethod.
//
@@ -163,7 +183,15 @@ func newArgon2Credential(ctx context.Context, accountId string, password string,
return nil, errors.Wrap(ctx, err, op, errors.WithCode(errors.Io))
}
c.Salt = salt
c.DerivedKey = argon2.IDKey([]byte(password), c.Salt, conf.Iterations, conf.Memory, uint8(conf.Threads), conf.KeyLength)
// Limit the number of concurrent calls to the argon2 hashing function,
// since each call consumes a significant amount of CPU and memory.
if err := hashingPermitPool.Do(ctx, func() {
c.DerivedKey = argon2.IDKey([]byte(password), c.Salt, conf.Iterations, conf.Memory, uint8(conf.Threads), conf.KeyLength)
}); err != nil {
// Context was canceled while waiting for a permit
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("context canceled while waiting for hashing permit"))
}
return c, nil
}
+96
View File
@@ -5,7 +5,12 @@ package password
import (
"context"
"runtime"
"slices"
"strconv"
"sync"
"testing"
"time"
"github.com/hashicorp/boundary/internal/auth/password/store"
"github.com/hashicorp/boundary/internal/db"
@@ -456,3 +461,94 @@ func TestArgon2Credential_New(t *testing.T) {
})
}
}
func TestArgon2Credential_ConcurrencyLimit(t *testing.T) {
// Do NOT run this concurrently with other tests in this package or elsewhere,
// since it relies on the global concurrency limit.
conn, _ := db.TestSetup(t, "postgres")
rootWrapper := db.TestWrapper(t)
o, _ := iam.TestScopes(t, iam.TestRepo(t, conn, rootWrapper))
auts := TestAuthMethods(t, conn, o.GetPublicId(), 1)
aut := auts[0]
accts := TestMultipleAccounts(t, conn, aut.PublicId, 5)
conf := testArgon2Confs(t, conn, accts[0].AuthMethodId, 1)[0]
testTimeout := time.Minute
testDeadline, ok := t.Deadline()
if ok && time.Until(testDeadline) < testTimeout {
// If the test deadline is less than the default timeout, use the deadline
testTimeout = time.Until(testDeadline)
}
deadlineCtx, deadlineCtxCancel := context.WithTimeout(context.Background(), testTimeout)
defer deadlineCtxCancel()
// Measure memory usage when using the default limit of 1
mean1, _, _ := measureCredentialCreations(deadlineCtx, t, accts[0].PublicId, conf)
// Now set the limit to 5 and measure again
require.NoError(t, SetHashingPermits(5))
t.Cleanup(func() {
require.NoError(t, SetHashingPermits(1))
})
mean5, _, _ := measureCredentialCreations(deadlineCtx, t, accts[0].PublicId, conf)
// Assert that we used less memory while the limit was in place
assert.Less(t, mean1, mean5)
}
func measureCredentialCreations(ctx context.Context, t testing.TB, publicId string, conf *Argon2Configuration) (mean float64, max, min uint64) {
wg := &sync.WaitGroup{}
start := make(chan struct{})
// Start 5 goroutines all trying to create a new credential concurrently
for i := range 5 {
wg.Add(1)
go func() {
defer wg.Done()
<-start
t.Log("Credential " + strconv.Itoa(i) + " starting")
_, err := newArgon2Credential(ctx, publicId, "password", conf)
assert.NoError(t, err)
t.Log("Credential " + strconv.Itoa(i) + " finished")
}()
}
doneDone := make(chan struct{})
go func() {
wg.Wait()
close(doneDone)
}()
// Start the goroutines
close(start)
var memStats runtime.MemStats
var measures []uint64
for {
select {
case <-ctx.Done():
t.Error("timeout")
return
case <-time.After(10 * time.Millisecond):
// Run GC and check memory use
runtime.GC()
runtime.ReadMemStats(&memStats)
measures = append(measures, memStats.HeapAlloc)
case <-doneDone:
// All credential creations done
return meanInt(measures), slices.Max(measures), slices.Min(measures)
}
}
}
func meanInt(in []uint64) float64 {
return sumInt(in) / float64(len(in))
}
func sumInt(in []uint64) float64 {
var sum float64
for _, n := range in {
sum += float64(n)
}
return sum
}
+59
View File
@@ -0,0 +1,59 @@
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: BUSL-1.1
package password
import (
"context"
"sync"
"github.com/hashicorp/boundary/internal/errors"
"github.com/hashicorp/go-secure-stdlib/permitpool"
)
// resizablePermitPool is a permit pool that can be resized at runtime.
type resizablePermitPool struct {
pool *permitpool.Pool
// lock is used to synchronize access to the permit pool
// This is an RWMutex to allow an unlimited number of readers
// and a single writer, since allowing a single reader or writer
// would effectively make the pool useless.
lock *sync.RWMutex
}
// newResizablePermitPool creates a new resizable permit pool with n permits.
func newResizablePermitPool(n int) *resizablePermitPool {
return &resizablePermitPool{
pool: permitpool.New(n),
lock: &sync.RWMutex{},
}
}
// SetPermit sets the number of permits available in the pool.
func (r *resizablePermitPool) SetPermits(n int) error {
const op = "resizablePermitPool.SetPermits"
if n <= 0 {
return errors.New(context.Background(), errors.InvalidParameter, op, "n must be greater than 0")
}
// Taking a write lock ensures there are no currently acquired permits
r.lock.Lock()
defer r.lock.Unlock()
r.pool = permitpool.New(n)
return nil
}
// Do executes the provided function with a permit acquired from the pool.
// If the context is canceled while waiting to acquire a permit, an error is returned.
func (r *resizablePermitPool) Do(ctx context.Context, fn func()) error {
const op = "resizablePermitPool.Do"
// We need to ensure both the Acquire and Release happen while the read lock is held,
// so that the pool cannot be resized in between.
r.lock.RLock()
defer r.lock.RUnlock()
if err := r.pool.Acquire(ctx); err != nil {
return errors.Wrap(ctx, err, op, errors.WithMsg("failed to acquire permit"))
}
defer r.pool.Release()
fn()
return nil
}
+53
View File
@@ -0,0 +1,53 @@
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: BUSL-1.1
package password
import (
"context"
"strconv"
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestPermitPool(t *testing.T) {
pool := newResizablePermitPool(1)
wg := &sync.WaitGroup{}
start := make(chan struct{})
ctx := context.Background()
// Start 5 goroutines all trying to acquire the permit at the same time
for i := range 5 {
wg.Add(1)
go func() {
defer wg.Done()
<-start
t.Log("Goroutine " + strconv.Itoa(i) + " starting")
err := pool.Do(ctx, func() {
// Do some expensive operation
time.Sleep(10 * time.Millisecond)
})
assert.NoError(t, err)
t.Log("Goroutine " + strconv.Itoa(i) + " finished")
}()
}
// Also start a few goroutines that attempt to resize the pool
for i := range 5 {
wg.Add(1)
go func() {
defer wg.Done()
<-start
t.Log("Resizing pool " + strconv.Itoa(i))
err := pool.SetPermits(2)
t.Log("Resized pool" + strconv.Itoa(i))
assert.NoError(t, err)
}()
}
close(start)
wg.Wait()
}