-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
386 lines (330 loc) · 12 KB
/
main.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
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"time"
"github.com/aquasecurity/trivy-operator/pkg/apis/aquasecurity/v1alpha1"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/securityhub"
"github.com/aws/aws-sdk-go-v2/service/securityhub/types"
"github.com/aws/aws-sdk-go-v2/service/sts"
"github.com/csepulveda/trivy-webhook-aws-security-hub/tools"
"github.com/gorilla/mux"
)
type webhook struct {
Kind string `json:"kind"`
APIVersion string `json:"apiVersion"`
}
// ProcessTrivyWebhook processes incoming vulnerability reports
func ProcessTrivyWebhook(w http.ResponseWriter, r *http.Request) {
var report webhook
// Read request body
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "Error reading request body", http.StatusBadRequest)
log.Printf("Error reading request body: %v", err)
return
}
// Validate request body is not empty
if len(body) == 0 {
http.Error(w, "Empty request body", http.StatusBadRequest)
log.Printf("Empty request body")
return
}
// Decode JSON
err = json.Unmarshal(body, &report)
if err != nil {
http.Error(w, "Invalid JSON", http.StatusBadRequest)
log.Printf("Error decoding JSON: %v", err)
return
}
var findings []types.AwsSecurityFinding
switch report.Kind {
case "ConfigAuditReport":
findings, err = getConfigAuditReportFindings(body)
if err != nil {
http.Error(w, "Error processing report", http.StatusInternalServerError)
log.Printf("Error processing report: %v", err)
return
}
case "InfraAssessmentReport":
findings, err = getInfraAssessmentReport(body)
if err != nil {
http.Error(w, "Error processing report", http.StatusInternalServerError)
log.Printf("Error processing report: %v", err)
return
}
case "ClusterComplianceReport":
findings, err = getClusterComplianceReport(body)
if err != nil {
http.Error(w, "Error processing report", http.StatusInternalServerError)
log.Printf("Error processing report: %v", err)
return
}
case "VulnerabilityReport":
findings, err = getVulnerabilityReportFindings(body)
if err != nil {
http.Error(w, "Error processing report", http.StatusInternalServerError)
log.Printf("Error processing report: %v", err)
return
}
default: // Unknown report type
http.Error(w, "unknown report type", http.StatusBadRequest)
log.Printf("unknown report type: %s", report.Kind)
return
}
//send findings to security hub
err = importFindingsToSecurityHub(findings)
if err != nil {
http.Error(w, "Error importing findings to Security Hub", http.StatusInternalServerError)
log.Printf("Error importing findings to Security Hub: %v", err)
return
}
// Return a success response
w.WriteHeader(http.StatusOK)
_, err = w.Write([]byte("Vulnerabilities processed and imported to Security Hub"))
if err != nil {
log.Printf("Error writing response: %v", err)
}
}
func getConfigAuditReportFindings(body []byte) ([]types.AwsSecurityFinding, error) {
configAuditReport := &v1alpha1.ConfigAuditReport{}
// Decode JSON
err := json.Unmarshal(body, &configAuditReport)
if err != nil {
return nil, fmt.Errorf("error decoding JSON: %v", err)
}
log.Printf("Processing report: %s", configAuditReport.Name)
// Prepare findings for AWS Security Hub BatchImportFindings API
var findings []types.AwsSecurityFinding
cfg, err := config.LoadDefaultConfig(context.TODO())
if err != nil {
return nil, fmt.Errorf("unable to load SDK config: %v", err)
}
// Create AWS STS clients
stsClient := sts.NewFromConfig(cfg)
callerIdentity, err := stsClient.GetCallerIdentity(context.TODO(), &sts.GetCallerIdentityInput{})
if err != nil {
return nil, fmt.Errorf("failed to get caller identity: %w", err)
}
// Prepare variables
AWSAccountID := aws.ToString(callerIdentity.Account)
AWSRegion := cfg.Region
ProductArn := fmt.Sprintf("arn:aws:securityhub:%s::product/aquasecurity/aquasecurity", AWSRegion)
Name := fmt.Sprintf("%s/%s", configAuditReport.OwnerReferences[0].Kind, configAuditReport.OwnerReferences[0].Name)
// Handle Checks
for _, check := range configAuditReport.Report.Checks {
severity := check.Severity
if severity == "UNKNOWN" {
severity = "INFORMATIONAL"
}
// Truncate description if too long
description := check.Description
if len(description) > 512 {
description = description[:512] + "..."
}
findings = append(findings, types.AwsSecurityFinding{
SchemaVersion: aws.String("2018-10-08"),
Id: aws.String(fmt.Sprintf("%s-%s", check.ID, Name)),
ProductArn: aws.String(ProductArn),
GeneratorId: aws.String(fmt.Sprintf("Trivy/%s", check.ID)),
AwsAccountId: aws.String(AWSAccountID),
Types: []string{"Software and Configuration Checks"},
CreatedAt: aws.String(time.Now().Format(time.RFC3339)),
UpdatedAt: aws.String(time.Now().Format(time.RFC3339)),
Severity: &types.Severity{Label: types.SeverityLabel(severity)},
Title: aws.String(fmt.Sprintf("Trivy found a misconfiguration in %s: %s", Name, check.Title)),
Description: aws.String(description),
Remediation: &types.Remediation{
Recommendation: &types.Recommendation{
Text: aws.String(check.Remediation),
},
},
ProductFields: map[string]string{"Product Name": "Trivy"},
Resources: []types.Resource{
{
Type: aws.String("Other"),
Id: aws.String(Name),
Partition: types.PartitionAws,
Region: aws.String(AWSRegion),
Details: &types.ResourceDetails{
Other: map[string]string{
"Message": check.Messages[0],
},
},
},
},
RecordState: types.RecordStateActive,
})
}
return findings, nil
}
func getInfraAssessmentReport(body []byte) ([]types.AwsSecurityFinding, error) {
infraAssessmentReport := &v1alpha1.InfraAssessmentReport{}
// Decode JSON
err := json.Unmarshal(body, &infraAssessmentReport)
if err != nil {
return nil, fmt.Errorf("error decoding JSON: %v", err)
}
log.Printf("Processing report: %s", infraAssessmentReport.Name)
// by the moment, only print the report for debugging purposes
reportJSON, err := json.MarshalIndent(infraAssessmentReport, "", " ")
if err != nil {
return nil, fmt.Errorf("error encoding JSON: %v", err)
}
log.Printf("Report: %s", reportJSON)
// Prepare findings for AWS Security Hub BatchImportFindings API
var findings []types.AwsSecurityFinding
return findings, nil
}
func getClusterComplianceReport(body []byte) ([]types.AwsSecurityFinding, error) {
clusterComplianceReport := &v1alpha1.ClusterComplianceReport{}
// Decode JSON
err := json.Unmarshal(body, &clusterComplianceReport)
if err != nil {
return nil, fmt.Errorf("error decoding JSON: %v", err)
}
log.Printf("Processing report: %s", clusterComplianceReport.Name)
// by the moment, only print the report for debugging purposes
reportJSON, err := json.MarshalIndent(clusterComplianceReport, "", " ")
if err != nil {
return nil, fmt.Errorf("error encoding JSON: %v", err)
}
log.Printf("Report: %s", reportJSON)
// Prepare findings for AWS Security Hub BatchImportFindings API
var findings []types.AwsSecurityFinding
return findings, nil
}
func getVulnerabilityReportFindings(body []byte) ([]types.AwsSecurityFinding, error) {
vulnerabilityReport := &v1alpha1.VulnerabilityReport{}
// Decode JSON
err := json.Unmarshal(body, &vulnerabilityReport)
if err != nil {
return nil, fmt.Errorf("error decoding JSON: %v", err)
}
log.Printf("Processing report: %s", vulnerabilityReport.Name)
// Load AWS SDK config
cfg, err := config.LoadDefaultConfig(context.TODO())
if err != nil {
return nil, fmt.Errorf("unable to load SDK config: %v", err)
}
// Create AWS STS clients
stsClient := sts.NewFromConfig(cfg)
callerIdentity, err := stsClient.GetCallerIdentity(context.TODO(), &sts.GetCallerIdentityInput{})
if err != nil {
return nil, fmt.Errorf("failed to get caller identity: %w", err)
}
// Prepare variables
AWSAccountID := aws.ToString(callerIdentity.Account)
AWSRegion := cfg.Region
ProductArn := fmt.Sprintf("arn:aws:securityhub:%s::product/aquasecurity/aquasecurity", AWSRegion)
Container := vulnerabilityReport.Labels["trivy-operator.container.name"]
Registry := vulnerabilityReport.Report.Registry.Server
Repository := vulnerabilityReport.Report.Artifact.Repository
Digest := vulnerabilityReport.Report.Artifact.Digest
FullImageName := fmt.Sprintf("%s/%s:%s", Registry, Repository, Digest)
ImageName := fmt.Sprintf("%s/%s", Registry, Repository)
// Prepare findings for AWS Security Hub BatchImportFindings API
var findings []types.AwsSecurityFinding
// Handle Vulnerabilities
for _, vulnerabilities := range vulnerabilityReport.Report.Vulnerabilities {
severity := vulnerabilities.Severity
if severity == "UNKNOWN" {
severity = "INFORMATIONAL"
}
// Truncate description if too long
description := vulnerabilities.Description
if len(description) > 512 {
description = description[:512] + "..."
}
findings = append(findings, types.AwsSecurityFinding{
SchemaVersion: aws.String("2018-10-08"),
Id: aws.String(fmt.Sprintf("%s-%s", FullImageName, vulnerabilities.VulnerabilityID)),
ProductArn: aws.String(ProductArn),
GeneratorId: aws.String(fmt.Sprintf("Trivy/%s", vulnerabilities.VulnerabilityID)),
AwsAccountId: aws.String(AWSAccountID),
Types: []string{"Software and Configuration Checks/Vulnerabilities/CVE"},
CreatedAt: aws.String(time.Now().Format(time.RFC3339)),
UpdatedAt: aws.String(time.Now().Format(time.RFC3339)),
Severity: &types.Severity{Label: types.SeverityLabel(severity)},
Title: aws.String(fmt.Sprintf("Trivy found a vulnerability in %s/%s related to %s", ImageName, Container, vulnerabilities.VulnerabilityID)),
Description: aws.String(description),
Remediation: &types.Remediation{
Recommendation: &types.Recommendation{
Text: aws.String("Upgrade to version " + vulnerabilities.FixedVersion),
Url: aws.String(vulnerabilities.PrimaryLink),
},
},
ProductFields: map[string]string{"Product Name": "Trivy"},
Resources: []types.Resource{
{
Type: aws.String("Container"),
Id: aws.String(ImageName),
Partition: types.PartitionAws,
Region: aws.String(AWSRegion),
Details: &types.ResourceDetails{
Other: map[string]string{
"Container Image": ImageName,
"CVE ID": vulnerabilities.VulnerabilityID,
"CVE Title": vulnerabilities.Title,
"PkgName": vulnerabilities.Resource,
"Installed Package": vulnerabilities.InstalledVersion,
"Patched Package": vulnerabilities.FixedVersion,
"NvdCvssScoreV3": fmt.Sprintf("%f", tools.GetVulnScore(vulnerabilities)),
"NvdCvssVectorV3": "",
},
},
},
},
RecordState: types.RecordStateActive,
})
}
return findings, err
}
// Import findings to AWS Security Hub in batches of 100
func importFindingsToSecurityHub(findings []types.AwsSecurityFinding) error {
cfg, err := config.LoadDefaultConfig(context.TODO())
if err != nil {
return fmt.Errorf("unable to load SDK config: %v", err)
}
client := securityhub.NewFromConfig(cfg)
batchSize := 100
for i := 0; i < len(findings); i += batchSize {
end := i + batchSize
if end > len(findings) {
end = len(findings)
}
batch := findings[i:end]
input := &securityhub.BatchImportFindingsInput{
Findings: batch,
}
// Call BatchImportFindings API
_, err := client.BatchImportFindings(context.TODO(), input)
if err != nil {
return fmt.Errorf("error importing findings to Security Hub: %v", err)
}
}
log.Printf("%d Findings imported to Security Hub", len(findings))
return nil
}
func main() {
r := mux.NewRouter()
// Define route
r.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, err := w.Write([]byte("OK"))
if err != nil {
log.Printf("Error writing response: %v", err)
}
}).Methods("GET")
r.HandleFunc("/trivy-webhook", ProcessTrivyWebhook).Methods("POST")
// Start the server
port := ":8080"
fmt.Println("Starting server on port", port)
log.Fatal(http.ListenAndServe(port, r))
}