From 1256f16f33bdd470dde161eca0aec70b97060da0 Mon Sep 17 00:00:00 2001 From: Matthieu MOREL Date: Mon, 31 May 2021 10:44:12 +0200 Subject: [PATCH] Fix lint and fail on error in the ci build --- .github/workflows/ci.yml | 1 - .golangci.yml | 30 +++++--- analyzer.go | 1 - analyzer_test.go | 7 -- call_list_test.go | 4 +- cmd/gosec/main.go | 8 +-- cmd/gosec/sort_issues.go | 1 - cmd/gosecutil/tools.go | 18 ++--- config.go | 2 +- config_test.go | 5 -- cwe/cwe_suite_test.go | 4 +- cwe/data.go | 12 ++-- cwe/data_test.go | 1 - cwe/types.go | 10 +-- gosec_suite_test.go | 4 +- helpers.go | 4 +- issue.go | 3 +- issue_test.go | 3 - report/csv/writer.go | 2 +- report/formatter_suite_test.go | 4 +- report/formatter_test.go | 8 +-- report/golint/writer.go | 2 +- report/html/writer.go | 2 +- report/json/writer.go | 2 +- report/junit/builder.go | 6 +- report/junit/formatter.go | 2 +- report/junit/types.go | 8 +-- report/junit/writer.go | 2 +- report/sarif/builder.go | 58 +++++++-------- report/sarif/data.go | 14 ++-- report/sarif/formatter.go | 3 +- report/sarif/writer.go | 2 +- report/sonar/builder.go | 6 +- report/sonar/formatter.go | 4 +- report/sonar/sonar_suite_test.go | 4 +- report/sonar/types.go | 8 +-- report/sonar/writer.go | 2 +- report/text/writer.go | 2 +- report/yaml/writer.go | 2 +- resolve_test.go | 1 - rule_test.go | 5 -- rules/bad_defer.go | 1 - rules/fileperms.go | 2 +- rules/hardcoded_credentials.go | 2 +- rules/rand.go | 6 +- rules/rules_suite_test.go | 4 +- rules/rules_test.go | 3 - rules/sql.go | 16 ++--- rules/templates.go | 1 - rules/tls.go | 1 - testutils/source.go | 118 +++++++++++++++++++++---------- 51 files changed, 218 insertions(+), 203 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ee47638..e3046a1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -20,7 +20,6 @@ jobs: ${{ runner.os }}-go- - name: golangci-lint uses: golangci/golangci-lint-action@v2 - continue-on-error: true with: version: latest test: diff --git a/.golangci.yml b/.golangci.yml index 55371b2..dcda646 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,13 +1,23 @@ linters: enable: - - megacheck - - govet - - unparam - - unconvert - - misspell - - gofmt - - golint - - gosec - - nakedret - - dogsled + - asciicheck + - bodyclose - depguard + - dogsled + - durationcheck + - errcheck + - exportloopref + - gofmt + - gofumpt + - goimports + - gosec + - govet + - importas + - megacheck + - misspell + - nakedret + - nolintlint + - revive + - unconvert + - unparam + - wastedassign \ No newline at end of file diff --git a/analyzer.go b/analyzer.go index d4aae3a..f669d5a 100644 --- a/analyzer.go +++ b/analyzer.go @@ -28,7 +28,6 @@ import ( "reflect" "regexp" "strconv" - "strings" "golang.org/x/tools/go/packages" diff --git a/analyzer_test.go b/analyzer_test.go index 4c6fc91..6eeb87b 100644 --- a/analyzer_test.go +++ b/analyzer_test.go @@ -17,7 +17,6 @@ import ( ) var _ = Describe("Analyzer", func() { - var ( analyzer *gosec.Analyzer logger *log.Logger @@ -30,7 +29,6 @@ var _ = Describe("Analyzer", func() { }) Context("when processing a package", func() { - It("should not report an error if the package contains no Go files", func() { analyzer.LoadRules(rules.Generate().Builders()) dir, err := ioutil.TempDir("", "empty") @@ -118,7 +116,6 @@ var _ = Describe("Analyzer", func() { Expect(err).ShouldNot(HaveOccurred()) controlIssues, _, _ := analyzer.Report() Expect(controlIssues).Should(HaveLen(sample.Errors)) - }) It("should report Go build errors and invalid files", func() { @@ -262,7 +259,6 @@ var _ = Describe("Analyzer", func() { Expect(err).ShouldNot(HaveOccurred()) nosecIssues, _, _ := customAnalyzer.Report() Expect(nosecIssues).Should(HaveLen(sample.Errors)) - }) It("should be possible to use an alternative nosec tag", func() { @@ -286,7 +282,6 @@ var _ = Describe("Analyzer", func() { Expect(err).ShouldNot(HaveOccurred()) nosecIssues, _, _ := customAnalyzer.Report() Expect(nosecIssues).Should(HaveLen(0)) - }) It("should ignore vulnerabilities when the default tag is found", func() { @@ -310,7 +305,6 @@ var _ = Describe("Analyzer", func() { Expect(err).ShouldNot(HaveOccurred()) nosecIssues, _, _ := customAnalyzer.Report() Expect(nosecIssues).Should(HaveLen(0)) - }) It("should be able to analyze Go test package", func() { @@ -356,7 +350,6 @@ var _ = Describe("Analyzer", func() { }) Context("when parsing errors from a package", func() { - It("should return no error when the error list is empty", func() { pkg := &packages.Package{} err := analyzer.ParseErrors(pkg) diff --git a/call_list_test.go b/call_list_test.go index f3668bd..6400234 100644 --- a/call_list_test.go +++ b/call_list_test.go @@ -10,9 +10,7 @@ import ( ) var _ = Describe("Call List", func() { - var ( - calls gosec.CallList - ) + var calls gosec.CallList BeforeEach(func() { calls = gosec.NewCallList() }) diff --git a/cmd/gosec/main.go b/cmd/gosec/main.go index 7524579..af0427a 100644 --- a/cmd/gosec/main.go +++ b/cmd/gosec/main.go @@ -120,7 +120,7 @@ var ( // stdout the results as well as write it in the output file flagStdOut = flag.Bool("stdout", false, "Stdout the results as well as write it in the output file") - //print the text report with color, this is enabled by default + // print the text report with color, this is enabled by default flagColor = flag.Bool("color", true, "Prints the text format report with colorization when it goes in the stdout") // overrides the output format when stdout the results while saving them in the output file @@ -209,7 +209,7 @@ func getRootPaths(paths []string) []string { } func getPrintedFormat(format string, verbose string) string { - var fileFormat = format + fileFormat := format if format != "" && verbose != "" { fileFormat = verbose } @@ -217,7 +217,6 @@ func getPrintedFormat(format string, verbose string) string { } func printReport(format string, color bool, rootPaths []string, reportInfo *gosec.ReportInfo) error { - err := report.CreateReport(os.Stdout, format, color, rootPaths, reportInfo) if err != nil { return err @@ -226,7 +225,6 @@ func printReport(format string, color bool, rootPaths []string, reportInfo *gose } func saveReport(filename, format string, rootPaths []string, reportInfo *gosec.ReportInfo) error { - outfile, err := os.Create(filename) if err != nil { return err @@ -386,7 +384,7 @@ func main() { reportInfo := gosec.NewReportInfo(issues, metrics, errors).WithVersion(Version) if *flagOutput == "" || *flagStdOut { - var fileFormat = getPrintedFormat(*flagOutput, *flagVerbose) + fileFormat := getPrintedFormat(*flagOutput, *flagVerbose) if err := printReport(fileFormat, *flagColor, rootPaths, reportInfo); err != nil { logger.Fatal((err)) } diff --git a/cmd/gosec/sort_issues.go b/cmd/gosec/sort_issues.go index ef27425..3d661e2 100644 --- a/cmd/gosec/sort_issues.go +++ b/cmd/gosec/sort_issues.go @@ -12,7 +12,6 @@ import ( func extractLineNumber(s string) int { lineNumber, _ := strconv.Atoi(strings.Split(s, "-")[0]) return lineNumber - } type sortBySeverity []*gosec.Issue diff --git a/cmd/gosecutil/tools.go b/cmd/gosecutil/tools.go index 23146c1..11d36c6 100644 --- a/cmd/gosecutil/tools.go +++ b/cmd/gosecutil/tools.go @@ -26,11 +26,13 @@ import ( "strings" ) -type command func(args ...string) -type utilities struct { - commands map[string]command - call []string -} +type ( + command func(args ...string) + utilities struct { + commands map[string]command + call []string + } +) // Custom commands / utilities to run instead of default analyzer func newUtils() *utilities { @@ -58,7 +60,6 @@ func (u *utilities) String() string { func (u *utilities) Set(opt string) error { if _, ok := u.commands[opt]; !ok { return fmt.Errorf("valid tools are: %s", u.String()) - } u.call = append(u.call, opt) return nil @@ -171,7 +172,6 @@ func checkContext(ctx *context, file string) bool { } func dumpCallObj(files ...string) { - for _, file := range files { if shouldSkip(file) { continue @@ -184,9 +184,9 @@ func dumpCallObj(files ...string) { var obj types.Object switch node := n.(type) { case *ast.Ident: - obj = context.info.ObjectOf(node) //context.info.Uses[node] + obj = context.info.ObjectOf(node) // context.info.Uses[node] case *ast.SelectorExpr: - obj = context.info.ObjectOf(node.Sel) //context.info.Uses[node.Sel] + obj = context.info.ObjectOf(node.Sel) // context.info.Uses[node.Sel] default: obj = nil } diff --git a/config.go b/config.go index 5b7f739..4af62b2 100644 --- a/config.go +++ b/config.go @@ -56,7 +56,7 @@ func (c Config) convertGlobals() { // ReadFrom implements the io.ReaderFrom interface. This // should be used with io.Reader to load configuration from -//file or from string etc. +// file or from string etc. func (c Config) ReadFrom(r io.Reader) (int64, error) { data, err := ioutil.ReadAll(r) if err != nil { diff --git a/config_test.go b/config_test.go index 51f8e4e..1a470b5 100644 --- a/config_test.go +++ b/config_test.go @@ -16,7 +16,6 @@ var _ = Describe("Configuration", func() { }) Context("when loading from disk", func() { - It("should be possible to load configuration from a file", func() { json := `{"G101": {}}` buffer := bytes.NewBufferString(json) @@ -35,7 +34,6 @@ var _ = Describe("Configuration", func() { _, err = configuration.ReadFrom(emptyBuffer) Expect(err).Should(HaveOccurred()) }) - }) Context("when saving to disk", func() { @@ -49,7 +47,6 @@ var _ = Describe("Configuration", func() { }) It("should be possible to save configuration to file", func() { - configuration.Set("G101", map[string]string{ "mode": "strict", }) @@ -59,12 +56,10 @@ var _ = Describe("Configuration", func() { Expect(int(nbytes)).ShouldNot(BeZero()) Expect(err).ShouldNot(HaveOccurred()) Expect(buffer.String()).Should(Equal(`{"G101":{"mode":"strict"},"global":{}}`)) - }) }) Context("when configuring rules", func() { - It("should be possible to get configuration for a rule", func() { settings := map[string]string{ "ciphers": "AES256-GCM", diff --git a/cwe/cwe_suite_test.go b/cwe/cwe_suite_test.go index cac835a..fd5bcf6 100644 --- a/cwe/cwe_suite_test.go +++ b/cwe/cwe_suite_test.go @@ -1,10 +1,10 @@ package cwe_test import ( + "testing" + . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - - "testing" ) func TestCwe(t *testing.T) { diff --git a/cwe/data.go b/cwe/data.go index 9f37044..80bd702 100644 --- a/cwe/data.go +++ b/cwe/data.go @@ -1,15 +1,15 @@ package cwe const ( - //Acronym is the acronym of CWE + // Acronym is the acronym of CWE Acronym = "CWE" - //Version the CWE version + // Version the CWE version Version = "4.4" - //ReleaseDateUtc the release Date of CWE Version + // ReleaseDateUtc the release Date of CWE Version ReleaseDateUtc = "2021-03-15" - //Organization MITRE + // Organization MITRE Organization = "MITRE" - //Description the description of CWE + // Description the description of CWE Description = "The MITRE Common Weakness Enumeration" ) @@ -126,7 +126,7 @@ func init() { } } -//Get Retrieves a CWE weakness by it's id +// Get Retrieves a CWE weakness by it's id func Get(id string) *Weakness { weakness, ok := data[id] if ok && weakness != nil { diff --git a/cwe/data_test.go b/cwe/data_test.go index 1fd171a..453a2af 100644 --- a/cwe/data_test.go +++ b/cwe/data_test.go @@ -17,6 +17,5 @@ var _ = Describe("CWE data", func() { Expect(weakness.Name).ShouldNot(BeNil()) Expect(weakness.Description).ShouldNot(BeNil()) }) - }) }) diff --git a/cwe/types.go b/cwe/types.go index 92e7b6a..908e191 100644 --- a/cwe/types.go +++ b/cwe/types.go @@ -12,17 +12,17 @@ type Weakness struct { Description string } -//SprintURL format the CWE URL +// SprintURL format the CWE URL func (w *Weakness) SprintURL() string { return fmt.Sprintf("https://cwe.mitre.org/data/definitions/%s.html", w.ID) } -//SprintID format the CWE ID +// SprintID format the CWE ID func (w *Weakness) SprintID() string { return fmt.Sprintf("%s-%s", Acronym, w.ID) } -//MarshalJSON print only id and URL +// MarshalJSON print only id and URL func (w *Weakness) MarshalJSON() ([]byte, error) { return json.Marshal(&struct { ID string `json:"id"` @@ -33,12 +33,12 @@ func (w *Weakness) MarshalJSON() ([]byte, error) { }) } -//InformationURI link to the published CWE PDF +// InformationURI link to the published CWE PDF func InformationURI() string { return fmt.Sprintf("https://cwe.mitre.org/data/published/cwe_v%s.pdf/", Version) } -//DownloadURI link to the zipped XML of the CWE list +// DownloadURI link to the zipped XML of the CWE list func DownloadURI() string { return fmt.Sprintf("https://cwe.mitre.org/data/xml/cwec_v%s.xml.zip", Version) } diff --git a/gosec_suite_test.go b/gosec_suite_test.go index 7475c35..891c207 100644 --- a/gosec_suite_test.go +++ b/gosec_suite_test.go @@ -1,10 +1,10 @@ package gosec_test import ( + "testing" + . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - - "testing" ) func TestGosec(t *testing.T) { diff --git a/helpers.go b/helpers.go index 83dfa29..b903269 100644 --- a/helpers.go +++ b/helpers.go @@ -168,7 +168,6 @@ func GetCallInfo(n ast.Node, ctx *Context) (string, string, error) { } } } - } } case *ast.Ident: @@ -220,7 +219,6 @@ func GetIdentStringValues(ident *ast.Ident) []string { } } } - } return values } @@ -298,7 +296,7 @@ func Gopath() []string { } // Getenv returns the values of the environment variable, otherwise -//returns the default if variable is not set +// returns the default if variable is not set func Getenv(key, userDefault string) string { if val := os.Getenv(key); val != "" { return val diff --git a/issue.go b/issue.go index 166ee35..d5091fe 100644 --- a/issue.go +++ b/issue.go @@ -19,11 +19,12 @@ import ( "bytes" "encoding/json" "fmt" - "github.com/securego/gosec/v2/cwe" "go/ast" "go/token" "os" "strconv" + + "github.com/securego/gosec/v2/cwe" ) // Score type used by severity and confidence values diff --git a/issue_test.go b/issue_test.go index 12a2405..eeedefb 100644 --- a/issue_test.go +++ b/issue_test.go @@ -11,7 +11,6 @@ import ( ) var _ = Describe("Issue", func() { - Context("when creating a new issue", func() { It("should create a code snippet from the specified ast.Node", func() { var target *ast.BasicLit @@ -134,7 +133,5 @@ func main() { It("should maintain the provided confidence score", func() { Skip("Not implemented") }) - }) - }) diff --git a/report/csv/writer.go b/report/csv/writer.go index 80eff13..40bb6a1 100644 --- a/report/csv/writer.go +++ b/report/csv/writer.go @@ -7,7 +7,7 @@ import ( "github.com/securego/gosec/v2" ) -//WriteReport write a report in csv format to the output writer +// WriteReport write a report in csv format to the output writer func WriteReport(w io.Writer, data *gosec.ReportInfo) error { out := csv.NewWriter(w) defer out.Flush() diff --git a/report/formatter_suite_test.go b/report/formatter_suite_test.go index 6ffb744..063bd7a 100644 --- a/report/formatter_suite_test.go +++ b/report/formatter_suite_test.go @@ -1,10 +1,10 @@ package report import ( + "testing" + . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - - "testing" ) func TestRules(t *testing.T) { diff --git a/report/formatter_test.go b/report/formatter_test.go index 2db39f1..ee37405 100644 --- a/report/formatter_test.go +++ b/report/formatter_test.go @@ -272,15 +272,15 @@ var _ = Describe("Formatter", func() { testSuite = junitReport.Testsuites[1] Expect(testSuite.Testcases[0].Name).To(Equal(issues[1].File)) - }) }) Context("When using different report formats", func() { - - grules := []string{"G101", "G102", "G103", "G104", "G106", + grules := []string{ + "G101", "G102", "G103", "G104", "G106", "G107", "G109", "G110", "G201", "G202", "G203", "G204", "G301", "G302", "G303", "G304", "G305", "G401", "G402", - "G403", "G404", "G501", "G502", "G503", "G504", "G505"} + "G403", "G404", "G501", "G502", "G503", "G504", "G505", + } It("csv formatted report should contain the CWE mapping", func() { for _, rule := range grules { diff --git a/report/golint/writer.go b/report/golint/writer.go index 633527c..e9d0245 100644 --- a/report/golint/writer.go +++ b/report/golint/writer.go @@ -8,7 +8,7 @@ import ( "github.com/securego/gosec/v2" ) -//WriteReport write a report in golint format to the output writer +// WriteReport write a report in golint format to the output writer func WriteReport(w io.Writer, data *gosec.ReportInfo) error { // Output Sample: // /tmp/main.go:11:14: [CWE-310] RSA keys should be at least 2048 bits (Rule:G403, Severity:MEDIUM, Confidence:HIGH) diff --git a/report/html/writer.go b/report/html/writer.go index eb95929..fed01c3 100644 --- a/report/html/writer.go +++ b/report/html/writer.go @@ -7,7 +7,7 @@ import ( "github.com/securego/gosec/v2" ) -//WriteReport write a report in html format to the output writer +// WriteReport write a report in html format to the output writer func WriteReport(w io.Writer, data *gosec.ReportInfo) error { t, e := template.New("gosec").Parse(templateContent) if e != nil { diff --git a/report/json/writer.go b/report/json/writer.go index bfa87da..7c20df8 100644 --- a/report/json/writer.go +++ b/report/json/writer.go @@ -7,7 +7,7 @@ import ( "github.com/securego/gosec/v2" ) -//WriteReport write a report in json format to the output writer +// WriteReport write a report in json format to the output writer func WriteReport(w io.Writer, data *gosec.ReportInfo) error { raw, err := json.MarshalIndent(data, "", "\t") if err != nil { diff --git a/report/junit/builder.go b/report/junit/builder.go index 8a51d7a..1b1e816 100644 --- a/report/junit/builder.go +++ b/report/junit/builder.go @@ -1,13 +1,13 @@ package junit -//NewTestsuite instantiate a Testsuite +// NewTestsuite instantiate a Testsuite func NewTestsuite(name string) *Testsuite { return &Testsuite{ Name: name, } } -//NewFailure instantiate a Failure +// NewFailure instantiate a Failure func NewFailure(message string, text string) *Failure { return &Failure{ Message: message, @@ -15,7 +15,7 @@ func NewFailure(message string, text string) *Failure { } } -//NewTestcase instantiate a Testcase +// NewTestcase instantiate a Testcase func NewTestcase(name string, failure *Failure) *Testcase { return &Testcase{ Name: name, diff --git a/report/junit/formatter.go b/report/junit/formatter.go index a5758de..187c854 100644 --- a/report/junit/formatter.go +++ b/report/junit/formatter.go @@ -15,7 +15,7 @@ func generatePlaintext(issue *gosec.Issue) string { ", CWE: " + issue.Cwe.ID + ")\n" + "> " + html.EscapeString(issue.Code) } -//GenerateReport Convert a gosec report to a JUnit Report +// GenerateReport Convert a gosec report to a JUnit Report func GenerateReport(data *gosec.ReportInfo) Report { var xmlReport Report testsuites := map[string]int{} diff --git a/report/junit/types.go b/report/junit/types.go index cc36e92..bac3218 100644 --- a/report/junit/types.go +++ b/report/junit/types.go @@ -4,13 +4,13 @@ import ( "encoding/xml" ) -//Report defines a JUnit XML report +// Report defines a JUnit XML report type Report struct { XMLName xml.Name `xml:"testsuites"` Testsuites []*Testsuite `xml:"testsuite"` } -//Testsuite defines a JUnit testsuite +// Testsuite defines a JUnit testsuite type Testsuite struct { XMLName xml.Name `xml:"testsuite"` Name string `xml:"name,attr"` @@ -18,14 +18,14 @@ type Testsuite struct { Testcases []*Testcase `xml:"testcase"` } -//Testcase defines a JUnit testcase +// Testcase defines a JUnit testcase type Testcase struct { XMLName xml.Name `xml:"testcase"` Name string `xml:"name,attr"` Failure *Failure `xml:"failure"` } -//Failure defines a JUnit failure +// Failure defines a JUnit failure type Failure struct { XMLName xml.Name `xml:"failure"` Message string `xml:"message,attr"` diff --git a/report/junit/writer.go b/report/junit/writer.go index 3b9461e..f16ed12 100644 --- a/report/junit/writer.go +++ b/report/junit/writer.go @@ -7,7 +7,7 @@ import ( "github.com/securego/gosec/v2" ) -//WriteReport write a report in JUnit format to the output writer +// WriteReport write a report in JUnit format to the output writer func WriteReport(w io.Writer, data *gosec.ReportInfo) error { junitXMLStruct := GenerateReport(data) raw, err := xml.MarshalIndent(junitXMLStruct, "", "\t") diff --git a/report/sarif/builder.go b/report/sarif/builder.go index a4f9cca..8845d7f 100644 --- a/report/sarif/builder.go +++ b/report/sarif/builder.go @@ -1,6 +1,6 @@ package sarif -//NewReport instantiate a SARIF Report +// NewReport instantiate a SARIF Report func NewReport(version string, schema string) *Report { return &Report{ Version: version, @@ -8,46 +8,46 @@ func NewReport(version string, schema string) *Report { } } -//WithRuns dafines runs for the current report +// WithRuns dafines runs for the current report func (r *Report) WithRuns(runs ...*Run) *Report { r.Runs = runs return r } -//NewMultiformatMessageString instantiate a MultiformatMessageString +// NewMultiformatMessageString instantiate a MultiformatMessageString func NewMultiformatMessageString(text string) *MultiformatMessageString { return &MultiformatMessageString{ Text: text, } } -//NewRun instantiate a Run +// NewRun instantiate a Run func NewRun(tool *Tool) *Run { return &Run{ Tool: tool, } } -//WithTaxonomies set the taxonomies for the current run +// WithTaxonomies set the taxonomies for the current run func (r *Run) WithTaxonomies(taxonomies ...*ToolComponent) *Run { r.Taxonomies = taxonomies return r } -//WithResults set the results for the current run +// WithResults set the results for the current run func (r *Run) WithResults(results ...*Result) *Run { r.Results = results return r } -//NewArtifactLocation instantiate an ArtifactLocation +// NewArtifactLocation instantiate an ArtifactLocation func NewArtifactLocation(uri string) *ArtifactLocation { return &ArtifactLocation{ URI: uri, } } -//NewRegion instantiate a Region +// NewRegion instantiate a Region func NewRegion(startLine int, endLine int, startColumn int, endColumn int, sourceLanguage string) *Region { return &Region{ StartLine: startLine, @@ -58,27 +58,27 @@ func NewRegion(startLine int, endLine int, startColumn int, endColumn int, sourc } } -//WithSnippet defines the Snippet for the current Region +// WithSnippet defines the Snippet for the current Region func (r *Region) WithSnippet(snippet *ArtifactContent) *Region { r.Snippet = snippet return r } -//NewArtifactContent instantiate an ArtifactContent +// NewArtifactContent instantiate an ArtifactContent func NewArtifactContent(text string) *ArtifactContent { return &ArtifactContent{ Text: text, } } -//NewTool instantiate a Tool +// NewTool instantiate a Tool func NewTool(driver *ToolComponent) *Tool { return &Tool{ Driver: driver, } } -//NewResult instantiate a Result +// NewResult instantiate a Result func NewResult(ruleID string, ruleIndex int, level Level, message string) *Result { return &Result{ RuleID: ruleID, @@ -88,27 +88,27 @@ func NewResult(ruleID string, ruleIndex int, level Level, message string) *Resul } } -//NewMessage instantiate a Message +// NewMessage instantiate a Message func NewMessage(text string) *Message { return &Message{ Text: text, } } -//WithLocations define the current result's locations +// WithLocations define the current result's locations func (r *Result) WithLocations(locations ...*Location) *Result { r.Locations = locations return r } -//NewLocation instantiate a Location +// NewLocation instantiate a Location func NewLocation(physicalLocation *PhysicalLocation) *Location { return &Location{ PhysicalLocation: physicalLocation, } } -//NewPhysicalLocation instantiate a PhysicalLocation +// NewPhysicalLocation instantiate a PhysicalLocation func NewPhysicalLocation(artifactLocation *ArtifactLocation, region *Region) *PhysicalLocation { return &PhysicalLocation{ ArtifactLocation: artifactLocation, @@ -116,7 +116,7 @@ func NewPhysicalLocation(artifactLocation *ArtifactLocation, region *Region) *Ph } } -//NewToolComponent instantiate a ToolComponent +// NewToolComponent instantiate a ToolComponent func NewToolComponent(name string, version string, informationURI string) *ToolComponent { return &ToolComponent{ Name: name, @@ -126,73 +126,73 @@ func NewToolComponent(name string, version string, informationURI string) *ToolC } } -//WithLanguage set Language for the current ToolComponent +// WithLanguage set Language for the current ToolComponent func (t *ToolComponent) WithLanguage(language string) *ToolComponent { t.Language = language return t } -//WithSemanticVersion set SemanticVersion for the current ToolComponent +// WithSemanticVersion set SemanticVersion for the current ToolComponent func (t *ToolComponent) WithSemanticVersion(semanticVersion string) *ToolComponent { t.SemanticVersion = semanticVersion return t } -//WithReleaseDateUtc set releaseDateUtc for the current ToolComponent +// WithReleaseDateUtc set releaseDateUtc for the current ToolComponent func (t *ToolComponent) WithReleaseDateUtc(releaseDateUtc string) *ToolComponent { t.ReleaseDateUtc = releaseDateUtc return t } -//WithDownloadURI set downloadURI for the current ToolComponent +// WithDownloadURI set downloadURI for the current ToolComponent func (t *ToolComponent) WithDownloadURI(downloadURI string) *ToolComponent { t.DownloadURI = downloadURI return t } -//WithOrganization set organization for the current ToolComponent +// WithOrganization set organization for the current ToolComponent func (t *ToolComponent) WithOrganization(organization string) *ToolComponent { t.Organization = organization return t } -//WithShortDescription set shortDescription for the current ToolComponent +// WithShortDescription set shortDescription for the current ToolComponent func (t *ToolComponent) WithShortDescription(shortDescription *MultiformatMessageString) *ToolComponent { t.ShortDescription = shortDescription return t } -//WithIsComprehensive set isComprehensive for the current ToolComponent +// WithIsComprehensive set isComprehensive for the current ToolComponent func (t *ToolComponent) WithIsComprehensive(isComprehensive bool) *ToolComponent { t.IsComprehensive = isComprehensive return t } -//WithMinimumRequiredLocalizedDataSemanticVersion set MinimumRequiredLocalizedDataSemanticVersion for the current ToolComponent +// WithMinimumRequiredLocalizedDataSemanticVersion set MinimumRequiredLocalizedDataSemanticVersion for the current ToolComponent func (t *ToolComponent) WithMinimumRequiredLocalizedDataSemanticVersion(minimumRequiredLocalizedDataSemanticVersion string) *ToolComponent { t.MinimumRequiredLocalizedDataSemanticVersion = minimumRequiredLocalizedDataSemanticVersion return t } -//WithTaxa set taxa for the current ToolComponent +// WithTaxa set taxa for the current ToolComponent func (t *ToolComponent) WithTaxa(taxa ...*ReportingDescriptor) *ToolComponent { t.Taxa = taxa return t } -//WithSupportedTaxonomies set the supported taxonomies for the current ToolComponent +// WithSupportedTaxonomies set the supported taxonomies for the current ToolComponent func (t *ToolComponent) WithSupportedTaxonomies(supportedTaxonomies ...*ToolComponentReference) *ToolComponent { t.SupportedTaxonomies = supportedTaxonomies return t } -//WithRules set the rules for the current ToolComponent +// WithRules set the rules for the current ToolComponent func (t *ToolComponent) WithRules(rules ...*ReportingDescriptor) *ToolComponent { t.Rules = rules return t } -//NewToolComponentReference instantiate a ToolComponentReference +// NewToolComponentReference instantiate a ToolComponentReference func NewToolComponentReference(name string) *ToolComponentReference { return &ToolComponentReference{ Name: name, diff --git a/report/sarif/data.go b/report/sarif/data.go index da4bcb3..a0e6611 100644 --- a/report/sarif/data.go +++ b/report/sarif/data.go @@ -1,22 +1,22 @@ package sarif -//Level SARIF level +// Level SARIF level // From https://docs.oasis-open.org/sarif/sarif/v2.0/csprd02/sarif-v2.0-csprd02.html#_Toc10127839 type Level string const ( - //None : The concept of “severity” does not apply to this result because the kind + // None : The concept of “severity” does not apply to this result because the kind // property (§3.27.9) has a value other than "fail". None = Level("none") - //Note : The rule specified by ruleId was evaluated and a minor problem or an opportunity + // Note : The rule specified by ruleId was evaluated and a minor problem or an opportunity // to improve the code was found. Note = Level("note") - //Warning : The rule specified by ruleId was evaluated and a problem was found. + // Warning : The rule specified by ruleId was evaluated and a problem was found. Warning = Level("warning") - //Error : The rule specified by ruleId was evaluated and a serious problem was found. + // Error : The rule specified by ruleId was evaluated and a serious problem was found. Error = Level("error") - //Version : SARIF Schema version + // Version : SARIF Schema version Version = "2.1.0" - //Schema : SARIF Schema URL + // Schema : SARIF Schema URL Schema = "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json" ) diff --git a/report/sarif/formatter.go b/report/sarif/formatter.go index 38d19b3..b9bcd7c 100644 --- a/report/sarif/formatter.go +++ b/report/sarif/formatter.go @@ -12,9 +12,8 @@ import ( "github.com/securego/gosec/v2/cwe" ) -//GenerateReport Convert a gosec report to a Sarif Report +// GenerateReport Convert a gosec report to a Sarif Report func GenerateReport(rootPaths []string, data *gosec.ReportInfo) (*Report, error) { - type rule struct { index int rule *ReportingDescriptor diff --git a/report/sarif/writer.go b/report/sarif/writer.go index cad6b9b..402b1e3 100644 --- a/report/sarif/writer.go +++ b/report/sarif/writer.go @@ -7,7 +7,7 @@ import ( "github.com/securego/gosec/v2" ) -//WriteReport write a report in SARIF format to the output writer +// WriteReport write a report in SARIF format to the output writer func WriteReport(w io.Writer, data *gosec.ReportInfo, rootPaths []string) error { sr, err := GenerateReport(rootPaths, data) if err != nil { diff --git a/report/sonar/builder.go b/report/sonar/builder.go index da455af..a55c8ca 100644 --- a/report/sonar/builder.go +++ b/report/sonar/builder.go @@ -1,6 +1,6 @@ package sonar -//NewLocation instantiate a Location +// NewLocation instantiate a Location func NewLocation(message string, filePath string, textRange *TextRange) *Location { return &Location{ Message: message, @@ -9,7 +9,7 @@ func NewLocation(message string, filePath string, textRange *TextRange) *Locatio } } -//NewTextRange instantiate a TextRange +// NewTextRange instantiate a TextRange func NewTextRange(startLine int, endLine int) *TextRange { return &TextRange{ StartLine: startLine, @@ -17,7 +17,7 @@ func NewTextRange(startLine int, endLine int) *TextRange { } } -//NewIssue instantiate an Issue +// NewIssue instantiate an Issue func NewIssue(engineID string, ruleID string, primaryLocation *Location, issueType string, severity string, effortMinutes int) *Issue { return &Issue{ EngineID: engineID, diff --git a/report/sonar/formatter.go b/report/sonar/formatter.go index 4cae178..5d1e59f 100644 --- a/report/sonar/formatter.go +++ b/report/sonar/formatter.go @@ -8,11 +8,11 @@ import ( ) const ( - //EffortMinutes effort to fix in minutes + // EffortMinutes effort to fix in minutes EffortMinutes = 5 ) -//GenerateReport Convert a gosec report to a Sonar Report +// GenerateReport Convert a gosec report to a Sonar Report func GenerateReport(rootPaths []string, data *gosec.ReportInfo) (*Report, error) { si := &Report{Issues: []*Issue{}} for _, issue := range data.Issues { diff --git a/report/sonar/sonar_suite_test.go b/report/sonar/sonar_suite_test.go index e7ab188..c8eb3d7 100644 --- a/report/sonar/sonar_suite_test.go +++ b/report/sonar/sonar_suite_test.go @@ -1,10 +1,10 @@ package sonar_test import ( + "testing" + . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - - "testing" ) func TestRules(t *testing.T) { diff --git a/report/sonar/types.go b/report/sonar/types.go index bf12a38..c29eb7e 100644 --- a/report/sonar/types.go +++ b/report/sonar/types.go @@ -1,6 +1,6 @@ package sonar -//TextRange defines the text range of an issue's location +// TextRange defines the text range of an issue's location type TextRange struct { StartLine int `json:"startLine"` EndLine int `json:"endLine"` @@ -8,14 +8,14 @@ type TextRange struct { EtartColumn int `json:"endColumn,omitempty"` } -//Location defines a sonar issue's location +// Location defines a sonar issue's location type Location struct { Message string `json:"message"` FilePath string `json:"filePath"` TextRange *TextRange `json:"textRange,omitempty"` } -//Issue defines a sonar issue +// Issue defines a sonar issue type Issue struct { EngineID string `json:"engineId"` RuleID string `json:"ruleId"` @@ -26,7 +26,7 @@ type Issue struct { SecondaryLocations []*Location `json:"secondaryLocations,omitempty"` } -//Report defines a sonar report +// Report defines a sonar report type Report struct { Issues []*Issue `json:"issues"` } diff --git a/report/sonar/writer.go b/report/sonar/writer.go index 74fda43..bf5ea53 100644 --- a/report/sonar/writer.go +++ b/report/sonar/writer.go @@ -7,7 +7,7 @@ import ( "github.com/securego/gosec/v2" ) -//WriteReport write a report in sonar format to the output writer +// WriteReport write a report in sonar format to the output writer func WriteReport(w io.Writer, data *gosec.ReportInfo, rootPaths []string) error { si, err := GenerateReport(rootPaths, data) if err != nil { diff --git a/report/text/writer.go b/report/text/writer.go index 840b738..614ffa1 100644 --- a/report/text/writer.go +++ b/report/text/writer.go @@ -19,7 +19,7 @@ var ( defaultTheme = color.New(color.FgWhite, color.BgBlack) ) -//WriteReport write a (colorized) report in text format +// WriteReport write a (colorized) report in text format func WriteReport(w io.Writer, data *gosec.ReportInfo, enableColor bool) error { t, e := template. New("gosec"). diff --git a/report/yaml/writer.go b/report/yaml/writer.go index 1617f08..73d7e06 100644 --- a/report/yaml/writer.go +++ b/report/yaml/writer.go @@ -7,7 +7,7 @@ import ( "gopkg.in/yaml.v2" ) -//WriteReport write a report in yaml format to the output writer +// WriteReport write a report in yaml format to the output writer func WriteReport(w io.Writer, data *gosec.ReportInfo) error { raw, err := yaml.Marshal(data) if err != nil { diff --git a/resolve_test.go b/resolve_test.go index 6e6c261..d1d0c98 100644 --- a/resolve_test.go +++ b/resolve_test.go @@ -336,6 +336,5 @@ var _ = Describe("Resolve ast node to concrete value", func() { Expect(value).ShouldNot(BeNil()) Expect(gosec.TryResolve(value, ctx)).Should(BeFalse()) }) - }) }) diff --git a/rule_test.go b/rule_test.go index 67cb4e2..074429f 100644 --- a/rule_test.go +++ b/rule_test.go @@ -27,9 +27,7 @@ func (m *mockrule) Match(n ast.Node, ctx *gosec.Context) (*gosec.Issue, error) { } var _ = Describe("Rule", func() { - Context("when using a ruleset", func() { - var ( ruleset gosec.RuleSet dummyErrorRule gosec.Rule @@ -65,7 +63,6 @@ var _ = Describe("Rule", func() { Expect(ruleset.RegisteredFor(unregisteredNode)).Should(BeEmpty()) Expect(ruleset.RegisteredFor(registeredNodeA)).Should(ContainElement(dummyIssueRule)) Expect(ruleset.RegisteredFor(registeredNodeB)).Should(ContainElement(dummyIssueRule)) - }) It("should not register a rule when no ast.Nodes are specified", func() { @@ -83,7 +80,5 @@ var _ = Describe("Rule", func() { Expect(ruleset.RegisteredFor(registeredNode)).Should(ContainElement(dummyErrorRule)) Expect(ruleset.RegisteredFor(registeredNode)).Should(ContainElement(dummyIssueRule)) }) - }) - }) diff --git a/rules/bad_defer.go b/rules/bad_defer.go index b33a047..13b4207 100644 --- a/rules/bad_defer.go +++ b/rules/bad_defer.go @@ -44,7 +44,6 @@ func (r *badDefer) Match(n ast.Node, c *gosec.Context) (*gosec.Issue, error) { } } } - } return nil, nil diff --git a/rules/fileperms.go b/rules/fileperms.go index f45dd60..e6a80a5 100644 --- a/rules/fileperms.go +++ b/rules/fileperms.go @@ -34,7 +34,7 @@ func (r *filePermissions) ID() string { } func getConfiguredMode(conf map[string]interface{}, configKey string, defaultMode int64) int64 { - var mode = defaultMode + mode := defaultMode if value, ok := conf[configKey]; ok { switch value := value.(type) { case int64: diff --git a/rules/hardcoded_credentials.go b/rules/hardcoded_credentials.go index 6b360c5..acdd583 100644 --- a/rules/hardcoded_credentials.go +++ b/rules/hardcoded_credentials.go @@ -121,7 +121,7 @@ func NewHardcodedCredentials(id string, conf gosec.Config) (gosec.Rule, []ast.No entropyThreshold := 80.0 perCharThreshold := 3.0 ignoreEntropy := false - var truncateString = 16 + truncateString := 16 if val, ok := conf["G101"]; ok { conf := val.(map[string]interface{}) if configPattern, ok := conf["pattern"]; ok { diff --git a/rules/rand.go b/rules/rand.go index bf86b76..055adce 100644 --- a/rules/rand.go +++ b/rules/rand.go @@ -43,8 +43,10 @@ func (w *weakRand) Match(n ast.Node, c *gosec.Context) (*gosec.Issue, error) { // NewWeakRandCheck detects the use of random number generator that isn't cryptographically secure func NewWeakRandCheck(id string, conf gosec.Config) (gosec.Rule, []ast.Node) { return &weakRand{ - funcNames: []string{"New", "Read", "Float32", "Float64", "Int", "Int31", - "Int31n", "Int63", "Int63n", "Intn", "NormalFloat64", "Uint32", "Uint64"}, + funcNames: []string{ + "New", "Read", "Float32", "Float64", "Int", "Int31", + "Int31n", "Int63", "Int63n", "Intn", "NormalFloat64", "Uint32", "Uint64", + }, packagePath: "math/rand", MetaData: gosec.MetaData{ ID: id, diff --git a/rules/rules_suite_test.go b/rules/rules_suite_test.go index 51a204e..73cd9cf 100644 --- a/rules/rules_suite_test.go +++ b/rules/rules_suite_test.go @@ -1,10 +1,10 @@ package rules_test import ( + "testing" + . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - - "testing" ) func TestRules(t *testing.T) { diff --git a/rules/rules_test.go b/rules/rules_test.go index f1c80b7..d13802b 100644 --- a/rules/rules_test.go +++ b/rules/rules_test.go @@ -13,7 +13,6 @@ import ( ) var _ = Describe("gosec rules", func() { - var ( logger *log.Logger config gosec.Config @@ -179,7 +178,5 @@ var _ = Describe("gosec rules", func() { It("should detect implicit aliasing in ForRange", func() { runner("G601", testutils.SampleCodeG601) }) - }) - }) diff --git a/rules/sql.go b/rules/sql.go index 127dec5..8a5b638 100644 --- a/rules/sql.go +++ b/rules/sql.go @@ -186,7 +186,7 @@ func (s *sqlStrFormat) checkQuery(call *ast.CallExpr, ctx *gosec.Context) (*gose decl := ident.Obj.Decl if assign, ok := decl.(*ast.AssignStmt); ok { for _, expr := range assign.Rhs { - issue, err := s.checkFormatting(expr, ctx) + issue := s.checkFormatting(expr, ctx) if issue != nil { return issue, err } @@ -197,7 +197,7 @@ func (s *sqlStrFormat) checkQuery(call *ast.CallExpr, ctx *gosec.Context) (*gose return nil, nil } -func (s *sqlStrFormat) checkFormatting(n ast.Node, ctx *gosec.Context) (*gosec.Issue, error) { +func (s *sqlStrFormat) checkFormatting(n ast.Node, ctx *gosec.Context) *gosec.Issue { // argIndex changes the function argument which gets matched to the regex argIndex := 0 if node := s.fmtCalls.ContainsPkgCallExpr(n, ctx, false); node != nil { @@ -208,7 +208,7 @@ func (s *sqlStrFormat) checkFormatting(n ast.Node, ctx *gosec.Context) (*gosec.I if arg, ok := node.Args[0].(*ast.SelectorExpr); ok { if ident, ok := arg.X.(*ast.Ident); ok { if s.noIssue.Contains(ident.Name, arg.Sel.Name) { - return nil, nil + return nil } } } @@ -219,7 +219,7 @@ func (s *sqlStrFormat) checkFormatting(n ast.Node, ctx *gosec.Context) (*gosec.I // no formatter if len(node.Args) == 0 { - return nil, nil + return nil } var formatter string @@ -233,7 +233,7 @@ func (s *sqlStrFormat) checkFormatting(n ast.Node, ctx *gosec.Context) (*gosec.I formatter = arg } if len(formatter) <= 0 { - return nil, nil + return nil } // If all formatter args are quoted or constant, then the SQL construction is safe @@ -246,14 +246,14 @@ func (s *sqlStrFormat) checkFormatting(n ast.Node, ctx *gosec.Context) (*gosec.I } } if allSafe { - return nil, nil + return nil } } if s.MatchPatterns(formatter) { - return gosec.NewIssue(ctx, n, s.ID(), s.What, s.Severity, s.Confidence), nil + return gosec.NewIssue(ctx, n, s.ID(), s.What, s.Severity, s.Confidence) } } - return nil, nil + return nil } // Check SQL query formatting issues such as "fmt.Sprintf("SELECT * FROM foo where '%s', userInput)" diff --git a/rules/templates.go b/rules/templates.go index 8192409..b9e7bb7 100644 --- a/rules/templates.go +++ b/rules/templates.go @@ -43,7 +43,6 @@ func (t *templateCheck) Match(n ast.Node, c *gosec.Context) (*gosec.Issue, error // NewTemplateCheck constructs the template check rule. This rule is used to // find use of templates where HTML/JS escaping is not being used func NewTemplateCheck(id string, conf gosec.Config) (gosec.Rule, []ast.Node) { - calls := gosec.NewCallList() calls.Add("html/template", "HTML") calls.Add("html/template", "HTMLAttr") diff --git a/rules/tls.go b/rules/tls.go index dc0ab6a..219d8fc 100644 --- a/rules/tls.go +++ b/rules/tls.go @@ -112,7 +112,6 @@ func (t *insecureConfigTLS) processTLSConfVal(n *ast.KeyValueExpr, c *gosec.Cont } } - } return nil } diff --git a/testutils/source.go b/testutils/source.go index b625cce..e30516a 100644 --- a/testutils/source.go +++ b/testutils/source.go @@ -11,14 +11,16 @@ type CodeSample struct { var ( // SampleCodeG101 code snippets for hardcoded credentials - SampleCodeG101 = []CodeSample{{[]string{` + SampleCodeG101 = []CodeSample{ + {[]string{` package main import "fmt" func main() { username := "admin" password := "f62e5bcda4fae4f82370da0c6f20697b8f8447ef" fmt.Println("Doing something with: ", username, password) -}`}, 1, gosec.NewConfig()}, {[]string{` +}`}, 1, gosec.NewConfig()}, + {[]string{` // Entropy check should not report this error by default package main import "fmt" @@ -26,21 +28,24 @@ func main() { username := "admin" password := "secret" fmt.Println("Doing something with: ", username, password) -}`}, 0, gosec.NewConfig()}, {[]string{` +}`}, 0, gosec.NewConfig()}, + {[]string{` package main import "fmt" var password = "f62e5bcda4fae4f82370da0c6f20697b8f8447ef" func main() { username := "admin" fmt.Println("Doing something with: ", username, password) -}`}, 1, gosec.NewConfig()}, {[]string{` +}`}, 1, gosec.NewConfig()}, + {[]string{` package main import "fmt" const password = "f62e5bcda4fae4f82370da0c6f20697b8f8447ef" func main() { username := "admin" fmt.Println("Doing something with: ", username, password) -}`}, 1, gosec.NewConfig()}, {[]string{` +}`}, 1, gosec.NewConfig()}, + {[]string{` package main import "fmt" const ( @@ -49,12 +54,14 @@ const ( ) func main() { fmt.Println("Doing something with: ", username, password) -}`}, 1, gosec.NewConfig()}, {[]string{` +}`}, 1, gosec.NewConfig()}, + {[]string{` package main var password string func init() { password = "f62e5bcda4fae4f82370da0c6f20697b8f8447ef" -}`}, 1, gosec.NewConfig()}, {[]string{` +}`}, 1, gosec.NewConfig()}, + {[]string{` package main const ( ATNStateSomethingElse = 1 @@ -62,7 +69,8 @@ const ( ) func main() { println(ATNStateTokenStart) -}`}, 0, gosec.NewConfig()}, {[]string{` +}`}, 0, gosec.NewConfig()}, + {[]string{` package main const ( ATNStateTokenStart = "f62e5bcda4fae4f82370da0c6f20697b8f8447ef" @@ -96,7 +104,8 @@ func main() { if p != "f62e5bcda4fae4f82370da0c6f20697b8f8447ef" { fmt.Println("password equality") } -}`}, 0, gosec.NewConfig()}} +}`}, 0, gosec.NewConfig()}, + } // SampleCodeG102 code snippets for network binding SampleCodeG102 = []CodeSample{ @@ -201,7 +210,8 @@ func main() { addressHolder := uintptr(unsafe.Pointer(intPtr)) + unsafe.Sizeof(intArray[0]) intPtr = (*int)(unsafe.Pointer(addressHolder)) fmt.Printf("\nintPtr=%p, *intPtr=%d.\n\n", intPtr, *intPtr) -}`}, 3, gosec.NewConfig()}} +}`}, 3, gosec.NewConfig()}, + } // SampleCodeG104 finds errors that aren't being handled SampleCodeG104 = []CodeSample{ @@ -314,7 +324,8 @@ func main() { createBuffer().WriteString("*bytes.Buffer") b := createBuffer() b.WriteString("*bytes.Buffer") -}`}, 0, gosec.NewConfig()}} // it shoudn't return any errors because all method calls are whitelisted by default +}`}, 0, gosec.NewConfig()}, + } // it shoudn't return any errors because all method calls are whitelisted by default // SampleCodeG104Audit finds errors that aren't being handled in audit mode SampleCodeG104Audit = []CodeSample{ @@ -372,7 +383,8 @@ func main() { }`, ` package main func dummy(){} -`}, 0, gosec.Config{gosec.Globals: map[gosec.GlobalOption]string{gosec.Audit: "enabled"}}}} +`}, 0, gosec.Config{gosec.Globals: map[gosec.GlobalOption]string{gosec.Audit: "enabled"}}}, + } // SampleCodeG106 - ssh InsecureIgnoreHostKey SampleCodeG106 = []CodeSample{{[]string{` @@ -675,7 +687,8 @@ func main() { } v := int32(value) fmt.Println(v) -}`}, 0, gosec.NewConfig()}} +}`}, 0, gosec.NewConfig()}, + } // SampleCodeG110 - potential DoS vulnerability via decompression bomb SampleCodeG110 = []CodeSample{ @@ -791,7 +804,8 @@ func main() { if err != nil { panic(err) } -}`}, 0, gosec.NewConfig()}} +}`}, 0, gosec.NewConfig()}, + } // SampleCodeG201 - SQL injection via format string SampleCodeG201 = []CodeSample{ @@ -971,7 +985,8 @@ import ( func main(){ fmt.Sprintln() -}`}, 0, gosec.NewConfig()}} +}`}, 0, gosec.NewConfig()}, + } // SampleCodeG202 - SQL query string building via string concatenation SampleCodeG202 = []CodeSample{ @@ -1125,7 +1140,8 @@ func main(){ } defer rows.Close() } -`}, 0, gosec.NewConfig()}} +`}, 0, gosec.NewConfig()}, + } // SampleCodeG203 - Template checks SampleCodeG203 = []CodeSample{ @@ -1163,7 +1179,8 @@ func main() { "Body": template.HTML(a), } t.Execute(os.Stdout, v) -}`}, 1, gosec.NewConfig()}, {[]string{ +}`, + }, 1, gosec.NewConfig()}, {[]string{ ` package main import ( @@ -1179,7 +1196,8 @@ func main() { "Body": template.JS(a), } t.Execute(os.Stdout, v) -}`}, 1, gosec.NewConfig()}, {[]string{ +}`, + }, 1, gosec.NewConfig()}, {[]string{ ` package main import ( @@ -1195,10 +1213,13 @@ func main() { "Body": template.URL(a), } t.Execute(os.Stdout, v) -}`}, 1, gosec.NewConfig()}} +}`, + }, 1, gosec.NewConfig()}, + } // SampleCodeG204 - Subprocess auditing - SampleCodeG204 = []CodeSample{{[]string{` + SampleCodeG204 = []CodeSample{ + {[]string{` package main import ( "log" @@ -1211,7 +1232,8 @@ func main() { log.Fatal(err) } log.Printf("Command finished with error: %v", err) -}`}, 0, gosec.NewConfig()}, {[]string{` +}`}, 0, gosec.NewConfig()}, + {[]string{` // Calling any function which starts a new process with using // command line arguments as it's arguments is considered dangerous package main @@ -1227,7 +1249,8 @@ func main() { log.Fatal(err) } log.Printf("Command finished with error: %v", err) -}`}, 1, gosec.NewConfig()}, {[]string{` +}`}, 1, gosec.NewConfig()}, + {[]string{` // Initializing a local variable using a environmental // variable is consider as a dangerous user input package main @@ -1246,7 +1269,8 @@ func main() { log.Printf("Waiting for command to finish...") err = cmd.Wait() log.Printf("Command finished with error: %v", err) -}`}, 1, gosec.NewConfig()}, {[]string{` +}`}, 1, gosec.NewConfig()}, + {[]string{` // gosec doesn't have enough context to decide that the // command argument of the RunCmd function is harcoded string // and that's why it's better to warn the user so he can audit it @@ -1269,7 +1293,8 @@ func RunCmd(command string) { func main() { RunCmd("sleep") -}`}, 1, gosec.NewConfig()}, {[]string{` +}`}, 1, gosec.NewConfig()}, + {[]string{` // syscall.Exec function called with harcoded arguments // shouldn't be consider as a command injection package main @@ -1283,7 +1308,8 @@ func main() { fmt.Printf("Error: %v\n", err) } }`}, 0, gosec.NewConfig()}, - {[]string{` + { + []string{` package main import ( @@ -1302,7 +1328,8 @@ func main() { RunCmd("sleep") }`}, 1, gosec.NewConfig(), }, - {[]string{` + { + []string{` package main import ( @@ -1340,7 +1367,8 @@ func main() { log.Printf("Waiting for command to finish...") err = cmd.Wait() log.Printf("Command finished with error: %v", err) -}`}, 0, gosec.NewConfig()}} +}`}, 0, gosec.NewConfig()}, + } // SampleCodeG301 - mkdir permission check SampleCodeG301 = []CodeSample{{[]string{` @@ -1855,7 +1883,8 @@ func main() { w.Flush() -}`}, 1, gosec.NewConfig()}} +}`}, 1, gosec.NewConfig()}, + } // SampleCodeG307 - Unsafe defer of os.Close SampleCodeG307 = []CodeSample{ {[]string{`package main @@ -1904,7 +1933,8 @@ func main() { w.Flush() -}`}, 1, gosec.NewConfig()}} +}`}, 1, gosec.NewConfig()}, + } // SampleCodeG401 - Use of weak crypto MD5 SampleCodeG401 = []CodeSample{ @@ -1937,7 +1967,8 @@ func main() { log.Fatal(err) } fmt.Printf("%x", h.Sum(nil)) -}`}, 1, gosec.NewConfig()}} +}`}, 1, gosec.NewConfig()}, + } // SampleCodeG401b - Use of weak crypto SHA1 SampleCodeG401b = []CodeSample{ @@ -1962,7 +1993,8 @@ func main() { log.Fatal(err) } fmt.Printf("%x", h.Sum(nil)) -}`}, 1, gosec.NewConfig()}} +}`}, 1, gosec.NewConfig()}, + } // SampleCodeG402 - TLS settings SampleCodeG402 = []CodeSample{{[]string{` @@ -2001,7 +2033,8 @@ func main() { if err != nil { fmt.Println(err) } -}`}, 1, gosec.NewConfig()}, {[]string{` +}`, + }, 1, gosec.NewConfig()}, {[]string{` // Insecure max version package main import ( @@ -2040,7 +2073,8 @@ func main() { if err != nil { fmt.Println(err) } -}`}, 1, gosec.NewConfig()}, {[]string{` +}`}, 1, gosec.NewConfig(), + }, {[]string{` // secure max version when min version is specified package main import ( @@ -2092,7 +2126,8 @@ func main() { fmt.Println(err) } fmt.Println(pvk) -}`}, 1, gosec.NewConfig()}} +}`}, 1, gosec.NewConfig()}, + } // SampleCodeG404 - weak random number SampleCodeG404 = []CodeSample{ @@ -2140,7 +2175,8 @@ import ( func main() { bad := rand.Intn(10) println(bad) -}`}, 1, gosec.NewConfig()}} +}`}, 1, gosec.NewConfig()}, + } // SampleCodeG501 - Blocklisted import MD5 SampleCodeG501 = []CodeSample{ @@ -2155,7 +2191,8 @@ func main() { for _, arg := range os.Args { fmt.Printf("%x - %s\n", md5.Sum([]byte(arg)), arg) } -}`}, 1, gosec.NewConfig()}} +}`}, 1, gosec.NewConfig()}, + } // SampleCodeG502 - Blocklisted import DES SampleCodeG502 = []CodeSample{ @@ -2183,7 +2220,8 @@ func main() { stream := cipher.NewCFBEncrypter(block, iv) stream.XORKeyStream(ciphertext[des.BlockSize:], plaintext) fmt.Println("Secret message is: %s", hex.EncodeToString(ciphertext)) -}`}, 1, gosec.NewConfig()}} +}`}, 1, gosec.NewConfig()}, + } // SampleCodeG503 - Blocklisted import RC4 SampleCodeG503 = []CodeSample{{[]string{` @@ -2227,11 +2265,13 @@ func main() { for _, arg := range os.Args { fmt.Printf("%x - %s\n", sha1.Sum([]byte(arg)), arg) } -}`}, 1, gosec.NewConfig()}} +}`}, 1, gosec.NewConfig()}, + } // SampleCodeG601 - Implicit aliasing over range statement SampleCodeG601 = []CodeSample{ - {[]string{` + {[]string{ + ` package main import "fmt"