forked from accuknox/discovery-engine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsystemPolicy.go
1544 lines (1296 loc) · 41.5 KB
/
systemPolicy.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 systempolicy
import (
"errors"
"io/ioutil"
"os"
"path/filepath"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
"time"
"github.com/clarketm/json"
"k8s.io/utils/strings/slices"
"sigs.k8s.io/yaml"
"github.com/accuknox/auto-policy-discovery/src/cluster"
"github.com/accuknox/auto-policy-discovery/src/common"
cfg "github.com/accuknox/auto-policy-discovery/src/config"
fc "github.com/accuknox/auto-policy-discovery/src/feedconsumer"
"github.com/accuknox/auto-policy-discovery/src/libs"
logger "github.com/accuknox/auto-policy-discovery/src/logging"
"github.com/accuknox/auto-policy-discovery/src/plugin"
wpb "github.com/accuknox/auto-policy-discovery/src/protobuf/v1/worker"
types "github.com/accuknox/auto-policy-discovery/src/types"
"github.com/rs/zerolog"
"github.com/robfig/cron"
)
var log *zerolog.Logger
func init() {
log = logger.GetInstance()
}
// const values
const (
// operation mode
OP_MODE_NOOP = 0
OP_MODE_CRONJOB = 1
OP_MODE_ONETIME = 2
// status
STATUS_RUNNING = "running"
STATUS_IDLE = "idle"
)
const (
SYS_OP_PROCESS = "Process"
SYS_OP_FILE = "File"
SYS_OP_NETWORK = "Network"
SYS_OP_PROCESS_INT = 1
SYS_OP_FILE_INT = 2
SYS_OP_NETWORK_INT = 4
SOURCE_ALL = "/ALL" // for fromSource 'off'
)
// ====================== //
// == Global Variables == //
// ====================== //
var CfgDB types.ConfigDB
// SystemWorkerStatus global worker
var SystemWorkerStatus string
// for cron job
var SystemCronJob *cron.Cron
var SystemStopChan chan struct{} // for hubble
var OperationTrigger int
var SystemLogLimit int
var SystemLogFrom string
var SystemLogFile string
var SystemPolicyTo string
var SystemPolicyTypes int
var SystemLogFilters []types.SystemLogFilter
var ProcessFromSource bool
var FileFromSource bool
// init Function
func init() {
SystemWorkerStatus = STATUS_IDLE
SystemStopChan = make(chan struct{})
}
// ====================== //
// == Internal Testing == //
// ====================== //
func ReplaceMultiubuntuPodName(logs []types.KnoxSystemLog, pods []types.Pod) {
var pod1Name, pod2Name, pod3Name, pod4Name, pod5Name string
for _, pod := range pods {
if strings.Contains(pod.PodName, "ubuntu-1-deployment") {
pod1Name = pod.PodName
}
if strings.Contains(pod.PodName, "ubuntu-2-deployment") {
pod2Name = pod.PodName
}
if strings.Contains(pod.PodName, "ubuntu-3-deployment") {
pod3Name = pod.PodName
}
if strings.Contains(pod.PodName, "ubuntu-4-deployment") {
pod4Name = pod.PodName
}
if strings.Contains(pod.PodName, "ubuntu-5-deployment") {
pod5Name = pod.PodName
}
}
for i, log := range logs {
if strings.Contains(log.PodName, "ubuntu-1-deployment") {
logs[i].PodName = pod1Name
}
///
if strings.Contains(log.PodName, "ubuntu-2-deployment") {
logs[i].PodName = pod2Name
}
///
if strings.Contains(log.PodName, "ubuntu-3-deployment") {
logs[i].PodName = pod3Name
}
///
if strings.Contains(log.PodName, "ubuntu-4-deployment") {
logs[i].PodName = pod4Name
}
///
if strings.Contains(log.PodName, "ubuntu-5-deployment") {
logs[i].PodName = pod5Name
}
}
}
// ========================== //
// == Inner Structure Type == //
// ========================== //
// SysLogKey Structure
type SysLogKey struct {
Namespace string
PodName string
}
// ================ //st
// == System Log == //
// ================ //
func getSystemLogs() []types.KnoxSystemLog {
systemLogs := []types.KnoxSystemLog{}
if SystemLogFrom == "file" {
// =============================== //
// == File (.json) for testing == //
// =============================== //
jsonLogs := []map[string]interface{}{}
log.Info().Msg("Get system logs from the json file : " + SystemLogFile)
// Opens jsonFile
logFile, err := os.Open(filepath.Clean(SystemLogFile))
if err != nil {
log.Error().Msg(err.Error())
if err := logFile.Close(); err != nil {
log.Error().Msg(err.Error())
}
return nil
}
byteValue, err := ioutil.ReadAll(logFile)
if err != nil {
log.Error().Msg(err.Error())
}
if err := json.Unmarshal(byteValue, &jsonLogs); err != nil {
log.Error().Msg(err.Error())
return nil
}
// raw json --> knoxSystemLog
if CfgDB.DBDriver == "mysql" {
systemLogs = plugin.ConvertMySQLKubeArmorLogsToKnoxSystemLogs(jsonLogs)
} else if CfgDB.DBDriver == "sqlite3" {
systemLogs = plugin.ConvertSQLiteKubeArmorLogsToKnoxSystemLogs(jsonLogs)
}
// replace the pod names in prepared-logs with the working pod names
pods := cluster.GetPodsFromK8sClient()
ReplaceMultiubuntuPodName(systemLogs, pods)
if err := logFile.Close(); err != nil {
log.Error().Msg(err.Error())
}
} else if SystemLogFrom == "kubearmor" {
// ================================ //
// === KubeArmor Relay === //
// ================================ //
// get system logs from kuberarmor relay
relayLogs := plugin.GetSystemAlertsFromKubeArmorRelay(OperationTrigger)
if len(relayLogs) == 0 || len(relayLogs) < OperationTrigger {
return nil
}
// convert kubearmor relay logs -> knox system logs
for _, relayLog := range relayLogs {
log, err := plugin.ConvertKubeArmorLogToKnoxSystemLog(relayLog)
if err == nil {
systemLogs = append(systemLogs, log)
}
}
} else if SystemLogFrom == "feed-consumer" {
log.Info().Msg("Get system log from feed-consumer")
// get system logs from kafka/pulsar
sysLogs := plugin.GetSystemLogsFromFeedConsumer(OperationTrigger)
if len(sysLogs) == 0 || len(sysLogs) < OperationTrigger {
return nil
}
// convert kubearmor system logs -> knox system logs
for _, sysLog := range sysLogs {
systemLogs = append(systemLogs, *sysLog)
}
} else {
log.Error().Msgf("System log from not correct: %s", SystemLogFrom)
return nil
}
return systemLogs
}
func populateKnoxSysPolicyFromWPFSDb(namespace, clustername, labels, fromsource string) []types.KnoxSystemPolicy {
wpfs := types.WorkloadProcessFileSet{
Namespace: namespace,
ClusterName: clustername,
Labels: labels,
FromSource: fromsource,
}
res, pnMap, err := libs.GetWorkloadProcessFileSet(CfgDB, wpfs)
if err != nil {
log.Error().Msgf("could not fetch WPFS err=%s", err.Error())
return nil
}
log.Info().Msgf("found %d WPFS records", len(res))
return ConvertWPFSToKnoxSysPolicy(res, pnMap)
}
func WriteSystemPoliciesToFile_Ext(namespace, clustername, labels, fromsource string, includeNetwork bool) {
kubearmorK8SPolicies := extractK8SSystemPolicies(namespace, clustername, labels, fromsource, includeNetwork)
for _, pol := range kubearmorK8SPolicies {
fname := "kubearmor_policies_" + pol.Metadata["clusterName"] + "_" + pol.Metadata["namespace"] + "_" + pol.Metadata["containername"] + "_" + pol.Metadata["name"]
libs.WriteKubeArmorPolicyToYamlFile(fname, []types.KubeArmorPolicy{pol})
}
kubearmorVMPolicies, sources := extractVMSystemPolicies(types.PolicyDiscoveryVMNamespace, clustername, labels, fromsource)
for index, pol := range kubearmorVMPolicies {
locSrc := strings.ReplaceAll(sources[index], "/", "-")
fname := "kubearmor_policies_" + pol.Metadata["namespace"] + "_" + pol.Metadata["containername"] + locSrc
libs.WriteKubeArmorPolicyToYamlFile(fname, []types.KubeArmorPolicy{pol})
}
}
func WriteSystemPoliciesToFile(namespace, clustername, labels, fromsource string, includeNetwork bool) {
latestPolicies := libs.GetSystemPolicies(CfgDB, namespace, "latest")
if len(latestPolicies) > 0 {
kubeArmorPolicies := plugin.ConvertKnoxSystemPolicyToKubeArmorPolicy(latestPolicies)
libs.WriteKubeArmorPolicyToYamlFile("kubearmor_policies", kubeArmorPolicies)
}
WriteSystemPoliciesToFile_Ext(namespace, clustername, labels, fromsource, includeNetwork)
}
func GetSysPolicy(namespace, clustername, labels, fromsource string, includeNetwork bool) *wpb.WorkerResponse {
kubearmorK8SPolicies := extractK8SSystemPolicies(namespace, clustername, labels, fromsource, includeNetwork)
kubearmorVMPolicies, _ := extractVMSystemPolicies(types.PolicyDiscoveryVMNamespace, clustername, labels, fromsource)
var response wpb.WorkerResponse
// system policy for k8s
for i := range kubearmorK8SPolicies {
kubearmorpolicy := wpb.Policy{}
val, err := json.Marshal(&kubearmorK8SPolicies[i])
if err != nil {
log.Error().Msgf("kubearmorK8SPolicy json marshal failed err=%v", err.Error())
}
kubearmorpolicy.Data = val
response.Kubearmorpolicy = append(response.Kubearmorpolicy, &kubearmorpolicy)
}
// system policy for VM
for i := range kubearmorVMPolicies {
kubearmorpolicy := wpb.Policy{}
val, err := json.Marshal(&kubearmorVMPolicies[i])
if err != nil {
log.Error().Msgf("kubearmorVMPolicy json marshal failed err=%v", err.Error())
}
kubearmorpolicy.Data = val
response.Kubearmorpolicy = append(response.Kubearmorpolicy, &kubearmorpolicy)
}
response.Res = "OK"
response.Ciliumpolicy = nil
return &response
}
func extractK8SSystemPolicies(namespace, clustername, labels, fromsource string, includeNetwork bool) []types.KubeArmorPolicy {
sysPols := populateKnoxSysPolicyFromWPFSDb(namespace, clustername, labels, fromsource)
policies := plugin.ConvertKnoxSystemPolicyToKubeArmorPolicy(sysPols)
var result []types.KubeArmorPolicy
for _, pol := range policies {
if pol.Metadata["namespace"] != types.PolicyDiscoveryVMNamespace {
if !includeNetwork {
pol.Spec.Network = types.NetworkRule{}
}
for i := range pol.Spec.Process.MatchPaths {
if len(pol.Spec.Process.MatchPaths[i].FromSource) != 0 {
pol.Spec.Process.MatchPaths[i].FromSource = []types.KnoxFromSource{}
}
}
for i := range pol.Spec.Process.MatchDirectories {
if len(pol.Spec.Process.MatchDirectories[i].FromSource) != 0 {
pol.Spec.Process.MatchDirectories[i].FromSource = []types.KnoxFromSource{}
}
}
// if a binary is a global binary, convert file access to global
globalbinaries := []string{}
for _, binary := range pol.Spec.Process.MatchPaths {
if len(binary.FromSource) == 0 && !slices.Contains(globalbinaries, binary.Path) {
globalbinaries = append(globalbinaries, binary.Path)
}
}
// add global binaries to file access list
for _, binary := range globalbinaries {
pol.Spec.File.MatchPaths = append(pol.Spec.File.MatchPaths, types.KnoxMatchPaths{
Path: binary,
ReadOnly: true,
})
}
for i, matchpath := range pol.Spec.File.MatchPaths {
for _, binary := range matchpath.FromSource {
if slices.Contains(globalbinaries, binary.Path) {
pol.Spec.File.MatchPaths[i].FromSource = []types.KnoxFromSource{}
break
}
}
}
for i, matchDir := range pol.Spec.File.MatchDirectories {
for _, binary := range matchDir.FromSource {
if slices.Contains(globalbinaries, binary.Path) {
pol.Spec.File.MatchDirectories[i].FromSource = []types.KnoxFromSource{}
break
}
}
}
for i, netRule := range pol.Spec.Network.MatchProtocols {
for _, binary := range netRule.FromSource {
if slices.Contains(globalbinaries, binary.Path) {
pol.Spec.Network.MatchProtocols[i].FromSource = []types.KnoxFromSource{}
break
}
}
}
result = append(result, pol)
}
}
return result
}
func extractVMSystemPolicies(namespace, clustername, labels, fromSource string) ([]types.KubeArmorPolicy, []string) {
var frmSrcSlice []string
var resFromSrc []string
if fromSource == "" {
frmSrcSlice = GetWPFSSources()
} else {
frmSrcSlice = append(frmSrcSlice, fromSource)
}
var result []types.KubeArmorPolicy
for _, fromSource := range frmSrcSlice {
sysPols := populateKnoxSysPolicyFromWPFSDb(namespace, clustername, labels, fromSource)
policies := plugin.ConvertKnoxSystemPolicyToKubeArmorPolicy(sysPols)
for _, pol := range policies {
if pol.Metadata["namespace"] == types.PolicyDiscoveryVMNamespace {
result = append(result, pol)
resFromSrc = append(resFromSrc, fromSource)
}
}
}
return result, resFromSrc
}
// ============================= //
// == Discover System Policy == //
// ============================= //
func clusteringSystemLogsByCluster(logs []types.KnoxSystemLog) map[string][]types.KnoxSystemLog {
results := map[string][]types.KnoxSystemLog{} // key: cluster name - val: system logs
for _, log := range logs {
results[log.ClusterName] = append(results[log.ClusterName], log)
}
return results
}
func clusteringSystemLogsByNamespacePod(logs []types.KnoxSystemLog) map[SysLogKey][]types.KnoxSystemLog {
results := map[SysLogKey][]types.KnoxSystemLog{} // key: cluster name - val: system logs
for _, log := range logs {
key := SysLogKey{
Namespace: log.Namespace,
PodName: log.PodName,
}
results[key] = append(results[key], log)
}
return results
}
func systemLogDeduplication(logs []types.KnoxSystemLog) []types.KnoxSystemLog {
results := []types.KnoxSystemLog{}
for _, log := range logs {
if libs.ContainsElement(results, log) {
continue
}
// if source == resource, skip
if log.Source == log.Resource {
continue
}
// if pod name or namespace == ""
if log.PodName == "" || log.Namespace == "" {
continue
}
results = append(results, log)
}
return results
}
func getOperationLogs(operation string, logs []types.KnoxSystemLog) []types.KnoxSystemLog {
results := []types.KnoxSystemLog{}
for _, log := range logs {
// operation can be : Process, File, Network
if log.Operation == operation {
results = append(results, log)
}
}
return results
}
func discoverFileOperationPolicy(results []types.KnoxSystemPolicy, pod types.Pod, logs []types.KnoxSystemLog) []types.KnoxSystemPolicy {
// step 1: [system logs] -> {source: []destination(resource)}
srcToDest := map[string][]string{}
// file spec is appended?
appended := false
for _, log := range logs {
if !FileFromSource {
log.Source = SOURCE_ALL
}
if val, ok := srcToDest[log.Source]; ok {
if !libs.ContainsElement(val, log.Resource) {
srcToDest[log.Source] = append(srcToDest[log.Source], log.Resource)
}
} else {
srcToDest[log.Source] = []string{log.Resource}
}
}
// step 2: build file operation
policy := buildSystemPolicy()
policy.Metadata["type"] = SYS_OP_FILE
policy.Spec.File = types.KnoxSys{}
// step 3: aggregate file paths
for src, filePaths := range srcToDest {
aggregatedFilePaths := common.AggregatePaths(filePaths)
// step 4: append spec to the policy
for _, filePath := range aggregatedFilePaths {
appended = true
policy = updateSysPolicySpec(SYS_OP_FILE, policy, src, filePath)
}
}
if appended {
results = append(results, policy)
}
return results
}
func discoverProcessOperationPolicy(results []types.KnoxSystemPolicy, pod types.Pod, logs []types.KnoxSystemLog) []types.KnoxSystemPolicy {
// step 1: [system logs] -> {source: []destination(resource)}
srcToDest := map[string][]string{}
// process spec is appended?
appended := false
for _, log := range logs {
if !ProcessFromSource {
log.Source = SOURCE_ALL
}
if val, ok := srcToDest[log.Source]; ok {
if !libs.ContainsElement(val, log.Resource) {
srcToDest[log.Source] = append(srcToDest[log.Source], log.Resource)
}
} else {
srcToDest[log.Source] = []string{log.Resource}
}
}
// step 2: build process operation
policy := buildSystemPolicy()
policy.Metadata["type"] = SYS_OP_PROCESS
policy.Spec.Process = types.KnoxSys{}
// step 3: aggregate process paths
for src, processPaths := range srcToDest {
aggregatedProcessPaths := common.AggregatePaths(processPaths)
// step 4: append spec to the policy
for _, processPath := range aggregatedProcessPaths {
appended = true
policy = updateSysPolicySpec(SYS_OP_PROCESS, policy, src, processPath)
}
}
if appended {
results = append(results, policy)
}
return results
}
func checkIfMetadataMatches(pin types.KnoxSystemPolicy, hay []types.KnoxSystemPolicy) int {
for idx, v := range hay {
if pin.Metadata["clusterName"] == v.Metadata["clusterName"] &&
pin.Metadata["namespace"] == v.Metadata["namespace"] &&
pin.Metadata["containername"] == v.Metadata["containername"] &&
pin.Metadata["labels"] == v.Metadata["labels"] {
return idx
}
}
return -1
}
func cmpGenPathDir(p1 string, p1fs []types.KnoxFromSource, p2 string, p2fs []types.KnoxFromSource) bool {
if len(p1fs) > 0 {
for _, v := range p1fs {
p1 = p1 + v.Path
}
}
if len(p2fs) > 0 {
for _, v := range p2fs {
p2 = p2 + v.Path
}
}
return p1 < p2
}
func cmpPaths(p1 types.KnoxMatchPaths, p2 types.KnoxMatchPaths) bool {
return cmpGenPathDir(p1.Path, p1.FromSource, p2.Path, p2.FromSource)
}
func cmpProts(p1 types.KnoxMatchProtocols, p2 types.KnoxMatchProtocols) bool {
return cmpGenPathDir(p1.Protocol, p1.FromSource, p2.Protocol, p2.FromSource)
}
func cmpDirs(p1 types.KnoxMatchDirectories, p2 types.KnoxMatchDirectories) bool {
return cmpGenPathDir(p1.Dir, p1.FromSource, p2.Dir, p2.FromSource)
}
func sortFromSource(fs *[]types.KnoxFromSource) {
if len(*fs) <= 1 {
return
}
sort.Slice(*fs, func(x, y int) bool {
return (*fs)[x].Path+(*fs)[x].Dir < (*fs)[y].Path+(*fs)[y].Dir
})
}
func mergeFromSourceMatchPaths(pmp []types.KnoxMatchPaths, mp *[]types.KnoxMatchPaths) {
for _, pp := range pmp {
match := false
for i := range *mp {
rp := &(*mp)[i]
if pp.Path == (*rp).Path {
(*rp).FromSource = append((*rp).FromSource, pp.FromSource...)
//remove dups
match = true
}
sortFromSource(&(*rp).FromSource)
}
if !match {
*mp = append(*mp, pp)
}
}
}
func mergeFromSourceMatchDirs(pmp []types.KnoxMatchDirectories, mp *[]types.KnoxMatchDirectories) {
for _, pp := range pmp {
match := false
for i := range *mp {
rp := &(*mp)[i]
if pp.Dir == (*rp).Dir {
(*rp).FromSource = append((*rp).FromSource, pp.FromSource...)
//remove dups
match = true
}
sortFromSource(&(*rp).FromSource)
}
if !match {
*mp = append(*mp, pp)
}
}
}
func mergeFromSourceMatchProt(pmp []types.KnoxMatchProtocols, mp *[]types.KnoxMatchProtocols) {
for _, pp := range pmp {
match := false
for i := range *mp {
rp := &(*mp)[i]
if pp.Protocol == (*rp).Protocol {
(*rp).FromSource = append((*rp).FromSource, pp.FromSource...)
//remove dups
match = true
}
sortFromSource(&(*rp).FromSource)
}
if !match {
*mp = append(*mp, pp)
}
}
}
/*
The aim of the foll API is to merge multiple fromSources within the same policy.
For e.g.,
---[Input]---
matchPaths:
- path: /etc/ld.so.cache
fromSource:
- path: /bin/ls
- path: /etc/ld.so.cache
fromSource:
- path: /bin/sleep
---
---[Expected Output]---
matchPaths:
- path: /etc/ld.so.cache
fromSource:
- path: /bin/ls
- path: /bin/sleep
---
*/
func mergeFromSource(pols []types.KnoxSystemPolicy) []types.KnoxSystemPolicy {
/*
Logic:
1. For every pol
2. Check if pol matches any policy in res
If no, Create new res (with metadata), without any MatchPath, MatchDir, Network
If yes,
3.
a. For every MatchPath in pol,
check if Path matches with any Path in res[i]
if Yes,
copy pol.MatchPath[I].FromSource to pol.MatchPath[J].FromSource
remove pol.MatchPath[J]
if No,
Append pol.MatchPath[i] -> res.MatchPath
b. Similarly for every MatchDirectories
If No,
a. For every MatchPath in pol,
check if Path
*/
var results []types.KnoxSystemPolicy
for _, pol := range pols {
checked := false
check:
i := checkIfMetadataMatches(pol, results)
if i < 0 {
if checked {
/* If a policy is not present in results, we create metadata
* for the newpol based on pol and reset Process/Network/File
* structure info. The aim is the checkIfMetadaMatches should
* return valid index of the newly appended newpol. */
// Ideally, this condition should never be hit.
log.Error().Msgf("assumptions went wrong. some policies wont work %+v", pol)
continue
}
newpol := pol
newpol.Spec.Process = types.KnoxSys{}
newpol.Spec.File = types.KnoxSys{}
newpol.Spec.Network = types.NetworkRule{}
results = append(results, newpol)
checked = true
goto check
}
mergeFromSourceMatchPaths(pol.Spec.File.MatchPaths, &results[i].Spec.File.MatchPaths)
mergeFromSourceMatchDirs(pol.Spec.File.MatchDirectories, &results[i].Spec.File.MatchDirectories)
mergeFromSourceMatchPaths(pol.Spec.Process.MatchPaths, &results[i].Spec.Process.MatchPaths)
mergeFromSourceMatchDirs(pol.Spec.Process.MatchDirectories, &results[i].Spec.Process.MatchDirectories)
mergeFromSourceMatchProt(pol.Spec.Network.MatchProtocols, &results[i].Spec.Network.MatchProtocols)
}
return results
}
func mergeSysPolicies(pols []types.KnoxSystemPolicy) []types.KnoxSystemPolicy {
var results []types.KnoxSystemPolicy
for _, pol := range pols {
pol.Metadata["name"] = "autopol-system-" +
strconv.FormatUint(uint64(common.HashInt(pol.Metadata["labels"]+
pol.Metadata["namespace"]+pol.Metadata["clustername"]+pol.Metadata["containername"])), 10)
i := checkIfMetadataMatches(pol, results)
if i < 0 {
results = append(results, pol)
continue
}
if len(pol.Spec.File.MatchPaths) > 0 {
mp := &results[i].Spec.File.MatchPaths
*mp = append(*mp, pol.Spec.File.MatchPaths...)
}
if len(pol.Spec.File.MatchDirectories) > 0 {
mp := &results[i].Spec.File.MatchDirectories
*mp = append(*mp, pol.Spec.File.MatchDirectories...)
}
if len(pol.Spec.Process.MatchPaths) > 0 {
mp := &results[i].Spec.Process.MatchPaths
*mp = append(*mp, pol.Spec.Process.MatchPaths...)
}
if len(pol.Spec.Process.MatchDirectories) > 0 {
mp := &results[i].Spec.Process.MatchDirectories
*mp = append(*mp, pol.Spec.Process.MatchDirectories...)
}
if len(pol.Spec.Network.MatchProtocols) > 0 {
mp := &results[i].Spec.Network.MatchProtocols
*mp = append(*mp, pol.Spec.Network.MatchProtocols...)
}
results[i].Metadata["name"] = pol.Metadata["name"]
}
results = mergeFromSource(results)
// merging and sorting all the rules at MatchPaths, MatchDirs, MatchProtocols level
// sorting is needed so that the rules are placed consistently in the
// same order everytime the policy is generated
for _, pol := range results {
if len(pol.Spec.File.MatchPaths) > 0 {
mp := &pol.Spec.File.MatchPaths
sort.Slice(*mp, func(x, y int) bool {
return cmpPaths((*mp)[x], (*mp)[y])
})
}
if len(pol.Spec.File.MatchDirectories) > 0 {
mp := &pol.Spec.File.MatchDirectories
sort.Slice(*mp, func(x, y int) bool {
return cmpDirs((*mp)[x], (*mp)[y])
})
}
if len(pol.Spec.Process.MatchPaths) > 0 {
mp := &pol.Spec.Process.MatchPaths
sort.Slice(*mp, func(x, y int) bool {
return cmpPaths((*mp)[x], (*mp)[y])
})
}
if len(pol.Spec.Process.MatchDirectories) > 0 {
mp := &pol.Spec.Process.MatchDirectories
sort.Slice(*mp, func(x, y int) bool {
return cmpDirs((*mp)[x], (*mp)[y])
})
}
if len(pol.Spec.Network.MatchProtocols) > 0 {
mp := &pol.Spec.Network.MatchProtocols
sort.Slice(*mp, func(x, y int) bool {
return cmpProts((*mp)[x], (*mp)[y])
})
}
}
log.Info().Msgf("Merged %d sys policies into %d policies", len(pols), len(results))
return results
}
func ConvertWPFSToKnoxSysPolicy(wpfsSet types.ResourceSetMap, pnMap types.PolicyNameMap) []types.KnoxSystemPolicy {
var results []types.KnoxSystemPolicy
for wpfs, fsset := range wpfsSet {
policy := buildSystemPolicy()
policy.Metadata["type"] = wpfs.SetType
for _, fpath := range fsset {
path := common.SysPath{
Path: fpath,
IsDir: strings.HasSuffix(fpath, "/"),
}
src := ""
if wpfs.SetType == SYS_OP_NETWORK || strings.HasPrefix(wpfs.FromSource, "/") {
src = wpfs.FromSource
}
policy = updateSysPolicySpec(wpfs.SetType, policy, src, path)
}
policy.Metadata["clusterName"] = wpfs.ClusterName
policy.Metadata["namespace"] = wpfs.Namespace
policy.Metadata["containername"] = wpfs.ContainerName
policy.Metadata["labels"] = wpfs.Labels
policy.Metadata["name"] = pnMap[wpfs]
if wpfs.Labels != "" {
labels := strings.Split(wpfs.Labels, ",")
for _, label := range labels {
k := strings.Split(label, "=")[0]
v := strings.Split(label, "=")[1]
policy.Spec.Selector.MatchLabels[k] = v
}
}
results = append(results, policy)
}
results = mergeSysPolicies(results)
return results
}
func getPodInstance(key SysLogKey, pods []types.Pod) (types.Pod, error) {
for _, pod := range pods {
if key.Namespace == pod.Namespace && key.PodName == pod.PodName {
return pod, nil
}
}
return types.Pod{}, errors.New("Not exist: " + key.Namespace + " " + key.PodName)
}
// ============================ //
// == Building System Policy == //
// ============================ //
func buildSystemPolicy() types.KnoxSystemPolicy {
return types.KnoxSystemPolicy{
APIVersion: "v1",
Kind: "KnoxSystemPolicy",
Metadata: map[string]string{},
Spec: types.KnoxSystemSpec{
Severity: 1, // by default
Selector: types.Selector{
MatchLabels: map[string]string{}},
Action: "Allow",
},
}
}
func updateSysPolicySpec(opType string, policy types.KnoxSystemPolicy, src string, pathSpec common.SysPath) types.KnoxSystemPolicy {
if opType == SYS_OP_NETWORK {
matchProtocols := types.KnoxMatchProtocols{
Protocol: pathSpec.Path,
}
matchProtocols.FromSource = []types.KnoxFromSource{
{
Path: src,
},
}
policy.Metadata["fromSource"] = src
policy.Spec.Network.MatchProtocols = append(policy.Spec.Network.MatchProtocols, matchProtocols)
return policy
}
// matchDirectories
if pathSpec.IsDir {
path := pathSpec.Path
if !strings.HasSuffix(path, "/") {
path = path + "/"
}
matchDirs := types.KnoxMatchDirectories{
Dir: path,
Recursive: true,
}
if opType == SYS_OP_FILE {
if FileFromSource {
if src != "" {
matchDirs.FromSource = []types.KnoxFromSource{
{
Path: src,
},
}
}
policy.Metadata["fromSource"] = src
}
policy.Spec.File.MatchDirectories = append(policy.Spec.File.MatchDirectories, matchDirs)
} else if opType == SYS_OP_PROCESS {
if ProcessFromSource {
if src != "" {
matchDirs.FromSource = []types.KnoxFromSource{
{
Path: src,
},
}
}
policy.Metadata["fromSource"] = src
}
policy.Spec.Process.MatchDirectories = append(policy.Spec.Process.MatchDirectories, matchDirs)
}
} else {
// matchPaths
matchPaths := types.KnoxMatchPaths{
Path: pathSpec.Path,
}
if opType == SYS_OP_FILE {
if FileFromSource {
if src != "" {
matchPaths.FromSource = []types.KnoxFromSource{
{
Path: src,
},
}
}
policy.Metadata["fromSource"] = src
}
policy.Spec.File.MatchPaths = append(policy.Spec.File.MatchPaths, matchPaths)
} else if opType == SYS_OP_PROCESS {
if ProcessFromSource {
if src != "" {
matchPaths.FromSource = []types.KnoxFromSource{
{
Path: src,
},
}
}
policy.Metadata["fromSource"] = src
}
policy.Spec.Process.MatchPaths = append(policy.Spec.Process.MatchPaths, matchPaths)