Skip to content
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
54 changes: 37 additions & 17 deletions issue.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,12 @@
package gosec

import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"go/ast"
"go/token"
"os"
"strconv"
)
Expand All @@ -34,6 +37,10 @@ const (
High
)

// SnippetOffset defines the number of lines captured before
// the beginning and after the end of a code snippet
const SnippetOffset = 1

// Cwe id and url
type Cwe struct {
ID string
Expand Down Expand Up @@ -124,43 +131,56 @@ func (c Score) String() string {
return "UNDEFINED"
}

// codeSnippet extracts a code snippet based on the ast reference
func codeSnippet(file *os.File, start int64, end int64, n ast.Node) (string, error) {
if n == nil {
return "", fmt.Errorf("Invalid AST node provided")
return "", fmt.Errorf("invalid AST node provided")
}

size := (int)(end - start) // Go bug, os.File.Read should return int64 ...
_, err := file.Seek(start, 0) // #nosec
if err != nil {
return "", fmt.Errorf("move to the beginning of file: %v", err)
var pos int64
var buf bytes.Buffer
scanner := bufio.NewScanner(file)
scanner.Split(bufio.ScanLines)
for scanner.Scan() {
pos++
if pos > end {
break
} else if pos >= start && pos <= end {
code := fmt.Sprintf("%d: %s\n", pos, scanner.Text())
buf.WriteString(code)
}
}
return buf.String(), nil
}

buf := make([]byte, size)
if nread, err := file.Read(buf); err != nil || nread != size {
return "", fmt.Errorf("Unable to read code")
func codeSnippetStartLine(node ast.Node, fobj *token.File) int64 {
s := (int64)(fobj.Line(node.Pos()))
if s-SnippetOffset > 0 {
return s - SnippetOffset
}
return string(buf), nil
return s
}

func codeSnippetEndLine(node ast.Node, fobj *token.File) int64 {
e := (int64)(fobj.Line(node.End()))
return e + SnippetOffset
}

// NewIssue creates a new Issue
func NewIssue(ctx *Context, node ast.Node, ruleID, desc string, severity Score, confidence Score) *Issue {
var code string
fobj := ctx.FileSet.File(node.Pos())
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)
}

col := strconv.Itoa(fobj.Position(node.Pos()).Column)

// #nosec
var code string
if file, err := os.Open(fobj.Name()); err == nil {
defer file.Close()
s := (int64)(fobj.Position(node.Pos()).Offset) // Go bug, should be int64
e := (int64)(fobj.Position(node.End()).Offset) // Go bug, should be int64
defer file.Close() // #nosec
s := codeSnippetStartLine(node, fobj)
e := codeSnippetEndLine(node, fobj)
code, err = codeSnippet(file, s, e, node)
if err != nil {
code = err.Error()
Expand Down
50 changes: 46 additions & 4 deletions output/formatter.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
package output

import (
"bufio"
"bytes"
"encoding/csv"
"encoding/json"
"encoding/xml"
Expand Down Expand Up @@ -59,7 +61,7 @@ Golang errors in file: [{{ $filePath }}]:
{{end}}
{{ range $index, $issue := .Issues }}
[{{ highlight $issue.FileLocation $issue.Severity }}] - {{ $issue.RuleID }} (CWE-{{ $issue.Cwe.ID }}): {{ $issue.What }} (Confidence: {{ $issue.Confidence}}, Severity: {{ $issue.Severity }})
> {{ $issue.Code }}
{{ printCode $issue }}

{{ end }}
{{ notice "Summary:" }}
Expand Down Expand Up @@ -286,6 +288,7 @@ func plainTextFuncMap(enableColor bool) plainTemplate.FuncMap {
"danger": color.Danger.Render,
"notice": color.Notice.Render,
"success": color.Success.Render,
"printCode": printCodeSnippet,
}
}

Expand All @@ -294,9 +297,10 @@ func plainTextFuncMap(enableColor bool) plainTemplate.FuncMap {
"highlight": func(t string, s gosec.Score) string {
return t
},
"danger": fmt.Sprint,
"notice": fmt.Sprint,
"success": fmt.Sprint,
"danger": fmt.Sprint,
"notice": fmt.Sprint,
"success": fmt.Sprint,
"printCode": printCodeSnippet,
}
}

Expand All @@ -317,3 +321,41 @@ func highlight(t string, s gosec.Score) string {
return defaultTheme.Sprint(t)
}
}

// printCodeSnippet prints the code snippet from the issue by adding a marker to the affected line
func printCodeSnippet(issue *gosec.Issue) string {
start, end := parseLine(issue.Line)
scanner := bufio.NewScanner(strings.NewReader(issue.Code))
var buf bytes.Buffer
line := start
for scanner.Scan() {
codeLine := scanner.Text()
if strings.HasPrefix(codeLine, strconv.Itoa(line)) && line <= end {
codeLine = " > " + codeLine + "\n"
line++
} else {
codeLine = " " + codeLine + "\n"
}
buf.WriteString(codeLine)
}
return buf.String()
}

// parseLine extract the start and the end line numbers from a issue line
func parseLine(line string) (int, int) {
parts := strings.Split(line, "-")
start := parts[0]
end := start
if len(parts) > 1 {
end = parts[1]
}
s, err := strconv.Atoi(start)
if err != nil {
return -1, -1
}
e, err := strconv.Atoi(end)
if err != nil {
return -1, -1
}
return s, e
}
6 changes: 3 additions & 3 deletions output/formatter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ func createIssue(ruleID string, cwe gosec.Cwe) gosec.Issue {
What: "test",
Confidence: gosec.High,
Severity: gosec.High,
Code: "testcode",
Code: "1: testcode",
Cwe: cwe,
}
}
Expand Down Expand Up @@ -264,7 +264,7 @@ var _ = Describe("Formatter", func() {
buf := new(bytes.Buffer)
err := CreateReport(buf, "csv", false, []string{}, []*gosec.Issue{&issue}, &gosec.Metrics{}, error)
Expect(err).ShouldNot(HaveOccurred())
pattern := "/home/src/project/test.go,1,test,HIGH,HIGH,testcode,CWE-%s\n"
pattern := "/home/src/project/test.go,1,test,HIGH,HIGH,1: testcode,CWE-%s\n"
expect := fmt.Sprintf(pattern, cwe.ID)
Expect(string(buf.String())).To(Equal(expect))
}
Expand All @@ -278,7 +278,7 @@ var _ = Describe("Formatter", func() {
buf := new(bytes.Buffer)
err := CreateReport(buf, "xml", false, []string{}, []*gosec.Issue{&issue}, &gosec.Metrics{NumFiles: 0, NumLines: 0, NumNosec: 0, NumFound: 0}, error)
Expect(err).ShouldNot(HaveOccurred())
pattern := "Results:\n\n\n[/home/src/project/test.go:1] - %s (CWE-%s): test (Confidence: HIGH, Severity: HIGH)\n > testcode\n\n\nSummary:\n Files: 0\n Lines: 0\n Nosec: 0\n Issues: 0\n\n"
pattern := "Results:\n\n\n[/home/src/project/test.go:1] - %s (CWE-%s): test (Confidence: HIGH, Severity: HIGH)\n > 1: testcode\n\n\n\nSummary:\n Files: 0\n Lines: 0\n Nosec: 0\n Issues: 0\n\n"
expect := fmt.Sprintf(pattern, rule, cwe.ID)
Expect(string(buf.String())).To(Equal(expect))
}
Expand Down