fix go check issues

G404: Replace math rand with crypto rand

Signed-off-by: Wang Yan <wangyan@vmware.com>
This commit is contained in:
Wang Yan 2021-11-16 17:35:06 +08:00
parent 691e62e7ef
commit 9a3ff11330
2 changed files with 21 additions and 7 deletions

View file

@ -2,9 +2,10 @@ package main
import ( import (
"context" "context"
"crypto/rand"
"encoding/json" "encoding/json"
"flag" "flag"
"math/rand" "math/big"
"net/http" "net/http"
"strconv" "strconv"
"strings" "strings"
@ -141,8 +142,15 @@ const refreshTokenLength = 15
func newRefreshToken() string { func newRefreshToken() string {
s := make([]rune, refreshTokenLength) s := make([]rune, refreshTokenLength)
max := int64(len(refreshCharacters))
for i := range s { for i := range s {
s[i] = refreshCharacters[rand.Intn(len(refreshCharacters))] randInt, err := rand.Int(rand.Reader, big.NewInt(max))
// let '0' serves the failure case
if err != nil {
logrus.Infof("Error on making refersh token: %v", err)
randInt = big.NewInt(0)
}
s[i] = refreshCharacters[randInt.Int64()]
} }
return string(s) return string(s)
} }

View file

@ -2,10 +2,11 @@ package handlers
import ( import (
"context" "context"
cryptorand "crypto/rand" "crypto/rand"
"expvar" "expvar"
"fmt" "fmt"
"math/rand" "math"
"math/big"
"net" "net"
"net/http" "net/http"
"net/url" "net/url"
@ -610,7 +611,7 @@ func (app *App) configureLogHook(configuration *configuration.Configuration) {
func (app *App) configureSecret(configuration *configuration.Configuration) { func (app *App) configureSecret(configuration *configuration.Configuration) {
if configuration.HTTP.Secret == "" { if configuration.HTTP.Secret == "" {
var secretBytes [randomSecretSize]byte var secretBytes [randomSecretSize]byte
if _, err := cryptorand.Read(secretBytes[:]); err != nil { if _, err := rand.Read(secretBytes[:]); err != nil {
panic(fmt.Sprintf("could not generate random bytes for HTTP secret: %v", err)) panic(fmt.Sprintf("could not generate random bytes for HTTP secret: %v", err))
} }
configuration.HTTP.Secret = string(secretBytes[:]) configuration.HTTP.Secret = string(secretBytes[:])
@ -1060,8 +1061,13 @@ func startUploadPurger(ctx context.Context, storageDriver storagedriver.StorageD
} }
go func() { go func() {
rand.Seed(time.Now().Unix()) randInt, err := rand.Int(rand.Reader, new(big.Int).SetInt64(math.MaxInt64))
jitter := time.Duration(rand.Int()%60) * time.Minute if err != nil {
log.Infof("Failed to generate random jitter: %v", err)
// sleep 30min for failure case
randInt = big.NewInt(30)
}
jitter := time.Duration(randInt.Int64()%60) * time.Minute
log.Infof("Starting upload purge in %s", jitter) log.Infof("Starting upload purge in %s", jitter)
time.Sleep(jitter) time.Sleep(jitter)