Description
math/rand is designed for uses such as statistical sampling. It provides no guarantee that session IDs or reset tokens will be unpredictable.
Potential impact
Predictable reset codes, verification codes or session IDs may give someone access to an account. Predictable cryptographic parameters can also weaken confidentiality or integrity where the algorithm requires unpredictability.
Remediation
- Generate security-sensitive values in a shared function using
crypto/rand. Use enough random bytes for the token and check its encoded length. Follow the algorithm’s length and uniqueness requirements for IVs and nonces. - Validate reset tokens on the server. Enforce expiry, single use and attempt limits. Protect stored tokens and keep their values out of logs.
Examples
Since Go 1.24 the package-level math/rand.Seed does nothing by default. The time seed in this example takes effect under the older behavior. fmt.Println is for demonstration.
Before
go
package main
import (
"fmt"
mrand "math/rand"
"time"
)
// Weak reset-token generation using math/rand
func generateResetTokenWeak() string {
// Legacy behavior: guessable time seed (a no-op by default since Go 1.24)
mrand.Seed(time.Now().UnixNano())
letters := []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
b := make([]rune, 16) // 16-character token
for i := range b {
b[i] = letters[mrand.Intn(len(letters))]
}
return string(b)
}
func main() {
token := generateResetTokenWeak()
fmt.Println("reset token:", token)
}
After
go
package main
import (
"crypto/rand"
"encoding/hex"
"fmt"
)
// Reset-token generation using crypto/rand
func generateResetTokenSecure() (string, error) {
// 16 random bytes (128 bits) become 32 hexadecimal characters
b := make([]byte, 16)
// crypto/rand.Read generates cryptographically secure random bytes
if _, err := rand.Read(b); err != nil {
return "", err
}
// Represent the bytes as a hexadecimal string
return hex.EncodeToString(b), nil
}
func main() {
token, err := generateResetTokenSecure()
if err != nil {
panic(err)
}
fmt.Println("reset token:", token)
}
crypto/rand generates 16 random bytes, displayed as 32 hexadecimal characters. The encoded token still has 128 bits of randomness.