diff --git a/go.mod b/go.mod index 4c3ae3a23..4357f62b5 100644 --- a/go.mod +++ b/go.mod @@ -4,7 +4,7 @@ go 1.19 require ( github.com/onsi/ginkgo v1.16.5 - github.com/onsi/gomega v1.28.0 + github.com/onsi/gomega v1.28.1 github.com/wI2L/jsondiff v0.4.0 k8s.io/apimachinery v0.28.2 k8s.io/client-go v0.28.2 @@ -54,7 +54,7 @@ require ( github.com/prometheus/common v0.44.0 // indirect github.com/prometheus/procfs v0.11.1 // indirect github.com/robfig/cron/v3 v3.0.1 - github.com/securego/gosec/v2 v2.17.0 + github.com/securego/gosec/v2 v2.18.2 github.com/sirupsen/logrus v1.9.3 github.com/spf13/cobra v1.7.0 github.com/spf13/pflag v1.0.6-0.20210604193023-d5e0c0615ace // indirect @@ -130,7 +130,7 @@ require ( github.com/xo/terminfo v0.0.0-20210125001918-ca9a967f8778 // indirect go4.org v0.0.0-20200104003542-c7e774b10ea0 // indirect golang.org/x/exp v0.0.0-20230510235704-dd950f8aeaea // indirect - golang.org/x/tools v0.13.0 // indirect + golang.org/x/tools v0.14.0 // indirect k8s.io/kube-aggregator v0.28.2 // indirect sigs.k8s.io/kube-storage-version-migrator v0.0.6-0.20230721195810-5c8923c5ff96 // indirect ) diff --git a/go.sum b/go.sum index 9116c06b6..1fd1a8118 100644 --- a/go.sum +++ b/go.sum @@ -198,6 +198,8 @@ github.com/onsi/gomega v1.27.10 h1:naR28SdDFlqrG6kScpT8VWpu1xWY5nJRCF3XaYyBjhI= github.com/onsi/gomega v1.27.10/go.mod h1:RsS8tutOdbdgzbPtzzATp12yT7kM5I5aElG3evPbQ0M= github.com/onsi/gomega v1.28.0 h1:i2rg/p9n/UqIDAMFUJ6qIUUMcsqOuUHgbpbu235Vr1c= github.com/onsi/gomega v1.28.0/go.mod h1:A1H2JE76sI14WIP57LMKj7FVfCHx3g3BcZVjJG8bjX8= +github.com/onsi/gomega v1.28.1 h1:MijcGUbfYuznzK/5R4CPNoUP/9Xvuo20sXfEm6XxoTA= +github.com/onsi/gomega v1.28.1/go.mod h1:9sxs+SwGrKI0+PWe4Fxa9tFQQBG5xSsSbMXOI8PPpoQ= github.com/openshift/api v0.0.0-20231002140248-174e989c9ee1 h1:a50eFxcKkdrH+tVjou4zOKH0RgSRmeeNdzucSqJlJ4I= github.com/openshift/api v0.0.0-20231002140248-174e989c9ee1/go.mod h1:qNtV0315F+f8ld52TLtPvrfivZpdimOzTi3kn9IVbtU= github.com/openshift/api v0.0.0-20231012181603-8f468d7b55a8 h1:x7k5FGR9J0/5qsDaXQjPz+zVydV4qX6pYBbGmdzSWxw= @@ -253,6 +255,8 @@ github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjR github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/securego/gosec/v2 v2.17.0 h1:ZpAStTDKY39insEG9OH6kV3IkhQZPTq9a9eGOLOjcdI= github.com/securego/gosec/v2 v2.17.0/go.mod h1:lt+mgC91VSmriVoJLentrMkRCYs+HLTBnUFUBuhV2hc= +github.com/securego/gosec/v2 v2.18.2 h1:DkDt3wCiOtAHf1XkiXZBhQ6m6mK/b9T/wD257R3/c+I= +github.com/securego/gosec/v2 v2.18.2/go.mod h1:xUuqSF6i0So56Y2wwohWAmB07EdBkUN6crbLlHwbyJs= github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= @@ -398,6 +402,8 @@ golang.org/x/tools v0.12.0 h1:YW6HUoUmYBpwSgyaGaZq1fHjrBjX1rlpZ54T6mu2kss= golang.org/x/tools v0.12.0/go.mod h1:Sc0INKfu04TlqNoRA1hgpFZbhYXHPr4V5DzpSBTPqQM= golang.org/x/tools v0.13.0 h1:Iey4qkscZuv0VvIt8E0neZjtPVQFSc870HQ448QgEmQ= golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58= +golang.org/x/tools v0.14.0 h1:jvNa2pY0M4r62jkRQ6RwEZZyPcymeL9XZMLBbV7U2nc= +golang.org/x/tools v0.14.0/go.mod h1:uYBEerGOWcJyEORxN+Ek8+TT266gXkNlHdJBwexUsBg= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= diff --git a/vendor/github.com/onsi/gomega/CHANGELOG.md b/vendor/github.com/onsi/gomega/CHANGELOG.md index fbb12a157..4f512a435 100644 --- a/vendor/github.com/onsi/gomega/CHANGELOG.md +++ b/vendor/github.com/onsi/gomega/CHANGELOG.md @@ -1,3 +1,12 @@ +## 1.28.1 + +### Maintenance +- Bump github.com/onsi/ginkgo/v2 from 2.12.0 to 2.13.0 [635d196] +- Bump github.com/google/go-cmp from 0.5.9 to 0.6.0 [14f8859] +- Bump golang.org/x/net from 0.14.0 to 0.17.0 [d8a6508] +- #703 doc(matchers): HaveEach() doc comment updated [2705bdb] +- Minor typos (#699) [375648c] + ## 1.28.0 ### Features diff --git a/vendor/github.com/onsi/gomega/gomega_dsl.go b/vendor/github.com/onsi/gomega/gomega_dsl.go index 675a17840..0625053ef 100644 --- a/vendor/github.com/onsi/gomega/gomega_dsl.go +++ b/vendor/github.com/onsi/gomega/gomega_dsl.go @@ -22,7 +22,7 @@ import ( "github.com/onsi/gomega/types" ) -const GOMEGA_VERSION = "1.28.0" +const GOMEGA_VERSION = "1.28.1" const nilGomegaPanic = `You are trying to make an assertion, but haven't registered Gomega's fail handler. If you're using Ginkgo then you probably forgot to put your assertion in an It(). @@ -242,7 +242,7 @@ func ExpectWithOffset(offset int, actual interface{}, extra ...interface{}) Asse Eventually enables making assertions on asynchronous behavior. Eventually checks that an assertion *eventually* passes. Eventually blocks when called and attempts an assertion periodically until it passes or a timeout occurs. Both the timeout and polling interval are configurable as optional arguments. -The first optional argument is the timeout (which defaults to 1s), the second is the polling interval (which defaults to 10ms). Both intervals can be specified as time.Duration, parsable duration strings or floats/integers (in which case they are interpreted as seconds). In addition an optional context.Context can be passed in - Eventually will keep trying until either the timeout epxires or the context is cancelled, whichever comes first. +The first optional argument is the timeout (which defaults to 1s), the second is the polling interval (which defaults to 10ms). Both intervals can be specified as time.Duration, parsable duration strings or floats/integers (in which case they are interpreted as seconds). In addition an optional context.Context can be passed in - Eventually will keep trying until either the timeout expires or the context is cancelled, whichever comes first. Eventually works with any Gomega compatible matcher and supports making assertions against three categories of actual value: @@ -313,13 +313,13 @@ It is important to note that the function passed into Eventually is invoked *syn }).Should(BeNumerically(">=", 17)) }, SpecTimeout(time.Second)) -you an also use Eventually().WithContext(ctx) to pass in the context. Passed-in contexts play nicely with paseed-in arguments as long as the context appears first. You can rewrite the above example as: +you an also use Eventually().WithContext(ctx) to pass in the context. Passed-in contexts play nicely with passed-in arguments as long as the context appears first. You can rewrite the above example as: It("fetches the correct count", func(ctx SpecContext) { Eventually(client.FetchCount).WithContext(ctx).WithArguments("/users").Should(BeNumerically(">=", 17)) }, SpecTimeout(time.Second)) -Either way the context passd to Eventually is also passed to the underlying funciton. Now, when Ginkgo cancels the context both the FetchCount client and Gomega will be informed and can exit. +Either way the context passd to Eventually is also passed to the underlying function. Now, when Ginkgo cancels the context both the FetchCount client and Gomega will be informed and can exit. **Category 3: Making assertions _in_ the function passed into Eventually** @@ -349,7 +349,7 @@ For example: will rerun the function until all assertions pass. -You can also pass additional arugments to functions that take a Gomega. The only rule is that the Gomega argument must be first. If you also want to pass the context attached to Eventually you must ensure that is the second argument. For example: +You can also pass additional arguments to functions that take a Gomega. The only rule is that the Gomega argument must be first. If you also want to pass the context attached to Eventually you must ensure that is the second argument. For example: Eventually(func(g Gomega, ctx context.Context, path string, expected ...string){ tok, err := client.GetToken(ctx) diff --git a/vendor/github.com/onsi/gomega/matchers.go b/vendor/github.com/onsi/gomega/matchers.go index 4c13ad0a7..88f100432 100644 --- a/vendor/github.com/onsi/gomega/matchers.go +++ b/vendor/github.com/onsi/gomega/matchers.go @@ -381,7 +381,7 @@ func ContainElements(elements ...interface{}) types.GomegaMatcher { } // HaveEach succeeds if actual solely contains elements that match the passed in element. -// Please note that if actual is empty, HaveEach always will succeed. +// Please note that if actual is empty, HaveEach always will fail. // By default HaveEach() uses Equal() to perform the match, however a // matcher can be passed in instead: // diff --git a/vendor/github.com/securego/gosec/v2/.golangci.yml b/vendor/github.com/securego/gosec/v2/.golangci.yml index d6c5de7ba..d591dc249 100644 --- a/vendor/github.com/securego/gosec/v2/.golangci.yml +++ b/vendor/github.com/securego/gosec/v2/.golangci.yml @@ -9,6 +9,7 @@ linters: - exportloopref - gci - ginkgolinter + - gochecknoinits - gofmt - gofumpt - goimports @@ -35,6 +36,10 @@ linters-settings: - standard - default - prefix(github.com/securego) + revive: + rules: + - name: dot-imports + disabled: true run: timeout: 5m diff --git a/vendor/github.com/securego/gosec/v2/Makefile b/vendor/github.com/securego/gosec/v2/Makefile index 09303d11a..dcfb4b2ed 100644 --- a/vendor/github.com/securego/gosec/v2/Makefile +++ b/vendor/github.com/securego/gosec/v2/Makefile @@ -11,7 +11,6 @@ endif BUILDFLAGS := "-w -s -X 'main.Version=$(GIT_TAG)' -X 'main.GitTag=$(GIT_TAG)' -X 'main.BuildDate=$(BUILD_DATE)'" CGO_ENABLED = 0 GO := GO111MODULE=on go -GO_NOMOD :=GO111MODULE=off go GOPATH ?= $(shell $(GO) env GOPATH) GOBIN ?= $(GOPATH)/bin GOSEC ?= $(GOBIN)/gosec @@ -25,15 +24,15 @@ default: install-test-deps: go install github.com/onsi/ginkgo/v2/ginkgo@latest - $(GO_NOMOD) get -u golang.org/x/crypto/ssh - $(GO_NOMOD) get -u github.com/lib/pq + go install golang.org/x/crypto/...@latest + go install github.com/lib/pq/...@latest install-govulncheck: @if [ $(GO_MINOR_VERSION) -gt $(GOVULN_MIN_VERSION) ]; then \ go install golang.org/x/vuln/cmd/govulncheck@latest; \ fi -test: install-test-deps build fmt vet sec govulncheck +test: install-test-deps build-race fmt vet sec govulncheck $(GINKGO) -v --fail-fast fmt: @@ -65,6 +64,9 @@ test-coverage: install-test-deps build: go build -o $(BIN) ./cmd/gosec/ +build-race: + go build -race -o $(BIN) ./cmd/gosec/ + clean: rm -rf build vendor dist coverage.txt rm -f release image $(BIN) @@ -89,5 +91,5 @@ image-push: image tlsconfig: go generate ./... - + .PHONY: test build clean release image image-push tlsconfig diff --git a/vendor/github.com/securego/gosec/v2/README.md b/vendor/github.com/securego/gosec/v2/README.md index 6c6d2982c..d9a33f12a 100644 --- a/vendor/github.com/securego/gosec/v2/README.md +++ b/vendor/github.com/securego/gosec/v2/README.md @@ -1,7 +1,7 @@ # gosec - Golang Security Checker -Inspects source code for security problems by scanning the Go AST. +Inspects source code for security problems by scanning the Go AST and SSA code representation. @@ -157,6 +157,7 @@ directory you can supply `./...` as the input argument. - G304: File path provided as taint input - G305: File traversal when extracting zip/tar archive - G306: Poor file permissions used when writing to a new file +- G307: Poor file permissions used when creating a file with os.Create - G401: Detect the usage of DES, RC4, MD5 or SHA1 - G402: Look for bad TLS connection settings - G403: Ensure minimum RSA key length of 2048 bits @@ -273,31 +274,33 @@ gosec -exclude-generated ./... ### Annotating code -As with all automated detection tools, there will be cases of false positives. In cases where gosec reports a failure that has been manually verified as being safe, +As with all automated detection tools, there will be cases of false positives. +In cases where gosec reports a failure that has been manually verified as being safe, it is possible to annotate the code with a comment that starts with `#nosec`. + The `#nosec` comment should have the format `#nosec [RuleList] [-- Justification]`. -The annotation causes gosec to stop processing any further nodes within the -AST so can apply to a whole block or more granularly to a single expression. +The `#nosec` comment needs to be placed on the line where the warning is reported. ```go - -import "md5" //#nosec - - -func main(){ - - /* #nosec */ - if x > y { - h := md5.New() // this will also be ignored - } - +func main() { + tr := &http.Transport{ + TLSClientConfig: &tls.Config{ + InsecureSkipVerify: true, // #nosec G402 + }, + } + + client := &http.Client{Transport: tr} + _, err := client.Get("https://golang.org/") + if err != nil { + fmt.Println(err) + } } - ``` -When a specific false positive has been identified and verified as safe, you may wish to suppress only that single rule (or a specific set of rules) -within a section of code, while continuing to scan for other problems. To do this, you can list the rule(s) to be suppressed within +When a specific false positive has been identified and verified as safe, you may +wish to suppress only that single rule (or a specific set of rules) within a section of code, +while continuing to scan for other problems. To do this, you can list the rule(s) to be suppressed within the `#nosec` annotation, e.g: `/* #nosec G401 */` or `//#nosec G201 G202 G203` You could put the description or justification text for the annotation. The diff --git a/vendor/github.com/securego/gosec/v2/USERS.md b/vendor/github.com/securego/gosec/v2/USERS.md index ffc056081..9b6e4eeee 100644 --- a/vendor/github.com/securego/gosec/v2/USERS.md +++ b/vendor/github.com/securego/gosec/v2/USERS.md @@ -15,6 +15,7 @@ This is a list of gosec's users. Please send a pull request with your organisati 9. [PingCAP/tidb](https://github.com/pingcap/tidb) 10. [Checkmarx](https://www.checkmarx.com/) 11. [SeatGeek](https://www.seatgeek.com/) +12. [reMarkable](https://remarkable.com) ## Projects diff --git a/vendor/github.com/securego/gosec/v2/action.yml b/vendor/github.com/securego/gosec/v2/action.yml index 8e28c346d..aba47b60c 100644 --- a/vendor/github.com/securego/gosec/v2/action.yml +++ b/vendor/github.com/securego/gosec/v2/action.yml @@ -10,7 +10,7 @@ inputs: runs: using: 'docker' - image: 'docker://securego/gosec:2.16.0' + image: 'docker://securego/gosec:2.18.1' args: - ${{ inputs.args }} diff --git a/vendor/github.com/securego/gosec/v2/analyzer.go b/vendor/github.com/securego/gosec/v2/analyzer.go index 023514b8a..1fd1f5649 100644 --- a/vendor/github.com/securego/gosec/v2/analyzer.go +++ b/vendor/github.com/securego/gosec/v2/analyzer.go @@ -57,6 +57,80 @@ const aliasOfAllRules = "*" var generatedCodePattern = regexp.MustCompile(`^// Code generated .* DO NOT EDIT\.$`) +type ignore struct { + start int + end int + suppressions map[string][]issue.SuppressionInfo +} + +type ignores map[string][]ignore + +func newIgnores() ignores { + return make(map[string][]ignore) +} + +func (i ignores) parseLine(line string) (int, int) { + parts := strings.Split(line, "-") + start, err := strconv.Atoi(parts[0]) + if err != nil { + start = 0 + } + end := start + if len(parts) > 1 { + if e, err := strconv.Atoi(parts[1]); err == nil { + end = e + } + } + return start, end +} + +func (i ignores) add(file string, line string, suppressions map[string]issue.SuppressionInfo) { + is := []ignore{} + if _, ok := i[file]; ok { + is = i[file] + } + found := false + start, end := i.parseLine(line) + for _, ig := range is { + if ig.start <= start && ig.end >= end { + found = true + for r, s := range suppressions { + ss, ok := ig.suppressions[r] + if !ok { + ss = []issue.SuppressionInfo{} + } + ss = append(ss, s) + ig.suppressions[r] = ss + } + break + } + } + if !found { + ig := ignore{ + start: start, + end: end, + suppressions: map[string][]issue.SuppressionInfo{}, + } + for r, s := range suppressions { + ig.suppressions[r] = []issue.SuppressionInfo{s} + } + is = append(is, ig) + } + i[file] = is +} + +func (i ignores) get(file string, line string) map[string][]issue.SuppressionInfo { + start, end := i.parseLine(line) + if is, ok := i[file]; ok { + for _, i := range is { + if i.start <= start && i.end >= end { + return i.suppressions + } + } + } + return map[string][]issue.SuppressionInfo{} +} + // The Context is populated with data parsed from the source code as it is scanned. // It is passed through to all rule functions as they are called. Rules may use // this data in conjunction with the encountered AST node. @@ -69,7 +143,7 @@ type Context struct { Root *ast.File Imports *ImportTracker Config Config - Ignores []map[string][]issue.SuppressionInfo + Ignores ignores PassedValues map[string]interface{} } @@ -110,6 +184,7 @@ type Analyzer struct { trackSuppressions bool concurrency int analyzerList []*analysis.Analyzer + mu sync.Mutex } // NewAnalyzer builds a new analyzer. @@ -231,9 +306,7 @@ func (gosec *Analyzer) Process(buildTags []string, packagePaths ...string) error return fmt.Errorf("parsing errors in pkg %q: %w", pkg.Name, err) } gosec.CheckRules(pkg) - if on, err := gosec.config.IsGlobalEnabled(SSA); err == nil && on { - gosec.CheckAnalyzers(pkg) - } + gosec.CheckAnalyzers(pkg) } } } @@ -252,7 +325,9 @@ func (gosec *Analyzer) load(pkgPath string, conf *packages.Config) ([]*packages. // step 1/3 create build context. buildD := build.Default // step 2/3: add build tags to get env dependent files into basePackage. + gosec.mu.Lock() buildD.BuildTags = conf.BuildFlags + gosec.mu.Unlock() basePackage, err := buildD.ImportDir(pkgPath, build.ImportComment) if err != nil { return []*packages.Package{}, fmt.Errorf("importing dir %q: %w", pkgPath, err) @@ -276,7 +351,9 @@ func (gosec *Analyzer) load(pkgPath string, conf *packages.Config) ([]*packages. } // step 3/3 remove build tags from conf to proceed build correctly. + gosec.mu.Lock() conf.BuildFlags = nil + defer gosec.mu.Unlock() pkgs, err := packages.Load(conf, packageFiles...) if err != nil { return []*packages.Package{}, fmt.Errorf("loading files from package %q: %w", pkgPath, err) @@ -284,7 +361,7 @@ func (gosec *Analyzer) load(pkgPath string, conf *packages.Config) ([]*packages. return pkgs, nil } -// CheckRules runs analysis on the given package +// CheckRules runs analysis on the given package. func (gosec *Analyzer) CheckRules(pkg *packages.Package) { gosec.logger.Println("Checking package:", pkg.Name) for _, file := range pkg.Syntax { @@ -314,37 +391,22 @@ func (gosec *Analyzer) CheckRules(pkg *packages.Package) { gosec.context.PkgFiles = pkg.Syntax gosec.context.Imports = NewImportTracker() gosec.context.PassedValues = make(map[string]interface{}) + gosec.context.Ignores = newIgnores() + gosec.updateIgnores() ast.Walk(gosec, file) gosec.stats.NumFiles++ gosec.stats.NumLines += pkg.Fset.File(file.Pos()).LineCount() } } -// CheckAnalyzers runs analyzers on a given package +// CheckAnalyzers runs analyzers on a given package. func (gosec *Analyzer) CheckAnalyzers(pkg *packages.Package) { - ssaPass := &analysis.Pass{ - Analyzer: buildssa.Analyzer, - Fset: pkg.Fset, - Files: pkg.Syntax, - OtherFiles: pkg.OtherFiles, - IgnoredFiles: pkg.IgnoredFiles, - Pkg: pkg.Types, - TypesInfo: pkg.TypesInfo, - TypesSizes: pkg.TypesSizes, - ResultOf: nil, - Report: nil, - ImportObjectFact: nil, - ExportObjectFact: nil, - ImportPackageFact: nil, - ExportPackageFact: nil, - AllObjectFacts: nil, - AllPackageFacts: nil, - } - ssaResult, err := ssaPass.Analyzer.Run(ssaPass) - if err != nil { - gosec.logger.Printf("Error running SSA analyser on package %q: %s", pkg.Name, err) + ssaResult, err := gosec.buildSSA(pkg) + if err != nil || ssaResult == nil { + gosec.logger.Printf("Error building the SSA representation of the package %q: %s", pkg.Name, err) return } + resultMap := map[*analysis.Analyzer]interface{}{ buildssa.Analyzer: &analyzers.SSAAnalyzerResult{ Config: gosec.Config(), @@ -377,13 +439,44 @@ func (gosec *Analyzer) CheckAnalyzers(pkg *packages.Package) { continue } if result != nil { - if aissue, ok := result.(*issue.Issue); ok { - gosec.updateIssues(aissue, false, []issue.SuppressionInfo{}) + if passIssues, ok := result.([]*issue.Issue); ok { + for _, iss := range passIssues { + gosec.updateIssues(iss) + } } } } } +// buildSSA runs the SSA pass which builds the SSA representation of the package. It handles gracefully any panic. +func (gosec *Analyzer) buildSSA(pkg *packages.Package) (interface{}, error) { + defer func() { + if r := recover(); r != nil { + gosec.logger.Printf("Panic when running SSA analyser on package: %s", pkg.Name) + } + }() + ssaPass := &analysis.Pass{ + Analyzer: buildssa.Analyzer, + Fset: pkg.Fset, + Files: pkg.Syntax, + OtherFiles: pkg.OtherFiles, + IgnoredFiles: pkg.IgnoredFiles, + Pkg: pkg.Types, + TypesInfo: pkg.TypesInfo, + TypesSizes: pkg.TypesSizes, + ResultOf: nil, + Report: nil, + ImportObjectFact: nil, + ExportObjectFact: nil, + ImportPackageFact: nil, + ExportPackageFact: nil, + AllObjectFacts: nil, + AllPackageFacts: nil, + } + + return ssaPass.Analyzer.Run(ssaPass) +} + func isGeneratedFile(file *ast.File) bool { for _, comment := range file.Comments { for _, row := range comment.List { @@ -449,7 +542,12 @@ func (gosec *Analyzer) ignore(n ast.Node) map[string]issue.SuppressionInfo { if groups, ok := gosec.context.Comments[n]; ok && !gosec.ignoreNosec { // Checks if an alternative for #nosec is set and, if not, uses the default. - noSecDefaultTag := NoSecTag(string(Nosec)) + noSecDefaultTag, err := gosec.config.GetGlobal(Nosec) + if err != nil { + noSecDefaultTag = NoSecTag(string(Nosec)) + } else { + noSecDefaultTag = NoSecTag(noSecDefaultTag) + } noSecAlternativeTag, err := gosec.config.GetGlobal(NoSecAlternative) if err != nil { noSecAlternativeTag = noSecDefaultTag @@ -509,11 +607,6 @@ func (gosec *Analyzer) ignore(n ast.Node) map[string]issue.SuppressionInfo { // Visit runs the gosec visitor logic over an AST created by parsing go code. // Rule methods added with AddRule will be invoked as necessary. func (gosec *Analyzer) Visit(n ast.Node) ast.Visitor { - ignores, ok := gosec.updateIgnoredRules(n) - if !ok { - return gosec - } - // Using ast.File instead of ast.ImportSpec, so that we can track all imports at once. switch i := n.(type) { case *ast.File: @@ -521,56 +614,48 @@ func (gosec *Analyzer) Visit(n ast.Node) ast.Visitor { } for _, rule := range gosec.ruleset.RegisteredFor(n) { - suppressions, ignored := gosec.updateSuppressions(rule.ID(), ignores) issue, err := rule.Match(n, gosec.context) if err != nil { file, line := GetLocation(n, gosec.context) file = path.Base(file) gosec.logger.Printf("Rule error: %v => %s (%s:%d)\n", reflect.TypeOf(rule), err, file, line) } - gosec.updateIssues(issue, ignored, suppressions) + gosec.updateIssues(issue) } return gosec } -func (gosec *Analyzer) updateIgnoredRules(n ast.Node) (map[string][]issue.SuppressionInfo, bool) { - if n == nil { - if len(gosec.context.Ignores) > 0 { - gosec.context.Ignores = gosec.context.Ignores[1:] - } - return nil, false +func (gosec *Analyzer) updateIgnores() { + for n := range gosec.context.Comments { + gosec.updateIgnoredRulesForNode(n) } - // Get any new rule exclusions. - ignoredRules := gosec.ignore(n) +} - // Now create the union of exclusions. - ignores := map[string][]issue.SuppressionInfo{} - if len(gosec.context.Ignores) > 0 { - for k, v := range gosec.context.Ignores[0] { - ignores[k] = v +func (gosec *Analyzer) updateIgnoredRulesForNode(n ast.Node) { + ignoredRules := gosec.ignore(n) + if len(ignoredRules) > 0 { + if gosec.context.Ignores == nil { + gosec.context.Ignores = newIgnores() } + line := issue.GetLine(gosec.context.FileSet.File(n.Pos()), n) + gosec.context.Ignores.add( + gosec.context.FileSet.File(n.Pos()).Name(), + line, + ignoredRules, + ) } - - for ruleID, suppression := range ignoredRules { - ignores[ruleID] = append(ignores[ruleID], suppression) - } - - // Push the new set onto the stack. - gosec.context.Ignores = append([]map[string][]issue.SuppressionInfo{ignores}, gosec.context.Ignores...) - - return ignores, true } -func (gosec *Analyzer) updateSuppressions(id string, ignores map[string][]issue.SuppressionInfo) ([]issue.SuppressionInfo, bool) { - // Check if all rules are ignored. - generalSuppressions, generalIgnored := ignores[aliasOfAllRules] - // Check if the specific rule is ignored - ruleSuppressions, ruleIgnored := ignores[id] +func (gosec *Analyzer) getSuppressionsAtLineInFile(file string, line string, id string) ([]issue.SuppressionInfo, bool) { + ignoredRules := gosec.context.Ignores.get(file, line) + // Check if the rule was specifically suppressed at this location. + generalSuppressions, generalIgnored := ignoredRules[aliasOfAllRules] + ruleSuppressions, ruleIgnored := ignoredRules[id] ignored := generalIgnored || ruleIgnored suppressions := append(generalSuppressions, ruleSuppressions...) - // Track external suppressions. + // Track external suppressions of this rule. if gosec.ruleset.IsRuleSuppressed(id) { ignored = true suppressions = append(suppressions, issue.SuppressionInfo{ @@ -581,8 +666,9 @@ func (gosec *Analyzer) updateSuppressions(id string, ignores map[string][]issue. return suppressions, ignored } -func (gosec *Analyzer) updateIssues(issue *issue.Issue, ignored bool, suppressions []issue.SuppressionInfo) { +func (gosec *Analyzer) updateIssues(issue *issue.Issue) { if issue != nil { + suppressions, ignored := gosec.getSuppressionsAtLineInFile(issue.File, issue.Line, issue.RuleID) if gosec.showIgnored { issue.NoSec = ignored } diff --git a/vendor/github.com/securego/gosec/v2/analyzers/slice_bounds.go b/vendor/github.com/securego/gosec/v2/analyzers/slice_bounds.go new file mode 100644 index 000000000..08a55eb42 --- /dev/null +++ b/vendor/github.com/securego/gosec/v2/analyzers/slice_bounds.go @@ -0,0 +1,386 @@ +// (c) Copyright gosec's authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package analyzers + +import ( + "errors" + "fmt" + "go/token" + "regexp" + "strconv" + "strings" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/buildssa" + "golang.org/x/tools/go/ssa" + + "github.com/securego/gosec/v2/issue" +) + +type bound int + +const ( + lowerUnbounded bound = iota + upperUnbounded + unbounded + upperBounded +) + +const maxDepth = 20 + +func newSliceBoundsAnalyzer(id string, description string) *analysis.Analyzer { + return &analysis.Analyzer{ + Name: id, + Doc: description, + Run: runSliceBounds, + Requires: []*analysis.Analyzer{buildssa.Analyzer}, + } +} + +func runSliceBounds(pass *analysis.Pass) (interface{}, error) { + ssaResult, err := getSSAResult(pass) + if err != nil { + return nil, err + } + + issues := map[ssa.Instruction]*issue.Issue{} + ifs := map[ssa.If]*ssa.BinOp{} + for _, mcall := range ssaResult.SSA.SrcFuncs { + for _, block := range mcall.DomPreorder() { + for _, instr := range block.Instrs { + switch instr := instr.(type) { + case *ssa.Alloc: + sliceCap, err := extractSliceCapFromAlloc(instr.String()) + if err != nil { + break + } + allocRefs := instr.Referrers() + if allocRefs == nil { + break + } + for _, instr := range *allocRefs { + if slice, ok := instr.(*ssa.Slice); ok { + if _, ok := slice.X.(*ssa.Alloc); ok { + if slice.Parent() != nil { + l, h := extractSliceBounds(slice) + newCap := computeSliceNewCap(l, h, sliceCap) + violations := []ssa.Instruction{} + trackSliceBounds(0, newCap, slice, &violations, ifs) + for _, s := range violations { + switch s := s.(type) { + case *ssa.Slice: + issue := newIssue( + pass.Analyzer.Name, + "slice bounds out of range", + pass.Fset, + s.Pos(), + issue.Low, + issue.High) + issues[s] = issue + case *ssa.IndexAddr: + issue := newIssue( + pass.Analyzer.Name, + "slice index out of range", + pass.Fset, + s.Pos(), + issue.Low, + issue.High) + issues[s] = issue + } + } + } + } + } + } + } + } + } + } + + for ifref, binop := range ifs { + bound, value, err := extractBinOpBound(binop) + if err != nil { + continue + } + for i, block := range ifref.Block().Succs { + if i == 1 { + bound = invBound(bound) + } + for _, instr := range block.Instrs { + if _, ok := issues[instr]; ok { + switch bound { + case lowerUnbounded: + break + case upperUnbounded, unbounded: + delete(issues, instr) + case upperBounded: + switch tinstr := instr.(type) { + case *ssa.Slice: + lower, upper := extractSliceBounds(tinstr) + if isSliceInsideBounds(0, value, lower, upper) { + delete(issues, instr) + } + case *ssa.IndexAddr: + indexValue, err := extractIntValue(tinstr.Index.String()) + if err != nil { + break + } + if isSliceIndexInsideBounds(0, value, indexValue) { + delete(issues, instr) + } + } + } + } + } + } + } + + foundIssues := []*issue.Issue{} + for _, issue := range issues { + foundIssues = append(foundIssues, issue) + } + if len(foundIssues) > 0 { + return foundIssues, nil + } + return nil, nil +} + +func trackSliceBounds(depth int, sliceCap int, slice ssa.Node, violations *[]ssa.Instruction, ifs map[ssa.If]*ssa.BinOp) { + if depth == maxDepth { + return + } + depth++ + if violations == nil { + violations = &[]ssa.Instruction{} + } + referrers := slice.Referrers() + if referrers != nil { + for _, refinstr := range *referrers { + switch refinstr := refinstr.(type) { + case *ssa.Slice: + checkAllSlicesBounds(depth, sliceCap, refinstr, violations, ifs) + switch refinstr.X.(type) { + case *ssa.Alloc, *ssa.Parameter: + l, h := extractSliceBounds(refinstr) + newCap := computeSliceNewCap(l, h, sliceCap) + trackSliceBounds(depth, newCap, refinstr, violations, ifs) + } + case *ssa.IndexAddr: + indexValue, err := extractIntValue(refinstr.Index.String()) + if err == nil && !isSliceIndexInsideBounds(0, sliceCap, indexValue) { + *violations = append(*violations, refinstr) + } + case *ssa.Call: + if ifref, cond := extractSliceIfLenCondition(refinstr); ifref != nil && cond != nil { + ifs[*ifref] = cond + } else { + parPos := -1 + for pos, arg := range refinstr.Call.Args { + if a, ok := arg.(*ssa.Slice); ok && a == slice { + parPos = pos + } + } + if fn, ok := refinstr.Call.Value.(*ssa.Function); ok { + if len(fn.Params) > parPos && parPos > -1 { + param := fn.Params[parPos] + trackSliceBounds(depth, sliceCap, param, violations, ifs) + } + } + } + } + } + } +} + +func checkAllSlicesBounds(depth int, sliceCap int, slice *ssa.Slice, violations *[]ssa.Instruction, ifs map[ssa.If]*ssa.BinOp) { + if depth == maxDepth { + return + } + depth++ + if violations == nil { + violations = &[]ssa.Instruction{} + } + sliceLow, sliceHigh := extractSliceBounds(slice) + if !isSliceInsideBounds(0, sliceCap, sliceLow, sliceHigh) { + *violations = append(*violations, slice) + } + switch slice.X.(type) { + case *ssa.Alloc, *ssa.Parameter, *ssa.Slice: + l, h := extractSliceBounds(slice) + newCap := computeSliceNewCap(l, h, sliceCap) + trackSliceBounds(depth, newCap, slice, violations, ifs) + } + + references := slice.Referrers() + if references == nil { + return + } + for _, ref := range *references { + switch s := ref.(type) { + case *ssa.Slice: + checkAllSlicesBounds(depth, sliceCap, s, violations, ifs) + switch s.X.(type) { + case *ssa.Alloc, *ssa.Parameter: + l, h := extractSliceBounds(s) + newCap := computeSliceNewCap(l, h, sliceCap) + trackSliceBounds(depth, newCap, s, violations, ifs) + } + } + } +} + +func extractSliceIfLenCondition(call *ssa.Call) (*ssa.If, *ssa.BinOp) { + if builtInLen, ok := call.Call.Value.(*ssa.Builtin); ok { + if builtInLen.Name() == "len" { + refs := call.Referrers() + if refs != nil { + for _, ref := range *refs { + if binop, ok := ref.(*ssa.BinOp); ok { + binoprefs := binop.Referrers() + for _, ref := range *binoprefs { + if ifref, ok := ref.(*ssa.If); ok { + return ifref, binop + } + } + } + } + } + } + } + return nil, nil +} + +func computeSliceNewCap(l, h, oldCap int) int { + if l == 0 && h == 0 { + return oldCap + } + if l > 0 && h == 0 { + return oldCap - l + } + if l == 0 && h > 0 { + return h + } + return h - l +} + +func invBound(bound bound) bound { + switch bound { + case lowerUnbounded: + return upperUnbounded + case upperUnbounded: + return lowerUnbounded + case upperBounded: + return unbounded + case unbounded: + return upperBounded + default: + return unbounded + } +} + +func extractBinOpBound(binop *ssa.BinOp) (bound, int, error) { + if binop.X != nil { + if x, ok := binop.X.(*ssa.Const); ok { + value, err := strconv.Atoi(x.Value.String()) + if err != nil { + return lowerUnbounded, value, err + } + switch binop.Op { + case token.LSS, token.LEQ: + return upperUnbounded, value, nil + case token.GTR, token.GEQ: + return lowerUnbounded, value, nil + case token.EQL: + return upperBounded, value, nil + case token.NEQ: + return unbounded, value, nil + } + } + } + if binop.Y != nil { + if y, ok := binop.Y.(*ssa.Const); ok { + value, err := strconv.Atoi(y.Value.String()) + if err != nil { + return lowerUnbounded, value, err + } + switch binop.Op { + case token.LSS, token.LEQ: + return lowerUnbounded, value, nil + case token.GTR, token.GEQ: + return upperUnbounded, value, nil + case token.EQL: + return upperBounded, value, nil + case token.NEQ: + return unbounded, value, nil + } + } + } + return lowerUnbounded, 0, fmt.Errorf("unable to extract constant from binop") +} + +func isSliceIndexInsideBounds(l, h int, index int) bool { + return (l <= index && index < h) +} + +func isSliceInsideBounds(l, h int, cl, ch int) bool { + return (l <= cl && h >= ch) && (l <= ch && h >= cl) +} + +func extractSliceBounds(slice *ssa.Slice) (int, int) { + var low int + if slice.Low != nil { + l, err := extractIntValue(slice.Low.String()) + if err == nil { + low = l + } + } + var high int + if slice.High != nil { + h, err := extractIntValue(slice.High.String()) + if err == nil { + high = h + } + } + return low, high +} + +func extractIntValue(value string) (int, error) { + parts := strings.Split(value, ":") + if len(parts) != 2 { + return 0, fmt.Errorf("invalid value: %s", value) + } + if parts[1] != "int" { + return 0, fmt.Errorf("invalid value: %s", value) + } + return strconv.Atoi(parts[0]) +} + +func extractSliceCapFromAlloc(instr string) (int, error) { + re := regexp.MustCompile(`new \[(\d+)\]*`) + var sliceCap int + matches := re.FindAllStringSubmatch(instr, -1) + if matches == nil { + return sliceCap, errors.New("no slice cap found") + } + + if len(matches) > 0 { + m := matches[0] + if len(m) > 1 { + return strconv.Atoi(m[1]) + } + } + + return 0, errors.New("no slice cap found") +} diff --git a/vendor/github.com/securego/gosec/v2/analyzers/ssrf.go b/vendor/github.com/securego/gosec/v2/analyzers/ssrf.go deleted file mode 100644 index 70e0211f1..000000000 --- a/vendor/github.com/securego/gosec/v2/analyzers/ssrf.go +++ /dev/null @@ -1,57 +0,0 @@ -// (c) Copyright gosec's authors -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package analyzers - -import ( - "golang.org/x/tools/go/analysis" - "golang.org/x/tools/go/analysis/passes/buildssa" - "golang.org/x/tools/go/ssa" - - "github.com/securego/gosec/v2/issue" -) - -func newSSRFAnalyzer(id string, description string) *analysis.Analyzer { - return &analysis.Analyzer{ - Name: id, - Doc: description, - Run: runSSRF, - Requires: []*analysis.Analyzer{buildssa.Analyzer}, - } -} - -func runSSRF(pass *analysis.Pass) (interface{}, error) { - ssaResult, err := getSSAResult(pass) - if err != nil { - return nil, err - } - // TODO: implement the analysis - for _, fn := range ssaResult.SSA.SrcFuncs { - for _, block := range fn.DomPreorder() { - for _, instr := range block.Instrs { - switch instr := instr.(type) { - case *ssa.Call: - callee := instr.Call.StaticCallee() - if callee != nil { - ssaResult.Logger.Printf("callee: %s\n", callee) - return newIssue(pass.Analyzer.Name, - "not implemented", - pass.Fset, instr.Call.Pos(), issue.Low, issue.High), nil - } - } - } - } - } - return nil, nil -} diff --git a/vendor/github.com/securego/gosec/v2/analyzers/util.go b/vendor/github.com/securego/gosec/v2/analyzers/util.go index f1bd867ae..5941184aa 100644 --- a/vendor/github.com/securego/gosec/v2/analyzers/util.go +++ b/vendor/github.com/securego/gosec/v2/analyzers/util.go @@ -38,7 +38,7 @@ type SSAAnalyzerResult struct { // BuildDefaultAnalyzers returns the default list of analyzers func BuildDefaultAnalyzers() []*analysis.Analyzer { return []*analysis.Analyzer{ - newSSRFAnalyzer("G107", "URL provided to HTTP request as taint input"), + newSliceBoundsAnalyzer("G602", "Possible slice bounds out of range"), } } diff --git a/vendor/github.com/securego/gosec/v2/cwe/data.go b/vendor/github.com/securego/gosec/v2/cwe/data.go index ff1ad3c7d..79a6b9d23 100644 --- a/vendor/github.com/securego/gosec/v2/cwe/data.go +++ b/vendor/github.com/securego/gosec/v2/cwe/data.go @@ -1,7 +1,5 @@ package cwe -import "fmt" - const ( // Acronym is the acronym of CWE Acronym = "CWE" @@ -13,139 +11,128 @@ const ( Organization = "MITRE" // Description the description of CWE Description = "The MITRE Common Weakness Enumeration" -) - -var ( // InformationURI link to the published CWE PDF - InformationURI = fmt.Sprintf("https://cwe.mitre.org/data/published/cwe_v%s.pdf/", Version) + InformationURI = "https://cwe.mitre.org/data/published/cwe_v" + Version + ".pdf/" // DownloadURI link to the zipped XML of the CWE list - DownloadURI = fmt.Sprintf("https://cwe.mitre.org/data/xml/cwec_v%s.xml.zip", Version) - - data = map[string]*Weakness{} - - weaknesses = []*Weakness{ - { - ID: "118", - Description: "The software does not restrict or incorrectly restricts operations within the boundaries of a resource that is accessed using an index or pointer, such as memory or files.", - Name: "Incorrect Access of Indexable Resource ('Range Error')", - }, - { - ID: "190", - Description: "The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.", - Name: "Integer Overflow or Wraparound", - }, - { - ID: "200", - Description: "The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.", - Name: "Exposure of Sensitive Information to an Unauthorized Actor", - }, - { - ID: "22", - Description: "The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.", - Name: "Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')", - }, - { - ID: "242", - Description: "The program calls a function that can never be guaranteed to work safely.", - Name: "Use of Inherently Dangerous Function", - }, - { - ID: "276", - Description: "During installation, installed file permissions are set to allow anyone to modify those files.", - Name: "Incorrect Default Permissions", - }, - { - ID: "295", - Description: "The software does not validate, or incorrectly validates, a certificate.", - Name: "Improper Certificate Validation", - }, - { - ID: "310", - Description: "Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed.", - Name: "Cryptographic Issues", - }, - { - ID: "322", - Description: "The software performs a key exchange with an actor without verifying the identity of that actor.", - Name: "Key Exchange without Entity Authentication", - }, - { - ID: "326", - Description: "The software stores or transmits sensitive data using an encryption scheme that is theoretically sound, but is not strong enough for the level of protection required.", - Name: "Inadequate Encryption Strength", - }, - { - ID: "327", - Description: "The use of a broken or risky cryptographic algorithm is an unnecessary risk that may result in the exposure of sensitive information.", - Name: "Use of a Broken or Risky Cryptographic Algorithm", - }, - { - ID: "338", - Description: "The product uses a Pseudo-Random Number Generator (PRNG) in a security context, but the PRNG's algorithm is not cryptographically strong.", - Name: "Use of Cryptographically Weak Pseudo-Random Number Generator (PRNG)", - }, - { - ID: "377", - Description: "Creating and using insecure temporary files can leave application and system data vulnerable to attack.", - Name: "Insecure Temporary File", - }, - { - ID: "400", - Description: "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", - Name: "Uncontrolled Resource Consumption", - }, - { - ID: "409", - Description: "The software does not handle or incorrectly handles a compressed input with a very high compression ratio that produces a large output.", - Name: "Improper Handling of Highly Compressed Data (Data Amplification)", - }, - { - ID: "703", - Description: "The software does not properly anticipate or handle exceptional conditions that rarely occur during normal operation of the software.", - Name: "Improper Check or Handling of Exceptional Conditions", - }, - { - ID: "78", - Description: "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", - Name: "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", - }, - { - ID: "79", - Description: "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", - Name: "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", - }, - { - ID: "798", - Description: "The software contains hard-coded credentials, such as a password or cryptographic key, which it uses for its own inbound authentication, outbound communication to external components, or encryption of internal data.", - Name: "Use of Hard-coded Credentials", - }, - { - ID: "88", - Description: "The software constructs a string for a command to executed by a separate component\nin another control sphere, but it does not properly delimit the\nintended arguments, options, or switches within that command string.", - Name: "Improper Neutralization of Argument Delimiters in a Command ('Argument Injection')", - }, - { - ID: "89", - Description: "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", - Name: "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", - }, - { - ID: "676", - Description: "The program invokes a potentially dangerous function that could introduce a vulnerability if it is used incorrectly, but the function can also be used safely.", - Name: "Use of Potentially Dangerous Function", - }, - } + DownloadURI = "https://cwe.mitre.org/data/xml/cwec_v" + Version + ".xml.zip" ) -func init() { - for _, weakness := range weaknesses { - data[weakness.ID] = weakness - } +var idWeaknesses = map[string]*Weakness{ + "118": { + ID: "118", + Description: "The software does not restrict or incorrectly restricts operations within the boundaries of a resource that is accessed using an index or pointer, such as memory or files.", + Name: "Incorrect Access of Indexable Resource ('Range Error')", + }, + "190": { + ID: "190", + Description: "The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.", + Name: "Integer Overflow or Wraparound", + }, + "200": { + ID: "200", + Description: "The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.", + Name: "Exposure of Sensitive Information to an Unauthorized Actor", + }, + "22": { + ID: "22", + Description: "The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.", + Name: "Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')", + }, + "242": { + ID: "242", + Description: "The program calls a function that can never be guaranteed to work safely.", + Name: "Use of Inherently Dangerous Function", + }, + "276": { + ID: "276", + Description: "During installation, installed file permissions are set to allow anyone to modify those files.", + Name: "Incorrect Default Permissions", + }, + "295": { + ID: "295", + Description: "The software does not validate, or incorrectly validates, a certificate.", + Name: "Improper Certificate Validation", + }, + "310": { + ID: "310", + Description: "Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed.", + Name: "Cryptographic Issues", + }, + "322": { + ID: "322", + Description: "The software performs a key exchange with an actor without verifying the identity of that actor.", + Name: "Key Exchange without Entity Authentication", + }, + "326": { + ID: "326", + Description: "The software stores or transmits sensitive data using an encryption scheme that is theoretically sound, but is not strong enough for the level of protection required.", + Name: "Inadequate Encryption Strength", + }, + "327": { + ID: "327", + Description: "The use of a broken or risky cryptographic algorithm is an unnecessary risk that may result in the exposure of sensitive information.", + Name: "Use of a Broken or Risky Cryptographic Algorithm", + }, + "338": { + ID: "338", + Description: "The product uses a Pseudo-Random Number Generator (PRNG) in a security context, but the PRNG's algorithm is not cryptographically strong.", + Name: "Use of Cryptographically Weak Pseudo-Random Number Generator (PRNG)", + }, + "377": { + ID: "377", + Description: "Creating and using insecure temporary files can leave application and system data vulnerable to attack.", + Name: "Insecure Temporary File", + }, + "400": { + ID: "400", + Description: "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", + Name: "Uncontrolled Resource Consumption", + }, + "409": { + ID: "409", + Description: "The software does not handle or incorrectly handles a compressed input with a very high compression ratio that produces a large output.", + Name: "Improper Handling of Highly Compressed Data (Data Amplification)", + }, + "703": { + ID: "703", + Description: "The software does not properly anticipate or handle exceptional conditions that rarely occur during normal operation of the software.", + Name: "Improper Check or Handling of Exceptional Conditions", + }, + "78": { + ID: "78", + Description: "The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.", + Name: "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", + }, + "79": { + ID: "79", + Description: "The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.", + Name: "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", + }, + "798": { + ID: "798", + Description: "The software contains hard-coded credentials, such as a password or cryptographic key, which it uses for its own inbound authentication, outbound communication to external components, or encryption of internal data.", + Name: "Use of Hard-coded Credentials", + }, + "88": { + ID: "88", + Description: "The software constructs a string for a command to executed by a separate component\nin another control sphere, but it does not properly delimit the\nintended arguments, options, or switches within that command string.", + Name: "Improper Neutralization of Argument Delimiters in a Command ('Argument Injection')", + }, + "89": { + ID: "89", + Description: "The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.", + Name: "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", + }, + "676": { + ID: "676", + Description: "The program invokes a potentially dangerous function that could introduce a vulnerability if it is used incorrectly, but the function can also be used safely.", + Name: "Use of Potentially Dangerous Function", + }, } // Get Retrieves a CWE weakness by it's id func Get(id string) *Weakness { - weakness, ok := data[id] + weakness, ok := idWeaknesses[id] if ok && weakness != nil { return weakness } diff --git a/vendor/github.com/securego/gosec/v2/helpers.go b/vendor/github.com/securego/gosec/v2/helpers.go index b4c23e5bb..15b2b5f3a 100644 --- a/vendor/github.com/securego/gosec/v2/helpers.go +++ b/vendor/github.com/securego/gosec/v2/helpers.go @@ -100,7 +100,7 @@ func GetChar(n ast.Node) (byte, error) { // Unlike the other getters, it does _not_ raise an error for unknown ast.Node types. At the base, the recursion will hit a non-BinaryExpr type, // either BasicLit or other, so it's not an error case. It will only error if `strconv.Unquote` errors. This matters, because there's // currently functionality that relies on error values being returned by GetString if and when it hits a non-basiclit string node type, -// hence for cases where recursion is needed, we use this separate function, so that we can still be backwards compatbile. +// hence for cases where recursion is needed, we use this separate function, so that we can still be backwards compatible. // // This was added to handle a SQL injection concatenation case where the injected value is infixed between two strings, not at the start or end. See example below // @@ -183,7 +183,7 @@ func GetCallInfo(n ast.Node, ctx *Context) (string, string, error) { case *ast.CallExpr: switch call := expr.Fun.(type) { case *ast.Ident: - if call.Name == "new" { + if call.Name == "new" && len(expr.Args) > 0 { t := ctx.Info.TypeOf(expr.Args[0]) if t != nil { return t.String(), fn.Sel.Name, nil diff --git a/vendor/github.com/securego/gosec/v2/issue/issue.go b/vendor/github.com/securego/gosec/v2/issue/issue.go index db4d630fa..1000b2042 100644 --- a/vendor/github.com/securego/gosec/v2/issue/issue.go +++ b/vendor/github.com/securego/gosec/v2/issue/issue.go @@ -178,11 +178,7 @@ func codeSnippetEndLine(node ast.Node, fobj *token.File) int64 { // New creates a new Issue func New(fobj *token.File, node ast.Node, ruleID, desc string, severity, confidence Score) *Issue { name := fobj.Name() - start, end := fobj.Line(node.Pos()), fobj.Line(node.End()) - line := strconv.Itoa(start) - if start != end { - line = fmt.Sprintf("%d-%d", start, end) - } + line := GetLine(fobj, node) col := strconv.Itoa(fobj.Position(node.Pos()).Column) var code string @@ -217,3 +213,13 @@ func (i *Issue) WithSuppressions(suppressions []SuppressionInfo) *Issue { i.Suppressions = suppressions return i } + +// GetLine returns the line number of a given ast.Node +func GetLine(fobj *token.File, node ast.Node) string { + start, end := fobj.Line(node.Pos()), fobj.Line(node.End()) + line := strconv.Itoa(start) + if start != end { + line = fmt.Sprintf("%d-%d", start, end) + } + return line +} diff --git a/vendor/github.com/securego/gosec/v2/report/html/template.html b/vendor/github.com/securego/gosec/v2/report/html/template.html index 3a63f068f..53a6b36ce 100644 --- a/vendor/github.com/securego/gosec/v2/report/html/template.html +++ b/vendor/github.com/securego/gosec/v2/report/html/template.html @@ -5,12 +5,12 @@ Golang Security Checker - - - + + + - +