44package dependency
55
66import (
7+ "crypto/rand"
78 "encoding/json"
89 "fmt"
910 "log"
10- "math/rand "
11+ "math/big "
1112 "sync"
1213 "time"
1314
@@ -185,15 +186,16 @@ func leaseCheckWait(s *Secret, retryCount int) time.Duration {
185186 sleep = sleep / 3.0
186187
187188 // Use some randomness so many clients do not hit Vault simultaneously.
188- sleep = sleep * (rand .Float64 () + 1 ) / 2.0
189+ randVal := secureRandomFloat64 ()
190+ sleep = sleep * (randVal + 1 ) / 2.0
189191 } else if ! rotatingSecret {
190192 // If the secret doesn't have a rotation period, this is a non-renewable leased
191193 // secret.
192194 // For non-renewable leases set the renew duration to use much of the secret
193195 // lease as possible. Use a stagger over the configured threshold
194196 // fraction of the lease duration so that many clients do not hit
195197 // Vault simultaneously.
196- finalFraction := VaultLeaseRenewalThreshold + (rand . Float64 ()- 0.5 )* 0.1
198+ finalFraction := VaultLeaseRenewalThreshold + (secureRandomFloat64 ()- 0.5 )* 0.1
197199 if finalFraction >= 1.0 || finalFraction <= 0.0 {
198200 // If the fraction randomly winds up outside of (0.0-1.0), clamp
199201 // back down to the VaultLeaseRenewalThreshold provided by the user,
@@ -208,10 +210,26 @@ func leaseCheckWait(s *Secret, retryCount int) time.Duration {
208210 return time .Duration (sleep )
209211}
210212
213+ // secureRandomFloat64 returns a cryptographically secure random float64 in [0.0, 1.0)
214+ func secureRandomFloat64 () float64 {
215+ // Generate a random 53-bit integer (mantissa precision of float64)
216+ // Use crypto/rand for secure random generation (CWE-338 fix)
217+
218+ max := big .NewInt (1 << 53 )
219+ n , err := rand .Int (rand .Reader , max )
220+ if err != nil {
221+ // Fallback to 0.5 on error (middle of range)
222+ log .Printf ("[WARN] failed to generate secure random number: %v" , err )
223+ return 0.5
224+ }
225+ return float64 (n .Int64 ()) / float64 (max .Int64 ())
226+ }
227+
211228// jitter adds randomness to a duration to prevent thundering herd.
212229// It reduces the duration by up to maxJitter (10%) randomly.
213230func jitter (t time.Duration ) time.Duration {
214- f := float64 (t ) * (1.0 - maxJitter * rand .Float64 ())
231+ randVal := secureRandomFloat64 ()
232+ f := float64 (t ) * (1.0 - maxJitter * randVal )
215233 return time .Duration (f )
216234}
217235
0 commit comments