forked from aquasecurity/defsec
-
Notifications
You must be signed in to change notification settings - Fork 0
/
scanner.go
352 lines (289 loc) · 9.19 KB
/
scanner.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
package terraform
import (
"context"
"io"
"io/fs"
"path/filepath"
"sort"
"strings"
"sync"
"time"
"github.com/wuwwlwwl/defsec/pkg/types"
"github.com/wuwwlwwl/defsec/pkg/framework"
"github.com/wuwwlwwl/defsec/pkg/debug"
"github.com/wuwwlwwl/defsec/pkg/scanners/options"
"github.com/wuwwlwwl/defsec/pkg/rego"
"github.com/wuwwlwwl/defsec/pkg/scanners"
"github.com/wuwwlwwl/defsec/pkg/scanners/terraform/executor"
"github.com/wuwwlwwl/defsec/pkg/scanners/terraform/parser"
"github.com/wuwwlwwl/defsec/pkg/scanners/terraform/parser/resolvers"
"github.com/wuwwlwwl/defsec/pkg/scan"
"github.com/wuwwlwwl/defsec/pkg/extrafs"
)
var _ scanners.FSScanner = (*Scanner)(nil)
var _ options.ConfigurableScanner = (*Scanner)(nil)
var _ ConfigurableTerraformScanner = (*Scanner)(nil)
type Scanner struct {
options []options.ScannerOption
parserOpt []options.ParserOption
executorOpt []executor.Option
dirs map[string]struct{}
forceAllDirs bool
policyDirs []string
policyReaders []io.Reader
regoScanner *rego.Scanner
execLock sync.RWMutex
debug debug.Logger
enableEmbeddedLibraries bool
sync.Mutex
frameworks []framework.Framework
spec string
loadEmbeddedLibraries bool
loadEmbeddedPolicies bool
}
func (s *Scanner) SetSpec(spec string) {
s.spec = spec
}
func (s *Scanner) SetRegoOnly(regoOnly bool) {
s.executorOpt = append(s.executorOpt, executor.OptionWithRegoOnly(regoOnly))
}
func (s *Scanner) SetFrameworks(frameworks []framework.Framework) {
s.frameworks = frameworks
}
func (s *Scanner) SetUseEmbeddedPolicies(b bool) {
s.loadEmbeddedPolicies = b
}
func (s *Scanner) SetUseEmbeddedLibraries(b bool) {
s.loadEmbeddedLibraries = b
}
func (s *Scanner) SetEmbeddedLibrariesEnabled(enabled bool) {
s.enableEmbeddedLibraries = enabled
}
func (s *Scanner) Name() string {
return "Terraform"
}
func (s *Scanner) SetForceAllDirs(b bool) {
s.forceAllDirs = b
}
func (s *Scanner) AddParserOptions(options ...options.ParserOption) {
s.parserOpt = append(s.parserOpt, options...)
}
func (s *Scanner) AddExecutorOptions(options ...executor.Option) {
s.executorOpt = append(s.executorOpt, options...)
}
func (s *Scanner) SetPolicyReaders(readers []io.Reader) {
s.policyReaders = readers
}
func (s *Scanner) SetSkipRequiredCheck(skip bool) {
s.parserOpt = append(s.parserOpt, options.ParserWithSkipRequiredCheck(skip))
}
func (s *Scanner) SetDebugWriter(writer io.Writer) {
s.parserOpt = append(s.parserOpt, options.ParserWithDebug(writer))
s.executorOpt = append(s.executorOpt, executor.OptionWithDebugWriter(writer))
s.debug = debug.New(writer, "terraform", "scanner")
}
func (s *Scanner) SetTraceWriter(_ io.Writer) {
}
func (s *Scanner) SetPerResultTracingEnabled(_ bool) {
}
func (s *Scanner) SetPolicyDirs(dirs ...string) {
s.policyDirs = dirs
}
func (s *Scanner) SetDataDirs(_ ...string) {}
func (s *Scanner) SetPolicyNamespaces(_ ...string) {}
func (s *Scanner) SetPolicyFilesystem(_ fs.FS) {
// handled by rego when option is passed on
}
func (s *Scanner) SetDataFilesystem(_ fs.FS) {
// handled by rego when option is passed on
}
func (s *Scanner) SetRegoErrorLimit(_ int) {}
type Metrics struct {
Parser parser.Metrics
Executor executor.Metrics
Timings struct {
Total time.Duration
}
}
func New(options ...options.ScannerOption) *Scanner {
s := &Scanner{
dirs: make(map[string]struct{}),
options: options,
}
for _, opt := range options {
opt(s)
}
return s
}
func (s *Scanner) ScanFS(ctx context.Context, target fs.FS, dir string) (scan.Results, error) {
results, _, err := s.ScanFSWithMetrics(ctx, target, dir)
return results, err
}
func (s *Scanner) initRegoScanner(srcFS fs.FS) (*rego.Scanner, error) {
s.Lock()
defer s.Unlock()
if s.regoScanner != nil {
return s.regoScanner, nil
}
regoScanner := rego.NewScanner(types.SourceCloud, s.options...)
regoScanner.SetParentDebugLogger(s.debug)
if err := regoScanner.LoadPolicies(s.loadEmbeddedLibraries, s.loadEmbeddedPolicies, srcFS, s.policyDirs, s.policyReaders); err != nil {
return nil, err
}
s.regoScanner = regoScanner
return regoScanner, nil
}
func (s *Scanner) ScanFSWithMetrics(ctx context.Context, target fs.FS, dir string) (scan.Results, Metrics, error) {
var metrics Metrics
s.debug.Log("Scanning [%s] at '%s'...", target, dir)
// find directories which directly contain tf files (and have no parent containing tf files)
rootDirs := s.findRootModules(target, dir, dir)
sort.Strings(rootDirs)
if len(rootDirs) == 0 {
s.debug.Log("no root modules found")
return nil, metrics, nil
}
regoScanner, err := s.initRegoScanner(target)
if err != nil {
return nil, metrics, err
}
s.execLock.Lock()
s.executorOpt = append(s.executorOpt, executor.OptionWithRegoScanner(regoScanner), executor.OptionWithFrameworks(s.frameworks...))
s.execLock.Unlock()
var allResults scan.Results
// parse all root module directories
for _, dir := range rootDirs {
s.debug.Log("Scanning root module '%s'...", dir)
p := parser.New(target, "", s.parserOpt...)
s.execLock.RLock()
e := executor.New(s.executorOpt...)
s.execLock.RUnlock()
if err := p.ParseFS(ctx, dir); err != nil {
return nil, metrics, err
}
modules, _, err := p.EvaluateAll(ctx)
if err != nil {
return nil, metrics, err
}
parserMetrics := p.Metrics()
metrics.Parser.Counts.Blocks += parserMetrics.Counts.Blocks
metrics.Parser.Counts.Modules += parserMetrics.Counts.Modules
metrics.Parser.Counts.Files += parserMetrics.Counts.Files
metrics.Parser.Timings.DiskIODuration += parserMetrics.Timings.DiskIODuration
metrics.Parser.Timings.ParseDuration += parserMetrics.Timings.ParseDuration
results, execMetrics, err := e.Execute(modules)
if err != nil {
return nil, metrics, err
}
fsMap := p.GetFilesystemMap()
for i, result := range results {
if result.Metadata().Range().GetFS() != nil {
continue
}
key := result.Metadata().Range().GetFSKey()
if key == "" {
continue
}
if filesystem, ok := fsMap[key]; ok {
override := scan.Results{
result,
}
override.SetSourceAndFilesystem(result.Range().GetSourcePrefix(), filesystem, false)
results[i] = override[0]
}
}
metrics.Executor.Counts.Passed += execMetrics.Counts.Passed
metrics.Executor.Counts.Failed += execMetrics.Counts.Failed
metrics.Executor.Counts.Ignored += execMetrics.Counts.Ignored
metrics.Executor.Counts.Critical += execMetrics.Counts.Critical
metrics.Executor.Counts.High += execMetrics.Counts.High
metrics.Executor.Counts.Medium += execMetrics.Counts.Medium
metrics.Executor.Counts.Low += execMetrics.Counts.Low
metrics.Executor.Timings.Adaptation += execMetrics.Timings.Adaptation
metrics.Executor.Timings.RunningChecks += execMetrics.Timings.RunningChecks
allResults = append(allResults, results...)
}
metrics.Parser.Counts.ModuleDownloads = resolvers.Remote.GetDownloadCount()
metrics.Timings.Total += metrics.Parser.Timings.DiskIODuration
metrics.Timings.Total += metrics.Parser.Timings.ParseDuration
metrics.Timings.Total += metrics.Executor.Timings.Adaptation
metrics.Timings.Total += metrics.Executor.Timings.RunningChecks
return allResults, metrics, nil
}
func (s *Scanner) removeNestedDirs(dirs []string) []string {
if s.forceAllDirs {
return dirs
}
var clean []string
for _, dirA := range dirs {
dirOK := true
for _, dirB := range dirs {
if dirA == dirB {
continue
}
if str, err := filepath.Rel(dirB, dirA); err == nil && !strings.HasPrefix(str, "..") {
dirOK = false
break
}
}
if dirOK {
clean = append(clean, dirA)
}
}
return clean
}
func (s *Scanner) findRootModules(target fs.FS, scanDir string, dirs ...string) []string {
var roots []string
var others []string
for _, dir := range dirs {
if s.isRootModule(target, dir) {
roots = append(roots, dir)
if !s.forceAllDirs {
continue
}
}
// if this isn't a root module, look at directories inside it
files, err := fs.ReadDir(target, filepath.ToSlash(dir))
if err != nil {
continue
}
for _, file := range files {
realPath := filepath.Join(dir, file.Name())
if symFS, ok := target.(extrafs.ReadLinkFS); ok {
realPath, err = symFS.ResolveSymlink(realPath, scanDir)
if err != nil {
s.debug.Log("failed to resolve symlink '%s': %s", file.Name(), err)
continue
}
}
if file.IsDir() {
others = append(others, realPath)
} else if statFS, ok := target.(fs.StatFS); ok {
info, err := statFS.Stat(filepath.ToSlash(realPath))
if err != nil {
continue
}
if info.IsDir() {
others = append(others, realPath)
}
}
}
}
if (len(roots) == 0 || s.forceAllDirs) && len(others) > 0 {
roots = append(roots, s.findRootModules(target, scanDir, others...)...)
}
return s.removeNestedDirs(roots)
}
func (s *Scanner) isRootModule(target fs.FS, dir string) bool {
files, err := fs.ReadDir(target, filepath.ToSlash(dir))
if err != nil {
s.debug.Log("failed to read dir '%s' from filesystem [%s]: %s", dir, target, err)
return false
}
for _, file := range files {
if strings.HasSuffix(file.Name(), ".tf") || strings.HasSuffix(file.Name(), ".tf.json") {
return true
}
}
return false
}