This repository has been archived by the owner on Mar 20, 2024. It is now read-only.
forked from cilium/cilium
-
Notifications
You must be signed in to change notification settings - Fork 0
/
repository.go
802 lines (693 loc) · 26.1 KB
/
repository.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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
// Copyright 2016-2019 Authors of Cilium
//
// 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 policy
import (
"encoding/json"
"sync"
"sync/atomic"
"github.com/cilium/cilium/api/v1/models"
"github.com/cilium/cilium/pkg/eventqueue"
"github.com/cilium/cilium/pkg/identity"
"github.com/cilium/cilium/pkg/identity/cache"
"github.com/cilium/cilium/pkg/labels"
"github.com/cilium/cilium/pkg/lock"
"github.com/cilium/cilium/pkg/metrics"
"github.com/cilium/cilium/pkg/option"
"github.com/cilium/cilium/pkg/policy/api"
"github.com/cilium/cilium/pkg/policy/trafficdirection"
)
// Repository is a list of policy rules which in combination form the security
// policy. A policy repository can be
type Repository struct {
// Mutex protects the whole policy tree
Mutex lock.RWMutex
rules ruleSlice
// revision is the revision of the policy repository. It will be
// incremented whenever the policy repository is changed.
// Always positive (>0).
revision uint64
// RepositoryChangeQueue is a queue which serializes changes to the policy
// repository.
RepositoryChangeQueue *eventqueue.EventQueue
// RuleReactionQueue is a queue which serializes the resultant events that
// need to occur after updating the state of the policy repository. This
// can include queueing endpoint regenerations, policy revision increments
// for endpoints, etc.
RuleReactionQueue *eventqueue.EventQueue
}
// NewPolicyRepository allocates a new policy repository
func NewPolicyRepository() *Repository {
repoChangeQueue := eventqueue.NewEventQueueBuffered("repository-change-queue", option.Config.PolicyQueueSize)
ruleReactionQueue := eventqueue.NewEventQueueBuffered("repository-reaction-queue", option.Config.PolicyQueueSize)
repoChangeQueue.Run()
ruleReactionQueue.Run()
return &Repository{
revision: 1,
RepositoryChangeQueue: repoChangeQueue,
RuleReactionQueue: ruleReactionQueue,
}
}
// traceState is an internal structure used to collect information
// while determining policy decision
type traceState struct {
// selectedRules is the number of rules with matching EndpointSelector
selectedRules int
// matchedRules is the number of rules that have allowed traffic
matchedRules int
// constrainedRules counts how many "FromRequires" constraints are
// unsatisfied
constrainedRules int
// ruleID is the rule ID currently being evaluated
ruleID int
}
func (state *traceState) trace(rules ruleSlice, ctx *SearchContext) {
ctx.PolicyTrace("%d/%d rules selected\n", state.selectedRules, len(rules))
if state.constrainedRules > 0 {
ctx.PolicyTrace("Found unsatisfied FromRequires constraint\n")
} else if state.matchedRules > 0 {
ctx.PolicyTrace("Found allow rule\n")
} else {
ctx.PolicyTrace("Found no allow rule\n")
}
}
// CanReachIngressRLocked evaluates the policy repository for the provided search
// context and returns the verdict or api.Undecided if no rule matches for
// ingress. The policy repository mutex must be held.
func (p *Repository) CanReachIngressRLocked(ctx *SearchContext) api.Decision {
return p.rules.canReachIngressRLocked(ctx)
}
// AllowsIngressLabelAccess evaluates the policy repository for the provided search
// context and returns the verdict for ingress policy. If no matching policy
// allows for the connection, the request will be denied. The policy repository
// mutex must be held.
func (p *Repository) AllowsIngressLabelAccess(ctx *SearchContext) api.Decision {
ctx.PolicyTrace("Tracing %s\n", ctx.String())
decision := api.Denied
if len(p.rules) == 0 {
ctx.PolicyTrace(" No rules found\n")
} else {
if p.CanReachIngressRLocked(ctx) == api.Allowed {
decision = api.Allowed
}
}
ctx.PolicyTrace("Label verdict: %s", decision.String())
return decision
}
func wildcardL3L4Rule(proto api.L4Proto, port int, endpoints api.EndpointSelectorSlice,
ruleLabels labels.LabelArray, l4Policy L4PolicyMap) {
for k, filter := range l4Policy {
if proto != filter.Protocol || (port != 0 && port != filter.Port) {
continue
}
switch filter.L7Parser {
case ParserTypeNone:
continue
case ParserTypeHTTP:
// Wildcard at L7 all the endpoints allowed at L3 or L4.
for _, sel := range endpoints {
filter.L7RulesPerEp[sel] = api.L7Rules{
HTTP: []api.PortRuleHTTP{{}},
}
}
case ParserTypeKafka:
// Wildcard at L7 all the endpoints allowed at L3 or L4.
for _, sel := range endpoints {
rule := api.PortRuleKafka{}
rule.Sanitize()
filter.L7RulesPerEp[sel] = api.L7Rules{
Kafka: []api.PortRuleKafka{rule},
}
}
case ParserTypeDNS:
// Wildcard at L7 all the endpoints allowed at L3 or L4.
for _, sel := range endpoints {
rule := api.PortRuleDNS{}
rule.Sanitize()
filter.L7RulesPerEp[sel] = api.L7Rules{
DNS: []api.PortRuleDNS{rule},
}
}
default:
// Wildcard at L7 all the endpoints allowed at L3 or L4.
for _, sel := range endpoints {
filter.L7RulesPerEp[sel] = api.L7Rules{
L7Proto: filter.L7Parser.String(),
L7: []api.PortRuleL7{},
}
}
}
filter.Endpoints = append(filter.Endpoints, endpoints...)
filter.DerivedFromRules = append(filter.DerivedFromRules, ruleLabels)
l4Policy[k] = filter
}
}
// wildcardL3L4Rules updates each ingress L7 rule to allow at L7 all traffic that
// is allowed at L3-only or L3/L4.
func (p *Repository) wildcardL3L4Rules(ctx *SearchContext, ingress bool, l4Policy L4PolicyMap) {
p.rules.wildcardL3L4Rules(ctx, ingress, l4Policy)
}
// ResolveL4IngressPolicy resolves the L4 ingress policy for a set of endpoints
// by searching the policy repository for `PortRule` rules that are attached to
// a `Rule` where the EndpointSelector matches `ctx.To`. `ctx.From` takes no effect and
// is ignored in the search. If multiple `PortRule` rules are found, all rules
// are merged together. If rules contains overlapping port definitions, the first
// rule found in the repository takes precedence.
//
// TODO: Coalesce l7 rules?
func (p *Repository) ResolveL4IngressPolicy(ctx *SearchContext) (*L4PolicyMap, error) {
result, err := p.rules.resolveL4IngressPolicy(ctx, p.GetRevision())
if err != nil {
return nil, err
}
return &result.Ingress, nil
}
// ResolveL4EgressPolicy resolves the L4 egress policy for a set of endpoints
// by searching the policy repository for `PortRule` rules that are attached to
// a `Rule` where the EndpointSelector matches `ctx.From`. `ctx.To` takes no effect and
// is ignored in the search. If multiple `PortRule` rules are found, all rules
// are merged together. If rules contains overlapping port definitions, the first
// rule found in the repository takes precedence.
func (p *Repository) ResolveL4EgressPolicy(ctx *SearchContext) (*L4PolicyMap, error) {
result, err := p.rules.resolveL4EgressPolicy(ctx, p.GetRevision())
if err != nil {
return nil, err
}
return &result.Egress, nil
}
// ResolveCIDRPolicy resolves the L3 policy for a set of endpoints by searching
// the policy repository for `CIDR` rules that are attached to a `Rule`
// where the EndpointSelector matches `ctx.To`. `ctx.From` takes no effect and
// is ignored in the search.
func (p *Repository) ResolveCIDRPolicy(ctx *SearchContext) *CIDRPolicy {
return p.rules.resolveCIDRPolicy(ctx)
}
func (p *Repository) allowsL4Egress(ctx *SearchContext) api.Decision {
egressL4Policy, err := p.ResolveL4EgressPolicy(ctx)
if err != nil {
log.WithError(err).Warn("Evaluation error while resolving L4 egress policy")
}
verdict := api.Undecided
if err == nil && len(*egressL4Policy) > 0 {
verdict = egressL4Policy.EgressCoversContext(ctx)
}
if len(ctx.DPorts) == 0 {
ctx.PolicyTrace("L4 egress verdict: [no port context specified]")
} else {
ctx.PolicyTrace("L4 egress verdict: %s", verdict.String())
}
return verdict
}
func (p *Repository) allowsL4Ingress(ctx *SearchContext) api.Decision {
ingressPolicy, err := p.ResolveL4IngressPolicy(ctx)
if err != nil {
log.WithError(err).Warn("Evaluation error while resolving L4 ingress policy")
}
verdict := api.Undecided
if err == nil && len(*ingressPolicy) > 0 {
verdict = ingressPolicy.IngressCoversContext(ctx)
}
if len(ctx.DPorts) == 0 {
ctx.PolicyTrace("L4 ingress verdict: [no port context specified]")
} else {
ctx.PolicyTrace("L4 ingress verdict: %s", verdict.String())
}
return verdict
}
// AllowsIngressRLocked evaluates the policy repository for the provided search
// context and returns the verdict for ingress. If no matching policy allows for
// the connection, the request will be denied. The policy repository mutex must
// be held.
func (p *Repository) AllowsIngressRLocked(ctx *SearchContext) api.Decision {
ctx.PolicyTrace("Tracing %s\n", ctx.String())
decision := p.CanReachIngressRLocked(ctx)
ctx.PolicyTrace("Label verdict: %s", decision.String())
if decision == api.Allowed {
ctx.PolicyTrace("L4 ingress policies skipped")
return decision
}
// We only report the overall decision as L4 inclusive if a port has
// been specified
if len(ctx.DPorts) != 0 {
decision = p.allowsL4Ingress(ctx)
}
if decision != api.Allowed {
decision = api.Denied
}
return decision
}
// AllowsEgressRLocked evaluates the policy repository for the provided search
// context and returns the verdict. If no matching policy allows for the
// connection, the request will be denied. The policy repository mutex must be
// held.
func (p *Repository) AllowsEgressRLocked(egressCtx *SearchContext) api.Decision {
egressCtx.PolicyTrace("Tracing %s\n", egressCtx.String())
egressDecision := p.CanReachEgressRLocked(egressCtx)
egressCtx.PolicyTrace("Egress label verdict: %s", egressDecision.String())
if egressDecision == api.Allowed {
egressCtx.PolicyTrace("L4 egress policies skipped")
return egressDecision
}
if len(egressCtx.DPorts) != 0 {
egressDecision = p.allowsL4Egress(egressCtx)
}
// If we cannot determine whether allowed at L4, undecided decision becomes
// deny decision.
if egressDecision != api.Allowed {
egressDecision = api.Denied
}
return egressDecision
}
// AllowsEgressLabelAccess evaluates the policy repository for the provided search
// context and returns the verdict for egress. If no matching
// policy allows for the connection, the request will be denied.
// The policy repository mutex must be held.
func (p *Repository) AllowsEgressLabelAccess(egressCtx *SearchContext) api.Decision {
egressCtx.PolicyTrace("Tracing %s\n", egressCtx.String())
egressDecision := api.Denied
if len(p.rules) == 0 {
egressCtx.PolicyTrace(" No rules found\n")
} else {
egressDecision = p.CanReachEgressRLocked(egressCtx)
}
egressCtx.PolicyTrace("Egress label verdict: %s", egressDecision.String())
return egressDecision
}
// CanReachEgressRLocked evaluates the policy repository for the provided search
// context and returns the verdict or api.Undecided if no rule matches for egress
// policy.
// The policy repository mutex must be held.
func (p *Repository) CanReachEgressRLocked(egressCtx *SearchContext) api.Decision {
return p.rules.canReachEgressRLocked(egressCtx)
}
// SearchRLocked searches the policy repository for rules which match the
// specified labels and will return an array of all rules which matched.
func (p *Repository) SearchRLocked(labels labels.LabelArray) api.Rules {
result := api.Rules{}
for _, r := range p.rules {
if r.Labels.Contains(labels) {
result = append(result, &r.Rule)
}
}
return result
}
// ContainsAllRLocked returns true if repository contains all the labels in
// needed. If needed contains no labels, ContainsAllRLocked() will always return
// true.
func (p *Repository) ContainsAllRLocked(needed labels.LabelArrayList) bool {
nextLabel:
for _, neededLabel := range needed {
for _, l := range p.rules {
if len(l.Labels) > 0 && neededLabel.Contains(l.Labels) {
continue nextLabel
}
}
return false
}
return true
}
// Add inserts a rule into the policy repository
// This is just a helper function for unit testing.
// TODO: this should be in a test_helpers.go file or something similar
// so we can clearly delineate what helpers are for testing.
func (p *Repository) Add(r api.Rule, localRuleConsumers []Endpoint) (uint64, map[uint16]struct{}, error) {
p.Mutex.Lock()
defer p.Mutex.Unlock()
if err := r.Sanitize(); err != nil {
return p.GetRevision(), nil, err
}
newList := make([]*api.Rule, 1)
newList[0] = &r
_, rev := p.AddListLocked(newList)
return rev, map[uint16]struct{}{}, nil
}
// AddListLocked inserts a rule into the policy repository with the repository already locked
// Expects that the entire rule list has already been sanitized.
func (p *Repository) AddListLocked(rules api.Rules) (ruleSlice, uint64) {
newList := make(ruleSlice, len(rules))
for i := range rules {
newRule := &rule{
Rule: *rules[i],
metadata: newRuleMetadata(),
}
newList[i] = newRule
}
p.rules = append(p.rules, newList...)
p.BumpRevision()
metrics.PolicyCount.Add(float64(len(newList)))
return newList, p.GetRevision()
}
// UpdateLocalConsumers updates the cache within each rule in the given repository
// which specifies whether said rule selects said identity. Returns a wait group
// which can be used to wait until all rules have had said caches updated.
func (p *Repository) UpdateLocalConsumers(eps []Endpoint) *sync.WaitGroup {
var policySelectionWG sync.WaitGroup
for _, ep := range eps {
policySelectionWG.Add(1)
go func(epp Endpoint) {
p.rules.refreshRulesForEndpoint(epp)
policySelectionWG.Done()
}(ep)
}
return &policySelectionWG
}
// RemoveEndpointIDFromRuleCaches removes identifier from the processedConsumers
// and localRuleConsumers sets in each rule within the repository. Returns a
// sync.WaitGroup which can be waited on once all rules have been processed in
// relation to the identifier.
func (p *Repository) RemoveEndpointIDFromRuleCaches(endpointID uint16) *sync.WaitGroup {
p.Mutex.RLock()
defer p.Mutex.RUnlock()
var wg sync.WaitGroup
wg.Add(len(p.rules))
for _, r := range p.rules {
go func(rr *rule, wgg *sync.WaitGroup) {
rr.metadata.deleteID(endpointID)
wgg.Done()
}(r, &wg)
}
return &wg
}
// AddList inserts a rule into the policy repository. It is used for
// unit-testing purposes only.
func (p *Repository) AddList(rules api.Rules) (ruleSlice, uint64) {
p.Mutex.Lock()
defer p.Mutex.Unlock()
return p.AddListLocked(rules)
}
// UpdateRulesEndpointsCaches updates the caches within each rule in r that
// specify whether the rule selects the endpoints in eps. If any rule matches
// the endpoints, it is added to the provided IDSet, and removed from the
// provided EndpointSet. The provided WaitGroup is signaled for a given endpoint
// when it is finished being processed.
func (r ruleSlice) UpdateRulesEndpointsCaches(endpointsToBumpRevision *EndpointSet, endpointsToRegenerate *IDSet, policySelectionWG *sync.WaitGroup) {
// No need to check whether endpoints need to be regenerated here since we
// will unconditionally regenerate all endpoints later.
if !option.Config.SelectiveRegeneration {
return
}
endpointsToBumpRevision.ForEach(policySelectionWG, func(epp Endpoint) {
endpointSelected, err := r.updateEndpointsCaches(epp, endpointsToRegenerate)
// If we could not evaluate the rules against the current endpoint, or
// the endpoint is not selected by the rules, remove it from the set
// of endpoints to bump the revision. If the error is non-nil, the
// endpoint is no longer in either set (endpointsToBumpRevision or
// endpointsToRegenerate, as we could not determine what to do for the
// endpoint). This is usually the case when the endpoint is no longer
// alive (i.e., it has been marked to be deleted).
if endpointSelected || err != nil {
if err != nil {
log.WithError(err).Debug("could not determine whether endpoint was selected by rule")
}
endpointsToBumpRevision.Delete(epp)
}
})
}
// DeleteByLabelsLocked deletes all rules in the policy repository which
// contain the specified labels. Returns the revision of the policy repository
// after deleting the rules, as well as now many rules were deleted.
func (p *Repository) DeleteByLabelsLocked(labels labels.LabelArray) (ruleSlice, uint64, int) {
deleted := 0
new := p.rules[:0]
deletedRules := ruleSlice{}
for _, r := range p.rules {
if !r.Labels.Contains(labels) {
new = append(new, r)
} else {
deletedRules = append(deletedRules, r)
deleted++
}
}
if deleted > 0 {
p.BumpRevision()
p.rules = new
metrics.PolicyCount.Sub(float64(deleted))
}
return deletedRules, p.GetRevision(), deleted
}
// DeleteByLabels deletes all rules in the policy repository which contain the
// specified labels
func (p *Repository) DeleteByLabels(labels labels.LabelArray) (uint64, int) {
p.Mutex.Lock()
defer p.Mutex.Unlock()
_, rev, numDeleted := p.DeleteByLabelsLocked(labels)
return rev, numDeleted
}
// JSONMarshalRules returns a slice of policy rules as string in JSON
// representation
func JSONMarshalRules(rules api.Rules) string {
b, err := json.MarshalIndent(rules, "", " ")
if err != nil {
return err.Error()
}
return string(b)
}
// GetJSON returns all rules of the policy repository as string in JSON
// representation
func (p *Repository) GetJSON() string {
p.Mutex.RLock()
defer p.Mutex.RUnlock()
result := api.Rules{}
for _, r := range p.rules {
result = append(result, &r.Rule)
}
return JSONMarshalRules(result)
}
// GetRulesMatching returns whether any of the rules in a repository contain a
// rule with labels matching the labels in the provided LabelArray.
//
// Must be called with p.Mutex held
func (p *Repository) GetRulesMatching(labels labels.LabelArray) (ingressMatch bool, egressMatch bool) {
ingressMatch = false
egressMatch = false
for _, r := range p.rules {
rulesMatch := r.EndpointSelector.Matches(labels)
if rulesMatch {
if len(r.Ingress) > 0 {
ingressMatch = true
}
if len(r.Egress) > 0 {
egressMatch = true
}
}
if ingressMatch && egressMatch {
return
}
}
return
}
// getMatchingRules returns whether any of the rules in a repository contain a
// rule with labels matching the labels in the provided LabelArray, as well as
// a slice of all rules which match.
//
// Must be called with p.Mutex held
func (p *Repository) getMatchingRules(id uint16, securityIdentity *identity.Identity) (ingressMatch bool, egressMatch bool, matchingRules ruleSlice) {
matchingRules = []*rule{}
ingressMatch = false
egressMatch = false
for _, r := range p.rules {
if ruleMatches := r.matches(id, securityIdentity); ruleMatches {
// Don't need to update whether ingressMatch is true if it already
// has been determined to be true - allows us to not have to check
// lenth of slice.
if !ingressMatch && len(r.Ingress) > 0 {
ingressMatch = true
}
if !egressMatch && len(r.Egress) > 0 {
egressMatch = true
}
matchingRules = append(matchingRules, r)
}
}
return
}
// NumRules returns the amount of rules in the policy repository.
//
// Must be called with p.Mutex held
func (p *Repository) NumRules() int {
return len(p.rules)
}
// GetRevision returns the revision of the policy repository
func (p *Repository) GetRevision() uint64 {
return atomic.LoadUint64(&p.revision)
}
// Empty returns 'true' if repository has no rules, 'false' otherwise.
//
// Must be called without p.Mutex held
func (p *Repository) Empty() bool {
p.Mutex.Lock()
defer p.Mutex.Unlock()
return p.NumRules() == 0
}
// TranslationResult contains the results of the rule translation
type TranslationResult struct {
// NumToServicesRules is the number of ToServices rules processed while
// translating the rules
NumToServicesRules int
}
// TranslateRules traverses rules and applies provided translator to rules
func (p *Repository) TranslateRules(translator Translator) (*TranslationResult, error) {
p.Mutex.Lock()
defer p.Mutex.Unlock()
result := &TranslationResult{}
for ruleIndex := range p.rules {
if err := translator.Translate(&p.rules[ruleIndex].Rule, result); err != nil {
return nil, err
}
}
return result, nil
}
// BumpRevision allows forcing policy regeneration
func (p *Repository) BumpRevision() {
metrics.PolicyRevision.Inc()
atomic.AddUint64(&p.revision, 1)
}
// GetRulesList returns the current policy
func (p *Repository) GetRulesList() *models.Policy {
p.Mutex.RLock()
defer p.Mutex.RUnlock()
lbls := labels.ParseSelectLabelArrayFromArray([]string{})
ruleList := p.SearchRLocked(lbls)
return &models.Policy{
Revision: int64(p.GetRevision()),
Policy: JSONMarshalRules(ruleList),
}
}
// ResolvePolicy returns the EndpointPolicy for the provided set of labels against the
// set of rules in the repository, and the provided set of identities.
// If the policy cannot be generated due to conflicts at L4 or L7, returns an
// error.
func (p *Repository) ResolvePolicy(id uint16, securityIdentity *identity.Identity, policyOwner PolicyOwner, identityCache cache.IdentityCache) (*EndpointPolicy, error) {
labels := securityIdentity.LabelArray
calculatedPolicy := &EndpointPolicy{
ID: id,
L4Policy: NewL4Policy(),
CIDRPolicy: NewCIDRPolicy(),
PolicyMapState: make(MapState),
PolicyOwner: policyOwner,
DeniedIngressIdentities: cache.IdentityCache{},
DeniedEgressIdentities: cache.IdentityCache{},
}
// First obtain whether policy applies in both traffic directions, as well
// as list of rules which actually select this endpoint. This allows us
// to not have to iterate through the entire rule list multiple times and
// perform the matching decision again when computing policy for each
// protocol layer, which is quite costly in terms of performance.
ingressEnabled, egressEnabled, matchingRules := p.computePolicyEnforcementAndRules(id, securityIdentity)
calculatedPolicy.IngressPolicyEnabled = ingressEnabled
calculatedPolicy.EgressPolicyEnabled = egressEnabled
ingressCtx := SearchContext{
To: labels,
rulesSelect: true,
skipL4RequirementsAggregation: true,
}
egressCtx := SearchContext{
From: labels,
rulesSelect: true,
skipL4RequirementsAggregation: true,
}
if option.Config.TracingEnabled() {
ingressCtx.Trace = TRACE_ENABLED
egressCtx.Trace = TRACE_ENABLED
}
if ingressEnabled {
newL4IngressPolicy, err := matchingRules.resolveL4IngressPolicy(&ingressCtx, p.GetRevision())
if err != nil {
return nil, err
}
newCIDRIngressPolicy := matchingRules.resolveCIDRPolicy(&ingressCtx)
if err := newCIDRIngressPolicy.Validate(); err != nil {
return nil, err
}
calculatedPolicy.CIDRPolicy.Ingress = newCIDRIngressPolicy.Ingress
calculatedPolicy.L4Policy.Ingress = newL4IngressPolicy.Ingress
for identity, labels := range identityCache {
ingressCtx.From = labels
egressCtx.To = labels
ingressAccess := matchingRules.canReachIngressRLocked(&ingressCtx)
if ingressAccess == api.Allowed {
keyToAdd := Key{
Identity: identity.Uint32(),
TrafficDirection: trafficdirection.Ingress.Uint8(),
}
calculatedPolicy.PolicyMapState[keyToAdd] = MapStateEntry{}
} else if ingressAccess == api.Denied {
calculatedPolicy.DeniedIngressIdentities[identity] = labels
}
}
} else {
calculatedPolicy.PolicyMapState.AllowAllIdentities(identityCache, trafficdirection.Ingress)
}
if egressEnabled {
newL4EgressPolicy, err := matchingRules.resolveL4EgressPolicy(&egressCtx, p.GetRevision())
if err != nil {
return nil, err
}
newCIDREgressPolicy := matchingRules.resolveCIDRPolicy(&egressCtx)
if err := newCIDREgressPolicy.Validate(); err != nil {
return nil, err
}
calculatedPolicy.CIDRPolicy.Egress = newCIDREgressPolicy.Egress
calculatedPolicy.L4Policy.Egress = newL4EgressPolicy.Egress
for identity, labels := range identityCache {
egressCtx.To = labels
egressAccess := matchingRules.canReachEgressRLocked(&egressCtx)
if egressAccess == api.Allowed {
keyToAdd := Key{
Identity: identity.Uint32(),
TrafficDirection: trafficdirection.Egress.Uint8(),
}
calculatedPolicy.PolicyMapState[keyToAdd] = MapStateEntry{}
} else if egressAccess == api.Denied {
calculatedPolicy.DeniedEgressIdentities[identity] = labels
}
}
} else {
// Allow all identities
calculatedPolicy.PolicyMapState.AllowAllIdentities(identityCache, trafficdirection.Egress)
}
calculatedPolicy.computeDesiredL4PolicyMapEntries(identityCache)
calculatedPolicy.PolicyMapState.DetermineAllowLocalhost(calculatedPolicy.L4Policy)
return calculatedPolicy, nil
}
// computePolicyEnforcementAndRules returns whether policy applies at ingress or ingress
// for the given set of labels, as well as a list of any rules which select
// the set of labels.
//
// Must be called with repo mutex held for reading.
func (p *Repository) computePolicyEnforcementAndRules(id uint16, securityIdentity *identity.Identity) (ingress bool, egress bool, matchingRules ruleSlice) {
lbls := securityIdentity.LabelArray
// Check if policy enforcement should be enabled at the daemon level.
switch GetPolicyEnabled() {
case option.AlwaysEnforce:
_, _, matchingRules = p.getMatchingRules(id, securityIdentity)
// If policy enforcement is enabled for the daemon, then it has to be
// enabled for the endpoint.
return true, true, matchingRules
case option.DefaultEnforcement:
ingress, egress, matchingRules = p.getMatchingRules(id, securityIdentity)
// If the endpoint has the reserved:init label, i.e. if it has not yet
// received any labels, always enforce policy (default deny).
if lbls.Has(labels.IDNameInit) {
return true, true, matchingRules
}
// Default mode means that if rules contain labels that match this
// endpoint, then enable policy enforcement for this endpoint.
return ingress, egress, matchingRules
default:
// If policy enforcement isn't enabled, we do not enable policy
// enforcement for the endpoint. We don't care about returning any
// rules that match.
return false, false, nil
}
}