forked from neuvector/neuvector
-
Notifications
You must be signed in to change notification settings - Fork 0
/
group_profile.go
1084 lines (966 loc) · 31.1 KB
/
group_profile.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
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"encoding/json"
"fmt"
"reflect"
"regexp"
"sort"
"strings"
"sync"
"time"
log "github.com/sirupsen/logrus"
"github.com/neuvector/neuvector/agent/policy"
"github.com/neuvector/neuvector/share"
"github.com/neuvector/neuvector/share/cluster"
"github.com/neuvector/neuvector/share/fsmon"
"github.com/neuvector/neuvector/share/utils"
)
//// group profile
type groupProfileData struct {
group *share.CLUSGroup
members utils.Set
proc *share.CLUSProcessProfile
file *share.CLUSFileMonitorProfile
access *share.CLUSFileAccessRule
}
var grpCacheLock sync.Mutex
var grpProfileCacheMap map[string]*groupProfileData = make(map[string]*groupProfileData)
var grpNotifyProc utils.Set = utils.NewSet()
var grpNotifyFile utils.Set = utils.NewSet()
/////
type fileMatchRule struct {
cfgtype int
group string
behavior string
regex *regexp.Regexp
}
//// workload profile map for policy lookups
type workloadProfile struct {
groups utils.Set
proc *share.CLUSProcessProfile
file *share.CLUSFileMonitorProfile
access *share.CLUSFileAccessRule
matchRules []*fileMatchRule // local usage: match path to (estimated) group
procCalculated bool
fileCalculated bool
}
var wlCacheLock sync.Mutex
var wlProfileMap map[string]*workloadProfile = make(map[string]*workloadProfile)
const federalGrpPrefix string = "fed."
/////// DEBUG functions /////////////
func outputGroupInfo(grpCache *groupProfileData) {
log.WithFields(log.Fields{"group": grpCache.group.Name, "member_count": grpCache.members.Cardinality()}).Debug("GRP:")
for cid := range grpCache.members.Iter() {
log.WithFields(log.Fields{"id": cid.(string)}).Debug("GRP: members")
}
log.WithFields(log.Fields{"Proc": grpCache.proc}).Debug("GRP:")
log.WithFields(log.Fields{"File": grpCache.file}).Debug("GRP:")
log.WithFields(log.Fields{"Access": grpCache.access}).Debug("GRP:")
}
/////
func loadGroupProfile(name string, profile interface{}) bool {
var ptype string
//log.WithFields(log.Fields{"name": name, "type": fmt.Sprintf("%T", profile)}).Debug()
host := Host.ID
if utils.IsGroupNodes(name) {
host = share.ProfileCommonGroup
}
switch profile.(type) {
case *share.CLUSGroup:
if value, err := cluster.Get(share.CLUSNodeProfileGroupKey(host, share.ProfileGroup, name)); err == nil {
value, _ = utils.UnzipDataIfValid(value)
json.Unmarshal(value, profile)
return true
}
ptype = "group"
case *share.CLUSProcessProfile:
if value, err := cluster.Get(share.CLUSNodeProfileGroupKey(host, share.ProfileProcess, name)); err == nil {
value, _ = utils.UnzipDataIfValid(value)
json.Unmarshal(value, profile)
return true
}
ptype = "process"
case *share.CLUSFileMonitorProfile:
if value, err := cluster.Get(share.CLUSNodeProfileGroupKey(host, share.ProfileFileMonitor, name)); err == nil {
value, _ = utils.UnzipDataIfValid(value)
json.Unmarshal(value, profile)
return true
}
ptype = "file"
case *share.CLUSFileAccessRule:
if value, err := cluster.Get(share.CLUSNodeProfileGroupKey(host, share.ProfileFileAccess, name)); err == nil {
value, _ = utils.UnzipDataIfValid(value)
json.Unmarshal(value, profile)
return true
}
ptype = "access"
default:
ptype = fmt.Sprintf("%T", profile)
}
log.WithFields(log.Fields{"group": name, "type": ptype}).Debug("GRP: invalid profile")
return false
}
func getProcessProfile(name string) (bool, *share.CLUSProcessProfile) {
grpCacheLock.Lock()
defer grpCacheLock.Unlock()
if grpCache, ok := grpProfileCacheMap[name]; ok {
if grpCache.proc.Group == "" {
if !loadGroupProfile(name, grpCache.proc) {
return false, nil
}
}
return true, grpCache.proc
}
return false, nil
}
func getFileMonitorProfile(name string) (bool, *share.CLUSFileMonitorProfile) {
grpCacheLock.Lock()
defer grpCacheLock.Unlock()
if grpCache, ok := grpProfileCacheMap[name]; ok {
if grpCache.file.Group == "" {
if !loadGroupProfile(name, grpCache.file) {
return false, nil
}
}
return true, grpCache.file
}
return false, nil
}
func getFileAccessProfile(name string) (bool, *share.CLUSFileAccessRule) {
grpCacheLock.Lock()
defer grpCacheLock.Unlock()
if grpCache, ok := grpProfileCacheMap[name]; ok {
if grpCache.access.Group == "" {
if !loadGroupProfile(name, grpCache.access) {
return false, nil
}
}
return true, grpCache.access
}
return false, nil
}
///// patch for random sequences of group creation( one-time)
func fillGroupProfiles(name string) bool {
grpCacheLock.Lock()
defer grpCacheLock.Unlock()
if grpCache, ok := grpProfileCacheMap[name]; ok {
loadGroupProfile(name, grpCache.proc)
for _, pp := range grpCache.proc.Process {
pp.DerivedGroup = name // late filled-up to save kv storages
}
loadGroupProfile(name, grpCache.file)
for i, _ := range grpCache.file.Filters {
grpCache.file.Filters[i].DerivedGroup = name // late filled-up to save kv storages
}
loadGroupProfile(name, grpCache.access)
grpCache.access.Group = name
refreshGroupMembers(grpCache)
// outputGroupInfo(grpCache)
grpNotifyProc = grpNotifyProc.Union(grpCache.members)
grpNotifyFile = grpNotifyFile.Union(grpCache.members)
return true
}
return false
}
///////
func addGroupCache(name string, grp share.CLUSGroup) bool {
if !utils.HasGroupProfiles(name) {
// ignore network services and nodes config type
return false
}
// log.WithFields(log.Fields{"group": name}).Debug("GRP:")
grpCache := &groupProfileData{
group: &grp,
members: utils.NewSet(),
proc: &share.CLUSProcessProfile{Process: make([]*share.CLUSProcessProfileEntry, 0)},
file: &share.CLUSFileMonitorProfile{Filters: make([]share.CLUSFileMonitorFilter, 0), FiltersCRD: make([]share.CLUSFileMonitorFilter, 0)},
access: &share.CLUSFileAccessRule{Filters: make(map[string]*share.CLUSFileAccessFilterRule), FiltersCRD: make(map[string]*share.CLUSFileAccessFilterRule)},
}
// protected by its calling function
grpProfileCacheMap[name] = grpCache
// best efforts to patch for random sequences of group creation
go func() {
time.Sleep(time.Second * 1)
fillGroupProfiles(name)
}()
return true
}
///////
func updateGroupProfileCache(nType cluster.ClusterNotifyType, name string, obj interface{}) bool {
log.WithFields(log.Fields{"group": name}).Debug("GRP:")
procUpdated := false
fileUpdated := false
grpCacheLock.Lock()
defer grpCacheLock.Unlock()
grpCache, ok := grpProfileCacheMap[name]
if !ok {
switch obj.(type) {
case share.CLUSGroup:
group := obj.(share.CLUSGroup)
return addGroupCache(name, group)
}
// the group data is not established yet
// patch random event sequence later
log.WithFields(log.Fields{"group": name, "obj": obj}).Debug("GRP: not exist yet")
return utils.HasGroupProfiles(name)
}
// log.WithFields(log.Fields{"group": name, "obj": obj}).Debug("GRP:")
targets := utils.NewSet()
switch obj.(type) {
case share.CLUSGroup:
group := obj.(share.CLUSGroup)
if reflect.DeepEqual(group, grpCache.group) == false {
grpCache.group = &group
old_members := grpCache.members.Clone()
refreshGroupMembers(grpCache)
targets = old_members.SymmetricDifference(grpCache.members)
// log.WithFields(log.Fields{"old": old_members, "new": grpCache.members, "targets": targets}).Debug("GRP:")
if targets.Cardinality() > 0 {
procUpdated = true
fileUpdated = true
}
old_members.Clear()
old_members = nil
}
case share.CLUSProcessProfile:
proc := obj.(share.CLUSProcessProfile)
if proc.Mode != grpCache.proc.Mode || len(grpCache.proc.Process)==0 || reflect.DeepEqual(proc.Process, grpCache.proc.Process) == false {
for _, pp := range proc.Process {
pp.DerivedGroup = name // late filled-up to save kv storages
}
grpCache.proc = &proc
targets = grpCache.members.Clone()
if targets.Cardinality() > 0 {
procUpdated = true
}
}
case share.CLUSFileMonitorProfile:
file := obj.(share.CLUSFileMonitorProfile)
if file.Mode != grpCache.file.Mode || len(grpCache.file.Filters)==0 || reflect.DeepEqual(file.Filters, grpCache.file.Filters) == false {
for i, _ := range file.Filters {
file.Filters[i].DerivedGroup = name // late filled-up to save kv storages
}
grpCache.file = &file
targets = grpCache.members.Clone()
if targets.Cardinality() > 0 {
fileUpdated = true
}
}
case share.CLUSFileAccessRule:
access := obj.(share.CLUSFileAccessRule)
if len(grpCache.access.Filters)==0 || reflect.DeepEqual(access.Filters, grpCache.access.Filters) == false {
grpCache.access = &access
targets = grpCache.members.Clone()
if targets.Cardinality() > 0 {
fileUpdated = true
}
}
default:
log.WithFields(log.Fields{"group": name, "type": obj}).Debug("GRP: unknown type")
return false
}
if procUpdated {
grpNotifyProc = grpNotifyProc.Union(targets)
}
if fileUpdated {
grpNotifyFile = grpNotifyFile.Union(targets)
}
targets.Clear()
targets = nil
return true
}
///////
func deleteGroupProfileCache(name string) bool {
grpCacheLock.Lock()
defer grpCacheLock.Unlock()
if grpCache, ok := grpProfileCacheMap[name]; ok {
log.WithFields(log.Fields{"group": name}).Debug("GRP: ")
grpNotifyFile = grpNotifyFile.Union(grpCache.members)
grpNotifyProc = grpNotifyProc.Union(grpCache.members)
grpCache.members.Clear()
delete(grpProfileCacheMap, name)
return true
}
log.WithFields(log.Fields{"group": name}).Debug("GRP: not found")
return false
}
//////////////////////////////////////////////////////
///////// Group-based selection functions ////////////
//////////////////////////////////////////////////////
func isContainerSelected(c *containerData, group *share.CLUSGroup) bool {
// TODO: remove "CriteriaKeyAddress" from entry ??
wl := createWorkload(c.info)
wl.Running = true // from activeContainer
wl.Name = c.name
wl.Service = c.service
wl.Domain = c.domain
return share.IsGroupMember(group, wl)
}
///////
func refreshGroupMembers(grpCache *groupProfileData) {
grpCache.members.Clear()
if utils.IsGroupNodes(grpCache.group.Name) {
grpCache.members.Add("") // only member : host
return
}
gInfoRLock()
for _, c := range gInfo.activeContainers {
if isContainerSelected(c, grpCache.group) {
grpCache.members.Add(c.id)
}
}
gInfoRUnlock()
}
///////////////////////////////////////////////////////
/////////////// Profile calculations //////////////////
// Group Profile has higher priority
///////////////////////////////////////////////////////
/////// Scheduler: trigger calculation(s) per containers for a certain of time
func group_profile_loop() {
calculationTicker := time.Tick(time.Second * 5)
for {
select {
case <-calculationTicker:
grpCacheLock.Lock()
targets_proc := grpNotifyProc.Clone()
targets_file := grpNotifyFile.Clone()
grpNotifyProc.Clear()
grpNotifyFile.Clear()
grpCacheLock.Unlock()
///
if targets_proc.Cardinality() > 0 {
go procMemberChanges(targets_proc)
}
///
if targets_file.Cardinality() > 0 {
go fileMemberChanges(targets_file)
}
}
}
}
/////// calcualting the runtime profiles
func procMemberChanges(members utils.Set) {
log.WithFields(log.Fields{"count": members.Cardinality()}).Debug("GRP:")
for cid := range members.Iter() {
id := cid.(string)
if id == "" {
applyHostProcGroupProfile("nodes") // system reserved entry
continue
}
gInfoRLock()
c, ok := gInfo.activeContainers[id]
gInfoRUnlock()
if ok {
go applyProcGroupProfile(c)
} else {
log.WithFields(log.Fields{"id": id}).Debug("GRP: left")
}
}
members.Clear()
}
func fileMemberChanges(members utils.Set) {
log.WithFields(log.Fields{"count": members.Cardinality()}).Debug("GRP:")
for cid := range members.Iter() {
id := cid.(string)
if id == "" {
// log.Debug("GRP: not support nodes")
continue
}
gInfoRLock()
c, ok := gInfo.activeContainers[id]
gInfoRUnlock()
if ok {
applyFileGroupProfile(c)
} else {
log.WithFields(log.Fields{"id": id}).Debug("GRP: left")
}
}
members.Clear()
}
//////
func mapProcToSortedSlices(m map[string]*share.CLUSProcessProfileEntry) []*share.CLUSProcessProfileEntry {
list := make([]*share.CLUSProcessProfileEntry, 0, len(m)) // single allocation
for _, item := range m { // map enumeration
list = append(list, item)
}
if len(list) > 0 {
// sort them by Name, then Path
sort.Slice(list, func(i, j int) bool {
if list[i].Name == list[j].Name {
return list[i].Path < list[j].Path
}
return list[i].Name < list[j].Name
})
}
return list
}
// Process Rules (priorities) :
// (0) *,* == apply all (only for allow)
// (1) deny: specific name and path
// (2) deny: recursive path (directories)
// (3) deny: wildcard name (whole container)
// (4) allow: specific name and path
// (5) allow: recursive path
// (6) allow: wildcard name
func mergeProcessProfiles(cur []*share.CLUSProcessProfileEntry) []*share.CLUSProcessProfileEntry {
m := make([]map[string]*share.CLUSProcessProfileEntry, 7, 7)
for i := 0; i < 7; i++ {
m[i] = make(map[string]*share.CLUSProcessProfileEntry)
}
for _, entry := range cur {
key := fmt.Sprintf("%s:%s", entry.Name, entry.Path)
if entry.Action == share.PolicyActionDeny {
if entry.Name == "*" && entry.Path == "*" {
// (0) deny all : this invalid entry is blocked at REST api level
} else if entry.Name == "*" {
// (3) deny and wildcard at name
m[3][key] = entry
} else if strings.HasSuffix(entry.Path, "/*") {
// (2) deny and wildcard at path
m[2][key] = entry
} else {
// (1) deny and specific
m[1][key] = entry
}
} else {
if entry.Name == "*" && entry.Path == "*" {
// (0) allow all : override all cases
m[0][key] = entry
} else if entry.Name == "*" {
// (6) allow and wildcard at name
m[6][key] = entry
} else if strings.HasSuffix(entry.Path, "/*") {
// (5) allow and wildcard at path
m[5][key] = entry
} else {
// (4) allow and specific
m[4][key] = entry
}
}
}
var list []*share.CLUSProcessProfileEntry
for _, mm := range m { // slice enumeration
list = append(list, mapProcToSortedSlices(mm)...)
}
return list
}
// FileMonitor Rules (SLICE: priorities) :
// (1) share.FileAccessBehaviorBlock > share.FileAccessBehaviorMonitor
// (2) recursive > non-recursive
// (3) customer-added > default-setting
func mergeFileMonitorProfile(filters []share.CLUSFileMonitorFilter) []share.CLUSFileMonitorFilter {
m := make(map[string]share.CLUSFileMonitorFilter)
for _, ff := range filters { // slice enumeration
key := GetPathRegexString(ff.Path, ff.Regex, ff.Recursive)
if v, ok := m[key]; ok {
if v.Behavior == share.FileAccessBehaviorBlock {
ff.Behavior = share.FileAccessBehaviorBlock // higher priority
if v.DerivedGroup != "" {
ff.DerivedGroup = v.DerivedGroup // keep the first group name
}
}
if v.Recursive {
ff.Recursive = true // higher priority
}
if v.CustomerAdd {
ff.CustomerAdd = true // higher priority
}
}
m[key] = ff
}
var list []share.CLUSFileMonitorFilter = make([]share.CLUSFileMonitorFilter, 0, len(m)) // single allocation
for _, item := range m { // map enumeration
list = append(list, item)
}
if len(list) > 0 {
// sort them by Name, then Path
sort.Slice(list, func(i, j int) bool {
if list[i].Filter == list[j].Filter {
return list[i].Path < list[j].Path
}
return list[i].Filter < list[j].Filter
})
}
return list
}
/// remove duplicates: O(N), sorting: O(NlogN)
func mergeStringSlices(bSort bool, s1, s2 []string) []string {
slices := append(s1, s2...)
m := make(map[string]bool)
for _, key := range slices { // slice enumeration
m[key] = true
}
var list []string = make([]string, 0, len(m)) // single allocation
for v, _ := range m { // map enumeration // map enumeration
list = append(list, v)
}
if bSort && len(list) > 0 {
sort.Slice(list, func(i, j int) bool { return list[i] < list[j] })
}
return list
}
// FileAccessMonitor Rules (MAP priorities) :
// (1) share.FileAccessBehaviorBlock > share.FileAccessBehaviorMonitor
func mergeFileAccessProfile(cur, add *share.CLUSFileAccessRule) {
for name, profile := range add.Filters { // map enumeration
if ffp, ok := cur.Filters[name]; ok {
ffp.CustomerAdd = true
ffp.Apps = mergeStringSlices(true, ffp.Apps, profile.Apps) // optional: false
if profile.Behavior == share.FileAccessBehaviorBlock {
ffp.Behavior = share.FileAccessBehaviorBlock // higher priority
}
} else {
cur.Filters[name] = profile // new entry
}
}
for name, profile := range add.FiltersCRD { // map enumeration
if ffp, ok := cur.FiltersCRD[name]; ok {
ffp.CustomerAdd = true
ffp.Apps = mergeStringSlices(true, ffp.Apps, profile.Apps) // optional: false
if profile.Behavior == share.FileAccessBehaviorBlock {
ffp.Behavior = share.FileAccessBehaviorBlock // higher priority
}
} else {
cur.FiltersCRD[name] = profile // new entry
}
}
}
////
func calculateProcGroupProfile(id, svc string) (*share.CLUSProcessProfile, bool) {
log.WithFields(log.Fields{"id": id, "svc": svc}).Debug("GRP: ")
/// merge group profiles
fedproc := &share.CLUSProcessProfile{Process: make([]*share.CLUSProcessProfileEntry, 0)}
crdproc := &share.CLUSProcessProfile{Process: make([]*share.CLUSProcessProfileEntry, 0)}
proc := &share.CLUSProcessProfile{Process: make([]*share.CLUSProcessProfileEntry, 0)}
grpCacheLock.Lock()
for grpName, grpCache := range grpProfileCacheMap {
if grpCache.members.Contains(id) {
if strings.HasPrefix(grpName, federalGrpPrefix) {
fedproc.Process = append(fedproc.Process, grpCache.proc.Process...)
} else {
for _, p := range grpCache.proc.Process { // separate CRD and other types
if p.CfgType == share.GroundCfg {
crdproc.Process = append(crdproc.Process, p)
} else {
proc.Process = append(proc.Process, p)
}
}
}
}
}
grpCacheLock.Unlock()
// load workload profile
ok, svc_proc := getProcessProfile(svc)
if !ok {
log.WithFields(log.Fields{"id": id, "svc": svc}).Debug("GRP: no profile")
return nil, false
}
for _, p := range svc_proc.Process { // separate CRD and other types
if p.CfgType == share.GroundCfg {
crdproc.Process = append(crdproc.Process, p)
} else {
proc.Process = append(proc.Process, p)
}
}
// remove the duplicate entries and prioritize the sequences
pp := &share.CLUSProcessProfile{Process: make([]*share.CLUSProcessProfileEntry, 0)}
if len(fedproc.Process) > 0 {
// keep federal rules at the top
fedproc.Process = mergeProcessProfiles(fedproc.Process)
pp.Process = append(pp.Process, fedproc.Process...)
}
if len(crdproc.Process) > 0 {
// keep crd rules at the secondary
crdproc.Process = mergeProcessProfiles(crdproc.Process)
pp.Process = append(pp.Process, crdproc.Process...)
}
if len(proc.Process) > 0 {
// merge service rules
proc.Process = mergeProcessProfiles(proc.Process)
pp.Process = append(pp.Process, proc.Process...)
}
proc.Group = svc_proc.Group
proc.Mode = svc_proc.Mode
proc.AlertDisable = svc_proc.AlertDisable
proc.HashEnable = svc_proc.HashEnable
proc.Process = pp.Process
if id != "" { // container only
for _, p := range proc.Process { // separate CRD and other types
// log.WithFields(log.Fields{"proc": p, "Svc": svc}).Debug("GRP:")
if p.Action == share.PolicyActionAllow {
prober.UpdateFromAllowRule(id, p.Path)
}
}
}
// log.WithFields(log.Fields{"Svc": svc, "id": id, "proc": proc.Process}).Debug("GRP:")
return proc, true
}
////
func calculateFileGroupProfile(id, svc string) (*share.CLUSFileMonitorProfile, *share.CLUSFileAccessRule, bool) {
log.WithFields(log.Fields{"id": id, "svc": svc}).Debug("GRP: ")
file := &share.CLUSFileMonitorProfile{
Filters: make([]share.CLUSFileMonitorFilter, 0),
FiltersCRD: make([]share.CLUSFileMonitorFilter, 0),
}
access := &share.CLUSFileAccessRule{
Filters: make(map[string]*share.CLUSFileAccessFilterRule),
FiltersCRD: make(map[string]*share.CLUSFileAccessFilterRule),
} // from (map).Filter
grpCacheLock.Lock()
for _, grpCache := range grpProfileCacheMap {
if grpCache.members.Contains(id) {
file.Filters = append(file.Filters, grpCache.file.Filters...)
file.FiltersCRD = append(file.FiltersCRD, grpCache.file.FiltersCRD...)
mergeFileAccessProfile(access, grpCache.access)
}
}
grpCacheLock.Unlock()
// log.WithFields(log.Fields{"filter": file.Filters}).Debug("GRP:")
ok, svc_file := getFileMonitorProfile(svc)
if !ok {
log.WithFields(log.Fields{"id": id, "svc": svc}).Debug("GRP: no file profile")
return nil, nil, false
}
// basic information
file.Group = svc_file.Group
file.Mode = svc_file.Mode
// merge regular files
file.Filters = append(file.Filters, svc_file.Filters...)
file.Filters = mergeFileMonitorProfile(file.Filters)
// merge CRD files
file.FiltersCRD = append(file.FiltersCRD, svc_file.FiltersCRD...)
file.FiltersCRD = mergeFileMonitorProfile(file.FiltersCRD)
// access profile
ok, svc_access := getFileAccessProfile(svc)
if !ok {
log.WithFields(log.Fields{"id": id, "svc": svc}).Debug("GRP: no access profile")
return file, nil, true
}
//log.WithFields(log.Fields{"svc": svc_access}).Debug("GRP:")
//for name, profile := range svc_access.Filters { // map enumeration
// log.WithFields(log.Fields{"name": name, "profile": profile}).Debug("GRP:")
//}
mergeFileAccessProfile(access, svc_access)
return file, access, true
}
///////
func GetPathRegexString(path, regex string, bRecursive bool) string {
regex_str := path
if bRecursive {
regex_str = fmt.Sprintf("%s/%s", regex_str, regex)
}
return fmt.Sprintf("^%s$", regex_str)
}
//////
func BuildFileMatchRules(filters []share.CLUSFileMonitorFilter, cfgtype int) []*fileMatchRule {
rules := make([]*fileMatchRule, 0, len(filters)) // single allocation
for _, ff := range filters {
regex, _ := regexp.Compile(GetPathRegexString(ff.Path, ff.Regex, ff.Recursive))
// log.WithFields(log.Fields{"regex": regex, "ff": ff}).Debug("GRP: ")
rr := &fileMatchRule{
group: ff.DerivedGroup,
cfgtype: cfgtype,
behavior: ff.Behavior,
regex: regex,
}
rules = append(rules, rr)
}
return rules
}
////
func applyHostProcGroupProfile(svc string) bool {
if proc, ok := calculateProcGroupProfile("", svc); ok {
wlCacheLock.Lock()
wl, ok := wlProfileMap[""]
if !ok {
wlProfileMap[""] = &workloadProfile{
groups: utils.NewSet(),
proc: &share.CLUSProcessProfile{Process: make([]*share.CLUSProcessProfileEntry, 0)},
file: &share.CLUSFileMonitorProfile{Filters: make([]share.CLUSFileMonitorFilter, 0)},
access: &share.CLUSFileAccessRule{Filters: make(map[string]*share.CLUSFileAccessFilterRule)},
}
wl = wlProfileMap[""]
}
wl.proc = proc
wl.procCalculated = true
wlCacheLock.Unlock()
// put a minimum data set
c := &containerData {
id: "",
name: "host",
pid : 1,
capBlock: false, // no process blocking control but kill processes
pushPHistory: true, // no history
}
// log.WithFields(log.Fields{"SVC": svc, "mode": proc.Mode}).Debug("GRP:")
applyProcessProfilePolicy(c, svc) // mode is passed later for process monitor reasons
return true
}
return false
}
////
func applyProcGroupProfile(c *containerData) bool {
svc := makeLearnedGroupName(utils.NormalizeForURL(c.service))
if proc, ok := calculateProcGroupProfile(c.id, svc); ok {
wlCacheLock.Lock()
if wl, ok := wlProfileMap[c.id]; ok {
wl.proc = proc
wl.procCalculated = true
}
wlCacheLock.Unlock()
applyProcessProfilePolicy(c, svc) // mode is passed later for process monitor reasons
return true
}
return false
}
////
func applyFileGroupProfile(c *containerData) bool {
svc := makeLearnedGroupName(utils.NormalizeForURL(c.service))
if file, access, ok := calculateFileGroupProfile(c.id, svc); ok {
matchRules := make([]*fileMatchRule, 0)
if len(file.FiltersCRD) > 0 { // higher report priority
matchRules = append(matchRules, BuildFileMatchRules(file.FiltersCRD, int(share.GroundCfg))...)
}
if len(file.Filters) > 0 {
matchRules = append(matchRules, BuildFileMatchRules(file.Filters, 0)...) // default: undefined
}
wlCacheLock.Lock()
if wl, ok := wlProfileMap[c.id]; ok {
wl.file = file
wl.access = access
wl.matchRules = matchRules
wl.fileCalculated = true
}
wlCacheLock.Unlock()
//////
config := &fsmon.FsmonConfig{
Profile: file,
Rule: access,
}
//
fileWatcher.ContainerCleanup(c.pid)
if len(file.Filters) > 0 {
fileWatcher.StartWatch(c.id, c.pid, config, c.capBlock, false)
}
return true
}
return false
}
//////
func uppdateFileGroupAccess(c *containerData) bool {
svc := makeLearnedGroupName(utils.NormalizeForURL(c.service))
if _, access, ok := calculateFileGroupProfile(c.id, svc); ok && (access != nil) {
log.WithFields(log.Fields{"ID": c.id, "svc": svc}).Debug("GRP:")
wlCacheLock.Lock()
if wl, ok := wlProfileMap[c.id]; ok {
wl.access = access
}
wlCacheLock.Unlock()
//
fileWatcher.UpdateAccessRules(svc, c.pid, access)
return true
}
return false
}
/////// "host" is not an actual workload, will NOT enter this function
func workloadJoinGroup(c *containerData) {
log.WithFields(log.Fields{"id": c.id}).Debug("GRP: ")
wlCacheLock.Lock()
if _, ok := wlProfileMap[c.id]; !ok {
wlProfileMap[c.id] = &workloadProfile{
groups: utils.NewSet(),
proc: &share.CLUSProcessProfile{Process: make([]*share.CLUSProcessProfileEntry, 0)},
file: &share.CLUSFileMonitorProfile{Filters: make([]share.CLUSFileMonitorFilter, 0)},
access: &share.CLUSFileAccessRule{Filters: make(map[string]*share.CLUSFileAccessFilterRule)},
}
}
wlCacheLock.Unlock()
grpCacheLock.Lock()
defer grpCacheLock.Unlock()
for name, grpCache := range grpProfileCacheMap {
if utils.IsGroupNodes(name) {
continue
}
if !grpCache.members.Contains(c.id) {
if isContainerSelected(c, grpCache.group) {
grpCache.members.Add(c.id)
// reference
wlProfileMap[c.id].groups.Add(name)
}
}
}
//
grpNotifyProc.Add(c.id)
grpNotifyFile.Add(c.id)
}
///////
func workloadLeaveGroup(c *containerData) {
// log.WithFields(log.Fields{"cid": id}).Debug("GRP: ")
// remove monitors
prober.RemoveProcessControl(c.id)
fileWatcher.ContainerCleanup(c.pid)
grpCacheLock.Lock()
for name, grpCache := range grpProfileCacheMap {
if utils.IsGroupNodes(name) {
continue
}
if grpCache.members.Contains(c.id) {
log.WithFields(log.Fields{"group": name, "id": c.id}).Debug("GRP: ")
grpCache.members.Remove(c.id)
}
}
grpNotifyProc.Remove(c.id)
grpNotifyFile.Remove(c.id)
grpCacheLock.Unlock()
wlCacheLock.Lock()
if wl, ok := wlProfileMap[c.id]; ok {
wl.groups.Clear() // clean up
wl.proc = nil
wl.file = nil
wl.access = nil
delete(wlProfileMap, c.id)
}
wlCacheLock.Unlock()
}
///////// Use GRPC to return actual policy to CTL
func ObtainGroupProcessPolicy(id string) (*share.CLUSProcessProfile, bool) {
if id == "nodes" { // from controller, workload id from runtime can not be like "nodes"
id = ""
}
if isNeuvectorContainerById(id) { // NeuVector: no group process profile
return nil, true
}
wlCacheLock.Lock()
defer wlCacheLock.Unlock()
if wl, ok := wlProfileMap[id]; ok {
if wl.proc != nil { // required
return wl.proc, wl.procCalculated
}
}
// log.WithFields(log.Fields{"id": id}).Debug("GRP: not ready")
return nil, false
}
///////// Use GRPC to return actual policy to CTL
func ObtainGroupFilePolicies(id string) (*share.CLUSFileMonitorProfile, *share.CLUSFileAccessRule, bool) {
if id == "nodes" { // TODO: from controller, workload id from runtime can not be like "nodes"
id = ""
}
wlCacheLock.Lock()
defer wlCacheLock.Unlock()
if wl, ok := wlProfileMap[id]; ok {
if wl.file != nil { // required
return wl.file, wl.access, wl.fileCalculated
}
}
return nil, nil, false
}
/////////////////////////////////////////////////////////////////////////////////
// It is very difficult to obtain the exact rule which applied on the incident
// since the lower (fanotify) layer has been optimized to reduce system resources.
// Also, it is costly by data memory to label all rules at the lower layer.
// Thus, better to use the emulatation of input vectors to find the rules
/////////////////////////////////////////////////////////////////////////////////
////// Estimate the rule from group name or service
func cbEstimateDeniedProcessdByGroup(id, name, path string) (string, string) {
if id == "" {
id = "nodes"
}
svcGroup, ok, _ := cbGetLearnedGroupName(id)
if !ok {
log.WithFields(log.Fields{"id": id}).Error("GRP: no svc")
return "", share.CLUSReservedUuidNotAlllowed // TODO: if possible
}
if profile, ok := ObtainGroupProcessPolicy(id); ok && profile != nil {
ppe := &share.CLUSProcessProfileEntry{
Name: name,
Path: path,
}
// match denied policy
for _, pp := range profile.Process {
if policy.MatchProfileProcess(pp, ppe) && pp.Action == share.PolicyActionDeny {
if pp.DerivedGroup == "" {
break // matched service group
}
return pp.DerivedGroup, pp.Uuid // user-defined group
}
}
// by default, it from service (include beyond its white list)
return svcGroup, share.CLUSReservedUuidNotAlllowed
}
if isNeuvectorContainerById(id) { // NeuVector
log.WithFields(log.Fields{"id": id, "name": name, "path": path}).Info("GRP: NV Protect")
return share.GroupNVProtect, share.CLUSReservedUuidNotAlllowed
}