Use cryptographically secure password generation (#854)

The current password generation algorithm is extremely deterministic, due to being based on the standard random number generator with a deterministic seed based on the current Unix timestamp (in seconds).

This can lead to a number of security issues, including:

The same passwords being used in different Kubernetes clusters if the operator is deployed in parallel. (This issue was discovered because of four deployments having the same generated passwords due to automatically being deployed in parallel.)
The passwords being easily guessable based on the time the operator pod started when the database was created. (This would typically be present in logs, metrics, etc., that may typically be accessible to more people than should have database access.)
Fix this issue by replacing the current randomness source with crypto/rand, which should produce cryptographically secure random data that is virtually unguessable. This will avoid both of the above problems as each deployment will be guaranteed to have unique, indeterministic passwords.
This commit is contained in:
Fredrik Østrem 2020-03-18 10:28:39 +01:00 committed by GitHub
parent cf829df1a4
commit 9ddee8f302
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 9 additions and 3 deletions

View File

@ -2,8 +2,10 @@ package util
import ( import (
"crypto/md5" // #nosec we need it to for PostgreSQL md5 passwords "crypto/md5" // #nosec we need it to for PostgreSQL md5 passwords
cryptoRand "crypto/rand"
"encoding/hex" "encoding/hex"
"fmt" "fmt"
"math/big"
"math/rand" "math/rand"
"regexp" "regexp"
"strings" "strings"
@ -37,13 +39,17 @@ func False() *bool {
return &b return &b
} }
// RandomPassword generates random alphanumeric password of a given length. // RandomPassword generates a secure, random alphanumeric password of a given length.
func RandomPassword(n int) string { func RandomPassword(n int) string {
b := make([]byte, n) b := make([]byte, n)
for i := range b { for i := range b {
b[i] = passwordChars[rand.Intn(len(passwordChars))] maxN := big.NewInt(int64(len(passwordChars)))
if n, err := cryptoRand.Int(cryptoRand.Reader, maxN); err != nil {
panic(fmt.Errorf("Unable to generate secure, random password: %v", err))
} else {
b[i] = passwordChars[n.Int64()]
}
} }
return string(b) return string(b)
} }