Skip to content

Commit

Permalink
*: Annotations and fixes related to gosec (pingcap#26907)
Browse files Browse the repository at this point in the history
  • Loading branch information
dveeden authored Aug 9, 2021
1 parent e539f9d commit 73bb7dd
Show file tree
Hide file tree
Showing 19 changed files with 41 additions and 39 deletions.
14 changes: 1 addition & 13 deletions .golangci.yml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
run:
timeout: 6m
timeout: 7m
linters:
disable-all: true
enable:
Expand All @@ -23,19 +23,7 @@ linters-settings:
checks: ["-ST1003"]
gosec:
excludes:
- G107
- G108
- G110
- G306
- G401
- G402
- G403
- G404
- G501
- G502
- G505
- G601

issues:
exclude-rules:
- path: _test\.go
Expand Down
2 changes: 1 addition & 1 deletion config/config_util.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ func atomicWriteConfig(c *Config, confPath string) (err error) {
return err
}
tmpConfPath := filepath.Join(os.TempDir(), fmt.Sprintf("tmp_conf_%v.toml", time.Now().Format("20060102150405")))
if err := os.WriteFile(tmpConfPath, []byte(content), 0666); err != nil {
if err := os.WriteFile(tmpConfPath, []byte(content), 0600); err != nil {
return errors.Trace(err)
}
return errors.Trace(os.Rename(tmpConfPath, confPath))
Expand Down
2 changes: 1 addition & 1 deletion domain/domain.go
Original file line number Diff line number Diff line change
Expand Up @@ -1511,7 +1511,7 @@ func (do *Domain) acquireServerID(ctx context.Context) error {
}

for {
randServerID := rand.Int63n(int64(util.MaxServerID)) + 1 // get a random serverID: [1, MaxServerID]
randServerID := rand.Int63n(int64(util.MaxServerID)) + 1 // get a random serverID: [1, MaxServerID] #nosec G404
key := fmt.Sprintf("%s/%v", serverIDEtcdPath, randServerID)
cmp := clientv3.Compare(clientv3.CreateRevision(key), "=", 0)
value := "0"
Expand Down
2 changes: 1 addition & 1 deletion domain/infosync/info.go
Original file line number Diff line number Diff line change
Expand Up @@ -691,7 +691,7 @@ func (is *InfoSyncer) getPrometheusAddr() (string, error) {
} else {
url = fmt.Sprintf("http://%s%s", pdAddrs[0], pdapi.Config)
}
resp, err := http.Get(url)
resp, err := http.Get(url) // #nosec G107
if err != nil {
return "", err
}
Expand Down
4 changes: 2 additions & 2 deletions executor/analyze.go
Original file line number Diff line number Diff line change
Expand Up @@ -1825,7 +1825,7 @@ func (e *AnalyzeFastExec) handleBatchSeekResponse(kvMap map[string][]byte) (err
}

func (e *AnalyzeFastExec) handleScanIter(iter kv.Iterator) (scanKeysSize int, err error) {
rander := rand.New(rand.NewSource(e.randSeed))
rander := rand.New(rand.NewSource(e.randSeed)) // #nosec G404
sampleSize := int64(e.opts[ast.AnalyzeOptNumSamples])
for ; iter.Valid() && err == nil; err = iter.Next() {
// reservoir sampling
Expand Down Expand Up @@ -1881,7 +1881,7 @@ func (e *AnalyzeFastExec) handleSampTasks(workID int, step uint32, err *error) {
snapshot.SetOption(kv.ReplicaRead, kv.ReplicaReadFollower)
}

rander := rand.New(rand.NewSource(e.randSeed))
rander := rand.New(rand.NewSource(e.randSeed)) // #nosec G404
for i := workID; i < len(e.sampTasks); i += e.concurrency {
task := e.sampTasks[i]
// randomize the estimate step in range [step - 2 * sqrt(step), step]
Expand Down
4 changes: 2 additions & 2 deletions executor/plan_recreator.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ package executor
import (
"archive/zip"
"context"
"crypto/md5"
"crypto/md5" // #nosec G501
"encoding/hex"
"fmt"
"math/rand"
Expand Down Expand Up @@ -155,7 +155,7 @@ func (e *PlanRecreatorSingleInfo) dumpSingle() (string, error) {
}
}
// Generate Token
token := md5.Sum([]byte(fmt.Sprintf("%s%d", fileName, rand.Int63())))
token := md5.Sum([]byte(fmt.Sprintf("%s%d", fileName, rand.Int63()))) // #nosec G401 G404
e.Ctx.Value(PlanRecreatorFileList).(fileList).FileInfo[fileName] = fileInfo{StartTime: startTime, Token: token}
e.Ctx.Value(PlanRecreatorFileList).(fileList).TokenMap[token] = fileName

Expand Down
9 changes: 5 additions & 4 deletions expression/builtin_encryption.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@ import (
"bytes"
"compress/zlib"
"crypto/aes"
"crypto/md5"
"crypto/md5" // #nosec G501
"crypto/rand"
"crypto/sha1"
"crypto/sha1" // #nosec G505
"crypto/sha256"
"crypto/sha512"
"encoding/binary"
Expand Down Expand Up @@ -624,7 +624,7 @@ func (b *builtinMD5Sig) evalString(row chunk.Row) (string, bool, error) {
if isNull || err != nil {
return "", isNull, err
}
sum := md5.Sum([]byte(arg))
sum := md5.Sum([]byte(arg)) // #nosec G401
hexStr := fmt.Sprintf("%x", sum)
return hexStr, false, nil
}
Expand Down Expand Up @@ -666,7 +666,7 @@ func (b *builtinSHA1Sig) evalString(row chunk.Row) (string, bool, error) {
if isNull || err != nil {
return "", isNull, err
}
hasher := sha1.New()
hasher := sha1.New() // #nosec G401
_, err = hasher.Write([]byte(str))
if err != nil {
return "", true, err
Expand Down Expand Up @@ -766,6 +766,7 @@ func inflate(compressStr []byte) ([]byte, error) {
if err != nil {
return nil, err
}
/* #nosec G110 */
if _, err = io.Copy(&out, r); err != nil {
return nil, err
}
Expand Down
8 changes: 4 additions & 4 deletions expression/builtin_encryption_vec.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ package expression
import (
"bytes"
"crypto/aes"
"crypto/md5"
"crypto/md5" // #nosec G501
"crypto/rand"
"crypto/sha1"
"crypto/sha1" // #nosec G505
"crypto/sha256"
"crypto/sha512"
"encoding/binary"
Expand Down Expand Up @@ -421,7 +421,7 @@ func (b *builtinMD5Sig) vecEvalString(input *chunk.Chunk, result *chunk.Column)
return err
}
result.ReserveString(n)
digest := md5.New()
digest := md5.New() // #nosec G401
for i := 0; i < n; i++ {
if buf.IsNull(i) {
result.AppendNull()
Expand Down Expand Up @@ -714,7 +714,7 @@ func (b *builtinSHA1Sig) vecEvalString(input *chunk.Chunk, result *chunk.Column)
return err
}
result.ReserveString(n)
hasher := sha1.New()
hasher := sha1.New() // #nosec G401
for i := 0; i < n; i++ {
if buf.IsNull(i) {
result.AppendNull()
Expand Down
2 changes: 1 addition & 1 deletion kv/txn.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ var (
// See http://www.awsarchitectureblog.com/2015/03/backoff.html.
func BackOff(attempts uint) int {
upper := int(math.Min(float64(retryBackOffCap), float64(retryBackOffBase)*math.Pow(2.0, float64(attempts))))
sleep := time.Duration(rand.Intn(upper)) * time.Millisecond
sleep := time.Duration(rand.Intn(upper)) * time.Millisecond // #nosec G404
time.Sleep(sleep)
return int(sleep)
}
2 changes: 1 addition & 1 deletion server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ import (
"net/http"

// For pprof
_ "net/http/pprof"
_ "net/http/pprof" // #nosec G108
"os"
"os/user"
"sync"
Expand Down
2 changes: 1 addition & 1 deletion sessionctx/variable/session.go
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ func (tc *TransactionContext) GetShard(shardRowIDBits uint64, typeBitsLength uin
return 0
}
if tc.shardRand == nil {
tc.shardRand = rand.New(rand.NewSource(int64(tc.StartTS)))
tc.shardRand = rand.New(rand.NewSource(int64(tc.StartTS))) // #nosec G404
}
if tc.shardRemain <= 0 {
tc.updateShard()
Expand Down
1 change: 1 addition & 0 deletions statistics/feedback.go
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,7 @@ func CollectFeedback(sc *stmtctx.StatementContext, q *QueryFeedback, numOfRanges
if q.Hist == nil || q.Hist.Len() == 0 {
return false
}
// #nosec G404
if numOfRanges > MaxNumberOfRanges || rand.Float64() > FeedbackProbability.Load() {
return false
}
Expand Down
1 change: 1 addition & 0 deletions store/copr/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ func NewStore(s *tikv.KVStore, coprCacheConfig *config.CoprocessorCache) (*Store
if err != nil {
return nil, errors.Trace(err)
}
/* #nosec G404 */
return &Store{
kvStore: &kvStore{store: s},
coprCache: coprCache,
Expand Down
1 change: 1 addition & 0 deletions store/mockstore/unistore/cophandler/analyze.go
Original file line number Diff line number Diff line change
Expand Up @@ -421,6 +421,7 @@ func handleAnalyzeFullSamplingReq(
colGroups = append(colGroups, colOffsets)
}
colReq := analyzeReq.ColReq
/* #nosec G404 */
builder := &statistics.RowSampleBuilder{
Sc: sc,
RecordSet: e,
Expand Down
4 changes: 2 additions & 2 deletions telemetry/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
package telemetry

import (
"crypto/sha1"
"crypto/sha1" // #nosec G505
"fmt"
"sort"
"strconv"
Expand All @@ -23,7 +23,7 @@ import (

// hashString returns the SHA1 checksum in hex of the string.
func hashString(text string) (string, error) {
hash := sha1.New()
hash := sha1.New() // #nosec G401
_, err := hash.Write([]byte(text))
if err != nil {
return "", err
Expand Down
15 changes: 12 additions & 3 deletions util/encrypt/aes_layer.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,12 @@ package encrypt
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/binary"
"errors"
"io"
"math/rand"
"math"
"math/big"
)

var errInvalidBlockSize = errors.New("invalid encrypt block size")
Expand All @@ -45,7 +47,10 @@ func NewCtrCipher() (ctr *CtrCipher, err error) {
// NewCtrCipherWithBlockSize return a CtrCipher with the encrypt block size
func NewCtrCipherWithBlockSize(encryptBlockSize int64) (ctr *CtrCipher, err error) {
key := make([]byte, aes.BlockSize)
rand.Read(key)
_, err = rand.Read(key)
if err != nil {
return nil, err
}
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
Expand All @@ -55,7 +60,11 @@ func NewCtrCipherWithBlockSize(encryptBlockSize int64) (ctr *CtrCipher, err erro
}
ctr = new(CtrCipher)
ctr.block = block
ctr.nonce = rand.Uint64()
nonce, err := rand.Int(rand.Reader, big.NewInt(int64(math.MaxInt64)))
if err != nil {
return nil, err
}
ctr.nonce = nonce.Uint64()
ctr.encryptBlockSize = encryptBlockSize
ctr.aesBlockCount = encryptBlockSize / aes.BlockSize
return
Expand Down
1 change: 1 addition & 0 deletions util/misc.go
Original file line number Diff line number Diff line change
Expand Up @@ -490,6 +490,7 @@ func LoadTLSCertificates(ca, key, cert string, autoTLS bool) (tlsConfig *tls.Con
}
}
}
/* #nosec G402 */
tlsConfig = &tls.Config{
Certificates: []tls.Certificate{tlsCert},
ClientCAs: certPool,
Expand Down
2 changes: 1 addition & 1 deletion util/selection/selection.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ func medianOfMedians(data Interface, left, right, k int) int {
}

func randomPivot(data Interface, left, right int) int {
return left + (rand.Int() % (right - left + 1))
return left + (rand.Int() % (right - left + 1)) // #nosec G404
}

func medianOfMediansPivot(data Interface, left, right int) int {
Expand Down
4 changes: 2 additions & 2 deletions util/vitess/vitess_hash.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ package vitess

import (
"crypto/cipher"
"crypto/des"
"crypto/des" // #nosec G502
"encoding/binary"

"github.com/pingcap/errors"
Expand All @@ -25,7 +25,7 @@ var nullKeyBlock cipher.Block

func init() {
var err error
nullKeyBlock, err = des.NewCipher(make([]byte, 8))
nullKeyBlock, err = des.NewCipher(make([]byte, 8)) // #nosec G401 G502
if err != nil {
panic(errors.Trace(err))
}
Expand Down

0 comments on commit 73bb7dd

Please sign in to comment.