-
Notifications
You must be signed in to change notification settings - Fork 83
/
Copy pathanalyze.go
201 lines (172 loc) · 5.05 KB
/
analyze.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
package cmd
import (
"encoding/json"
"fmt"
"os"
"text/template"
"strings"
"github.com/coreos/clair/api/v1"
"github.com/coreos/clair/utils/types"
"github.com/fatih/color"
"github.com/jgsqware/clairctl/clair"
"github.com/jgsqware/clairctl/config"
"github.com/jgsqware/clairctl/docker"
"github.com/spf13/cobra"
)
type AnalyseInfo struct {
Image string
Vulns []PriorityCount
}
const analyzeTplt = `
Image: {{.String}}
{{range $v := vulns .MostRecentLayer}}
{{$v | colorized}}{{end}}
`
var filters string
var whitelistConfig string
var noFail bool
var format string
var analyzeCmd = &cobra.Command{
Use: "analyze IMAGE",
Short: "Analyze Docker image",
Long: `Analyze a Docker image with Clair, against Ubuntu, Red hat and Debian vulnerabilities databases`,
Run: func(cmd *cobra.Command, args []string) {
if len(args) != 1 {
fmt.Printf("clairctl: \"analyze\" requires a minimum of 1 argument")
os.Exit(1)
}
config.ImageName = args[0]
image, manifest, err := docker.RetrieveManifest(config.ImageName, true)
if err != nil {
fmt.Println(errInternalError)
log.Fatalf("retrieving manifest for %q: %v", config.ImageName, err)
}
if config.IsLocal {
startLocalServer()
}
if err := clair.Push(image, manifest); err != nil {
if err != nil {
fmt.Println(errInternalError)
log.Fatalf("pushing image %q: %v", image.String(), err)
}
}
analysis := clair.Analyze(image, manifest)
if whitelistConfig != "" {
whiteListProcessor := NewWhiteList(whitelistConfig)
whiteListProcessor.filter(analysis)
}
log.Debug("Using priority filters: ", filters)
switch format {
case "plain":
funcMap := template.FuncMap{
"vulns": CountVulnerabilities,
"colorized": colorized,
}
err = template.Must(template.New("analysis").Funcs(funcMap).Parse(analyzeTplt)).Execute(os.Stdout, analysis)
if err != nil {
fmt.Println(errInternalError)
log.Fatalf("rendering analysis: %v", err)
}
case "json":
var vulnsMap = make(map[string]v1.Vulnerability)
for _, layer := range analysis.Layers {
for _, f := range layer.Layer.Features {
for _, vuln := range f.Vulnerabilities {
vulnsMap[vuln.Name] = vuln
}
}
}
var rawVulns = make([]v1.Vulnerability, 0, len(vulnsMap))
for _, value := range vulnsMap {
rawVulns = append(rawVulns, value)
}
var vulns = CountRawVulnerabilities(rawVulns)
var info = AnalyseInfo{Image: analysis.ImageName, Vulns: vulns}
b, _ := json.MarshalIndent(info, "", " ")
fmt.Println(string(b))
default:
log.Fatalf("Bad format type '%s'", format)
}
if !isValid(analysis.MostRecentLayer()) && !noFail {
os.Exit(1)
}
},
}
type PriorityCount struct {
Priority types.Priority
Count int
}
func colorized(p PriorityCount) string {
switch p.Priority {
case types.Unknown:
return color.WhiteString("%v: %v", p.Priority, p.Count)
case types.Negligible:
return color.HiWhiteString("%v: %v", p.Priority, p.Count)
case types.Low:
return color.YellowString("%v: %v", p.Priority, p.Count)
case types.Medium:
return color.HiYellowString("%v: %v", p.Priority, p.Count)
case types.High:
return color.MagentaString("%v: %v", p.Priority, p.Count)
case types.Critical:
return color.RedString("%v: %v", p.Priority, p.Count)
case types.Defcon1:
return color.HiRedString("%v: %v", p.Priority, p.Count)
default:
return color.WhiteString("%v: %v", p.Priority, p.Count)
}
}
func isValid(l v1.LayerEnvelope) bool {
for _, v := range CountVulnerabilities(l) {
if v.Count != 0 {
return false
}
}
return true
}
func getPrioritiesFromArgs() []types.Priority {
f := []types.Priority{}
for _, aa := range strings.Split(filters, ",") {
if types.Priority(aa).IsValid() {
f = append(f, types.Priority(aa))
}
}
return f
}
func CountRawVulnerabilities(vulns []v1.Vulnerability) []PriorityCount {
filtersS := getPrioritiesFromArgs()
if len(filtersS) == 0 {
filtersS = types.Priorities
}
r := make(map[types.Priority]int)
for _, v := range filtersS {
r[v] = 0
}
for _, v := range vulns {
if _, ok := r[types.Priority(v.Severity)]; ok {
r[types.Priority(v.Severity)]++
}
}
result := []PriorityCount{}
for _, p := range types.Priorities {
if pp, ok := r[p]; ok {
result = append(result, PriorityCount{p, pp})
}
}
return result
}
func CountVulnerabilities(l v1.LayerEnvelope) []PriorityCount {
var vulns = []v1.Vulnerability{}
for _, f := range l.Layer.Features {
vulns = append(vulns, f.Vulnerabilities...)
}
return CountRawVulnerabilities(vulns)
}
func init() {
RootCmd.AddCommand(analyzeCmd)
analyzeCmd.Flags().StringVarP(&filters, "filters", "f", "", "Filters Severity, comma separated (eg. High,Critical)")
analyzeCmd.Flags().StringVarP(&whitelistConfig, "whitelist", "w", "", "YAML Configuration file for severity whitelisting")
analyzeCmd.Flags().BoolVarP(&config.IsLocal, "local", "l", false, "Use local images")
analyzeCmd.Flags().BoolVarP(&noFail, "noFail", "n", false, "Not exiting with non-zero even with vulnerabilities found")
analyzeCmd.Flags().StringVar(&format, "format", "plain", "Output format (plain, json)")
}