This commit is contained in:
@@ -0,0 +1,43 @@
|
||||
package security
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ClientMTLSConfig builds a TLS 1.3 client configuration with an explicit
|
||||
// workload certificate. The service name is verified against the server
|
||||
// certificate; neither InsecureSkipVerify nor the host trust store is used.
|
||||
func ClientMTLSConfig(caFile, certFile, keyFile, serverName string) (*tls.Config, error) {
|
||||
caFile = strings.TrimSpace(caFile)
|
||||
certFile = strings.TrimSpace(certFile)
|
||||
keyFile = strings.TrimSpace(keyFile)
|
||||
serverName = strings.TrimSpace(serverName)
|
||||
if caFile == "" || certFile == "" || keyFile == "" || serverName == "" {
|
||||
return nil, errors.New("client CA, certificate, key, and server name are required")
|
||||
}
|
||||
|
||||
caPEM, err := os.ReadFile(caFile)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read client TLS CA: %w", err)
|
||||
}
|
||||
roots := x509.NewCertPool()
|
||||
if !roots.AppendCertsFromPEM(caPEM) {
|
||||
return nil, errors.New("client TLS CA file contains no certificate")
|
||||
}
|
||||
certificate, err := tls.LoadX509KeyPair(certFile, keyFile)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("load client TLS identity: %w", err)
|
||||
}
|
||||
|
||||
return &tls.Config{
|
||||
MinVersion: tls.VersionTLS13,
|
||||
RootCAs: roots,
|
||||
Certificates: []tls.Certificate{certificate},
|
||||
ServerName: serverName,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package security
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func ServerMTLSConfig(clientCAFile string, allowedClientURI string, allowedClientURIFile string) (*tls.Config, error) {
|
||||
clientCAFile = strings.TrimSpace(clientCAFile)
|
||||
allowedClientURI = strings.TrimSpace(allowedClientURI)
|
||||
allowedClientURIFile = strings.TrimSpace(allowedClientURIFile)
|
||||
if clientCAFile == "" || (allowedClientURI == "" && allowedClientURIFile == "") {
|
||||
return nil, errors.New("TLS_CLIENT_CA_FILE and an allowed client URI source are required")
|
||||
}
|
||||
allowedClientURIs := make(map[string]struct{})
|
||||
if allowedClientURI != "" {
|
||||
allowedClientURIs[allowedClientURI] = struct{}{}
|
||||
}
|
||||
if allowedClientURIFile != "" {
|
||||
allowedPEM, readErr := os.ReadFile(allowedClientURIFile)
|
||||
if readErr != nil {
|
||||
return nil, fmt.Errorf("read allowed client URI file: %w", readErr)
|
||||
}
|
||||
for _, line := range strings.Split(string(allowedPEM), "\n") {
|
||||
line = strings.TrimSpace(line)
|
||||
if line != "" && !strings.HasPrefix(line, "#") {
|
||||
allowedClientURIs[line] = struct{}{}
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(allowedClientURIs) == 0 {
|
||||
return nil, errors.New("allowed client URI set is empty")
|
||||
}
|
||||
caPEM, err := os.ReadFile(clientCAFile)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read client CA: %w", err)
|
||||
}
|
||||
clientRoots := x509.NewCertPool()
|
||||
if !clientRoots.AppendCertsFromPEM(caPEM) {
|
||||
return nil, errors.New("client CA file contains no certificate")
|
||||
}
|
||||
return &tls.Config{
|
||||
MinVersion: tls.VersionTLS13,
|
||||
ClientAuth: tls.RequireAndVerifyClientCert,
|
||||
ClientCAs: clientRoots,
|
||||
NextProtos: []string{"h2", "http/1.1"},
|
||||
VerifyConnection: func(state tls.ConnectionState) error {
|
||||
if len(state.VerifiedChains) == 0 || len(state.PeerCertificates) == 0 {
|
||||
return errors.New("verified client certificate is required")
|
||||
}
|
||||
leaf := state.PeerCertificates[0]
|
||||
for _, identity := range leaf.URIs {
|
||||
if _, allowed := allowedClientURIs[identity.String()]; allowed {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("client certificate URI SAN is not allowed")
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
package security
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultArgonMemory uint32 = 19 * 1024
|
||||
defaultArgonIterations uint32 = 2
|
||||
defaultArgonParallelism uint8 = 1
|
||||
argonSaltLength = 16
|
||||
argonKeyLength uint32 = 32
|
||||
|
||||
minPasswordLength = 12
|
||||
maxPasswordLength = 128
|
||||
)
|
||||
|
||||
var ErrInvalidPasswordHash = errors.New("invalid password hash")
|
||||
|
||||
func ValidatePassword(password string) error {
|
||||
if !utf8.ValidString(password) {
|
||||
return errors.New("password must be valid UTF-8")
|
||||
}
|
||||
|
||||
length := utf8.RuneCountInString(password)
|
||||
if length < minPasswordLength || length > maxPasswordLength {
|
||||
return fmt.Errorf(
|
||||
"password length must be between %d and %d code points",
|
||||
minPasswordLength,
|
||||
maxPasswordLength,
|
||||
)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func HashPassword(password string) (string, error) {
|
||||
if err := ValidatePassword(password); err != nil {
|
||||
return "", err
|
||||
}
|
||||
parameters, err := passwordParametersFromEnvironment()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
salt := make([]byte, argonSaltLength)
|
||||
if _, err = rand.Read(salt); err != nil {
|
||||
return "", fmt.Errorf("generate password salt: %w", err)
|
||||
}
|
||||
|
||||
hash := argon2.IDKey(
|
||||
[]byte(password),
|
||||
salt,
|
||||
parameters.iterations,
|
||||
parameters.memory,
|
||||
parameters.parallelism,
|
||||
argonKeyLength,
|
||||
)
|
||||
|
||||
encodedSalt := base64.RawStdEncoding.EncodeToString(salt)
|
||||
encodedHash := base64.RawStdEncoding.EncodeToString(hash)
|
||||
|
||||
encoded := fmt.Sprintf(
|
||||
"$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
|
||||
argon2.Version,
|
||||
parameters.memory,
|
||||
parameters.iterations,
|
||||
parameters.parallelism,
|
||||
encodedSalt,
|
||||
encodedHash,
|
||||
)
|
||||
|
||||
return encoded, nil
|
||||
}
|
||||
|
||||
func VerifyPassword(
|
||||
password string,
|
||||
encodedHash string,
|
||||
) (bool, error) {
|
||||
parameters, salt, expectedHash, err := decodePasswordHash(encodedHash)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
actualHash := argon2.IDKey(
|
||||
[]byte(password),
|
||||
salt,
|
||||
parameters.iterations,
|
||||
parameters.memory,
|
||||
parameters.parallelism,
|
||||
uint32(len(expectedHash)),
|
||||
)
|
||||
|
||||
matches := subtle.ConstantTimeCompare(
|
||||
actualHash,
|
||||
expectedHash,
|
||||
) == 1
|
||||
|
||||
return matches, nil
|
||||
}
|
||||
|
||||
// NeedsPasswordRehash reports whether a verified stored hash must be upgraded
|
||||
// to the active Argon2id policy. Callers must verify the password first.
|
||||
func NeedsPasswordRehash(encodedHash string) (bool, error) {
|
||||
stored, salt, hash, err := decodePasswordHash(encodedHash)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
active, err := passwordParametersFromEnvironment()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return stored != active || len(salt) != argonSaltLength || uint32(len(hash)) != argonKeyLength, nil
|
||||
}
|
||||
|
||||
type argonParameters struct {
|
||||
memory uint32
|
||||
iterations uint32
|
||||
parallelism uint8
|
||||
}
|
||||
|
||||
func passwordParametersFromEnvironment() (argonParameters, error) {
|
||||
memory, err := boundedUint32Environment(
|
||||
"ARGON2_MEMORY_KIB", defaultArgonMemory, defaultArgonMemory, 256*1024,
|
||||
)
|
||||
if err != nil {
|
||||
return argonParameters{}, err
|
||||
}
|
||||
iterations, err := boundedUint32Environment(
|
||||
"ARGON2_ITERATIONS", defaultArgonIterations, defaultArgonIterations, 10,
|
||||
)
|
||||
if err != nil {
|
||||
return argonParameters{}, err
|
||||
}
|
||||
parallelism, err := boundedUint32Environment(
|
||||
"ARGON2_PARALLELISM", uint32(defaultArgonParallelism), 1, 8,
|
||||
)
|
||||
if err != nil {
|
||||
return argonParameters{}, err
|
||||
}
|
||||
return argonParameters{
|
||||
memory: memory, iterations: iterations, parallelism: uint8(parallelism),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func boundedUint32Environment(
|
||||
name string,
|
||||
fallback uint32,
|
||||
minimum uint32,
|
||||
maximum uint32,
|
||||
) (uint32, error) {
|
||||
raw := strings.TrimSpace(os.Getenv(name))
|
||||
if raw == "" {
|
||||
return fallback, nil
|
||||
}
|
||||
value, err := strconv.ParseUint(raw, 10, 32)
|
||||
if err != nil || value < uint64(minimum) || value > uint64(maximum) {
|
||||
return 0, fmt.Errorf("%s must be an integer from %d to %d", name, minimum, maximum)
|
||||
}
|
||||
return uint32(value), nil
|
||||
}
|
||||
|
||||
func decodePasswordHash(
|
||||
encodedHash string,
|
||||
) (argonParameters, []byte, []byte, error) {
|
||||
parts := strings.Split(encodedHash, "$")
|
||||
if len(parts) != 6 ||
|
||||
parts[0] != "" ||
|
||||
parts[1] != "argon2id" {
|
||||
return argonParameters{}, nil, nil, ErrInvalidPasswordHash
|
||||
}
|
||||
|
||||
var version int
|
||||
if _, err := fmt.Sscanf(parts[2], "v=%d", &version); err != nil {
|
||||
return argonParameters{}, nil, nil, ErrInvalidPasswordHash
|
||||
}
|
||||
|
||||
if version != argon2.Version {
|
||||
return argonParameters{}, nil, nil, ErrInvalidPasswordHash
|
||||
}
|
||||
|
||||
var parameters argonParameters
|
||||
if _, err := fmt.Sscanf(
|
||||
parts[3],
|
||||
"m=%d,t=%d,p=%d",
|
||||
¶meters.memory,
|
||||
¶meters.iterations,
|
||||
¶meters.parallelism,
|
||||
); err != nil {
|
||||
return argonParameters{}, nil, nil, ErrInvalidPasswordHash
|
||||
}
|
||||
|
||||
// Ограничения не позволяют повреждённой строке из БД запросить
|
||||
// гигантский объём памяти или процессорного времени.
|
||||
if parameters.memory < 8*1024 ||
|
||||
parameters.memory > 256*1024 ||
|
||||
parameters.iterations < 1 ||
|
||||
parameters.iterations > 10 ||
|
||||
parameters.parallelism < 1 ||
|
||||
parameters.parallelism > 8 {
|
||||
return argonParameters{}, nil, nil, ErrInvalidPasswordHash
|
||||
}
|
||||
|
||||
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
|
||||
if err != nil || len(salt) < 16 || len(salt) > 64 {
|
||||
return argonParameters{}, nil, nil, ErrInvalidPasswordHash
|
||||
}
|
||||
|
||||
hash, err := base64.RawStdEncoding.DecodeString(parts[5])
|
||||
if err != nil || len(hash) < 16 || len(hash) > 64 {
|
||||
return argonParameters{}, nil, nil, ErrInvalidPasswordHash
|
||||
}
|
||||
|
||||
return parameters, salt, hash, nil
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
package security
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func BenchmarkHashPasswordGrade3(b *testing.B) {
|
||||
const password = "benchmark-password-123"
|
||||
for index := 0; index < b.N; index++ {
|
||||
if _, err := HashPassword(password); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkVerifyPasswordGrade4(b *testing.B) {
|
||||
const password = "benchmark-password-123"
|
||||
encodedHash, err := HashPassword(password)
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
b.ResetTimer()
|
||||
for index := 0; index < b.N; index++ {
|
||||
matches, verifyErr := VerifyPassword(password, encodedHash)
|
||||
if verifyErr != nil || !matches {
|
||||
b.Fatalf("verify failed: matches=%v err=%v", matches, verifyErr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHashPasswordRejectsWeakConfiguredCost(t *testing.T) {
|
||||
t.Setenv("ARGON2_MEMORY_KIB", "8192")
|
||||
if _, err := HashPassword("valid-password-123"); err == nil {
|
||||
t.Fatal("HashPassword accepted memory below the lab7 minimum")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPasswordHashAndVerify(t *testing.T) {
|
||||
password := "Correct-password-123"
|
||||
|
||||
encodedHash, err := HashPassword(password)
|
||||
if err != nil {
|
||||
t.Fatalf("HashPassword returned error: %v", err)
|
||||
}
|
||||
|
||||
if strings.Contains(encodedHash, password) {
|
||||
t.Fatal("encoded hash contains plaintext password")
|
||||
}
|
||||
|
||||
matches, err := VerifyPassword(password, encodedHash)
|
||||
if err != nil {
|
||||
t.Fatalf("VerifyPassword returned error: %v", err)
|
||||
}
|
||||
if !matches {
|
||||
t.Fatal("correct password did not match")
|
||||
}
|
||||
|
||||
matches, err = VerifyPassword("Wrong-password-123", encodedHash)
|
||||
if err != nil {
|
||||
t.Fatalf("VerifyPassword returned error: %v", err)
|
||||
}
|
||||
if matches {
|
||||
t.Fatal("wrong password matched")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPasswordHashesUseDifferentSalts(t *testing.T) {
|
||||
password := "Correct-password-123"
|
||||
|
||||
firstHash, err := HashPassword(password)
|
||||
if err != nil {
|
||||
t.Fatalf("first HashPassword returned error: %v", err)
|
||||
}
|
||||
|
||||
secondHash, err := HashPassword(password)
|
||||
if err != nil {
|
||||
t.Fatalf("second HashPassword returned error: %v", err)
|
||||
}
|
||||
|
||||
if firstHash == secondHash {
|
||||
t.Fatal("equal passwords produced equal encoded hashes")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPasswordValidation(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
password string
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "minimum length",
|
||||
password: "123456789012",
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "unicode",
|
||||
password: "пароль-проверка-123",
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "colon is allowed",
|
||||
password: "password:with:colon",
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "too short",
|
||||
password: "short",
|
||||
wantErr: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
err := ValidatePassword(testCase.password)
|
||||
|
||||
if testCase.wantErr && err == nil {
|
||||
t.Fatal("expected validation error")
|
||||
}
|
||||
if !testCase.wantErr && err != nil {
|
||||
t.Fatalf("unexpected validation error: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMalformedPasswordHash(t *testing.T) {
|
||||
_, err := VerifyPassword(
|
||||
"Correct-password-123",
|
||||
"not-an-argon2-hash",
|
||||
)
|
||||
if err == nil {
|
||||
t.Fatal("expected malformed hash error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNeedsPasswordRehash(t *testing.T) {
|
||||
currentHash, err := HashPassword("Correct-password-123")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
needsRehash, err := NeedsPasswordRehash(currentHash)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if needsRehash {
|
||||
t.Fatal("current policy hash unexpectedly requires rehash")
|
||||
}
|
||||
|
||||
legacyHash := strings.Replace(currentHash, "m=19456,t=2,p=1", "m=8192,t=2,p=1", 1)
|
||||
needsRehash, err = NeedsPasswordRehash(legacyHash)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !needsRehash {
|
||||
t.Fatal("legacy policy hash was not marked for rehash")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package security
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
const sessionTokenBytes = 32
|
||||
|
||||
func GenerateSessionToken() (string, []byte, error) {
|
||||
randomBytes := make([]byte, sessionTokenBytes)
|
||||
|
||||
if _, err := rand.Read(randomBytes); err != nil {
|
||||
return "", nil, fmt.Errorf("generate session token: %w", err)
|
||||
}
|
||||
|
||||
token := base64.RawURLEncoding.EncodeToString(randomBytes)
|
||||
tokenHash := HashSessionToken(token)
|
||||
|
||||
return token, tokenHash, nil
|
||||
}
|
||||
|
||||
func HashSessionToken(token string) []byte {
|
||||
digest := sha256.Sum256([]byte(token))
|
||||
|
||||
hash := make([]byte, len(digest))
|
||||
copy(hash, digest[:])
|
||||
|
||||
return hash
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package security
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestGenerateSessionToken(t *testing.T) {
|
||||
firstToken, firstHash, err := GenerateSessionToken()
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateSessionToken returned error: %v", err)
|
||||
}
|
||||
|
||||
secondToken, secondHash, err := GenerateSessionToken()
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateSessionToken returned error: %v", err)
|
||||
}
|
||||
|
||||
if firstToken == secondToken {
|
||||
t.Fatal("generated session tokens are equal")
|
||||
}
|
||||
|
||||
if bytes.Equal(firstHash, secondHash) {
|
||||
t.Fatal("generated session token hashes are equal")
|
||||
}
|
||||
|
||||
if len(firstHash) != 32 {
|
||||
t.Fatalf("expected 32-byte token hash, got %d", len(firstHash))
|
||||
}
|
||||
|
||||
recalculatedHash := HashSessionToken(firstToken)
|
||||
if !bytes.Equal(firstHash, recalculatedHash) {
|
||||
t.Fatal("token hash is not reproducible")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user