Skip to content

Commit 0b584b7

Browse files
committed
fixing CWE-338 Use of Cryptographically Secure Pseudo-Random Number
1 parent b0fc949 commit 0b584b7

File tree

1 file changed

+17
-5
lines changed

1 file changed

+17
-5
lines changed

dependency/vault_common.go

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,12 @@
44
package dependency
55

66
import (
7+
cryptorand "crypto/rand"
78
"encoding/json"
89
"fmt"
910
"log"
10-
"math/rand"
11+
"math/big"
12+
mathrand "math/rand"
1113
"sync"
1214
"time"
1315

@@ -185,15 +187,15 @@ func leaseCheckWait(s *Secret, retryCount int) time.Duration {
185187
sleep = sleep / 3.0
186188

187189
// Use some randomness so many clients do not hit Vault simultaneously.
188-
sleep = sleep * (rand.Float64() + 1) / 2.0
190+
sleep = sleep * (mathrand.Float64() + 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 + (mathrand.Float64()-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,
@@ -209,9 +211,19 @@ func leaseCheckWait(s *Secret, retryCount int) time.Duration {
209211
}
210212

211213
// jitter adds randomness to a duration to prevent thundering herd.
212-
// It reduces the duration by up to maxJitter (10%) randomly.
214+
// It reduces the duration by up to maxJitter (10%) randomly using crypto/rand.
215+
// using this to fix CWE-338: Use of Cryptographically Secure Pseudo-Random Number Generator (CSPRNG)
213216
func jitter(t time.Duration) time.Duration {
214-
f := float64(t) * (1.0 - maxJitter*rand.Float64())
217+
// Generate cryptographically secure random value between 0.0 and 1.0
218+
max := big.NewInt(1000000)
219+
n, err := cryptorand.Int(cryptorand.Reader, max)
220+
if err != nil {
221+
// Fallback to no jitter if crypto/rand fails
222+
log.Printf("[WARN] Failed to generate secure random jitter: %v", err)
223+
return t
224+
}
225+
randomFloat := float64(n.Int64()) / 1000000.0
226+
f := float64(t) * (1.0 - maxJitter*randomFloat)
215227
return time.Duration(f)
216228
}
217229

0 commit comments

Comments
 (0)