forked from securego/gosec
-
Notifications
You must be signed in to change notification settings - Fork 0
/
analyzer.go
822 lines (735 loc) · 23.5 KB
/
analyzer.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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
// (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 gosec holds the central scanning logic used by gosec security scanner
package gosec
import (
"fmt"
"go/ast"
"go/build"
"go/token"
"go/types"
"io"
"log"
"os"
"path"
"path/filepath"
"reflect"
"regexp"
"strconv"
"strings"
"sync"
"golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/analysis/passes/buildssa"
"golang.org/x/tools/go/packages"
"github.com/securego/gosec/v2/analyzers"
"github.com/securego/gosec/v2/issue"
)
// LoadMode controls the amount of details to return when loading the packages
const LoadMode = packages.NeedName |
packages.NeedFiles |
packages.NeedCompiledGoFiles |
packages.NeedImports |
packages.NeedTypes |
packages.NeedTypesSizes |
packages.NeedTypesInfo |
packages.NeedSyntax |
packages.NeedModule |
packages.NeedEmbedFiles |
packages.NeedEmbedPatterns
const externalSuppressionJustification = "Globally suppressed."
const aliasOfAllRules = "*"
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 || start <= i.start && end >= i.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.
type Context struct {
FileSet *token.FileSet
Comments ast.CommentMap
Info *types.Info
Pkg *types.Package
PkgFiles []*ast.File
Root *ast.File
Imports *ImportTracker
Config Config
Ignores ignores
PassedValues map[string]interface{}
}
// GetFileAtNodePos returns the file at the node position in the file set available in the context.
func (ctx *Context) GetFileAtNodePos(node ast.Node) *token.File {
return ctx.FileSet.File(node.Pos())
}
// NewIssue creates a new issue
func (ctx *Context) NewIssue(node ast.Node, ruleID, desc string,
severity, confidence issue.Score,
) *issue.Issue {
return issue.New(ctx.GetFileAtNodePos(node), node, ruleID, desc, severity, confidence)
}
// Metrics used when reporting information about a scanning run.
type Metrics struct {
NumFiles int `json:"files"`
NumLines int `json:"lines"`
NumNosec int `json:"nosec"`
NumFound int `json:"found"`
}
// Analyzer object is the main object of gosec. It has methods traverse an AST
// and invoke the correct checking rules as on each node as required.
type Analyzer struct {
ignoreNosec bool
ruleset RuleSet
context *Context
config Config
logger *log.Logger
issues []*issue.Issue
stats *Metrics
errors map[string][]Error // keys are file paths; values are the golang errors in those files
tests bool
excludeGenerated bool
showIgnored bool
trackSuppressions bool
concurrency int
analyzerList []*analysis.Analyzer
mu sync.Mutex
}
// NewAnalyzer builds a new analyzer.
func NewAnalyzer(conf Config, tests bool, excludeGenerated bool, trackSuppressions bool, concurrency int, logger *log.Logger) *Analyzer {
ignoreNoSec := false
if enabled, err := conf.IsGlobalEnabled(Nosec); err == nil {
ignoreNoSec = enabled
}
showIgnored := false
if enabled, err := conf.IsGlobalEnabled(ShowIgnored); err == nil {
showIgnored = enabled
}
if logger == nil {
logger = log.New(os.Stderr, "[gosec]", log.LstdFlags)
}
return &Analyzer{
ignoreNosec: ignoreNoSec,
showIgnored: showIgnored,
ruleset: NewRuleSet(),
context: &Context{},
config: conf,
logger: logger,
issues: make([]*issue.Issue, 0, 16),
stats: &Metrics{},
errors: make(map[string][]Error),
tests: tests,
concurrency: concurrency,
excludeGenerated: excludeGenerated,
trackSuppressions: trackSuppressions,
analyzerList: analyzers.BuildDefaultAnalyzers(),
}
}
// SetConfig updates the analyzer configuration
func (gosec *Analyzer) SetConfig(conf Config) {
gosec.config = conf
}
// Config returns the current configuration
func (gosec *Analyzer) Config() Config {
return gosec.config
}
// LoadRules instantiates all the rules to be used when analyzing source
// packages
func (gosec *Analyzer) LoadRules(ruleDefinitions map[string]RuleBuilder, ruleSuppressed map[string]bool) {
for id, def := range ruleDefinitions {
r, nodes := def(id, gosec.config)
gosec.ruleset.Register(r, ruleSuppressed[id], nodes...)
}
}
// Process kicks off the analysis process for a given package
func (gosec *Analyzer) Process(buildTags []string, packagePaths ...string) error {
//gosec.logger.Println("DEBUG: Entered Process() for packagePaths: ", packagePaths)
config := &packages.Config{
Mode: LoadMode,
BuildFlags: buildTags,
Tests: gosec.tests,
}
type result struct {
pkgPath string
pkgs []*packages.Package
err error
}
results := make(chan result)
jobs := make(chan string, len(packagePaths))
quit := make(chan struct{})
var wg sync.WaitGroup
worker := func(j chan string, r chan result, quit chan struct{}) {
for {
select {
case s := <-j:
pkgs, err := gosec.load(s, config)
//gosec.logger.Println("DEBUG: ", len(pkgs), " packages returned from load().")
select {
case r <- result{pkgPath: s, pkgs: pkgs, err: err}:
case <-quit:
// we've been told to stop, probably an error while
// processing a previous result.
//gosec.logger.Println("DEBUG: in case quit in Process().")
wg.Done()
return
}
default:
// j is empty and there are no jobs left
//gosec.logger.Println("DEBUG: in case default with no jobs in Process().")
wg.Done()
return
}
}
}
// fill the buffer
for _, pkgPath := range packagePaths {
jobs <- pkgPath
//gosec.logger.Println("DEBUG: Added ", pkgPath, " to job buffer.")
}
for i := 0; i < gosec.concurrency; i++ {
wg.Add(1)
go worker(jobs, results, quit)
}
go func() {
wg.Wait()
close(results)
}()
for r := range results {
if r.err != nil {
gosec.AppendError(r.pkgPath, r.err)
}
for _, pkg := range r.pkgs {
//gosec.logger.Println("DEBUG: pkg.Name=", pkg.Name)
if pkg.Name != "" {
err := gosec.ParseErrors(pkg)
if err != nil {
close(quit)
wg.Wait() // wait for the goroutines to stop
return fmt.Errorf("parsing errors in pkg %q: %w", pkg.Name, err)
}
gosec.CheckRules(pkg)
gosec.CheckAnalyzers(pkg)
}
}
}
sortErrors(gosec.errors)
return nil
}
func copyFile(src, dst string) error {
//fmt.Println("DEBUG: Entered copyFile src=", src, " dst=", dst)
sourceFile, err := os.Open(src)
if err != nil {
return err
}
defer sourceFile.Close()
/*
// Check if the destination file already exists
_, err = os.Stat(dst)
if err == nil {
// Destination file exists, generate a unique filename
base := filepath.Base(dst)
dir := filepath.Dir(dst)
ext := filepath.Ext(base)
filename := strings.TrimSuffix(base, ext)
var newDst string
counter := 1
for {
newFilename := fmt.Sprintf("%s.%d%s", filename, counter, ext)
newDst = filepath.Join(dir, newFilename)
_, err := os.Stat(newDst)
if os.IsNotExist(err) {
break
}
counter++
}
dst = newDst
} else if !os.IsNotExist(err) {
return "", err
}
*/
destinationFile, err := os.Create(dst)
if err != nil {
return err
}
defer destinationFile.Close()
_, err = io.Copy(destinationFile, sourceFile)
if err != nil {
return err
}
err = destinationFile.Sync()
if err != nil {
return err
}
return nil
}
func (gosec *Analyzer) load(pkgPath string, conf *packages.Config) ([]*packages.Package, error) {
//gosec.logger.Println("DEBUG: Entered load pkgPath=", pkgPath)
abspath, err := GetPkgAbsPath(pkgPath)
if err != nil {
gosec.logger.Printf("Skipping: %s. Path doesn't exist.", abspath)
return []*packages.Package{}, nil
}
gosec.logger.Println("Import directory:", abspath)
// 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 && !strings.Contains(err.Error(), "no buildable Go source files") { // Ignore "no Go files" error
//gosec.logger.Println("DEBUG: Error importing directory:", err)
return []*packages.Package{}, fmt.Errorf("importing dir %q: %w", pkgPath, err)
}
var packageFiles []string
// Include .go files if any
if basePackage != nil {
//gosec.logger.Println("DEBUG: Looking for go files in load()...")
for _, filename := range basePackage.GoFiles {
pkgFile := path.Join(pkgPath, filename)
//gosec.logger.Println("DEBUG: Adding to packageFiles: ", pkgFile, " where pkgPath=", pkgPath)
packageFiles = append(packageFiles, pkgFile)
}
for _, filename := range basePackage.CgoFiles {
packageFiles = append(packageFiles, path.Join(pkgPath, filename))
}
}
// Include .gno files
//gosec.logger.Println("DEBUG: Looking recursively for gno files in load() in ", pkgPath, "...")
// Walk through directory recursively to find .gno files
err = filepath.Walk(pkgPath, func(filePath string, info os.FileInfo, err error) error {
if err != nil {
//gosec.logger.Println("DEBUG: Error walking directory:", err)
return fmt.Errorf("walking directory %q: %w", pkgPath, err)
}
if !info.IsDir() && strings.HasSuffix(info.Name(), ".gno") {
// Construct destination .go file path
goFilePath := filePath + ".go"
// Copy .gno file to .go file
err := copyFile(filePath, goFilePath)
//gosec.logger.Println("DEBUG: Copied .gno file to .go file:", goFilePath)
if err != nil {
//gosec.logger.Println("DEBUG: Error copying file:", err)
return fmt.Errorf("copying file %q to %q: %w", filePath, goFilePath, err)
}
// Add .go file path to packageFiles
packageFiles = append(packageFiles, goFilePath)
//gosec.logger.Println("DEBUG: Added .gno file: ", goFilePath)
}
return nil
})
if err != nil {
//gosec.logger.Println("Error walking directory:", err)
return []*packages.Package{}, fmt.Errorf("walking directory %q: %w", pkgPath, err)
}
if gosec.tests {
testsFiles := make([]string, 0)
testsFiles = append(testsFiles, basePackage.TestGoFiles...)
testsFiles = append(testsFiles, basePackage.XTestGoFiles...)
for _, filename := range testsFiles {
packageFiles = append(packageFiles, path.Join(pkgPath, filename))
}
}
// step 3/3 remove build tags from conf to proceed build correctly.
gosec.mu.Lock()
conf.BuildFlags = nil
defer gosec.mu.Unlock()
//gosec.logger.Println("DEBUG: packageFiles length=", len(packageFiles), " packageFiles=", packageFiles)
pkgs, err := packages.Load(conf, packageFiles...)
if err != nil {
//gosec.logger.Println("DEBUG: Encountered error loading packages: ", err)
return []*packages.Package{}, fmt.Errorf("loading files from package %q: %w", pkgPath, err)
}
//gosec.logger.Println("DEBUG: Returning ", len(pkgs), " packages from load(): ", pkgs)
return pkgs, nil
}
// 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 {
fp := pkg.Fset.File(file.Pos())
if fp == nil {
// skip files which cannot be located
continue
}
checkedFile := fp.Name()
// Skip the no-Go file from analysis (e.g. a Cgo files is expanded in 3 different files
// stored in the cache which do not need to by analyzed)
if filepath.Ext(checkedFile) != ".go" && filepath.Ext(checkedFile) != ".gno" {
continue
}
if gosec.excludeGenerated && ast.IsGenerated(file) {
gosec.logger.Println("Ignoring generated file:", checkedFile)
continue
}
gosec.logger.Println("Checking file:", checkedFile)
gosec.context.FileSet = pkg.Fset
gosec.context.Config = gosec.config
gosec.context.Comments = ast.NewCommentMap(gosec.context.FileSet, file, file.Comments)
gosec.context.Root = file
gosec.context.Info = pkg.TypesInfo
gosec.context.Pkg = pkg.Types
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.
func (gosec *Analyzer) CheckAnalyzers(pkg *packages.Package) {
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(),
Logger: gosec.logger,
SSA: ssaResult.(*buildssa.SSA),
},
}
generatedFiles := gosec.generatedFiles(pkg)
for _, analyzer := range gosec.analyzerList {
pass := &analysis.Pass{
Analyzer: analyzer,
Fset: pkg.Fset,
Files: pkg.Syntax,
OtherFiles: pkg.OtherFiles,
IgnoredFiles: pkg.IgnoredFiles,
Pkg: pkg.Types,
TypesInfo: pkg.TypesInfo,
TypesSizes: pkg.TypesSizes,
ResultOf: resultMap,
Report: func(d analysis.Diagnostic) {},
ImportObjectFact: nil,
ExportObjectFact: nil,
ImportPackageFact: nil,
ExportPackageFact: nil,
AllObjectFacts: nil,
AllPackageFacts: nil,
}
result, err := pass.Analyzer.Run(pass)
if err != nil {
gosec.logger.Printf("Error running analyzer %s: %s\n", analyzer.Name, err)
continue
}
if result != nil {
if passIssues, ok := result.([]*issue.Issue); ok {
for _, iss := range passIssues {
if gosec.excludeGenerated {
if _, ok := generatedFiles[iss.File]; ok {
continue
}
}
gosec.updateIssues(iss)
}
}
}
}
}
func (gosec *Analyzer) generatedFiles(pkg *packages.Package) map[string]bool {
generatedFiles := map[string]bool{}
for _, file := range pkg.Syntax {
if ast.IsGenerated(file) {
fp := pkg.Fset.File(file.Pos())
if fp == nil {
// skip files which cannot be located
continue
}
generatedFiles[fp.Name()] = true
}
}
return generatedFiles
}
// 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)
}
// ParseErrors parses the errors from given package
func (gosec *Analyzer) ParseErrors(pkg *packages.Package) error {
if len(pkg.Errors) == 0 {
return nil
}
for _, pkgErr := range pkg.Errors {
parts := strings.Split(pkgErr.Pos, ":")
file := parts[0]
var err error
var line int
if len(parts) > 1 {
if line, err = strconv.Atoi(parts[1]); err != nil {
return fmt.Errorf("parsing line: %w", err)
}
}
var column int
if len(parts) > 2 {
if column, err = strconv.Atoi(parts[2]); err != nil {
return fmt.Errorf("parsing column: %w", err)
}
}
msg := strings.TrimSpace(pkgErr.Msg)
newErr := NewError(line, column, msg)
if errSlice, ok := gosec.errors[file]; ok {
gosec.errors[file] = append(errSlice, *newErr)
} else {
errSlice = []Error{}
gosec.errors[file] = append(errSlice, *newErr)
}
}
return nil
}
// AppendError appends an error to the file errors
func (gosec *Analyzer) AppendError(file string, err error) {
// Do not report the error for empty packages (e.g. files excluded from build with a tag)
r := regexp.MustCompile(`no buildable Go source files in`)
if r.MatchString(err.Error()) {
return
}
errors := make([]Error, 0)
if ferrs, ok := gosec.errors[file]; ok {
errors = ferrs
}
ferr := NewError(0, 0, err.Error())
errors = append(errors, *ferr)
gosec.errors[file] = errors
}
// ignore a node (and sub-tree) if it is tagged with a nosec tag comment
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, 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
} else {
noSecAlternativeTag = NoSecTag(noSecAlternativeTag)
}
for _, group := range groups {
comment := strings.TrimSpace(group.Text())
foundDefaultTag := strings.HasPrefix(comment, noSecDefaultTag) || regexp.MustCompile("\n *"+noSecDefaultTag).MatchString(comment)
foundAlternativeTag := strings.HasPrefix(comment, noSecAlternativeTag) || regexp.MustCompile("\n *"+noSecAlternativeTag).MatchString(comment)
if foundDefaultTag || foundAlternativeTag {
gosec.stats.NumNosec++
// Discard what's in front of the nosec tag.
if foundDefaultTag {
comment = strings.SplitN(comment, noSecDefaultTag, 2)[1]
} else {
comment = strings.SplitN(comment, noSecAlternativeTag, 2)[1]
}
// Extract the directive and the justification.
justification := ""
commentParts := regexp.MustCompile(`-{2,}`).Split(comment, 2)
directive := commentParts[0]
if len(commentParts) > 1 {
justification = strings.TrimSpace(strings.TrimRight(commentParts[1], "\n"))
}
// Pull out the specific rules that are listed to be ignored.
re := regexp.MustCompile(`(G\d{3})`)
matches := re.FindAllStringSubmatch(directive, -1)
suppression := issue.SuppressionInfo{
Kind: "inSource",
Justification: justification,
}
// Find the rule IDs to ignore.
ignores := make(map[string]issue.SuppressionInfo)
for _, v := range matches {
ignores[v[1]] = suppression
}
// If no specific rules were given, ignore everything.
if len(matches) == 0 {
ignores[aliasOfAllRules] = suppression
}
return ignores
}
}
}
return nil
}
// 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 {
// Using ast.File instead of ast.ImportSpec, so that we can track all imports at once.
switch i := n.(type) {
case *ast.File:
gosec.context.Imports.TrackFile(i)
}
for _, rule := range gosec.ruleset.RegisteredFor(n) {
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)
}
return gosec
}
func (gosec *Analyzer) updateIgnores() {
for n := range gosec.context.Comments {
gosec.updateIgnoredRulesForNode(n)
}
}
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,
)
}
}
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 of this rule.
if gosec.ruleset.IsRuleSuppressed(id) {
ignored = true
suppressions = append(suppressions, issue.SuppressionInfo{
Kind: "external",
Justification: externalSuppressionJustification,
})
}
return suppressions, ignored
}
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
}
if !ignored || !gosec.showIgnored {
gosec.stats.NumFound++
}
if ignored && gosec.trackSuppressions {
issue.WithSuppressions(suppressions)
gosec.issues = append(gosec.issues, issue)
} else if !ignored || gosec.showIgnored || gosec.ignoreNosec {
gosec.issues = append(gosec.issues, issue)
}
}
}
// Report returns the current issues discovered and the metrics about the scan
func (gosec *Analyzer) Report() ([]*issue.Issue, *Metrics, map[string][]Error) {
return gosec.issues, gosec.stats, gosec.errors
}
// Reset clears state such as context, issues and metrics from the configured analyzer
func (gosec *Analyzer) Reset() {
gosec.context = &Context{}
gosec.issues = make([]*issue.Issue, 0, 16)
gosec.stats = &Metrics{}
gosec.ruleset = NewRuleSet()
}