-
Notifications
You must be signed in to change notification settings - Fork 24
/
vulnerabilityreport_controller.go
301 lines (257 loc) · 9.63 KB
/
vulnerabilityreport_controller.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
/*
Copyright 2021.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package vulnerabilityreport
import (
"context"
"fmt"
"sync"
aqua "github.com/aquasecurity/starboard/pkg/apis/aquasecurity/v1alpha1"
"github.com/go-logr/logr"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/runtime"
apitypes "k8s.io/apimachinery/pkg/types"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
ctrlutil "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/metrics"
"github.com/giantswarm/starboard-exporter/controllers"
"github.com/giantswarm/starboard-exporter/utils"
)
const (
VulnerabilityReportFinalizer = "starboard-exporter.giantswarm.io/vulnerabilityreport"
)
var registerMetricsOnce sync.Once
// VulnerabilityReportReconciler reconciles a VulnerabilityReport object
type VulnerabilityReportReconciler struct {
client.Client
Log logr.Logger
Scheme *runtime.Scheme
MaxJitterPercent int
ShardHelper *utils.ShardHelper
TargetLabels []VulnerabilityLabel
}
//+kubebuilder:rbac:groups=aquasecurity.github.io.giantswarm,resources=vulnerabilityreports,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=aquasecurity.github.io.giantswarm,resources=vulnerabilityreports/status,verbs=get;update;patch
//+kubebuilder:rbac:groups=aquasecurity.github.io.giantswarm,resources=vulnerabilityreports/finalizers,verbs=update
func (r *VulnerabilityReportReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
_ = log.FromContext(ctx)
_ = r.Log.WithValues("vulnerabilityreport", req.NamespacedName)
registerMetricsOnce.Do(r.registerMetrics)
// The report has changed, meaning our metrics are out of date for this report. Clear them.
deletedSummaries := VulnerabilitySummary.DeletePartialMatch(prometheus.Labels{"report_name": req.NamespacedName.String()})
deletedDetails := VulnerabilityInfo.DeletePartialMatch(prometheus.Labels{"report_name": req.NamespacedName.String()})
shouldOwn := r.ShardHelper.ShouldOwn(req.NamespacedName.String())
if shouldOwn {
// Try to get the report. It might not exist anymore, in which case we don't need to do anything.
report := &aqua.VulnerabilityReport{}
if err := r.Client.Get(ctx, req.NamespacedName, report); err != nil {
if apierrors.IsNotFound(err) {
// Most likely the report was deleted.
return ctrl.Result{}, nil
}
// Error reading the object.
r.Log.Error(err, "Unable to read report")
return ctrl.Result{}, err
}
r.Log.Info(fmt.Sprintf("Reconciled %s || Found (C/H/M/L/N/U): %d/%d/%d/%d/%d/%d",
req.NamespacedName,
report.Report.Summary.CriticalCount,
report.Report.Summary.HighCount,
report.Report.Summary.MediumCount,
report.Report.Summary.LowCount,
report.Report.Summary.NoneCount,
report.Report.Summary.UnknownCount,
))
// Publish summary and CVE metrics for this report.
r.publishImageMetrics(report)
if utils.SliceContains(report.GetFinalizers(), VulnerabilityReportFinalizer) {
// Remove the finalizer if we're the shard owner.
ctrlutil.RemoveFinalizer(report, VulnerabilityReportFinalizer)
if err := r.Update(ctx, report); err != nil {
return ctrl.Result{}, err
}
}
// Add a label to this report so any previous owners will reconcile and drop the metric.
report.Labels[controllers.ShardOwnerLabel] = r.ShardHelper.PodIP
err := r.Client.Update(ctx, report, &client.UpdateOptions{})
if err != nil {
r.Log.Error(err, "unable to add shard owner label")
}
} else {
if deletedSummaries > 0 || deletedDetails > 0 {
r.Log.Info(fmt.Sprintf("cleared %d summary and %d detail metrics", deletedSummaries, deletedDetails))
}
}
return utils.JitterRequeue(controllers.DefaultRequeueDuration, r.MaxJitterPercent, r.Log), nil
}
func (r *VulnerabilityReportReconciler) registerMetrics() {
VulnerabilityInfo = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Namespace: metricNamespace,
Subsystem: metricSubsystem,
Name: "image_vulnerability",
Help: "Indicates the presence of a CVE in an image.",
},
LabelNamesForList(r.TargetLabels),
)
metrics.Registry.MustRegister(VulnerabilityInfo)
}
// SetupWithManager sets up the controller with the Manager.
func (r *VulnerabilityReportReconciler) SetupWithManager(mgr ctrl.Manager) error {
err := ctrl.NewControllerManagedBy(mgr).
For(&aqua.VulnerabilityReport{}).
Complete(r)
if err != nil {
return errors.Wrap(err, "failed setting up controller with controller manager")
}
return nil
}
func (r *VulnerabilityReportReconciler) publishImageMetrics(report *aqua.VulnerabilityReport) {
publishSummaryMetrics(report)
// If we have custom metrics to expose, do it.
if len(r.TargetLabels) > 0 {
publishCustomMetrics(report, r.TargetLabels)
}
}
func RequeueReportsForPod(c client.Client, log logr.Logger, podIP string) {
vulnList := &aqua.VulnerabilityReportList{}
opts := []client.ListOption{
client.MatchingLabels{controllers.ShardOwnerLabel: podIP},
}
// Get the list of reports with our label.
err := c.List(context.Background(), vulnList, opts...)
if err != nil {
log.Error(err, "unable to fetch vulnerabilityreport")
}
for _, r := range vulnList.Items {
// Retrieve the individual report.
report := &aqua.VulnerabilityReport{}
err := c.Get(context.Background(), client.ObjectKey{Name: r.Name, Namespace: r.Namespace}, report)
if err != nil {
log.Error(err, "unable to fetch vulnerabilityreport")
}
// Clear the shard-owner label if it still has our label
if r.Labels[controllers.ShardOwnerLabel] == podIP {
r.Labels[controllers.ShardOwnerLabel] = ""
err = c.Update(context.Background(), report, &client.UpdateOptions{})
if err != nil {
log.Error(err, fmt.Sprintf("unable to remove %s label", controllers.ShardOwnerLabel))
}
}
}
}
func getCountPerSeverity(report *aqua.VulnerabilityReport) map[string]float64 {
// Format is e.g. {CRITICAL: 10}.
return map[string]float64{
string(aqua.SeverityCritical): float64(report.Report.Summary.CriticalCount),
string(aqua.SeverityHigh): float64(report.Report.Summary.HighCount),
string(aqua.SeverityMedium): float64(report.Report.Summary.MediumCount),
string(aqua.SeverityLow): float64(report.Report.Summary.LowCount),
string(aqua.SeverityNone): float64(report.Report.Summary.NoneCount),
string(aqua.SeverityUnknown): float64(report.Report.Summary.UnknownCount),
}
}
func publishSummaryMetrics(report *aqua.VulnerabilityReport) {
summaryValues := valuesForReport(report, LabelsForGroup(labelGroupSummary))
// Add the severity label after the standard labels and expose each severity metric.
for severity, count := range getCountPerSeverity(report) {
v := summaryValues
v["severity"] = severity
// Expose the metric.
VulnerabilitySummary.With(
v,
).Set(count)
}
}
func publishCustomMetrics(report *aqua.VulnerabilityReport, targetLabels []VulnerabilityLabel) {
reportValues := valuesForReport(report, targetLabels)
for _, v := range report.Report.Vulnerabilities {
vulnValues := valuesForVulnerability(v, targetLabels)
// Include the Report-level values.
for label, value := range reportValues {
vulnValues[label] = value
}
// If we have a score, use it for the value.
score := float64(0)
if v.Score != nil {
score = *v.Score
}
// Expose the metric
VulnerabilityInfo.With(
vulnValues,
).Set(score)
}
}
func valuesForReport(report *aqua.VulnerabilityReport, labels []VulnerabilityLabel) map[string]string {
result := map[string]string{}
for _, label := range labels {
if label.Scope == FieldScopeReport {
result[label.Name] = reportValueFor(label.Name, report)
}
}
return result
}
func valuesForVulnerability(vuln aqua.Vulnerability, labels []VulnerabilityLabel) map[string]string {
result := map[string]string{}
for _, label := range labels {
if label.Scope == FieldScopeVulnerability {
result[label.Name] = vulnValueFor(label.Name, vuln)
}
}
return result
}
func reportValueFor(field string, report *aqua.VulnerabilityReport) string {
switch field {
case "report_name":
// Construct the namespacedname which we'll later be given at reconciliation.
return apitypes.NamespacedName{Name: report.Name, Namespace: report.Namespace}.String()
case "image_namespace":
return report.Namespace
case "image_registry":
return report.Report.Registry.Server
case "image_repository":
return report.Report.Artifact.Repository
case "image_tag":
return report.Report.Artifact.Tag
case "image_digest":
return report.Report.Artifact.Digest
default:
// Error?
return ""
}
}
func vulnValueFor(field string, vuln aqua.Vulnerability) string {
switch field {
case "vulnerability_id":
return vuln.VulnerabilityID
case "vulnerable_resource_name":
return vuln.Resource
case "installed_resource_version":
return vuln.InstalledVersion
case "fixed_resource_version":
return vuln.FixedVersion
case "vulnerability_title":
return vuln.Title
case "vulnerability_link":
return vuln.PrimaryLink
case "severity":
// Severity is a custom type in the Aqua library.
return string(vuln.Severity)
default:
// Error?
return ""
}
}