-
Notifications
You must be signed in to change notification settings - Fork 5
/
run-once.go
245 lines (219 loc) · 6.45 KB
/
run-once.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
package main
import (
"context"
"encoding/json"
"fmt"
"os"
"path"
"sort"
"strings"
"time"
out "github.com/deepfence/package-scanner/output"
"github.com/deepfence/package-scanner/sbom/syft"
"github.com/deepfence/package-scanner/scanner"
"github.com/deepfence/package-scanner/scanner/grype"
"github.com/deepfence/package-scanner/utils"
"github.com/google/uuid"
log "github.com/sirupsen/logrus"
)
func RunOnce(config utils.Config) {
if config.Source == "" {
log.Fatal("error: source is required")
}
if config.FailOnScore > 10.0 {
log.Fatal("error: fail-on-score should be between -1 and 10")
}
if config.Output != utils.TableOutput && config.Output != utils.JSONOutput {
log.Errorf("error: output should be %s or %s", utils.JSONOutput, utils.TableOutput)
}
// trim any spaces from severities passed from command line
cSeverity := []string{}
if len(*severity) > 0 {
for _, s := range strings.Split(*severity, ",") {
cSeverity = append(cSeverity, strings.TrimSpace(s))
}
}
hostname := utils.GetHostname()
if strings.HasPrefix(config.Source, "dir:") || config.Source == "." {
hostname := utils.GetHostname()
config.HostName = hostname
config.NodeID = hostname
config.NodeType = utils.NodeTypeHost
if config.ScanID == "" {
config.ScanID = fmt.Sprintf("%s_%d", hostname, utils.GetIntTimestamp())
}
} else {
config.NodeID = config.Source
config.HostName = hostname
config.NodeType = utils.NodeTypeImage
if config.ScanID == "" {
config.ScanID = fmt.Sprintf("%s_%d", hostname, utils.GetIntTimestamp())
}
if imageID, err := config.ContainerRuntime.GetImageID(config.Source); err != nil {
log.Error(err)
// generate image_id if we are unable to get it from runtime
imageID = []byte(uuid.New().String())
config.ImageID = string(imageID)
config.NodeID = string(imageID)
} else {
sp := strings.Split(strings.TrimSpace(string(imageID)), ":")
config.ImageID = sp[len(sp)-1]
config.NodeID = sp[len(sp)-1]
}
log.Debugf("image_id: %s", config.ImageID)
}
// try to get image id
var pub *out.Publisher
var err error
// send sbom to console if console url and key are configured
if len(config.ConsoleURL) != 0 && len(config.DeepfenceKey) != 0 {
pub, err = out.NewPublisher(config)
if err != nil {
log.Error(err)
}
pub.SendReport()
scanID := pub.StartScan()
if scanID == "" {
log.Warn("console scan id is empty")
scanID = fmt.Sprintf("%s-%d", config.ImageID, time.Now().UnixMilli())
}
config.ScanID = scanID
pub.SetScanID(scanID)
}
log.Infof("scan id %s", config.ScanID)
log.Debugf("config: %+v", config)
log.Debugf("generating sbom for %s ...", config.Source)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
sbomResult, err := syft.GenerateSBOM(ctx, config)
if err != nil {
log.Errorf("Error: %v", err)
return
}
// send sbom to console if console url and key are configured
if len(config.ConsoleURL) != 0 && len(config.DeepfenceKey) != 0 {
log.Infof("sending sbom to console at %s", config.ConsoleURL)
pub.RunVulnerabilityScan(sbomResult)
}
// create a temporary file to store the user input(SBOM)
file, err := utils.CreateTempFile(sbomResult)
if err != nil {
log.Errorf("error on CreateTempFile: %s", err.Error())
return
}
if !config.KeepSbom {
defer os.Remove(file.Name())
} else {
log.Infof("generated sbom file at %s", file.Name())
}
// get user cache dir
cacheDir, dirErr := os.UserCacheDir()
if dirErr != nil {
log.Panic(dirErr)
}
env := []string{
fmt.Sprintf("GRYPE_DB_CACHE_DIR=%s", path.Join(cacheDir, "grype", "db")),
}
log.Debug("scanning sbom for vulnerabilities ...")
vulnerabilities, err := grype.Scan(config.GrypeBinPath, config.GrypeConfigPath, file.Name(), &env)
if err != nil {
log.Panicf("error on sbom scan: %s %s", err.Error(), vulnerabilities)
}
report, err := grype.PopulateFinalReport(vulnerabilities, config)
if err != nil {
log.Panicf("error on generate vulnerability report: %s", err.Error())
}
// send vulnerability scan results to console
if len(config.ConsoleURL) != 0 && len(config.DeepfenceKey) != 0 {
log.Infof("sending scan result to console at %s", config.ConsoleURL)
_ = pub.SendScanResultToConsole(report)
}
// scan details
details := out.CountBySeverity(&report)
// filter by severity
filtered := FilterBySeverity(&report, cSeverity)
// sort by severity
sort.Slice(filtered, func(i, j int) bool {
return severityToInt(filtered[i].CveSeverity) > severityToInt(filtered[j].CveSeverity)
})
exploitable, others := GroupByExploitability(&filtered)
if *output != utils.JSONOutput {
fmt.Printf("summary:\n total=%d %s=%d %s=%d %s=%d %s=%d %s=%d\n",
details.Total,
utils.CRITICAL, details.Severity.Critical,
utils.HIGH, details.Severity.High,
utils.MEDIUM, details.Severity.Medium,
utils.LOW, details.Severity.Low,
utils.UNKNOWN, details.Severity.Unknown)
if len(exploitable) > 0 {
fmt.Println("\nMost Exploitable Vulnerabilities:")
_ = out.TableOutput(&exploitable)
}
if len(others) > 0 {
fmt.Println("\nOther Vulnerabilities:")
_ = out.TableOutput(&others)
}
// out.TableOutput(&filtered)
} else {
final := map[string]interface{}{
"summary": details,
"most_exploitable_vulnerabilities": exploitable,
"other_vulnerabilities": others,
}
data, err := json.MarshalIndent(final, "", " ")
if err != nil {
log.Panicf("error converting report to json, %s", err)
}
fmt.Println(string(data))
}
out.FailOn(&config, details)
}
func severityToInt(severity string) int {
switch severity {
case utils.CRITICAL:
return 5
case utils.HIGH:
return 4
case utils.MEDIUM:
return 3
case utils.LOW:
return 2
case utils.NEGLIGIBLE:
return 1
case utils.UNKNOWN:
return 0
default:
return -1
}
}
func FilterBySeverity(
report *[]scanner.VulnerabilityScanReport,
severity []string,
) []scanner.VulnerabilityScanReport {
// if there are no filters return original report
if len(severity) < 1 {
return *report
}
filtered := []scanner.VulnerabilityScanReport{}
for _, r := range *report {
if utils.Contains(severity, r.CveSeverity) {
filtered = append(filtered, r)
}
}
return filtered
}
func GroupByExploitability(
reports *[]scanner.VulnerabilityScanReport,
) (
exploitable []scanner.VulnerabilityScanReport,
others []scanner.VulnerabilityScanReport,
) {
for _, r := range *reports {
if r.InitExploitabilityScore > 0 {
exploitable = append(exploitable, r)
} else {
others = append(others, r)
}
}
return
}