-
Notifications
You must be signed in to change notification settings - Fork 6
/
kove.go
424 lines (362 loc) · 12.1 KB
/
kove.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
414
415
416
417
418
419
420
421
422
423
424
package main
import (
"context"
"flag"
"fmt"
"net/http"
"os"
"strings"
"sync"
"github.com/open-policy-agent/opa/rego"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
diff "github.com/r3labs/diff/v2"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/client-go/discovery"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/dynamic/dynamicinformer"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/tools/clientcmd"
klog "k8s.io/klog/v2"
)
var (
configPath *string
conf *config
ruleSet string
data string
wg = new(sync.WaitGroup)
// Metric type we serve to surface offending objects
violation = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "opa_policy_violation",
Help: "Kubernetes object violating policy evaluation.",
},
[]string{"name", "namespace", "kind", "api_version", "ruleset", "data"},
)
totalViolations = prometheus.NewCounter(
prometheus.CounterOpts{
Name: "opa_policy_violations_total",
Help: "Total count of policy violations observed.",
},
)
totalViolationsResolved = prometheus.NewCounter(
prometheus.CounterOpts{
Name: "opa_policy_violations_resolved_total",
Help: "Total count of policy violation resolutions observed.",
},
)
totalObjectEvaluations = prometheus.NewCounter(
prometheus.CounterOpts{
Name: "opa_object_evaluations_total",
Help: "Total count of Kubernetes object evaluations conducted.",
},
)
)
// Healthcheck endpoint
func healthz(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
}
// Web server helper
func serveMetrics(port int) error {
prometheus.MustRegister(violation)
prometheus.MustRegister(totalViolations)
prometheus.MustRegister(totalViolationsResolved)
prometheus.MustRegister(totalObjectEvaluations)
http.HandleFunc("/healthz", healthz)
http.Handle("/metrics", promhttp.Handler())
http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
return nil
}
// Initialise our flags and start the metric webserver
func init() {
configPath = flag.String("config", "", "Path to the configuration")
go func() {
if err := serveMetrics(3000); err != nil {
klog.ErrorS(err, "unable to serve metric")
os.Exit(1)
}
}()
}
func main() {
// Parse our flags and set up configuration
flag.Parse()
klog.InitFlags(nil)
conf = getConfig()
// Disable deprecation warning logs
rest.SetDefaultWarningHandler(rest.NoWarnings{})
// If we're inside the cluster, get our config from there.
// Otherwise, construct one from a kube config file
cfg, err := rest.InClusterConfig()
if kubeconfig := os.Getenv("KUBECONFIG"); kubeconfig != "" {
cfg, err = clientcmd.BuildConfigFromFlags("", kubeconfig)
}
if err != nil {
klog.ErrorS(err, "unable to retrieve kube config")
os.Exit(1)
}
// Initiate a dynamic client from our configuration
dc, err := dynamic.NewForConfig(cfg)
if err != nil {
klog.ErrorS(err, "unable to construct kube config")
os.Exit(1)
}
discover, err := discovery.NewDiscoveryClientForConfig(cfg)
if err != nil {
klog.ErrorS(err, "unable to construct discovery client")
}
var toWatch []schema.GroupVersionResource
// Log if any of the provided objects aren't supported
if len(conf.Objects) > 0 {
for _, r := range conf.Objects {
if err := discovery.ServerSupportsVersion(discover, r.GroupVersion()); err != nil {
klog.ErrorS(err, "unsupported object")
}
}
toWatch = conf.Objects
} else {
toWatch, err = getRegisteredResources(discover)
if err != nil {
klog.ErrorS(err, "unable to retrieve list of registered resources")
}
}
// Construct a dynamic informer from our client.
// From this, we can grab informers for multiple kinds of kubernetes objects.
// If a 'namespace' value has been provided in the configuration, this factory
// will only lease informers for objects in that namespace. Otherwise (if 'namespace' is omitted
// or an empty string) provide informers for all namespaces
factory := dynamicinformer.NewFilteredDynamicSharedInformerFactory(dc, 0, conf.Namespace, nil)
// Log where we're watching
if conf.Namespace != "" {
klog.InfoS("monitoring '" + conf.Namespace + "' namespace...")
} else {
klog.InfoS("monitoring all namespaces...")
}
// Grab an informer for each GVR outlined in our config
// Add generic event handlers for each informer and start them
klog.InfoS("starting informers...")
for _, obj := range toWatch {
o := factory.ForResource(obj)
klog.Infof("watching %s...", strings.TrimPrefix(strings.Join([]string{obj.Group, obj.Version, obj.Resource}, "/"), "/"))
o.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: onAdd,
DeleteFunc: onDelete,
UpdateFunc: onUpdate,
})
}
// Initiate a stop channel and start our factory with it
stopCh := make(chan struct{})
defer close(stopCh)
defer utilruntime.HandleCrash()
factory.Start(stopCh)
// Wait for a stop
<-stopCh
klog.InfoS("shutting down informers")
}
// onAdd evaluates the object
func onAdd(obj interface{}) {
r := obj.(*unstructured.Unstructured)
if conf.IgnoreChildren && hasOwnerRefs(r) {
return
}
kind := strings.ToLower(r.GetKind())
klog.InfoS("evaluating object", kind, klog.KObj(r))
// Allows tests to wait for backgrounded go routine to complete before checking result
wg.Add(1)
go func() {
defer wg.Done()
if err := evaluate(r, 0); err != nil {
klog.ErrorS(err, "unable to evaluate", kind, klog.KObj(r))
}
}()
}
// onUpdate evaluates the object when a legitimate change is observed
func onUpdate(oldObj, newObj interface{}) {
if conf.IgnoreChildren && hasOwnerRefs(newObj.(*unstructured.Unstructured)) {
return
}
objDiff, err := diff.Diff(oldObj, newObj)
if err != nil {
klog.ErrorS(err, "unable to diff object generations")
}
// Without this, we see duplicate evaluations
if legitimateChange(objDiff) {
metricsRemoved := deleteAllMetricsForObject(oldObj.(*unstructured.Unstructured))
r := newObj.(*unstructured.Unstructured)
kind := strings.ToLower(r.GetKind())
klog.InfoS("change observed, reevaluating object", kind, klog.KObj(r))
// Allows tests to wait for backgrounded go routine to complete before checking result
wg.Add(1)
go func() {
defer wg.Done()
if err := evaluate(r, metricsRemoved); err != nil {
klog.ErrorS(err, "unable to evaluate", kind, klog.KObj(r))
}
}()
}
}
// onDelete deletes object associated metrics
func onDelete(obj interface{}) {
r := obj.(*unstructured.Unstructured)
if conf.IgnoreChildren && hasOwnerRefs(r) {
return
}
klog.InfoS("object deleted", r.GetKind(), klog.KObj(r))
deleteAllMetricsForObject(r)
}
// deleteAllMetricsForObjects removes and series associated with a kubernetes object.
// We do not check the result or truthiness intetntionally, as this function
// may be called for an object with no associated metric.
func deleteAllMetricsForObject(obj *unstructured.Unstructured) int {
return violation.DeletePartialMatch(prometheus.Labels{
"name": obj.GetName(),
"namespace": obj.GetNamespace(),
"kind": obj.GetKind(),
"api_version": obj.GetAPIVersion(),
})
}
// legitimateChange inspects a diff.Changelog and reports if its a collection of
// kubernetes object changes that should be considered legitimate
func legitimateChange(cl diff.Changelog) bool {
if len(cl) == 0 {
return false
}
var ignorable int
for _, v := range cl {
if v.Type == "update" && contains(conf.IgnoreDifferingPaths, strings.Join(v.Path, "/")) {
ignorable++
}
}
if len(cl) == ignorable {
return false
}
return true
}
// contains is a simple helper func to assert the presence of a string in a slice
func contains(l []string, s string) bool {
for _, v := range l {
if v == s {
return true
}
}
return false
}
// hasOwnerRefs checks if an object has any owner references.
// This is useful for circumstances where you may wish to avoid child objects.
func hasOwnerRefs(obj *unstructured.Unstructured) bool {
ors := obj.GetOwnerReferences()
if len(ors) > 0 {
klog.InfoS("ignoring child object", strings.ToLower(obj.GetKind()), klog.KObj(obj))
return true
}
return false
}
// evaluate evaluates a kubernetes object against a rego policy
func evaluate(obj *unstructured.Unstructured, previousViolations int) error {
// Get our context
ctx := context.Background()
// Prepare a rego object for use with our query & policy data
r := rego.New(rego.Query(conf.RegoQuery), rego.Load(conf.Policies, nil))
pq, err := r.PrepareForEval(ctx)
if err != nil {
klog.ErrorS(err, "unable to prepare query from policy data")
}
// Evaluate the kubernetes object against our prepared query
rs, err := pq.Eval(ctx, rego.EvalInput(obj.Object))
if err != nil {
klog.ErrorS(err, "unable to evaluate prepared query")
}
// Set up a var that indicates the presence of a violation
violations := 0
// Range the returned rego expressions in our resulting ruleset.
// Any violations will expose a Prometheus metric with labels providing object details
for _, r := range rs {
for _, e := range r.Expressions {
for _, i := range e.Value.([]interface{}) {
m := i.(map[string]interface{})
if _, ok := m["RuleSet"]; ok {
ruleSet = m["RuleSet"].(string) // Record globally so we can reference elsewhere
}
if _, ok := m["Data"]; ok {
data = m["Data"].(string) // Record globally so we can reference elsewhere
}
violations += 1
klog.InfoS("violation observed", strings.ToLower(obj.GetKind()), klog.KObj(obj), "ruleset", ruleSet, "data", data)
registerViolation(
m["Name"].(string),
m["Namespace"].(string),
m["Kind"].(string),
m["ApiVersion"].(string),
ruleSet,
data,
)
}
}
}
// If this is an existing object and no violation is found
// we delete the associated metric (if there is one... if not
// we just silently ignore it)
resolvedViolations := previousViolations - violations
for resolvedViolations > 0 {
totalViolationsResolved.Inc()
resolvedViolations -= 1
}
// Record the evaluation in the total counter
totalObjectEvaluations.Inc()
return nil
}
func registerViolation(name, namespace, kind, apiVersion, ruleset, data string) {
violation.WithLabelValues(name, namespace, kind, apiVersion, ruleset, data).Set(1)
// Record the violation in the total counter
totalViolations.Inc()
}
func getRegisteredResources(discover *discovery.DiscoveryClient) ([]schema.GroupVersionResource, error) {
var r []schema.GroupVersionResource
_, resources, err := discover.ServerGroupsAndResources()
if err != nil {
return nil, fmt.Errorf("unable to discover server-groups-and-resources")
}
// Here, we reason about the sort of resources that should be watched based on verbs.
// The logic is such that - if it is a user-managed resource (and thus controllable) - it'll
// likely support said verbs.
// Along with this, if configured to monitor a specific namespace, we need to only discover
// namespaced resources
var filtered []*metav1.APIResourceList
wantedVerbs := []string{
"create", "delete", "get", "list", "patch", "update", "watch",
}
if conf.Namespace != "" {
filtered = discovery.FilteredBy(namespacedImportantResource{Verbs: wantedVerbs, NotKind: conf.IgnoreKinds}, resources)
} else {
filtered = discovery.FilteredBy(importantResource{Verbs: wantedVerbs, NotKind: conf.IgnoreKinds}, resources)
}
gvrs, err := discovery.GroupVersionResources(filtered)
if err != nil {
return nil, fmt.Errorf("unable to convert discovered resources to GVRs")
}
for k := range gvrs {
r = append(r, k)
}
return r, nil
}
type importantResource struct {
Verbs []string
NotKind []string
}
func (i importantResource) Match(groupVersion string, r *metav1.APIResource) bool {
return !contains(i.NotKind, strings.ToLower(r.Kind)) &&
sets.NewString([]string(r.Verbs)...).HasAll(i.Verbs...)
}
type namespacedImportantResource struct {
Verbs []string
NotKind []string
}
func (n namespacedImportantResource) Match(groupVersion string, r *metav1.APIResource) bool {
return !contains(n.NotKind, strings.ToLower(r.Kind)) &&
sets.NewString([]string(r.Verbs)...).HasAll(n.Verbs...) &&
r.Namespaced
}