lab7: безопасность, mTLS, OpenBao и PKI lifecycle
This commit is contained in:
@@ -0,0 +1,197 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package password_test
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"mtusi-messenger/internal/platform/password"
|
||||
)
|
||||
|
||||
func TestHashVerifyRoundTrip(t *testing.T) {
|
||||
encoded, err := password.Hash("very-secret-password")
|
||||
require.NoError(t, err)
|
||||
verified, err := password.Verify("very-secret-password", encoded)
|
||||
require.NoError(t, err)
|
||||
require.True(t, verified.Match)
|
||||
require.False(t, verified.NeedsRehash)
|
||||
verified, err = password.Verify("wrong-password-value", encoded)
|
||||
require.NoError(t, err)
|
||||
require.False(t, verified.Match)
|
||||
require.False(t, verified.NeedsRehash)
|
||||
}
|
||||
|
||||
func TestHashIsSalted(t *testing.T) {
|
||||
first, err := password.Hash("very-secret-password")
|
||||
require.NoError(t, err)
|
||||
|
||||
second, err := password.Hash("very-secret-password")
|
||||
require.NoError(t, err)
|
||||
|
||||
require.NotEqual(t, first, second)
|
||||
}
|
||||
|
||||
func TestVerifyRejectsMalformedHash(t *testing.T) {
|
||||
for _, encoded := range []string{"", "plain-text", strings.Repeat("x", 64)} {
|
||||
verified, err := password.Verify("very-secret-password", encoded)
|
||||
require.NoError(t, err)
|
||||
require.False(t, verified.Match)
|
||||
require.False(t, verified.NeedsRehash)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package password
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
func TestVerifyRejectsMalformedAndCostlyPHCBeforeDerivation(t *testing.T) {
|
||||
salt := base64.RawStdEncoding.EncodeToString(make([]byte, argonSaltLen))
|
||||
hash := base64.RawStdEncoding.EncodeToString(make([]byte, argonKeyLen))
|
||||
prefix := "$argon2id$v=19$"
|
||||
suffix := "$" + salt + "$" + hash
|
||||
invalid := []string{
|
||||
strings.Repeat("x", 513),
|
||||
prefix + "m=65537,t=2,p=1" + suffix,
|
||||
prefix + "m=19456,t=5,p=1" + suffix,
|
||||
prefix + "m=19456,t=2,p=5" + suffix,
|
||||
prefix + "m=7,t=2,p=1" + suffix,
|
||||
prefix + "m=31,t=2,p=4" + suffix,
|
||||
prefix + "m=0,t=2,p=1" + suffix,
|
||||
prefix + "m=19456,t=0,p=1" + suffix,
|
||||
prefix + "m=19456,t=2,p=0" + suffix,
|
||||
prefix + "m=-1,t=2,p=1" + suffix,
|
||||
prefix + "m=+19456,t=2,p=1" + suffix,
|
||||
prefix + "m=019456,t=2,p=1" + suffix,
|
||||
prefix + "m=4294967296,t=2,p=1" + suffix,
|
||||
prefix + "m=19456,t=2,p=1,x=1" + suffix,
|
||||
prefix + "m=19456,t=2,t=1" + suffix,
|
||||
"$argon2id$v=16$m=19456,t=2,p=1" + suffix,
|
||||
prefix + "m=19456,t=2,p=1$" + salt + "$" + hash[:42] + "!",
|
||||
prefix + "m=19456,t=2,p=1$" + salt + "=$" + hash,
|
||||
"argon2id$" + salt + "$" + hash + "$extra",
|
||||
}
|
||||
// Exhausting the budget proves these inputs never reach Argon2: a valid
|
||||
// encoding returns ErrBusy here, while malformed encodings are denied.
|
||||
require.True(t, acquire())
|
||||
defer release()
|
||||
require.True(t, acquire())
|
||||
defer release()
|
||||
for _, encoded := range invalid {
|
||||
got, err := Verify("password", encoded)
|
||||
require.NoError(t, err)
|
||||
require.False(t, got.Match)
|
||||
require.False(t, got.NeedsRehash)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDerivationBudgetIsNonblockingAndShared(t *testing.T) {
|
||||
encoded, err := Hash("secret-password")
|
||||
require.NoError(t, err)
|
||||
require.True(t, acquire())
|
||||
defer release()
|
||||
require.True(t, acquire())
|
||||
defer release()
|
||||
require.False(t, acquire())
|
||||
_, err = Hash("secret-password")
|
||||
require.ErrorIs(t, err, ErrBusy)
|
||||
_, err = Verify("secret-password", encoded)
|
||||
require.ErrorIs(t, err, ErrBusy)
|
||||
}
|
||||
|
||||
func TestLegacyAndObsoletePHCRequireOnlySuccessfulRehash(t *testing.T) {
|
||||
var salt [argonSaltLen]byte
|
||||
legacy := argon2.IDKey([]byte("secret-password"), salt[:], 1, 64*1024, 4, argonKeyLen)
|
||||
legacyEncoded := "argon2id$" + base64.RawStdEncoding.EncodeToString(salt[:]) + "$" +
|
||||
base64.RawStdEncoding.EncodeToString(legacy)
|
||||
obsolete := argon2.IDKey([]byte("secret-password"), salt[:], 1, 32, 1, argonKeyLen)
|
||||
obsoleteEncoded := "$argon2id$v=19$m=32,t=1,p=1$" + base64.RawStdEncoding.EncodeToString(salt[:]) + "$" +
|
||||
base64.RawStdEncoding.EncodeToString(obsolete)
|
||||
for _, encoded := range []string{legacyEncoded, obsoleteEncoded} {
|
||||
got, err := Verify("wrong-password", encoded)
|
||||
require.NoError(t, err)
|
||||
require.False(t, got.Match)
|
||||
require.False(t, got.NeedsRehash)
|
||||
got, err = Verify("secret-password", encoded)
|
||||
require.NoError(t, err)
|
||||
require.True(t, got.Match)
|
||||
require.True(t, got.NeedsRehash)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user