Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add sonarqube output #288

Merged
merged 7 commits into from
Mar 20, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ gosec -tag debug,ignore ./...

### Output formats

gosec currently supports text, json, yaml, csv and JUnit XML output formats. By default
gosec currently supports text, json, yaml, csv, sonarqube and JUnit XML output formats. By default
results will be reported to stdout, but can also be written to an output
file. The output format is controlled by the '-fmt' flag, and the output file is controlled by the '-out' flag as follows:

Expand Down
13 changes: 7 additions & 6 deletions cmd/gosec/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ var (
flagIgnoreNoSec = flag.Bool("nosec", false, "Ignores #nosec comments when set")

// format output
flagFormat = flag.String("fmt", "text", "Set output format. Valid options are: json, yaml, csv, junit-xml, html, or text")
flagFormat = flag.String("fmt", "text", "Set output format. Valid options are: json, yaml, csv, junit-xml, html, sonarqube, or text")

// output file
flagOutput = flag.String("out", "", "Set output file for results")
Expand Down Expand Up @@ -165,19 +165,19 @@ func loadRules(include, exclude string) rules.RuleList {
return rules.Generate(filters...)
}

func saveOutput(filename, format string, issues []*gosec.Issue, metrics *gosec.Metrics, errors map[string][]gosec.Error) error {
func saveOutput(filename, format, rootPath string, issues []*gosec.Issue, metrics *gosec.Metrics, errors map[string][]gosec.Error) error {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure modifying the interface to achieve a truncated file path is the best solution here. Is there any specific reason for it? Sonarqube only recognize relative paths?

This is certainly something we can look at fixing though.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, sonarqube reports from the root of the project. I needed a way to remove the full path. Happy to refactor, if you can think of a better way of doing this.

Copy link
Contributor Author

@kmcrawford kmcrawford Mar 11, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Example of this working:
image

From:

                {
			"engineId": "gosec",
			"ruleId": "G505",
			"primaryLocation": {
				"message": "Blacklisted import crypto/sha1: weak cryptographic primitive",
				"filePath": "service/caching.go",
				"textRange": {
					"startLine": 5,
					"endLine": 5
				}
			},
			"type": "VULNERABILITY",
			"severity": "MAJOR",
			"effortMinutes": 5
		}

if filename != "" {
outfile, err := os.Create(filename)
if err != nil {
return err
}
defer outfile.Close()
err = output.CreateReport(outfile, format, issues, metrics, errors)
err = output.CreateReport(outfile, format, rootPath, issues, metrics, errors)
if err != nil {
return err
}
} else {
err := output.CreateReport(os.Stdout, format, issues, metrics, errors)
err := output.CreateReport(os.Stdout, format, rootPath, issues, metrics, errors)
if err != nil {
return err
}
Expand Down Expand Up @@ -318,6 +318,7 @@ func main() {
if *flagBuildTags != "" {
buildTags = strings.Split(*flagBuildTags, ",")
}

if err := analyzer.Process(buildTags, packages...); err != nil {
logger.Fatal(err)
}
Expand All @@ -342,9 +343,9 @@ func main() {
if !issuesFound && *flagQuiet {
os.Exit(0)
}

rootPath := packages[0]
// Create output report
if err := saveOutput(*flagOutput, *flagFormat, issues, metrics, errors); err != nil {
if err := saveOutput(*flagOutput, *flagFormat, rootPath, issues, metrics, errors); err != nil {
logger.Fatal(err)
}

Expand Down
46 changes: 41 additions & 5 deletions output/formatter.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ import (
"encoding/xml"
htmlTemplate "html/template"
"io"
"strconv"
"strings"
plainTemplate "text/template"

"github.com/securego/gosec"
Expand All @@ -41,6 +43,9 @@ const (

// ReportJUnitXML set the output format to junit xml
ReportJUnitXML // JUnit XML format

//SonarqubeEffortMinutes effort to fix in minutes
SonarqubeEffortMinutes = 5
)

var text = `Results:
Expand Down Expand Up @@ -71,7 +76,7 @@ type reportInfo struct {

// CreateReport generates a report based for the supplied issues and metrics given
// the specified format. The formats currently accepted are: json, csv, html and text.
func CreateReport(w io.Writer, format string, issues []*gosec.Issue, metrics *gosec.Metrics, errors map[string][]gosec.Error) error {
func CreateReport(w io.Writer, format, rootPath string, issues []*gosec.Issue, metrics *gosec.Metrics, errors map[string][]gosec.Error) error {
data := &reportInfo{
Errors: errors,
Issues: issues,
Expand All @@ -91,22 +96,53 @@ func CreateReport(w io.Writer, format string, issues []*gosec.Issue, metrics *go
err = reportFromHTMLTemplate(w, html, data)
case "text":
err = reportFromPlaintextTemplate(w, text, data)
case "sonarqube":
err = reportSonarqube(rootPath, w, data)
default:
err = reportFromPlaintextTemplate(w, text, data)
}
return err
}

func reportSonarqube(rootPath string, w io.Writer, data *reportInfo) error {
var si sonarIssues
for _, issue := range data.Issues {
lines := strings.Split(issue.Line, "-")

startLine, _ := strconv.Atoi(lines[0])
endLine := startLine
if len(lines) > 1 {
endLine, _ = strconv.Atoi(lines[1])
}
s := sonarIssue{
EngineID: "gosec",
RuleID: issue.RuleID,
PrimaryLocation: location{
Message: issue.What,
FilePath: strings.Replace(issue.File, rootPath+"/", "", 1),
TextRange: textRange{StartLine: startLine, EndLine: endLine},
},
Type: "VULNERABILITY",
Severity: getSonarSeverity(issue.Severity.String()),
EffortMinutes: SonarqubeEffortMinutes,
}
si.SonarIssues = append(si.SonarIssues, s)
}
raw, err := json.MarshalIndent(si, "", "\t")
if err != nil {
return err
}
_, err = w.Write(raw)
return err
}

func reportJSON(w io.Writer, data *reportInfo) error {
raw, err := json.MarshalIndent(data, "", "\t")
if err != nil {
panic(err)
return err
}

_, err = w.Write(raw)
if err != nil {
panic(err)
}
return err
}

Expand Down
40 changes: 40 additions & 0 deletions output/sonarqube_format.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package output

type textRange struct {
StartLine int `json:"startLine"`
EndLine int `json:"endLine"`
StartColumn int `json:"startColumn,omitempty"`
EtartColumn int `json:"endColumn,omitempty"`
}
type location struct {
Message string `json:"message"`
FilePath string `json:"filePath"`
TextRange textRange `json:"textRange,omitempty"`
}

type sonarIssue struct {
EngineID string `json:"engineId"`
RuleID string `json:"ruleId"`
PrimaryLocation location `json:"primaryLocation"`
Type string `json:"type"`
Severity string `json:"severity"`
EffortMinutes int `json:"effortMinutes"`
SecondaryLocations []location `json:"secondaryLocations,omitempty"`
}

type sonarIssues struct {
SonarIssues []sonarIssue `json:"issues"`
}

func getSonarSeverity(s string) string {
switch s {
case "LOW":
return "MINOR"
case "MEDIUM":
return "MAJOR"
case "HIGH":
return "BLOCKER"
default:
return "INFO"
}
}