-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
Copy pathdockerfile.go
86 lines (72 loc) · 2.04 KB
/
dockerfile.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
package dockerfile
import (
"bytes"
"context"
"strings"
"golang.org/x/xerrors"
"github.com/aquasecurity/trivy/pkg/fanal/analyzer"
"github.com/aquasecurity/trivy/pkg/fanal/types"
"github.com/aquasecurity/trivy/pkg/misconf"
)
const analyzerVersion = 1
func init() {
analyzer.RegisterConfigAnalyzer(analyzer.TypeHistoryDockerfile, newHistoryAnalyzer)
}
type historyAnalyzer struct {
scanner misconf.Scanner
}
func newHistoryAnalyzer(opts analyzer.ConfigAnalyzerOptions) (analyzer.ConfigAnalyzer, error) {
s, err := misconf.NewScanner(opts.FilePatterns, opts.MisconfScannerOption)
if err != nil {
return nil, xerrors.Errorf("misconfiguration scanner error: %w", err)
}
return &historyAnalyzer{
scanner: s,
}, nil
}
func (a *historyAnalyzer) Analyze(ctx context.Context, input analyzer.ConfigAnalysisInput) (*analyzer.
ConfigAnalysisResult, error) {
if input.Config == nil {
return nil, nil
}
dockerfile := new(bytes.Buffer)
for _, h := range input.Config.History {
var createdBy string
switch {
case strings.HasPrefix(h.CreatedBy, "/bin/sh -c #(nop)"):
// Instruction other than RUN
createdBy = strings.TrimPrefix(h.CreatedBy, "/bin/sh -c #(nop)")
case strings.HasPrefix(h.CreatedBy, "/bin/sh -c"):
// RUN instruction
createdBy = strings.ReplaceAll(h.CreatedBy, "/bin/sh -c", "RUN")
}
dockerfile.WriteString(strings.TrimSpace(createdBy) + "\n")
}
files := []types.File{
{
Type: types.Dockerfile,
Path: "Dockerfile",
Content: dockerfile.Bytes(),
},
}
misconfs, err := a.scanner.Scan(ctx, files)
if err != nil {
return nil, xerrors.Errorf("history scan error: %w", err)
}
// The result should be a single element as it passes one Dockerfile.
if len(misconfs) != 1 {
return nil, nil
}
return &analyzer.ConfigAnalysisResult{
Misconfiguration: &misconfs[0],
}, nil
}
func (a *historyAnalyzer) Required(_ types.OS) bool {
return true
}
func (a *historyAnalyzer) Type() analyzer.Type {
return analyzer.TypeHistoryDockerfile
}
func (a *historyAnalyzer) Version() int {
return analyzerVersion
}