/
sarifprinter.go
413 lines (349 loc) · 12.2 KB
/
sarifprinter.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
package printer
import (
"context"
"encoding/json"
"fmt"
"net/url"
"os"
"path"
"path/filepath"
"strconv"
"strings"
"github.com/anchore/grype/grype/presenter"
"github.com/anchore/grype/grype/presenter/models"
logger "github.com/kubescape/go-logger"
"github.com/kubescape/go-logger/helpers"
"github.com/kubescape/kubescape/v2/core/cautils"
"github.com/kubescape/kubescape/v2/core/pkg/fixhandler"
"github.com/kubescape/kubescape/v2/core/pkg/resultshandling/locationresolver"
"github.com/kubescape/kubescape/v2/core/pkg/resultshandling/printer"
"github.com/kubescape/opa-utils/objectsenvelopes/localworkload"
"github.com/kubescape/opa-utils/reporthandling/results/v1/reportsummary"
"github.com/kubescape/opa-utils/reporthandling/results/v1/resourcesresults"
v2 "github.com/kubescape/opa-utils/reporthandling/v2"
"github.com/owenrumney/go-sarif/v2/sarif"
"github.com/sergi/go-diff/diffmatchpatch"
)
const (
sarifOutputFile = "report"
sarifOutputExt = ".sarif"
toolName = "kubescape"
toolInfoURI = "https://armosec.io"
)
// sarifSeverityLevel is a SARIF-specific severity level for Rules and Results
type sarifSeverityLevel string
const (
sarifSeverityLevelNote sarifSeverityLevel = "note"
sarifSeverityLevelWarning sarifSeverityLevel = "warning"
sarifSeverityLevelError sarifSeverityLevel = "error"
)
// scoreFactorToSARIFSeverityLevel returns a SARIF severity level that matches
// a given Kubescape severity score
func scoreFactorToSARIFSeverityLevel(score float32) sarifSeverityLevel {
switch {
case score >= 9.0:
return sarifSeverityLevelError
case score >= 4.0:
return sarifSeverityLevelWarning
}
return sarifSeverityLevelNote
}
var _ printer.IPrinter = &SARIFPrinter{}
// SARIFPrinter is a printer that emits the report in the SARIF format
type SARIFPrinter struct {
// outputFile is the name of the output file
writer *os.File
}
// NewSARIFPrinter returns a new SARIF printer instance
func NewSARIFPrinter() *SARIFPrinter {
return &SARIFPrinter{}
}
func (sp *SARIFPrinter) Score(score float32) {
}
func (sp *SARIFPrinter) SetWriter(ctx context.Context, outputFile string) {
if strings.TrimSpace(outputFile) == "" {
outputFile = sarifOutputFile
}
if filepath.Ext(strings.TrimSpace(outputFile)) != sarifOutputExt {
outputFile = outputFile + sarifOutputExt
}
sp.writer = printer.GetWriter(ctx, outputFile)
}
// addRule adds a rule description to the scan run based on the given control summary
func (sp *SARIFPrinter) addRule(scanRun *sarif.Run, control reportsummary.IControlSummary) {
controlSARIFSeverity := string(scoreFactorToSARIFSeverityLevel(control.GetScoreFactor()))
configuration := sarif.NewReportingConfiguration().WithLevel(controlSARIFSeverity)
scanRun.AddRule(control.GetID()).
WithDefaultConfiguration(configuration).
WithShortDescription(sarif.NewMultiformatMessageString(control.GetName())).
WithFullDescription(sarif.NewMultiformatMessageString(control.GetDescription())).
WithHelp(sarif.NewMultiformatMessageString(sp.generateRemediationMessage(control)))
}
// addResult adds a result of checking a rule to the scan run based on the given control summary
func (sp *SARIFPrinter) addResult(scanRun *sarif.Run, ctl reportsummary.IControlSummary, filepath string, location locationresolver.Location) *sarif.Result {
return scanRun.CreateResultForRule(ctl.GetID()).
WithMessage(sarif.NewTextMessage(ctl.GetDescription())).
WithLocations([]*sarif.Location{
sarif.NewLocationWithPhysicalLocation(
sarif.NewPhysicalLocation().
WithArtifactLocation(
sarif.NewSimpleArtifactLocation(filepath),
).WithRegion(
sarif.NewRegion().WithStartLine(location.Line).WithStartColumn(location.Column),
),
),
})
}
func (sp *SARIFPrinter) printImageScan(ctx context.Context, scanResults *models.PresenterConfig) error {
if scanResults == nil {
return fmt.Errorf("no no image vulnerability data provided")
}
presenterConfig, err := presenter.ValidatedConfig(printer.SARIFFormat, "", false)
if err != nil {
return err
}
pres := presenter.GetPresenter(presenterConfig, *scanResults)
if err := pres.Present(sp.writer); err != nil {
return err
}
// Change driver name to Kubescape
jsonReport, err := os.ReadFile(sp.writer.Name())
if err != nil {
logger.L().Ctx(ctx).Error("failed to read json file - results will not be patched", helpers.Error(err))
return nil
}
var sarifReport sarif.Report
if err := json.Unmarshal(jsonReport, &sarifReport); err != nil {
return err
}
// Patch driver name
for i := range sarifReport.Runs {
sarifReport.Runs[i].Tool.Driver.Name = "Kubescape"
}
// Write back to file
updatedSarifReport, err := json.MarshalIndent(sarifReport, "", " ")
if err != nil {
return err
}
return os.WriteFile(sp.writer.Name(), updatedSarifReport, os.ModePerm)
}
func (sp *SARIFPrinter) PrintNextSteps() {
}
func (sp *SARIFPrinter) ActionPrint(ctx context.Context, opaSessionObj *cautils.OPASessionObj, imageScanData []cautils.ImageScanData) {
if opaSessionObj == nil {
if len(imageScanData) == 0 {
logger.L().Ctx(ctx).Fatal("failed to write results in sarif format: no data provided")
return
}
// image scan
if err := sp.printImageScan(ctx, imageScanData[0].PresenterConfig); err != nil {
logger.L().Ctx(ctx).Error("failed to write results in sarif format", helpers.Error(err))
return
}
} else {
// configuration scan
if err := sp.printConfigurationScan(ctx, opaSessionObj); err != nil {
logger.L().Ctx(ctx).Error("failed to write results in sarif format", helpers.Error(err))
return
}
}
printer.LogOutputFile(sp.writer.Name())
}
func (sp *SARIFPrinter) printConfigurationScan(ctx context.Context, opaSessionObj *cautils.OPASessionObj) error {
report, err := sarif.New(sarif.Version210)
if err != nil {
return err
}
run := sarif.NewRunWithInformationURI(toolName, toolInfoURI)
basePath := getBasePathFromMetadata(*opaSessionObj)
for resourceID, result := range opaSessionObj.ResourcesResult {
if result.GetStatus(nil).IsFailed() {
resourceSource := opaSessionObj.ResourceSource[resourceID]
filepath := resourceSource.RelativePath
// Github Code Scanning considers results not associated to a file path meaningless and invalid when uploading
if filepath == "" || basePath == "" {
continue
}
rsrcAbsPath := path.Join(basePath, filepath)
locationResolver, err := locationresolver.NewFixPathLocationResolver(rsrcAbsPath)
if err != nil {
logger.L().Debug("failed to create location resolver", helpers.Error(err))
continue
}
for _, toPin := range result.AssociatedControls {
ac := toPin
if ac.GetStatus(nil).IsFailed() {
ctl := opaSessionObj.Report.SummaryDetails.Controls.GetControl(reportsummary.EControlCriteriaID, ac.GetID())
location := sp.resolveFixLocation(opaSessionObj, locationResolver, &ac, resourceID)
sp.addRule(run, ctl)
result := sp.addResult(run, ctl, filepath, location)
collectFixes(ctx, result, ac, opaSessionObj, resourceID, filepath)
}
}
}
}
report.AddRun(run)
report.PrettyWrite(sp.writer)
return nil
}
func (sp *SARIFPrinter) resolveFixLocation(opaSessionObj *cautils.OPASessionObj, locationResolver *locationresolver.FixPathLocationResolver, ac *resourcesresults.ResourceAssociatedControl, resourceID string) locationresolver.Location {
defaultLocation := locationresolver.Location{Line: 1, Column: 1}
if locationResolver == nil {
return defaultLocation
}
fixPaths := AssistedRemediationPathsToString(ac)
var fixPath string
if len(fixPaths) > 0 {
fixPath = fixPaths[0]
}
var location locationresolver.Location
if fixPath == "" {
return defaultLocation
}
docIndex, ok := getDocIndex(opaSessionObj, resourceID)
if !ok {
return defaultLocation
}
location, _ = locationResolver.ResolveLocation(fixPath, docIndex)
if location.Line == 0 {
return defaultLocation
}
return location
}
func addFix(result *sarif.Result, filepath string, startLine int, startColumn int, endLine int, endColumn int, text string) {
result.AddFix(
sarif.NewFix().
WithArtifactChanges([]*sarif.ArtifactChange{
sarif.NewArtifactChange(
sarif.NewSimpleArtifactLocation(filepath),
).WithReplacement(
sarif.NewReplacement(sarif.NewRegion().
WithStartLine(startLine).
WithStartColumn(startColumn).
WithEndLine(endLine).
WithEndColumn(endColumn),
).WithInsertedContent(
sarif.NewArtifactContent().WithText(text),
),
),
}),
)
}
func calculateMove(str string, file []string, endColumn int, endLine int) (int, int, bool) {
num, err := strconv.Atoi(str)
if err != nil {
logger.L().Debug("failed to get move from string "+str, helpers.Error(err))
return 0, 0, false
}
for num+endColumn-1 > len(file[endLine-1]) {
num -= len(file[endLine-1]) - endColumn + 2
endLine++
endColumn = 1
}
endColumn += num
return endLine, endColumn, true
}
func collectDiffs(dmp *diffmatchpatch.DiffMatchPatch, diffs []diffmatchpatch.Diff, result *sarif.Result, filepath string, fileAsString string) {
file := strings.Split(fileAsString, "\n")
text := ""
startLine := 1
startColumn := 1
endLine := 1
endColumn := 1
delta := strings.Split(dmp.DiffToDelta(diffs), "\t")
for index, seg := range delta {
switch seg[0] {
case '+':
var err error
text, err = url.QueryUnescape(seg[1:])
if err != nil {
logger.L().Debug("failed to unescape string", helpers.Error(err))
continue
}
if index >= len(delta)-1 || delta[index+1][0] == '=' {
addFix(result, filepath, startLine, startColumn, endLine, endColumn, text)
}
case '-':
var ok bool
endLine, endColumn, ok = calculateMove(seg[1:], file, endColumn, endLine)
if !ok {
continue
}
if index >= len(delta)-1 || delta[index+1][0] == '=' {
addFix(result, filepath, startLine, startColumn, endLine, endColumn, text)
}
case '=':
var ok bool
endLine, endColumn, ok = calculateMove(seg[1:], file, endColumn, endLine)
if !ok {
continue
}
startLine = endLine
startColumn = endColumn
text = ""
}
}
}
func collectFixes(ctx context.Context, result *sarif.Result, ac resourcesresults.ResourceAssociatedControl, opaSessionObj *cautils.OPASessionObj, resourceID string, filepath string) {
for _, rule := range ac.ResourceAssociatedRules {
if !rule.GetStatus(nil).IsFailed() {
continue
}
for _, rulePaths := range rule.Paths {
if rulePaths.FixPath.Path == "" {
continue
}
// if strings.HasPrefix(rulePaths.FixPath.Value, fixhandler.UserValuePrefix) {
// continue
// }
documentIndex, ok := getDocIndex(opaSessionObj, resourceID)
if !ok {
continue
}
yamlExpression := fixhandler.FixPathToValidYamlExpression(rulePaths.FixPath.Path, rulePaths.FixPath.Value, documentIndex)
fileAsString, err := fixhandler.GetFileString(filepath)
if err != nil {
logger.L().Debug("failed to access "+filepath, helpers.Error(err))
continue
}
fixedYamlString, err := fixhandler.ApplyFixToContent(ctx, fileAsString, yamlExpression)
if err != nil {
logger.L().Debug("failed to fix "+filepath+" with "+yamlExpression, helpers.Error(err))
continue
}
dmp := diffmatchpatch.New()
diffs := dmp.DiffMain(fileAsString, fixedYamlString, false)
collectDiffs(dmp, diffs, result, filepath, fileAsString)
}
}
}
func getDocIndex(opaSessionObj *cautils.OPASessionObj, resourceID string) (int, bool) {
resource := opaSessionObj.AllResources[resourceID]
localworkload, ok := resource.(*localworkload.LocalWorkload)
if !ok {
return 0, false
}
splittedPath := strings.Split(localworkload.GetPath(), ":")
if len(splittedPath) <= 1 {
return 0, false
}
docIndex, err := strconv.Atoi(splittedPath[1])
if err != nil {
return 0, false
}
return docIndex, true
}
func getBasePathFromMetadata(opaSessionObj cautils.OPASessionObj) string {
switch opaSessionObj.Metadata.ScanMetadata.ScanningTarget {
case v2.GitLocal:
return opaSessionObj.Metadata.ContextMetadata.RepoContextMetadata.LocalRootPath
case v2.Directory:
return opaSessionObj.Metadata.ContextMetadata.DirectoryContextMetadata.BasePath
default:
return ""
}
}
// generateRemediationMessage generates a remediation message for the given control summary
func (sp *SARIFPrinter) generateRemediationMessage(control reportsummary.IControlSummary) string {
return fmt.Sprintf("Remediation: %s", control.GetRemediation())
}