-
Notifications
You must be signed in to change notification settings - Fork 1
/
report.go
368 lines (306 loc) · 9.44 KB
/
report.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
package report
import (
"fmt"
"io"
"strings"
"golang.org/x/exp/maps"
"golang.org/x/exp/slices"
"golang.org/x/xerrors"
dbTypes "github.com/aquasecurity/trivy-db/pkg/types"
"github.com/aquasecurity/trivy-kubernetes/pkg/artifacts"
ftypes "github.com/zhanglimao/trivy/pkg/fanal/types"
"github.com/zhanglimao/trivy/pkg/log"
"github.com/zhanglimao/trivy/pkg/report/table"
"github.com/zhanglimao/trivy/pkg/types"
)
const (
allReport = "all"
summaryReport = "summary"
tableFormat = "table"
jsonFormat = "json"
workloadComponent = "workload"
infraComponent = "infra"
)
type Option struct {
Format string
Report string
Output io.Writer
Severities []dbTypes.Severity
ColumnHeading []string
Scanners types.Scanners
Components []string
}
// Report represents a kubernetes scan report
type Report struct {
SchemaVersion int `json:",omitempty"`
ClusterName string
Resources []Resource `json:",omitempty"`
name string
}
// ConsolidatedReport represents a kubernetes scan report with consolidated findings
type ConsolidatedReport struct {
SchemaVersion int `json:",omitempty"`
ClusterName string
Findings []Resource `json:",omitempty"`
}
// Resource represents a kubernetes resource report
type Resource struct {
Namespace string `json:",omitempty"`
Kind string
Name string
// TODO(josedonizetti): should add metadata? per report? per Result?
// Metadata Metadata `json:",omitempty"`
Results types.Results `json:",omitempty"`
Error string `json:",omitempty"`
// original report
Report types.Report `json:"-"`
}
func (r Resource) fullname() string {
return strings.ToLower(fmt.Sprintf("%s/%s/%s", r.Namespace, r.Kind, r.Name))
}
// Failed returns whether the k8s report includes any vulnerabilities or misconfigurations
func (r Report) Failed() bool {
for _, v := range r.Resources {
if v.Results.Failed() {
return true
}
}
return false
}
func (r Report) consolidate() ConsolidatedReport {
consolidated := ConsolidatedReport{
SchemaVersion: r.SchemaVersion,
ClusterName: r.ClusterName,
}
index := make(map[string]Resource)
vulnerabilities := make([]Resource, 0)
for _, m := range r.Resources {
if vulnerabilitiesOrSecretResource(m) {
vulnerabilities = append(vulnerabilities, m)
} else {
index[m.fullname()] = m
}
}
for _, v := range vulnerabilities {
key := v.fullname()
if res, ok := index[key]; ok {
index[key] = Resource{
Namespace: res.Namespace,
Kind: res.Kind,
Name: res.Name,
Results: append(res.Results, v.Results...),
Error: res.Error,
}
continue
}
index[key] = v
}
consolidated.Findings = maps.Values(index)
return consolidated
}
// Writer defines the result write operation
type Writer interface {
Write(Report) error
}
// Write writes the results in the give format
func Write(report Report, option Option) error {
report.printErrors()
switch option.Format {
case jsonFormat:
jwriter := JSONWriter{
Output: option.Output,
Report: option.Report,
}
return jwriter.Write(report)
case tableFormat:
separatedReports := separateMisconfigReports(report, option.Scanners, option.Components)
if option.Report == summaryReport {
target := fmt.Sprintf("Summary Report for %s", report.ClusterName)
table.RenderTarget(option.Output, target, table.IsOutputToTerminal(option.Output))
}
for _, r := range separatedReports {
writer := &TableWriter{
Output: option.Output,
Report: option.Report,
Severities: option.Severities,
ColumnHeading: ColumnHeading(option.Scanners, option.Components, r.columns),
}
if err := writer.Write(r.report); err != nil {
return err
}
}
return nil
default:
return xerrors.Errorf(`unknown format %q. Use "json" or "table"`, option.Format)
}
}
type reports struct {
report Report
columns []string
}
// separateMisconfigReports returns 3 reports based on scanners and components flags,
// - misconfiguration report
// - rbac report
// - infra checks report
func separateMisconfigReports(k8sReport Report, scanners types.Scanners, components []string) []reports {
workloadMisconfig := make([]Resource, 0)
infraMisconfig := make([]Resource, 0)
rbacAssessment := make([]Resource, 0)
workloadVulnerabilities := make([]Resource, 0)
workloadResource := make([]Resource, 0)
for _, resource := range k8sReport.Resources {
if vulnerabilitiesOrSecretResource(resource) {
workloadVulnerabilities = append(workloadVulnerabilities, resource)
continue
}
switch {
case scanners.Enabled(types.RBACScanner) && rbacResource(resource):
rbacAssessment = append(rbacAssessment, resource)
case infraResource(resource):
workload, infra := splitInfraAndWorkloadResources(resource)
if slices.Contains(components, infraComponent) {
infraMisconfig = append(infraMisconfig, infra)
}
if slices.Contains(components, workloadComponent) {
workloadMisconfig = append(workloadMisconfig, workload)
}
case scanners.Enabled(types.MisconfigScanner) && !rbacResource(resource):
if slices.Contains(components, workloadComponent) {
workloadMisconfig = append(workloadMisconfig, resource)
}
}
}
r := make([]reports, 0)
workloadResource = append(workloadResource, workloadVulnerabilities...)
workloadResource = append(workloadResource, workloadMisconfig...)
if shouldAddWorkloadReport(scanners) {
workloadReport := Report{
SchemaVersion: 0,
ClusterName: k8sReport.ClusterName,
Resources: workloadResource,
name: "Workload Assessment",
}
if (slices.Contains(components, workloadComponent) &&
len(workloadMisconfig) > 0) ||
len(workloadVulnerabilities) > 0 {
r = append(r, reports{
report: workloadReport,
columns: WorkloadColumns(),
})
}
}
if scanners.Enabled(types.RBACScanner) && len(rbacAssessment) > 0 {
r = append(r, reports{
report: Report{
SchemaVersion: 0,
ClusterName: k8sReport.ClusterName,
Resources: rbacAssessment,
name: "RBAC Assessment",
},
columns: RoleColumns(),
})
}
if scanners.Enabled(types.MisconfigScanner) &&
slices.Contains(components, infraComponent) &&
len(infraMisconfig) > 0 {
r = append(r, reports{
report: Report{
SchemaVersion: 0,
ClusterName: k8sReport.ClusterName,
Resources: infraMisconfig,
name: "Infra Assessment",
},
columns: InfraColumns(),
})
}
return r
}
func rbacResource(misConfig Resource) bool {
return misConfig.Kind == "Role" || misConfig.Kind == "RoleBinding" || misConfig.Kind == "ClusterRole" || misConfig.Kind == "ClusterRoleBinding"
}
func infraResource(misConfig Resource) bool {
return (misConfig.Kind == "Pod" && misConfig.Namespace == "kube-system") || misConfig.Kind == "NodeInfo"
}
func CreateResource(artifact *artifacts.Artifact, report types.Report, err error) Resource {
results := make([]types.Result, 0, len(report.Results))
// fix target name
for _, result := range report.Results {
// if resource is a kubernetes file fix the target name,
// to avoid showing the temp file that was removed.
if result.Type == ftypes.Kubernetes {
result.Target = fmt.Sprintf("%s/%s", artifact.Kind, artifact.Name)
}
results = append(results, result)
}
r := Resource{
Namespace: artifact.Namespace,
Kind: artifact.Kind,
Name: artifact.Name,
Results: results,
Report: report,
}
// if there was any error during the scan
if err != nil {
r.Error = err.Error()
}
return r
}
func (r Report) printErrors() {
for _, resource := range r.Resources {
if resource.Error != "" {
log.Logger.Errorf("Error during vulnerabilities or misconfiguration scan: %s", resource.Error)
}
}
}
func splitInfraAndWorkloadResources(misconfig Resource) (Resource, Resource) {
workload := copyResource(misconfig)
infra := copyResource(misconfig)
workloadResults := make(types.Results, 0)
infraResults := make(types.Results, 0)
for _, result := range misconfig.Results {
workloadMisconfigs := make([]types.DetectedMisconfiguration, 0)
infraMisconfigs := make([]types.DetectedMisconfiguration, 0)
for _, m := range result.Misconfigurations {
if strings.HasPrefix(m.ID, "KCV") {
infraMisconfigs = append(infraMisconfigs, m)
continue
}
workloadMisconfigs = append(workloadMisconfigs, m)
}
if len(workloadMisconfigs) > 0 {
workloadResults = append(workloadResults, copyResult(result, workloadMisconfigs))
}
if len(infraMisconfigs) > 0 {
infraResults = append(infraResults, copyResult(result, infraMisconfigs))
}
}
workload.Results = workloadResults
workload.Report.Results = workloadResults
infra.Results = infraResults
infra.Report.Results = infraResults
return workload, infra
}
func copyResource(r Resource) Resource {
return Resource{
Namespace: r.Namespace,
Kind: r.Kind,
Name: r.Name,
Error: r.Error,
Report: r.Report,
}
}
func copyResult(r types.Result, misconfigs []types.DetectedMisconfiguration) types.Result {
return types.Result{
Target: r.Target,
Class: r.Class,
Type: r.Type,
MisconfSummary: r.MisconfSummary,
Misconfigurations: misconfigs,
}
}
func shouldAddWorkloadReport(scanners types.Scanners) bool {
return scanners.AnyEnabled(types.MisconfigScanner, types.VulnerabilityScanner, types.SecretScanner)
}
func vulnerabilitiesOrSecretResource(resource Resource) bool {
return len(resource.Results) > 0 && (len(resource.Results[0].Vulnerabilities) > 0 || len(resource.Results[0].Secrets) > 0)
}