/
main.go
310 lines (256 loc) · 7.59 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
// (c) Copyright 2016 Hewlett Packard Enterprise Development LP
//
// 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 main
import (
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"regexp"
"sort"
"strings"
"github.com/kisielk/gotool"
"github.com/securego/gosec"
"github.com/securego/gosec/output"
"github.com/securego/gosec/rules"
)
const (
usageText = `
gosec - Golang security checker
gosec analyzes Go source code to look for common programming mistakes that
can lead to security problems.
VERSION: %s
GIT TAG: %s
BUILD DATE: %s
USAGE:
# Check a single package
$ gosec $GOPATH/src/github.com/example/project
# Check all packages under the current directory and save results in
# json format.
$ gosec -fmt=json -out=results.json ./...
# Run a specific set of rules (by default all rules will be run):
$ gosec -include=G101,G203,G401 ./...
# Run all rules except the provided
$ gosec -exclude=G101 $GOPATH/src/github.com/example/project/...
`
)
var (
// #nosec flag
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, sonarqube, or text")
// output file
flagOutput = flag.String("out", "", "Set output file for results")
// config file
flagConfig = flag.String("conf", "", "Path to optional config file")
// quiet
flagQuiet = flag.Bool("quiet", false, "Only show output when errors are found")
// rules to explicitly include
flagRulesInclude = flag.String("include", "", "Comma separated list of rules IDs to include. (see rule list)")
// rules to explicitly exclude
flagRulesExclude = flag.String("exclude", "", "Comma separated list of rules IDs to exclude. (see rule list)")
// log to file or stderr
flagLogfile = flag.String("log", "", "Log messages to file rather than stderr")
// sort the issues by severity
flagSortIssues = flag.Bool("sort", true, "Sort issues by severity")
// go build tags
flagBuildTags = flag.String("tags", "", "Comma separated list of build tags")
// scan the vendor folder
flagScanVendor = flag.Bool("vendor", false, "Scan the vendor folder")
// fail by severity
flagSeverity = flag.String("severity", "low", "Fail the scanning for issues with the given or higher severity. Valid options are: low, medium, high")
// do not fail
flagNoFail = flag.Bool("no-fail", false, "Do not fail the scanning, even if issues were found")
logger *log.Logger
)
// #nosec
func usage() {
usageText := fmt.Sprintf(usageText, Version, GitTag, BuildDate)
fmt.Fprintln(os.Stderr, usageText)
fmt.Fprint(os.Stderr, "OPTIONS:\n\n")
flag.PrintDefaults()
fmt.Fprint(os.Stderr, "\n\nRULES:\n\n")
// sorted rule list for ease of reading
rl := rules.Generate()
keys := make([]string, 0, len(rl))
for key := range rl {
keys = append(keys, key)
}
sort.Strings(keys)
for _, k := range keys {
v := rl[k]
fmt.Fprintf(os.Stderr, "\t%s: %s\n", k, v.Description)
}
fmt.Fprint(os.Stderr, "\n")
}
func loadConfig(configFile string) (gosec.Config, error) {
config := gosec.NewConfig()
if configFile != "" {
// #nosec
file, err := os.Open(configFile)
if err != nil {
return nil, err
}
defer file.Close()
if _, err := config.ReadFrom(file); err != nil {
return nil, err
}
}
if *flagIgnoreNoSec {
config.SetGlobal(gosec.Nosec, "true")
}
return config, nil
}
func loadRules(include, exclude string) rules.RuleList {
var filters []rules.RuleFilter
if include != "" {
logger.Printf("including rules: %s", include)
including := strings.Split(include, ",")
filters = append(filters, rules.NewRuleFilter(false, including...))
} else {
logger.Println("including rules: default")
}
if exclude != "" {
logger.Printf("excluding rules: %s", exclude)
excluding := strings.Split(exclude, ",")
filters = append(filters, rules.NewRuleFilter(true, excluding...))
} else {
logger.Println("excluding rules: default")
}
return rules.Generate(filters...)
}
func saveOutput(filename, format, rootPath string, issues []*gosec.Issue, metrics *gosec.Metrics, errors map[string][]gosec.Error) error {
if filename != "" {
outfile, err := os.Create(filename)
if err != nil {
return err
}
defer outfile.Close()
err = output.CreateReport(outfile, format, rootPath, issues, metrics, errors)
if err != nil {
return err
}
} else {
err := output.CreateReport(os.Stdout, format, rootPath, issues, metrics, errors)
if err != nil {
return err
}
}
return nil
}
func convertToScore(severity string) (gosec.Score, error) {
severity = strings.ToLower(severity)
switch severity {
case "low":
return gosec.Low, nil
case "medium":
return gosec.Medium, nil
case "high":
return gosec.High, nil
default:
return gosec.Low, fmt.Errorf("provided severity '%s' not valid. Valid options: low, medium, high", severity)
}
}
func main() {
// Setup usage description
flag.Usage = usage
// Parse command line arguments
flag.Parse()
// Ensure at least one file was specified
if flag.NArg() == 0 {
fmt.Fprintf(os.Stderr, "\nError: FILE [FILE...] or './...' expected\n") // #nosec
flag.Usage()
os.Exit(1)
}
// Setup logging
logWriter := os.Stderr
if *flagLogfile != "" {
var e error
logWriter, e = os.Create(*flagLogfile)
if e != nil {
flag.Usage()
log.Fatal(e)
}
}
if *flagQuiet {
logger = log.New(ioutil.Discard, "", 0)
} else {
logger = log.New(logWriter, "[gosec] ", log.LstdFlags)
}
failSeverity, err := convertToScore(*flagSeverity)
if err != nil {
logger.Fatal(err)
}
// Load config
config, err := loadConfig(*flagConfig)
if err != nil {
logger.Fatal(err)
}
// Load enabled rule definitions
ruleDefinitions := loadRules(*flagRulesInclude, *flagRulesExclude)
if len(ruleDefinitions) == 0 {
logger.Fatal("cannot continue: no rules are configured.")
}
// Create the analyzer
analyzer := gosec.NewAnalyzer(config, logger)
analyzer.LoadRules(ruleDefinitions.Builders())
vendor := regexp.MustCompile(`[\\/]vendor([\\/]|$)`)
var packages []string
// Iterate over packages on the import paths
for _, pkg := range gotool.ImportPaths(flag.Args()) {
// Skip vendor directory
if !*flagScanVendor {
if vendor.MatchString(pkg) {
continue
}
}
packages = append(packages, pkg)
}
var buildTags []string
if *flagBuildTags != "" {
buildTags = strings.Split(*flagBuildTags, ",")
}
if err := analyzer.Process(buildTags, packages...); err != nil {
logger.Fatal(err)
}
// Collect the results
issues, metrics, errors := analyzer.Report()
// Sort the issue by severity
if *flagSortIssues {
sortIssues(issues)
}
issuesFound := false
for _, issue := range issues {
if issue.Severity >= failSeverity {
issuesFound = true
break
}
}
// Exit quietly if nothing was found
if !issuesFound && *flagQuiet {
os.Exit(0)
}
rootPath := packages[0]
// Create output report
if err := saveOutput(*flagOutput, *flagFormat, rootPath, issues, metrics, errors); err != nil {
logger.Fatal(err)
}
// Finalize logging
logWriter.Close() // #nosec
// Do we have an issue? If so exit 1 unless NoFail is set
if (issuesFound || len(errors) != 0) && !*flagNoFail {
os.Exit(1)
}
}