gopkg.in/alecthomas/gometalinter.v3@v3.0.0/_linters/src/github.com/securego/gosec/rules/rand.go (about)

     1  // (c) Copyright 2016 Hewlett Packard Enterprise Development LP
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package rules
    16  
    17  import (
    18  	"go/ast"
    19  
    20  	"github.com/securego/gosec"
    21  )
    22  
    23  type weakRand struct {
    24  	gosec.MetaData
    25  	funcNames   []string
    26  	packagePath string
    27  }
    28  
    29  func (w *weakRand) ID() string {
    30  	return w.MetaData.ID
    31  }
    32  
    33  func (w *weakRand) Match(n ast.Node, c *gosec.Context) (*gosec.Issue, error) {
    34  	for _, funcName := range w.funcNames {
    35  		if _, matched := gosec.MatchCallByPackage(n, c, w.packagePath, funcName); matched {
    36  			return gosec.NewIssue(c, n, w.ID(), w.What, w.Severity, w.Confidence), nil
    37  		}
    38  	}
    39  
    40  	return nil, nil
    41  }
    42  
    43  // NewWeakRandCheck detects the use of random number generator that isn't cryptographically secure
    44  func NewWeakRandCheck(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
    45  	return &weakRand{
    46  		funcNames:   []string{"Read", "Int"},
    47  		packagePath: "math/rand",
    48  		MetaData: gosec.MetaData{
    49  			ID:         id,
    50  			Severity:   gosec.High,
    51  			Confidence: gosec.Medium,
    52  			What:       "Use of weak random number generator (math/rand instead of crypto/rand)",
    53  		},
    54  	}, []ast.Node{(*ast.CallExpr)(nil)}
    55  }