From 30c8f54e68c4600f54c90fc14ba6b4458c475ee1 Mon Sep 17 00:00:00 2001 From: Jaehyun Nam Date: Mon, 11 Apr 2022 06:32:27 +0000 Subject: [PATCH 1/4] update Policy Mathcer Signed-off-by: Jaehyun Nam --- KubeArmor/BPF/system_monitor.c | 37 +- KubeArmor/Makefile | 10 +- KubeArmor/build/test_kubearmor.sh | 2 +- KubeArmor/core/kubeArmor.go | 65 +- KubeArmor/core/kubeUpdate.go | 83 +- KubeArmor/enforcer/appArmorEnforcer.go | 10 +- KubeArmor/enforcer/appArmorHostProfile.go | 746 +++++--------- KubeArmor/enforcer/appArmorProfile.go | 826 ++++++--------- KubeArmor/enforcer/runtimeEnforcer.go | 16 +- KubeArmor/feeder/feeder.go | 24 +- KubeArmor/feeder/policyMatcher.go | 379 ++++--- KubeArmor/go.mod | 6 +- KubeArmor/go.sum | 52 +- KubeArmor/monitor/logUpdate.go | 44 +- KubeArmor/monitor/processTree.go | 72 +- KubeArmor/monitor/syscallParser.go | 1144 ++++++++++----------- KubeArmor/monitor/systemMonitor.go | 17 +- KubeArmor/types/types.go | 14 +- protobuf/Makefile | 3 +- protobuf/go.mod | 4 +- protobuf/kubearmor.pb.go | 418 ++------ protobuf/kubearmor.proto | 2 + protobuf/kubearmor_grpc.pb.go | 293 ++++++ protobuf/kvm.pb.go | 155 +-- protobuf/kvm_grpc.pb.go | 172 ++++ protobuf/policy.pb.go | 86 +- protobuf/policy_grpc.pb.go | 103 ++ 27 files changed, 2295 insertions(+), 2488 deletions(-) create mode 100644 protobuf/kubearmor_grpc.pb.go create mode 100644 protobuf/kvm_grpc.pb.go create mode 100644 protobuf/policy_grpc.pb.go diff --git a/KubeArmor/BPF/system_monitor.c b/KubeArmor/BPF/system_monitor.c index 7cff87259f..8f78e53e17 100644 --- a/KubeArmor/BPF/system_monitor.c +++ b/KubeArmor/BPF/system_monitor.c @@ -121,15 +121,14 @@ typedef struct args { } args_t; BPF_HASH(args_map, u64, args_t); -BPF_HASH(exec_map, u64, struct path); BPF_HASH(file_map, u64, struct path); typedef struct buffers { u8 buf[MAX_BUFFER_SIZE]; } bufs_t; -BPF_PERCPU_ARRAY(bufs, bufs_t, 2); -BPF_PERCPU_ARRAY(bufs_offset, u32, 2); +BPF_PERCPU_ARRAY(bufs, bufs_t, 3); +BPF_PERCPU_ARRAY(bufs_offset, u32, 3); BPF_PERF_OUTPUT(sys_events); @@ -199,7 +198,7 @@ static __always_inline u32 get_task_ns_pid(struct task_struct *task) static __always_inline u32 get_task_ppid(struct task_struct *task) { - return task->real_parent->pid; + return task->parent->pid; } // == Pid NS Management == // @@ -546,37 +545,29 @@ static __always_inline bool prepend_path(struct path *path, bufs_t *string_p, in return true; } -static __always_inline struct path* load_file_p(int buf_type) +static __always_inline struct path* load_file_p() { u64 pid_tgid = bpf_get_current_pid_tgid(); - - if (buf_type == EXEC_BUF_TYPE) { - struct path *p = exec_map.lookup(&pid_tgid); - exec_map.delete(&pid_tgid); - return p; - } - - // FILE_BUF_TYPE struct path *p = file_map.lookup(&pid_tgid); file_map.delete(&pid_tgid); return p; } -static __always_inline int save_file_to_buffer(bufs_t *bufs_p, int buf_type) +static __always_inline int save_file_to_buffer(bufs_t *bufs_p, void *ptr) { - struct path *path = load_file_p(buf_type); + struct path *path = load_file_p(); - bufs_t *string_p = get_buffer(buf_type); + bufs_t *string_p = get_buffer(FILE_BUF_TYPE); if (string_p == NULL) - return -1; + return save_str_to_buffer(bufs_p, ptr); - if (!prepend_path(path, string_p, buf_type)) { - return -1; + if (!prepend_path(path, string_p, FILE_BUF_TYPE)) { + return save_str_to_buffer(bufs_p, ptr); } - u32 *off = get_buffer_offset(buf_type); + u32 *off = get_buffer_offset(FILE_BUF_TYPE); if (off == NULL) - return -1; + return save_str_to_buffer(bufs_p, ptr); return save_str_to_buffer(bufs_p, (void *)&string_p->buf[*off]); } @@ -673,8 +664,8 @@ static __always_inline int save_args_to_buffer(u64 types, args_t *args) save_to_buffer(bufs_p, (void*)&(args->args[i]), sizeof(int), OPEN_FLAGS_T); break; case FILE_TYPE_T: - if (!save_file_to_buffer(bufs_p, FILE_BUF_TYPE)) - break; + save_file_to_buffer(bufs_p, (void *)args->args[i]); + break; case STR_T: save_str_to_buffer(bufs_p, (void *)args->args[i]); break; diff --git a/KubeArmor/Makefile b/KubeArmor/Makefile index 2b5df911d7..2b8cac088d 100644 --- a/KubeArmor/Makefile +++ b/KubeArmor/Makefile @@ -33,13 +33,13 @@ run: build cd $(CRDDIR); kubectl apply -f KubeArmorPolicy.yaml cd $(CRDDIR); kubectl apply -f KubeArmorHostPolicy.yaml cd $(CURDIR); sudo rm -f /tmp/kubearmor.log - cd $(CURDIR); sudo -E ./kubearmor -logPath=/tmp/kubearmor.log -enableKubeArmorPolicy=true -enableKubeArmorHostPolicy=true + cd $(CURDIR); sudo -E ./kubearmor -logPath=/tmp/kubearmor.log -enableKubeArmorPolicy=true -enableKubeArmorHostPolicy=true -hostVisibility=process,file,network,capabilities .PHONY: run-host-only run-host-only: build cd $(CRDDIR); kubectl apply -f KubeArmorHostPolicy.yaml cd $(CURDIR); sudo rm -f /tmp/kubearmor.log - cd $(CURDIR); sudo -E ./kubearmor -logPath=/tmp/kubearmor.log -enableKubeArmorPolicy=false -enableKubeArmorHostPolicy=true + cd $(CURDIR); sudo -E ./kubearmor -logPath=/tmp/kubearmor.log -enableKubeArmorPolicy=false -enableKubeArmorHostPolicy=true -hostVisibility=process,file,network,capabilities .PHONY: test test: @@ -69,7 +69,8 @@ ifeq (, $(shell which golint)) GOLINT_TMP_DIR=$$(mktemp -d) ;\ cd $$GOLINT_TMP_DIR ;\ go mod init tmp ;\ - go get -u golang.org/x/lint/golint ;\ + go get golang.org/x/lint/golint ;\ + go install golang.org/x/lint/golint ;\ rm -rf $$GOLINT_TMP_DIR ;\ } endif @@ -83,7 +84,8 @@ ifeq (, $(shell which gosec)) GOSEC_TMP_DIR=$$(mktemp -d) ;\ cd $$GOSEC_TMP_DIR ;\ go mod init tmp ;\ - go get -u github.com/securego/gosec/v2/cmd/gosec ;\ + go get github.com/securego/gosec/v2/cmd/gosec ;\ + go install github.com/securego/gosec/v2/cmd/gosec ;\ rm -rf $$GOSEC_TMP_DIR ;\ } endif diff --git a/KubeArmor/build/test_kubearmor.sh b/KubeArmor/build/test_kubearmor.sh index 961eccc8b6..643e40cd55 100755 --- a/KubeArmor/build/test_kubearmor.sh +++ b/KubeArmor/build/test_kubearmor.sh @@ -69,7 +69,7 @@ fi cd $ARMOR_HOME/tests # test scenarios -./test-scenarios-local.sh -testAll +./test-scenarios-local.sh RESULT=$? diff --git a/KubeArmor/core/kubeArmor.go b/KubeArmor/core/kubeArmor.go index e6916ccf7a..03b112c924 100644 --- a/KubeArmor/core/kubeArmor.go +++ b/KubeArmor/core/kubeArmor.go @@ -338,50 +338,53 @@ func KubeArmor() { dm.Node.KernelVersion = kl.GetCommandOutputWithoutErr("uname", []string{"-r"}) dm.Node.KernelVersion = strings.TrimSuffix(dm.Node.KernelVersion, "\n") - dm.Node.PolicyEnabled = tp.KubeArmorPolicyEnabled + kg.Print("Updated the node information") - cfg.GlobalCfg.Policy = false - cfg.GlobalCfg.HostPolicy = true + } else if cfg.GlobalCfg.K8sEnv { + if K8s.InitK8sClient() { + kg.Print("Initialized Kubernetes client") - kg.Print("Updated the node information") + // set the flag + dm.K8sEnabled = true - } else if K8s.InitK8sClient() { - kg.Print("Initialized Kubernetes client") + // watch k8s nodes + go dm.WatchK8sNodes() + kg.Print("Started to monitor node events") - // set the flag - dm.K8sEnabled = true + // == // - // watch k8s nodes - go dm.WatchK8sNodes() - kg.Print("Started to monitor node events") + // wait for a while + time.Sleep(time.Second * 1) - // == // + if dm.Node.NodeIP == "" { + for timeout := 0; timeout <= 60; timeout++ { + if dm.Node.NodeIP != "" { + break + } - // wait for a while - time.Sleep(time.Second * 1) + if dm.Node.NodeIP == "" && timeout == 60 { + kg.Print("The node information is not available, terminating KubeArmor") - if dm.Node.NodeIP == "" { - for timeout := 0; timeout <= 60; timeout++ { - if dm.Node.NodeIP != "" { - break - } + // destroy the daemon + dm.DestroyKubeArmorDaemon() - if dm.Node.NodeIP == "" && timeout == 60 { - kg.Print("The node information is not available, terminating KubeArmor") + return + } - // destroy the daemon - dm.DestroyKubeArmorDaemon() + kg.Print("The node information is not available") - return + // wait for a while + time.Sleep(time.Second * 1) } + } + } else { + kg.Err("Failed to initialize Kubernetes client") - kg.Print("The node information is not available") + // destroy the daemon + dm.DestroyKubeArmorDaemon() - // wait for a while - time.Sleep(time.Second * 1) - } + return } - } // == // @@ -525,7 +528,7 @@ func KubeArmor() { dm.Logger.Print("Started to monitor host security policies") } - if !dm.K8sEnabled && cfg.GlobalCfg.HostPolicy { + if !cfg.GlobalCfg.K8sEnv && cfg.GlobalCfg.HostPolicy { policyService := &policy.ServiceServer{} policyService.UpdateHostPolicy = dm.ParseAndUpdateHostSecurityPolicy @@ -545,7 +548,7 @@ func KubeArmor() { // == // - if !cfg.GlobalCfg.K8sEnv && (cfg.GlobalCfg.KVMAgent || cfg.GlobalCfg.HostPolicy) { + if cfg.GlobalCfg.KVMAgent || (!cfg.GlobalCfg.K8sEnv && cfg.GlobalCfg.HostPolicy) { // Restore and apply all kubearmor host security policies dm.restoreKubeArmorHostPolicies() } diff --git a/KubeArmor/core/kubeUpdate.go b/KubeArmor/core/kubeUpdate.go index e170d587da..5a32436b81 100644 --- a/KubeArmor/core/kubeUpdate.go +++ b/KubeArmor/core/kubeUpdate.go @@ -502,6 +502,13 @@ func (dm *KubeArmorDaemon) WatchK8sPods() { pod.Annotations["kubearmor-policy"] = "audited" } } + + if kl.IsInK8sCluster() && strings.Contains(string(lsm), "selinux") { + // exception: KubeArmor in a daemonset even though SELinux is enabled + if pod.Annotations["kubearmor-policy"] == "enabled" { + pod.Annotations["kubearmor-policy"] = "audited" + } + } } // == Exception == // @@ -1665,21 +1672,6 @@ func (dm *KubeArmorDaemon) WatchHostSecurityPolicies() { // == HostPolicy Backup & Restore == // // ================================= // -// removeBackUpPolicy Function -func (dm *KubeArmorDaemon) removeBackUpPolicy(name string) { - - fname := cfg.PolicyDir + name + ".yaml" - // Check for "/opt/kubearmor/policies" path. If dir not found, create the same - if _, err := os.Stat(fname); err != nil { - kg.Printf("Backup policy [%v] not exist", fname) - return - } - - if err := os.Remove(fname); err != nil { - kg.Errf("unable to delete file:%s err=%s", fname, err.Error()) - } -} - // backupKubeArmorHostPolicy Function func (dm *KubeArmorDaemon) backupKubeArmorHostPolicy(policy tp.HostSecurityPolicy) { // Check for "/opt/kubearmor/policies" path. If dir not found, create the same @@ -1729,31 +1721,25 @@ func (dm *KubeArmorDaemon) restoreKubeArmorHostPolicies() { } } -// WatchDefaultPosture Function -func (dm *KubeArmorDaemon) WatchDefaultPosture() { - nsWatcher, err := K8s.K8sClient.CoreV1().Namespaces().Watch(context.Background(), metav1.ListOptions{}) - defer nsWatcher.Stop() - if err == nil { - for resp := range nsWatcher.ResultChan() { - if resp.Type == watch.Modified || resp.Type == watch.Added { - if ns, ok := resp.Object.(*corev1.Namespace); ok { - defaultPosture := tp.DefaultPosture{ - FileAction: validateDefaultPosture("kubearmor-file-posture", ns, cfg.GlobalCfg.DefaultFilePosture), - NetworkAction: validateDefaultPosture("kubearmor-network-posture", ns, cfg.GlobalCfg.DefaultNetworkPosture), - CapabilitiesAction: validateDefaultPosture("kubearmor-capabilities-posture", ns, cfg.GlobalCfg.DefaultCapabilitiesPosture), - } - dm.UpdateDefaultPosture(string(resp.Type), ns.Name, defaultPosture) +// removeBackUpPolicy Function +func (dm *KubeArmorDaemon) removeBackUpPolicy(name string) { - } - } else if resp.Type == watch.Deleted { - if ns, ok := resp.Object.(*corev1.Namespace); ok { - dm.UpdateDefaultPosture(string(resp.Type), ns.Name, tp.DefaultPosture{}) - } - } - } + fname := cfg.PolicyDir + name + ".yaml" + // Check for "/opt/kubearmor/policies" path. If dir not found, create the same + if _, err := os.Stat(fname); err != nil { + kg.Printf("Backup policy [%v] not exist", fname) + return + } + + if err := os.Remove(fname); err != nil { + kg.Errf("unable to delete file:%s err=%s", fname, err.Error()) } } +// ===================== // +// == Default Posture == // +// ===================== // + func validateDefaultPosture(key string, ns *corev1.Namespace, defaultPosture string) string { if posture, ok := ns.Annotations[key]; ok { if posture == "audit" || posture == "Audit" { @@ -1809,3 +1795,28 @@ func (dm *KubeArmorDaemon) UpdateDefaultPosture(action string, namespace string, } } } + +// WatchDefaultPosture Function +func (dm *KubeArmorDaemon) WatchDefaultPosture() { + nsWatcher, err := K8s.K8sClient.CoreV1().Namespaces().Watch(context.Background(), metav1.ListOptions{}) + defer nsWatcher.Stop() + if err == nil { + for resp := range nsWatcher.ResultChan() { + if resp.Type == watch.Modified || resp.Type == watch.Added { + if ns, ok := resp.Object.(*corev1.Namespace); ok { + defaultPosture := tp.DefaultPosture{ + FileAction: validateDefaultPosture("kubearmor-file-posture", ns, cfg.GlobalCfg.DefaultFilePosture), + NetworkAction: validateDefaultPosture("kubearmor-network-posture", ns, cfg.GlobalCfg.DefaultNetworkPosture), + CapabilitiesAction: validateDefaultPosture("kubearmor-capabilities-posture", ns, cfg.GlobalCfg.DefaultCapabilitiesPosture), + } + dm.UpdateDefaultPosture(string(resp.Type), ns.Name, defaultPosture) + + } + } else if resp.Type == watch.Deleted { + if ns, ok := resp.Object.(*corev1.Namespace); ok { + dm.UpdateDefaultPosture(string(resp.Type), ns.Name, tp.DefaultPosture{}) + } + } + } + } +} diff --git a/KubeArmor/enforcer/appArmorEnforcer.go b/KubeArmor/enforcer/appArmorEnforcer.go index 980e9bbf46..97f9a1d7ea 100644 --- a/KubeArmor/enforcer/appArmorEnforcer.go +++ b/KubeArmor/enforcer/appArmorEnforcer.go @@ -449,7 +449,7 @@ func (ae *AppArmorEnforcer) UnregisterAppArmorHostProfile() bool { // UpdateAppArmorProfile Function func (ae *AppArmorEnforcer) UpdateAppArmorProfile(endPoint tp.EndPoint, appArmorProfile string, securityPolicies []tp.SecurityPolicy) { - if policyCount, newProfile, ok := ae.GenerateAppArmorProfile(appArmorProfile, endPoint.DefaultPosture, securityPolicies); ok { + if policyCount, newProfile, ok := ae.GenerateAppArmorProfile(appArmorProfile, securityPolicies, endPoint.DefaultPosture); ok { newfile, err := os.Create(filepath.Clean("/etc/apparmor.d/" + appArmorProfile)) if err != nil { ae.Logger.Warnf("Unable to open an AppArmor profile (%s, %s)", appArmorProfile, err.Error()) @@ -526,7 +526,13 @@ func (ae *AppArmorEnforcer) UpdateSecurityPolicies(endPoint tp.EndPoint) { // UpdateAppArmorHostProfile Function func (ae *AppArmorEnforcer) UpdateAppArmorHostProfile(secPolicies []tp.HostSecurityPolicy) { - if policyCount, newProfile, ok := ae.GenerateAppArmorHostProfile(secPolicies); ok { + globalDefaultPosture := tp.DefaultPosture{ + FileAction: cfg.GlobalCfg.DefaultFilePosture, + NetworkAction: cfg.GlobalCfg.DefaultNetworkPosture, + CapabilitiesAction: cfg.GlobalCfg.DefaultCapabilitiesPosture, + } + + if policyCount, newProfile, ok := ae.GenerateAppArmorHostProfile(secPolicies, globalDefaultPosture); ok { newfile, err := os.Create(filepath.Clean(appArmorHostFile)) if err != nil { ae.Logger.Warnf("Unable to open the KubeArmor host profile in %s (%s)", cfg.GlobalCfg.Host, err.Error()) diff --git a/KubeArmor/enforcer/appArmorHostProfile.go b/KubeArmor/enforcer/appArmorHostProfile.go index b1a9ec7ba7..308fb6a5c9 100644 --- a/KubeArmor/enforcer/appArmorHostProfile.go +++ b/KubeArmor/enforcer/appArmorHostProfile.go @@ -16,233 +16,52 @@ import ( // AllowedHostProcessMatchPaths Function func (ae *AppArmorEnforcer) AllowedHostProcessMatchPaths(path tp.ProcessPathType, fromSources map[string][]string) { - if len(path.FromSource) > 0 { - for _, src := range path.FromSource { - source := "" - - if len(src.Path) > 0 { - source = src.Path - if _, ok := fromSources[source]; !ok { - fromSources[source] = []string{} - } - } else { - continue - } - - var line string - if path.OwnerOnly { - line = fmt.Sprintf(" owner %s ix,\n", path.Path) - } else { // !path.OwnerOnly - line = fmt.Sprintf(" %s ix,\n", path.Path) - } - if !kl.ContainsElement(fromSources[source], line) { - fromSources[source] = append(fromSources[source], line) - } - } + if len(path.FromSource) == 0 { + return } -} -// AllowedHostProcessMatchDirectories Function -func (ae *AppArmorEnforcer) AllowedHostProcessMatchDirectories(dir tp.ProcessDirectoryType, fromSources map[string][]string) { - if len(dir.FromSource) > 0 { - for _, src := range dir.FromSource { - source := "" - - if len(src.Path) > 0 { - source = src.Path - if _, ok := fromSources[source]; !ok { - fromSources[source] = []string{} - } - } else { - continue - } + for _, src := range path.FromSource { + line := "" - var line string - if dir.Recursive && dir.OwnerOnly { - line = fmt.Sprintf(" owner %s{*,**} ix,\n", dir.Directory) - } else if dir.Recursive && !dir.OwnerOnly { - line = fmt.Sprintf(" %s{*,**} ix,\n", dir.Directory) - } else if !dir.Recursive && dir.OwnerOnly { - line = fmt.Sprintf(" owner %s* ix,\n", dir.Directory) - } else { // !dir.Recursive && !dir.OwnerOnly - line = fmt.Sprintf(" %s* ix,\n", dir.Directory) - } - if !kl.ContainsElement(fromSources[source], line) { - fromSources[source] = append(fromSources[source], line) - } + if len(src.Path) == 0 { + continue } - } -} -// AllowedHostFileMatchPaths Function -func (ae *AppArmorEnforcer) AllowedHostFileMatchPaths(path tp.FilePathType, fromSources map[string][]string) { - if len(path.FromSource) > 0 { - for _, src := range path.FromSource { - source := "" - - if len(src.Path) > 0 { - source = src.Path - if _, ok := fromSources[source]; !ok { - fromSources[source] = []string{} - } - } else { - continue - } - - var line string - if path.ReadOnly && path.OwnerOnly { - line = fmt.Sprintf(" owner %s r,\n", path.Path) - } else if path.ReadOnly && !path.OwnerOnly { - line = fmt.Sprintf(" %s r,\n", path.Path) - } else if !path.ReadOnly && path.OwnerOnly { - line = fmt.Sprintf(" owner %s rw,\n", path.Path) - } else { // !path.ReadOnly && !path.OwnerOnly - line = fmt.Sprintf(" %s rw,\n", path.Path) - } - if !kl.ContainsElement(fromSources[source], line) { - fromSources[source] = append(fromSources[source], line) - } + source := src.Path + if _, ok := fromSources[src.Path]; !ok { + fromSources[src.Path] = []string{} } - } -} - -// AllowedHostFileMatchDirectories Function -func (ae *AppArmorEnforcer) AllowedHostFileMatchDirectories(dir tp.FileDirectoryType, fromSources map[string][]string) { - if len(dir.FromSource) > 0 { - for _, src := range dir.FromSource { - source := "" - - if len(src.Path) > 0 { - source = src.Path - if _, ok := fromSources[source]; !ok { - fromSources[source] = []string{} - } - } else { - continue - } - var line string - if dir.ReadOnly && dir.OwnerOnly { - if dir.Recursive { - line = fmt.Sprintf(" owner %s{*,**} r,\n", dir.Directory) - } else { - line = fmt.Sprintf(" owner %s* r,\n", dir.Directory) - } - } else if dir.ReadOnly && !dir.OwnerOnly { - if dir.Recursive { - line = fmt.Sprintf(" %s{*,**} r,\n", dir.Directory) - } else { - line = fmt.Sprintf(" %s* r,\n", dir.Directory) - } - } else if !dir.ReadOnly && dir.OwnerOnly { - if dir.Recursive { - line = fmt.Sprintf(" owner %s{*,**} rw,\n", dir.Directory) - } else { - line = fmt.Sprintf(" owner %s* rw,\n", dir.Directory) - } - } else { // !dir.ReadOnly && !dir.OwnerOnly - if dir.Recursive { - line = fmt.Sprintf(" %s{*,**} rw,\n", dir.Directory) - } else { - line = fmt.Sprintf(" %s* rw,\n", dir.Directory) - } - } - if !kl.ContainsElement(fromSources[source], line) { - fromSources[source] = append(fromSources[source], line) - } + if path.OwnerOnly { + line = fmt.Sprintf(" owner %s ix,\n", path.Path) + } else { // !path.OwnerOnly + line = fmt.Sprintf(" %s ix,\n", path.Path) } - } -} - -// AllowedHostNetworkMatchProtocols Function -func (ae *AppArmorEnforcer) AllowedHostNetworkMatchProtocols(proto tp.NetworkProtocolType, fromSources map[string][]string) { - if len(proto.FromSource) > 0 { - for _, src := range proto.FromSource { - source := "" - - if len(src.Path) > 0 { - source = src.Path - if _, ok := fromSources[source]; !ok { - fromSources[source] = []string{} - } - } else { - continue - } - line := fmt.Sprintf(" network %s,\n", proto.Protocol) - if !kl.ContainsElement(fromSources[source], line) { - fromSources[source] = append(fromSources[source], line) - } + if !kl.ContainsElement(fromSources[source], line) { + fromSources[source] = append(fromSources[source], line) } } } -// AllowedHostCapabilitiesMatchCapabilities Function -func (ae *AppArmorEnforcer) AllowedHostCapabilitiesMatchCapabilities(cap tp.CapabilitiesCapabilityType, fromSources map[string][]string) { - if len(cap.FromSource) > 0 { - for _, src := range cap.FromSource { - source := "" - - if len(src.Path) > 0 { - source = src.Path - if _, ok := fromSources[source]; !ok { - fromSources[source] = []string{} - } - } else { - continue - } - - line := fmt.Sprintf(" capability %s,\n", cap.Capability) - if !kl.ContainsElement(fromSources[source], line) { - fromSources[source] = append(fromSources[source], line) - } - } +// AllowedHostProcessMatchDirectories Function +func (ae *AppArmorEnforcer) AllowedHostProcessMatchDirectories(dir tp.ProcessDirectoryType, fromSources map[string][]string) { + if len(dir.FromSource) == 0 { + return } -} -// + for _, src := range dir.FromSource { + line := "" -// AuditedHostProcessMatchPaths Function -func (ae *AppArmorEnforcer) AuditedHostProcessMatchPaths(path tp.ProcessPathType, processAuditList *[]string, fromSources map[string][]string) { - var line string - if len(path.FromSource) == 0 { - if path.OwnerOnly { - line = fmt.Sprintf(" owner %s ix,\n", path.Path) - } else { // !path.OwnerOnly - line = fmt.Sprintf(" %s ix,\n", path.Path) - } - if !kl.ContainsElement(*processAuditList, line) { - *processAuditList = append(*processAuditList, line) + if len(src.Path) == 0 { + continue } - } else { - for _, src := range path.FromSource { - source := "" - if len(src.Path) > 0 { - source = src.Path - if _, ok := fromSources[source]; !ok { - fromSources[source] = []string{} - } - } else { - continue - } - - if path.OwnerOnly { - line = fmt.Sprintf(" owner %s ix,\n", path.Path) - } else { // !path.OwnerOnly - line = fmt.Sprintf(" %s ix,\n", path.Path) - } - if !kl.ContainsElement(fromSources[source], line) { - fromSources[source] = append(fromSources[source], line) - } + source := src.Path + if _, ok := fromSources[source]; !ok { + fromSources[source] = []string{} } - } -} -// AuditedHostProcessMatchDirectories Function -func (ae *AppArmorEnforcer) AuditedHostProcessMatchDirectories(dir tp.ProcessDirectoryType, processAuditList *[]string, fromSources map[string][]string) { - var line string - if len(dir.FromSource) == 0 { if dir.Recursive && dir.OwnerOnly { line = fmt.Sprintf(" owner %s{*,**} ix,\n", dir.Directory) } else if dir.Recursive && !dir.OwnerOnly { @@ -252,55 +71,31 @@ func (ae *AppArmorEnforcer) AuditedHostProcessMatchDirectories(dir tp.ProcessDir } else { // !dir.Recursive && !dir.OwnerOnly line = fmt.Sprintf(" %s* ix,\n", dir.Directory) } - if !kl.ContainsElement(*processAuditList, line) { - *processAuditList = append(*processAuditList, line) - } - } else { - for _, src := range dir.FromSource { - source := "" - - if len(src.Path) > 0 { - source = src.Path - if _, ok := fromSources[source]; !ok { - fromSources[source] = []string{} - } - } else { - continue - } - if dir.Recursive && dir.OwnerOnly { - line = fmt.Sprintf(" owner %s{*,**} ix,\n", dir.Directory) - } else if dir.Recursive && !dir.OwnerOnly { - line = fmt.Sprintf(" %s{*,**} ix,\n", dir.Directory) - } else if !dir.Recursive && dir.OwnerOnly { - line = fmt.Sprintf(" owner %s* ix,\n", dir.Directory) - } else { // !dir.Recursive && !dir.OwnerOnly - line = fmt.Sprintf(" %s* ix,\n", dir.Directory) - } - if !kl.ContainsElement(fromSources[source], line) { - fromSources[source] = append(fromSources[source], line) - } + if !kl.ContainsElement(fromSources[source], line) { + fromSources[source] = append(fromSources[source], line) } } } -// AuditedHostProcessMatchPatterns Function -func (ae *AppArmorEnforcer) AuditedHostProcessMatchPatterns(pat tp.ProcessPatternType, processAuditList *[]string) { - var line string - if pat.OwnerOnly { - line = fmt.Sprintf(" owner %s ix,\n", pat.Pattern) - } else { // !pat.OwnerOnly - line = fmt.Sprintf(" %s* ix,\n", pat.Pattern) - } - if !kl.ContainsElement(*processAuditList, line) { - *processAuditList = append(*processAuditList, line) +// AllowedHostFileMatchPaths Function +func (ae *AppArmorEnforcer) AllowedHostFileMatchPaths(path tp.FilePathType, fromSources map[string][]string) { + if len(path.FromSource) == 0 { + return } -} -// AuditedHostFileMatchPaths Function -func (ae *AppArmorEnforcer) AuditedHostFileMatchPaths(path tp.FilePathType, fileAuditList *[]string, fromSources map[string][]string) { - var line string - if len(path.FromSource) == 0 { + for _, src := range path.FromSource { + line := "" + + if len(src.Path) == 0 { + continue + } + + source := src.Path + if _, ok := fromSources[source]; !ok { + fromSources[source] = []string{} + } + if path.ReadOnly && path.OwnerOnly { line = fmt.Sprintf(" owner %s r,\n", path.Path) } else if path.ReadOnly && !path.OwnerOnly { @@ -310,42 +105,31 @@ func (ae *AppArmorEnforcer) AuditedHostFileMatchPaths(path tp.FilePathType, file } else { // !path.ReadOnly && !path.OwnerOnly line = fmt.Sprintf(" %s rw,\n", path.Path) } - if !kl.ContainsElement(*fileAuditList, line) { - *fileAuditList = append(*fileAuditList, line) - } - } else { - for _, src := range path.FromSource { - source := "" - - if len(src.Path) > 0 { - source = src.Path - if _, ok := fromSources[source]; !ok { - fromSources[source] = []string{} - } - } else { - continue - } - if path.ReadOnly && path.OwnerOnly { - line = fmt.Sprintf(" owner %s r,\n", path.Path) - } else if path.ReadOnly && !path.OwnerOnly { - line = fmt.Sprintf(" %s r,\n", path.Path) - } else if !path.ReadOnly && path.OwnerOnly { - line = fmt.Sprintf(" owner %s rw,\n", path.Path) - } else { // !path.ReadOnly && !path.OwnerOnly - line = fmt.Sprintf(" %s rw,\n", path.Path) - } - if !kl.ContainsElement(fromSources[source], line) { - fromSources[source] = append(fromSources[source], line) - } + if !kl.ContainsElement(fromSources[source], line) { + fromSources[source] = append(fromSources[source], line) } } } -// AuditedHostFileMatchDirectories Function -func (ae *AppArmorEnforcer) AuditedHostFileMatchDirectories(dir tp.FileDirectoryType, fileAuditList *[]string, fromSources map[string][]string) { - var line string +// AllowedHostFileMatchDirectories Function +func (ae *AppArmorEnforcer) AllowedHostFileMatchDirectories(dir tp.FileDirectoryType, fromSources map[string][]string) { if len(dir.FromSource) == 0 { + return + } + + for _, src := range dir.FromSource { + line := "" + + if len(src.Path) == 0 { + continue + } + + source := src.Path + if _, ok := fromSources[source]; !ok { + fromSources[source] = []string{} + } + if dir.ReadOnly && dir.OwnerOnly { if dir.Recursive { line = fmt.Sprintf(" owner %s{*,**} r,\n", dir.Directory) @@ -371,68 +155,56 @@ func (ae *AppArmorEnforcer) AuditedHostFileMatchDirectories(dir tp.FileDirectory line = fmt.Sprintf(" %s* rw,\n", dir.Directory) } } - if !kl.ContainsElement(*fileAuditList, line) { - *fileAuditList = append(*fileAuditList, line) + + if !kl.ContainsElement(fromSources[source], line) { + fromSources[source] = append(fromSources[source], line) } - } else { - for _, src := range dir.FromSource { - source := "" + } +} - if len(src.Path) > 0 { - source = src.Path - if _, ok := fromSources[source]; !ok { - fromSources[source] = []string{} - } - } else { - continue - } +// AllowedHostNetworkMatchProtocols Function +func (ae *AppArmorEnforcer) AllowedHostNetworkMatchProtocols(proto tp.NetworkProtocolType, fromSources map[string][]string) { + if len(proto.FromSource) == 0 { + return + } - if dir.ReadOnly && dir.OwnerOnly { - if dir.Recursive { - line = fmt.Sprintf(" owner %s{*,**} r,\n", dir.Directory) - } else { - line = fmt.Sprintf(" owner %s* r,\n", dir.Directory) - } - } else if dir.ReadOnly && !dir.OwnerOnly { - if dir.Recursive { - line = fmt.Sprintf(" %s{*,**} r,\n", dir.Directory) - } else { - line = fmt.Sprintf(" %s* r,\n", dir.Directory) - } - } else if !dir.ReadOnly && dir.OwnerOnly { - if dir.Recursive { - line = fmt.Sprintf(" owner %s{*,**} rw,\n", dir.Directory) - } else { - line = fmt.Sprintf(" owner %s* rw,\n", dir.Directory) - } - } else { // !dir.ReadOnly && !dir.OwnerOnly - if dir.Recursive { - line = fmt.Sprintf(" %s{*,**} rw,\n", dir.Directory) - } else { - line = fmt.Sprintf(" %s* rw,\n", dir.Directory) - } - } - if !kl.ContainsElement(fromSources[source], line) { - fromSources[source] = append(fromSources[source], line) - } + for _, src := range proto.FromSource { + if len(src.Path) == 0 { + continue + } + + source := src.Path + if _, ok := fromSources[source]; !ok { + fromSources[source] = []string{} + } + + line := fmt.Sprintf(" network %s,\n", proto.Protocol) + if !kl.ContainsElement(fromSources[source], line) { + fromSources[source] = append(fromSources[source], line) } } } -// AuditedHostFileMatchPatterns Function -func (ae *AppArmorEnforcer) AuditedHostFileMatchPatterns(pat tp.FilePatternType, fileAuditList *[]string) { - var line string - if pat.ReadOnly && pat.OwnerOnly { - line = fmt.Sprintf(" owner %s r,\n", pat.Pattern) - } else if pat.ReadOnly && !pat.OwnerOnly { - line = fmt.Sprintf(" %s r,\n", pat.Pattern) - } else if !pat.ReadOnly && pat.OwnerOnly { - line = fmt.Sprintf(" owner %s rw,\n", pat.Pattern) - } else { // !pat.ReadOnly && !pat.OwnerOnly - line = fmt.Sprintf(" %s rw,\n", pat.Pattern) +// AllowedHostCapabilitiesMatchCapabilities Function +func (ae *AppArmorEnforcer) AllowedHostCapabilitiesMatchCapabilities(cap tp.CapabilitiesCapabilityType, fromSources map[string][]string) { + if len(cap.FromSource) == 0 { + return } - if !kl.ContainsElement(*fileAuditList, line) { - *fileAuditList = append(*fileAuditList, line) + + for _, src := range cap.FromSource { + if len(src.Path) == 0 { + continue + } + + source := src.Path + if _, ok := fromSources[source]; !ok { + fromSources[source] = []string{} + } + + line := fmt.Sprintf(" capability %s,\n", cap.Capability) + if !kl.ContainsElement(fromSources[source], line) { + fromSources[source] = append(fromSources[source], line) + } } } @@ -440,45 +212,51 @@ func (ae *AppArmorEnforcer) AuditedHostFileMatchPatterns(pat tp.FilePatternType, // BlockedHostProcessMatchPaths Function func (ae *AppArmorEnforcer) BlockedHostProcessMatchPaths(path tp.ProcessPathType, processBlackList *[]string, fromSources map[string][]string) { - var line string if len(path.FromSource) == 0 { + line := "" + if path.OwnerOnly { line = fmt.Sprintf(" owner %s ix,\n deny other %s x,\n", path.Path, path.Path) } else { // !path.OwnerOnly line = fmt.Sprintf(" deny %s x,\n", path.Path) } + if !kl.ContainsElement(*processBlackList, line) { *processBlackList = append(*processBlackList, line) } - } else { - for _, src := range path.FromSource { - source := "" - if len(src.Path) > 0 { - source = src.Path - if _, ok := fromSources[source]; !ok { - fromSources[source] = []string{} - } - } else { - continue - } + return + } - if path.OwnerOnly { - line = fmt.Sprintf(" owner %s ix,\n deny other %s x,\n", path.Path, path.Path) - } else { // !path.OwnerOnly - line = fmt.Sprintf(" deny %s x,\n", path.Path) - } - if !kl.ContainsElement(fromSources[source], line) { - fromSources[source] = append(fromSources[source], line) - } + for _, src := range path.FromSource { + line := "" + + if len(src.Path) == 0 { + continue + } + + source := src.Path + if _, ok := fromSources[source]; !ok { + fromSources[source] = []string{} + } + + if path.OwnerOnly { + line = fmt.Sprintf(" owner %s ix,\n deny other %s x,\n", path.Path, path.Path) + } else { // !path.OwnerOnly + line = fmt.Sprintf(" deny %s x,\n", path.Path) + } + + if !kl.ContainsElement(fromSources[source], line) { + fromSources[source] = append(fromSources[source], line) } } } // BlockedHostProcessMatchDirectories Function func (ae *AppArmorEnforcer) BlockedHostProcessMatchDirectories(dir tp.ProcessDirectoryType, processBlackList *[]string, fromSources map[string][]string) { - var line string if len(dir.FromSource) == 0 { + line := "" + if dir.Recursive && dir.OwnerOnly { line = fmt.Sprintf(" owner %s{*,**} ix,\n deny other %s{*,**} x,\n", dir.Directory, dir.Directory) } else if dir.Recursive && !dir.OwnerOnly { @@ -488,46 +266,52 @@ func (ae *AppArmorEnforcer) BlockedHostProcessMatchDirectories(dir tp.ProcessDir } else { // !dir.Recursive && !dir.OwnerOnly line = fmt.Sprintf(" deny %s* x,\n", dir.Directory) } + if !kl.ContainsElement(*processBlackList, line) { *processBlackList = append(*processBlackList, line) } - } else { - for _, src := range dir.FromSource { - source := "" - if len(src.Path) > 0 { - source = src.Path - if _, ok := fromSources[source]; !ok { - fromSources[source] = []string{} - } - } else { - continue - } + return + } - if dir.Recursive && dir.OwnerOnly { - line = fmt.Sprintf(" owner %s{*,**} ix,\n deny other %s{*,**} x,\n", dir.Directory, dir.Directory) - } else if dir.Recursive && !dir.OwnerOnly { - line = fmt.Sprintf(" deny %s{*,**} x,\n", dir.Directory) - } else if !dir.Recursive && dir.OwnerOnly { - line = fmt.Sprintf(" owner %s* ix,\n deny other %s* x,\n", dir.Directory, dir.Directory) - } else { // !dir.Recursive && !dir.OwnerOnly - line = fmt.Sprintf(" deny %s* x,\n", dir.Directory) - } - if !kl.ContainsElement(fromSources[source], line) { - fromSources[source] = append(fromSources[source], line) - } + for _, src := range dir.FromSource { + line := "" + + if len(src.Path) == 0 { + continue + } + + source := src.Path + if _, ok := fromSources[source]; !ok { + fromSources[source] = []string{} + } + + if dir.Recursive && dir.OwnerOnly { + line = fmt.Sprintf(" owner %s{*,**} ix,\n deny other %s{*,**} x,\n", dir.Directory, dir.Directory) + } else if dir.Recursive && !dir.OwnerOnly { + line = fmt.Sprintf(" deny %s{*,**} x,\n", dir.Directory) + } else if !dir.Recursive && dir.OwnerOnly { + line = fmt.Sprintf(" owner %s* ix,\n deny other %s* x,\n", dir.Directory, dir.Directory) + } else { // !dir.Recursive && !dir.OwnerOnly + line = fmt.Sprintf(" deny %s* x,\n", dir.Directory) + } + + if !kl.ContainsElement(fromSources[source], line) { + fromSources[source] = append(fromSources[source], line) } } } // BlockedHostProcessMatchPatterns Function func (ae *AppArmorEnforcer) BlockedHostProcessMatchPatterns(pat tp.ProcessPatternType, processBlackList *[]string) { - var line string + line := "" + if pat.OwnerOnly { line = fmt.Sprintf(" owner %s ix,\n deny other %s x,\n", pat.Pattern, pat.Pattern) } else { // !path.OwnerOnly line = fmt.Sprintf(" deny %s x,\n", pat.Pattern) } + if !kl.ContainsElement(*processBlackList, line) { *processBlackList = append(*processBlackList, line) } @@ -535,8 +319,9 @@ func (ae *AppArmorEnforcer) BlockedHostProcessMatchPatterns(pat tp.ProcessPatter // BlockedHostFileMatchPaths Function func (ae *AppArmorEnforcer) BlockedHostFileMatchPaths(path tp.FilePathType, fileBlackList *[]string, fromSources map[string][]string) { - var line string if len(path.FromSource) == 0 { + line := "" + if path.ReadOnly && path.OwnerOnly { line = fmt.Sprintf(" deny owner %s w,\n deny other %s rw,\n", path.Path, path.Path) } else if path.ReadOnly && !path.OwnerOnly { @@ -546,42 +331,47 @@ func (ae *AppArmorEnforcer) BlockedHostFileMatchPaths(path tp.FilePathType, file } else { // !path.ReadOnly && !path.OwnerOnly line = fmt.Sprintf(" deny %s rw,\n", path.Path) } + if !kl.ContainsElement(*fileBlackList, line) { *fileBlackList = append(*fileBlackList, line) } - } else { - for _, src := range path.FromSource { - source := "" - if len(src.Path) > 0 { - source = src.Path - if _, ok := fromSources[source]; !ok { - fromSources[source] = []string{} - } - } else { - continue - } + return + } - if path.ReadOnly && path.OwnerOnly { - line = fmt.Sprintf(" deny owner %s w,\n deny other %s rw,\n", path.Path, path.Path) - } else if path.ReadOnly && !path.OwnerOnly { - line = fmt.Sprintf(" deny %s w,\n", path.Path) - } else if !path.ReadOnly && path.OwnerOnly { - line = fmt.Sprintf(" owner %s rw,\n deny other %s rw,\n", path.Path, path.Path) - } else { // !path.ReadOnly && !path.OwnerOnly - line = fmt.Sprintf(" deny %s rw,\n", path.Path) - } - if !kl.ContainsElement(fromSources[source], line) { - fromSources[source] = append(fromSources[source], line) - } + for _, src := range path.FromSource { + line := "" + + if len(src.Path) == 0 { + continue + } + + source := src.Path + if _, ok := fromSources[source]; !ok { + fromSources[source] = []string{} + } + + if path.ReadOnly && path.OwnerOnly { + line = fmt.Sprintf(" deny owner %s w,\n deny other %s rw,\n", path.Path, path.Path) + } else if path.ReadOnly && !path.OwnerOnly { + line = fmt.Sprintf(" deny %s w,\n", path.Path) + } else if !path.ReadOnly && path.OwnerOnly { + line = fmt.Sprintf(" owner %s rw,\n deny other %s rw,\n", path.Path, path.Path) + } else { // !path.ReadOnly && !path.OwnerOnly + line = fmt.Sprintf(" deny %s rw,\n", path.Path) + } + + if !kl.ContainsElement(fromSources[source], line) { + fromSources[source] = append(fromSources[source], line) } } } // BlockedHostFileMatchDirectories Function func (ae *AppArmorEnforcer) BlockedHostFileMatchDirectories(dir tp.FileDirectoryType, fileBlackList *[]string, fromSources map[string][]string) { - var line string if len(dir.FromSource) == 0 { + line := "" + if dir.ReadOnly && dir.OwnerOnly { if dir.Recursive { line = fmt.Sprintf(" deny owner %s{*,**} w,\n deny other %s{*,**} rw,\n", dir.Directory, dir.Directory) @@ -607,57 +397,62 @@ func (ae *AppArmorEnforcer) BlockedHostFileMatchDirectories(dir tp.FileDirectory line = fmt.Sprintf(" deny %s* rw,\n", dir.Directory) } } + if !kl.ContainsElement(*fileBlackList, line) { *fileBlackList = append(*fileBlackList, line) } - } else { - for _, src := range dir.FromSource { - source := "" - if len(src.Path) > 0 { - source = src.Path - if _, ok := fromSources[source]; !ok { - fromSources[source] = []string{} - } + return + } + + for _, src := range dir.FromSource { + line := "" + + if len(src.Path) == 0 { + continue + } + + source := src.Path + if _, ok := fromSources[source]; !ok { + fromSources[source] = []string{} + } + + if dir.ReadOnly && dir.OwnerOnly { + if dir.Recursive { + line = fmt.Sprintf(" deny owner %s{*,**} w,\n deny other %s{*,**} rw,\n", dir.Directory, dir.Directory) } else { - continue + line = fmt.Sprintf(" deny owner %s* w,\n deny other %s* rw,\n", dir.Directory, dir.Directory) } - - if dir.ReadOnly && dir.OwnerOnly { - if dir.Recursive { - line = fmt.Sprintf(" deny owner %s{*,**} w,\n deny other %s{*,**} rw,\n", dir.Directory, dir.Directory) - } else { - line = fmt.Sprintf(" deny owner %s* w,\n deny other %s* rw,\n", dir.Directory, dir.Directory) - } - } else if dir.ReadOnly && !dir.OwnerOnly { - if dir.Recursive { - line = fmt.Sprintf(" deny %s{*,**} w,\n", dir.Directory) - } else { - line = fmt.Sprintf(" deny %s* w,\n", dir.Directory) - } - } else if !dir.ReadOnly && dir.OwnerOnly { - if dir.Recursive { - line = fmt.Sprintf(" owner %s{*,**} rw,\n deny other %s{*,**} rw,\n", dir.Directory, dir.Directory) - } else { - line = fmt.Sprintf(" owner %s* rw,\n deny other %s* w,\n", dir.Directory, dir.Directory) - } - } else { // !dir.ReadOnly && !dir.OwnerOnly - if dir.Recursive { - line = fmt.Sprintf(" deny %s{*,**} rw,\n", dir.Directory) - } else { - line = fmt.Sprintf(" deny %s* rw,\n", dir.Directory) - } + } else if dir.ReadOnly && !dir.OwnerOnly { + if dir.Recursive { + line = fmt.Sprintf(" deny %s{*,**} w,\n", dir.Directory) + } else { + line = fmt.Sprintf(" deny %s* w,\n", dir.Directory) } - if !kl.ContainsElement(fromSources[source], line) { - fromSources[source] = append(fromSources[source], line) + } else if !dir.ReadOnly && dir.OwnerOnly { + if dir.Recursive { + line = fmt.Sprintf(" owner %s{*,**} rw,\n deny other %s{*,**} rw,\n", dir.Directory, dir.Directory) + } else { + line = fmt.Sprintf(" owner %s* rw,\n deny other %s* w,\n", dir.Directory, dir.Directory) } + } else { // !dir.ReadOnly && !dir.OwnerOnly + if dir.Recursive { + line = fmt.Sprintf(" deny %s{*,**} rw,\n", dir.Directory) + } else { + line = fmt.Sprintf(" deny %s* rw,\n", dir.Directory) + } + } + + if !kl.ContainsElement(fromSources[source], line) { + fromSources[source] = append(fromSources[source], line) } } } // BlockedHostFileMatchPatterns Function func (ae *AppArmorEnforcer) BlockedHostFileMatchPatterns(pat tp.FilePatternType, fileBlackList *[]string) { - var line string + line := "" + if pat.ReadOnly && pat.OwnerOnly { line = fmt.Sprintf(" deny owner %s w,\n deny other %s rw,\n", pat.Pattern, pat.Pattern) } else if pat.ReadOnly && !pat.OwnerOnly { @@ -667,6 +462,7 @@ func (ae *AppArmorEnforcer) BlockedHostFileMatchPatterns(pat tp.FilePatternType, } else { // !pat.ReadOnly && !pat.OwnerOnly line = fmt.Sprintf(" deny %s rw,\n", pat.Pattern) } + if !kl.ContainsElement(*fileBlackList, line) { *fileBlackList = append(*fileBlackList, line) } @@ -674,21 +470,20 @@ func (ae *AppArmorEnforcer) BlockedHostFileMatchPatterns(pat tp.FilePatternType, // BlockedHostNetworkMatchProtocols Function func (ae *AppArmorEnforcer) BlockedHostNetworkMatchProtocols(proto tp.NetworkProtocolType, fromSources map[string][]string) { - if len(proto.FromSource) <= 0 { + if len(proto.FromSource) == 0 { return } - for _, src := range proto.FromSource { - source := "" - if len(src.Path) > 0 { - source = src.Path - if _, ok := fromSources[source]; !ok { - fromSources[source] = []string{} - } - } else { + for _, src := range proto.FromSource { + if len(src.Path) == 0 { continue } + source := src.Path + if _, ok := fromSources[source]; !ok { + fromSources[source] = []string{} + } + line := fmt.Sprintf(" deny network %s,\n", proto.Protocol) if !kl.ContainsElement(fromSources[source], line) { fromSources[source] = append(fromSources[source], line) @@ -698,15 +493,18 @@ func (ae *AppArmorEnforcer) BlockedHostNetworkMatchProtocols(proto tp.NetworkPro // BlockedHostCapabilitiesMatchCapabilities Function func (ae *AppArmorEnforcer) BlockedHostCapabilitiesMatchCapabilities(cap tp.CapabilitiesCapabilityType, fromSources map[string][]string) { - if len(cap.FromSource) <= 0 { + if len(cap.FromSource) == 0 { return } + for _, src := range cap.FromSource { - if len(src.Path) <= 0 { + if len(src.Path) == 0 { continue } - if _, ok := fromSources[src.Path]; !ok { - fromSources[src.Path] = []string{} + + source := src.Path + if _, ok := fromSources[source]; !ok { + fromSources[source] = []string{} } line := fmt.Sprintf(" deny capability %s,\n", cap.Capability) @@ -751,13 +549,11 @@ func (ae *AppArmorEnforcer) GenerateHostProfileFoot() string { // == // // GenerateHostProfileBody Function -func (ae *AppArmorEnforcer) GenerateHostProfileBody(securityPolicies []tp.HostSecurityPolicy) (int, string) { +func (ae *AppArmorEnforcer) GenerateHostProfileBody(securityPolicies []tp.HostSecurityPolicy, defaultPosture tp.DefaultPosture) (int, string) { count := 0 - processAuditList := []string{} processBlackList := []string{} - fileAuditList := []string{} fileBlackList := []string{} fromSources := map[string][]string{} @@ -780,7 +576,7 @@ func (ae *AppArmorEnforcer) GenerateHostProfileBody(securityPolicies []tp.HostSe if path.Action == "Allow" { ae.AllowedHostProcessMatchPaths(path, fromSources) } else if path.Action == "Audit" { - ae.AuditedHostProcessMatchPaths(path, &processAuditList, fromSources) + // } else if path.Action == "Block" { ae.BlockedHostProcessMatchPaths(path, &processBlackList, fromSources) } @@ -791,7 +587,7 @@ func (ae *AppArmorEnforcer) GenerateHostProfileBody(securityPolicies []tp.HostSe if dir.Action == "Allow" { ae.AllowedHostProcessMatchDirectories(dir, fromSources) } else if dir.Action == "Audit" { - ae.AuditedHostProcessMatchDirectories(dir, &processAuditList, fromSources) + // } else if dir.Action == "Block" { ae.BlockedHostProcessMatchDirectories(dir, &processBlackList, fromSources) } @@ -800,7 +596,7 @@ func (ae *AppArmorEnforcer) GenerateHostProfileBody(securityPolicies []tp.HostSe if len(secPolicy.Spec.Process.MatchPatterns) > 0 { for _, pat := range secPolicy.Spec.Process.MatchPatterns { if pat.Action == "Audit" { - ae.AuditedHostProcessMatchPatterns(pat, &processAuditList) + // } else if pat.Action == "Block" { ae.BlockedHostProcessMatchPatterns(pat, &processBlackList) } @@ -812,7 +608,7 @@ func (ae *AppArmorEnforcer) GenerateHostProfileBody(securityPolicies []tp.HostSe if path.Action == "Allow" { ae.AllowedHostFileMatchPaths(path, fromSources) } else if path.Action == "Audit" { - ae.AuditedHostFileMatchPaths(path, &fileAuditList, fromSources) + // } else if path.Action == "Block" { ae.BlockedHostFileMatchPaths(path, &fileBlackList, fromSources) } @@ -823,7 +619,7 @@ func (ae *AppArmorEnforcer) GenerateHostProfileBody(securityPolicies []tp.HostSe if dir.Action == "Allow" { ae.AllowedHostFileMatchDirectories(dir, fromSources) } else if dir.Action == "Audit" { - ae.AuditedHostFileMatchDirectories(dir, &fileAuditList, fromSources) + // } else if dir.Action == "Block" { ae.BlockedHostFileMatchDirectories(dir, &fileBlackList, fromSources) } @@ -832,7 +628,7 @@ func (ae *AppArmorEnforcer) GenerateHostProfileBody(securityPolicies []tp.HostSe if len(secPolicy.Spec.File.MatchPatterns) > 0 { for _, pat := range secPolicy.Spec.File.MatchPatterns { if pat.Action == "Audit" { - ae.AuditedHostFileMatchPatterns(pat, &fileAuditList) + // } else if pat.Action == "Block" { ae.BlockedHostFileMatchPatterns(pat, &fileBlackList) } @@ -864,20 +660,6 @@ func (ae *AppArmorEnforcer) GenerateHostProfileBody(securityPolicies []tp.HostSe profileBody := "" - // body - audit list - - for _, line := range processAuditList { - profileBody = profileBody + line - } - - count = count + len(processAuditList) - - for _, line := range fileAuditList { - profileBody = profileBody + line - } - - count = count + len(fileAuditList) - // body - black list for _, line := range processBlackList { @@ -925,7 +707,7 @@ func (ae *AppArmorEnforcer) GenerateHostProfileBody(securityPolicies []tp.HostSe continue } - if strings.Contains(line, " owner") { + if strings.Contains(line, " owner") && strings.Contains(line, "deny") { continue } @@ -936,15 +718,15 @@ func (ae *AppArmorEnforcer) GenerateHostProfileBody(securityPolicies []tp.HostSe file = false } - if file { + if defaultPosture.FileAction != "block" && file { bodyFromSource = bodyFromSource + " file,\n" } - if network { + if defaultPosture.FileAction != "block" && network { bodyFromSource = bodyFromSource + " network,\n" } - if capability { + if defaultPosture.CapabilitiesAction != "block" && capability { bodyFromSource = bodyFromSource + " capability,\n" } @@ -986,11 +768,11 @@ func (ae *AppArmorEnforcer) GenerateHostProfileBody(securityPolicies []tp.HostSe } // GenerateAppArmorHostProfile Function -func (ae *AppArmorEnforcer) GenerateAppArmorHostProfile(secPolicies []tp.HostSecurityPolicy) (int, string, bool) { +func (ae *AppArmorEnforcer) GenerateAppArmorHostProfile(secPolicies []tp.HostSecurityPolicy, defaultPosture tp.DefaultPosture) (int, string, bool) { // generate a profile body - count, profileBody := ae.GenerateHostProfileBody(secPolicies) + count, profileBody := ae.GenerateHostProfileBody(secPolicies, defaultPosture) // generate a new profile diff --git a/KubeArmor/enforcer/appArmorProfile.go b/KubeArmor/enforcer/appArmorProfile.go index e23c5102eb..5a26da6c62 100644 --- a/KubeArmor/enforcer/appArmorProfile.go +++ b/KubeArmor/enforcer/appArmorProfile.go @@ -31,6 +31,7 @@ func (ae *AppArmorEnforcer) ResolvedProcessWhiteListConflicts(processWhiteList * // remove line from WhiteList prunedProcessWhiteList = kl.RemoveStringElement(prunedProcessWhiteList, index-numOfRemovedElements) numOfRemovedElements = numOfRemovedElements + 1 + break } } @@ -41,42 +42,51 @@ func (ae *AppArmorEnforcer) ResolvedProcessWhiteListConflicts(processWhiteList * // AllowedProcessMatchPaths Function func (ae *AppArmorEnforcer) AllowedProcessMatchPaths(path tp.ProcessPathType, processWhiteList *[]string, fromSources map[string][]string) { - var line string if len(path.FromSource) == 0 { + line := "" + if path.OwnerOnly { line = fmt.Sprintf(" owner %s ix,\n", path.Path) } else { // !path.OwnerOnly line = fmt.Sprintf(" %s ix,\n", path.Path) } + if !kl.ContainsElement(*processWhiteList, line) { *processWhiteList = append(*processWhiteList, line) } - } else { - for _, src := range path.FromSource { - if len(src.Path) <= 0 { - continue - } - source := src.Path - if _, ok := fromSources[source]; !ok { - fromSources[source] = []string{} - } - if path.OwnerOnly { - line = fmt.Sprintf(" owner %s ix,\n", path.Path) - } else { // !path.OwnerOnly - line = fmt.Sprintf(" %s ix,\n", path.Path) - } - if !kl.ContainsElement(fromSources[source], line) { - fromSources[source] = append(fromSources[source], line) - } + return + } + + for _, src := range path.FromSource { + line := "" + + if len(src.Path) == 0 { + continue + } + + source := src.Path + if _, ok := fromSources[source]; !ok { + fromSources[source] = []string{} + } + + if path.OwnerOnly { + line = fmt.Sprintf(" owner %s ix,\n", path.Path) + } else { // !path.OwnerOnly + line = fmt.Sprintf(" %s ix,\n", path.Path) + } + + if !kl.ContainsElement(fromSources[source], line) { + fromSources[source] = append(fromSources[source], line) } } } // AllowedProcessMatchDirectories Function func (ae *AppArmorEnforcer) AllowedProcessMatchDirectories(dir tp.ProcessDirectoryType, processWhiteList *[]string, fromSources map[string][]string) { - var line string if len(dir.FromSource) == 0 { + line := "" + if dir.Recursive && dir.OwnerOnly { line = fmt.Sprintf(" owner %s{*,**} ix,\n", dir.Directory) } else if dir.Recursive && !dir.OwnerOnly { @@ -86,43 +96,52 @@ func (ae *AppArmorEnforcer) AllowedProcessMatchDirectories(dir tp.ProcessDirecto } else { // !dir.Recursive && !dir.OwnerOnly line = fmt.Sprintf(" %s* ix,\n", dir.Directory) } + if !kl.ContainsElement(*processWhiteList, line) { *processWhiteList = append(*processWhiteList, line) } - } else { - for _, src := range dir.FromSource { - if len(src.Path) <= 0 { - continue - } - source := src.Path - if _, ok := fromSources[source]; !ok { - fromSources[source] = []string{} - } - if dir.Recursive && dir.OwnerOnly { - line = fmt.Sprintf(" owner %s{*,**} ix,\n", dir.Directory) - } else if dir.Recursive && !dir.OwnerOnly { - line = fmt.Sprintf(" %s{*,**} ix,\n", dir.Directory) - } else if !dir.Recursive && dir.OwnerOnly { - line = fmt.Sprintf(" owner %s* ix,\n", dir.Directory) - } else { // !dir.Recursive && !dir.OwnerOnly - line = fmt.Sprintf(" %s* ix,\n", dir.Directory) - } - if !kl.ContainsElement(fromSources[source], line) { - fromSources[source] = append(fromSources[source], line) - } + return + } + + for _, src := range dir.FromSource { + line := "" + + if len(src.Path) == 0 { + continue + } + + source := src.Path + if _, ok := fromSources[source]; !ok { + fromSources[source] = []string{} + } + + if dir.Recursive && dir.OwnerOnly { + line = fmt.Sprintf(" owner %s{*,**} ix,\n", dir.Directory) + } else if dir.Recursive && !dir.OwnerOnly { + line = fmt.Sprintf(" %s{*,**} ix,\n", dir.Directory) + } else if !dir.Recursive && dir.OwnerOnly { + line = fmt.Sprintf(" owner %s* ix,\n", dir.Directory) + } else { // !dir.Recursive && !dir.OwnerOnly + line = fmt.Sprintf(" %s* ix,\n", dir.Directory) + } + + if !kl.ContainsElement(fromSources[source], line) { + fromSources[source] = append(fromSources[source], line) } } } // AllowedProcessMatchPatterns Function func (ae *AppArmorEnforcer) AllowedProcessMatchPatterns(pat tp.ProcessPatternType, processWhiteList *[]string) { - var line string + line := "" + if pat.OwnerOnly { line = fmt.Sprintf(" owner %s ix,\n", pat.Pattern) } else { // !pat.OwnerOnly line = fmt.Sprintf(" %s* ix,\n", pat.Pattern) } + if !kl.ContainsElement(*processWhiteList, line) { *processWhiteList = append(*processWhiteList, line) } @@ -130,8 +149,9 @@ func (ae *AppArmorEnforcer) AllowedProcessMatchPatterns(pat tp.ProcessPatternTyp // AllowedFileMatchPaths Function func (ae *AppArmorEnforcer) AllowedFileMatchPaths(path tp.FilePathType, fileWhiteList *[]string, fromSources map[string][]string) { - var line string if len(path.FromSource) == 0 { + line := "" + if path.ReadOnly && path.OwnerOnly { line = fmt.Sprintf(" owner %s r,\n", path.Path) } else if path.ReadOnly && !path.OwnerOnly { @@ -141,39 +161,47 @@ func (ae *AppArmorEnforcer) AllowedFileMatchPaths(path tp.FilePathType, fileWhit } else { // !path.ReadOnly && !path.OwnerOnly line = fmt.Sprintf(" %s rw,\n", path.Path) } + if !kl.ContainsElement(*fileWhiteList, line) { *fileWhiteList = append(*fileWhiteList, line) } - } else { - for _, src := range path.FromSource { - if len(src.Path) <= 0 { - continue - } - source := src.Path - if _, ok := fromSources[source]; !ok { - fromSources[source] = []string{} - } - if path.ReadOnly && path.OwnerOnly { - line = fmt.Sprintf(" owner %s r,\n", path.Path) - } else if path.ReadOnly && !path.OwnerOnly { - line = fmt.Sprintf(" %s r,\n", path.Path) - } else if !path.ReadOnly && path.OwnerOnly { - line = fmt.Sprintf(" owner %s rw,\n", path.Path) - } else { // !path.ReadOnly && !path.OwnerOnly - line = fmt.Sprintf(" %s rw,\n", path.Path) - } - if !kl.ContainsElement(fromSources[source], line) { - fromSources[source] = append(fromSources[source], line) - } + return + } + + for _, src := range path.FromSource { + line := "" + + if len(src.Path) == 0 { + continue + } + + source := src.Path + if _, ok := fromSources[source]; !ok { + fromSources[source] = []string{} + } + + if path.ReadOnly && path.OwnerOnly { + line = fmt.Sprintf(" owner %s r,\n", path.Path) + } else if path.ReadOnly && !path.OwnerOnly { + line = fmt.Sprintf(" %s r,\n", path.Path) + } else if !path.ReadOnly && path.OwnerOnly { + line = fmt.Sprintf(" owner %s rw,\n", path.Path) + } else { // !path.ReadOnly && !path.OwnerOnly + line = fmt.Sprintf(" %s rw,\n", path.Path) + } + + if !kl.ContainsElement(fromSources[source], line) { + fromSources[source] = append(fromSources[source], line) } } } // AllowedFileMatchDirectories Function func (ae *AppArmorEnforcer) AllowedFileMatchDirectories(dir tp.FileDirectoryType, fileWhiteList *[]string, fromSources map[string][]string) { - var line string if len(dir.FromSource) == 0 { + line := "" + if dir.ReadOnly && dir.OwnerOnly { if dir.Recursive { line = fmt.Sprintf(" owner %s{*,**} r,\n", dir.Directory) @@ -199,54 +227,62 @@ func (ae *AppArmorEnforcer) AllowedFileMatchDirectories(dir tp.FileDirectoryType line = fmt.Sprintf(" %s* rw,\n", dir.Directory) } } + if !kl.ContainsElement(*fileWhiteList, line) { *fileWhiteList = append(*fileWhiteList, line) } - } else { - for _, src := range dir.FromSource { - if len(src.Path) <= 0 { - continue + + return + } + + for _, src := range dir.FromSource { + line := "" + + if len(src.Path) == 0 { + continue + } + + source := src.Path + if _, ok := fromSources[source]; !ok { + fromSources[source] = []string{} + } + + if dir.ReadOnly && dir.OwnerOnly { + if dir.Recursive { + line = fmt.Sprintf(" owner %s{*,**} r,\n", dir.Directory) + } else { + line = fmt.Sprintf(" owner %s* r,\n", dir.Directory) } - source := src.Path - if _, ok := fromSources[source]; !ok { - fromSources[source] = []string{} + } else if dir.ReadOnly && !dir.OwnerOnly { + if dir.Recursive { + line = fmt.Sprintf(" %s{*,**} r,\n", dir.Directory) + } else { + line = fmt.Sprintf(" %s* r,\n", dir.Directory) } - - if dir.ReadOnly && dir.OwnerOnly { - if dir.Recursive { - line = fmt.Sprintf(" owner %s{*,**} r,\n", dir.Directory) - } else { - line = fmt.Sprintf(" owner %s* r,\n", dir.Directory) - } - } else if dir.ReadOnly && !dir.OwnerOnly { - if dir.Recursive { - line = fmt.Sprintf(" %s{*,**} r,\n", dir.Directory) - } else { - line = fmt.Sprintf(" %s* r,\n", dir.Directory) - } - } else if !dir.ReadOnly && dir.OwnerOnly { - if dir.Recursive { - line = fmt.Sprintf(" owner %s{*,**} rw,\n", dir.Directory) - } else { - line = fmt.Sprintf(" owner %s* rw,\n", dir.Directory) - } - } else { // !dir.ReadOnly && !dir.OwnerOnly - if dir.Recursive { - line = fmt.Sprintf(" %s{*,**} rw,\n", dir.Directory) - } else { - line = fmt.Sprintf(" %s* rw,\n", dir.Directory) - } + } else if !dir.ReadOnly && dir.OwnerOnly { + if dir.Recursive { + line = fmt.Sprintf(" owner %s{*,**} rw,\n", dir.Directory) + } else { + line = fmt.Sprintf(" owner %s* rw,\n", dir.Directory) } - if !kl.ContainsElement(fromSources[source], line) { - fromSources[source] = append(fromSources[source], line) + } else { // !dir.ReadOnly && !dir.OwnerOnly + if dir.Recursive { + line = fmt.Sprintf(" %s{*,**} rw,\n", dir.Directory) + } else { + line = fmt.Sprintf(" %s* rw,\n", dir.Directory) } } + + if !kl.ContainsElement(fromSources[source], line) { + fromSources[source] = append(fromSources[source], line) + } } } // AllowedFileMatchPatterns Function func (ae *AppArmorEnforcer) AllowedFileMatchPatterns(pat tp.FilePatternType, fileWhiteList *[]string) { - var line string + line := "" + if pat.ReadOnly && pat.OwnerOnly { line = fmt.Sprintf(" owner %s r,\n", pat.Pattern) } else if pat.ReadOnly && !pat.OwnerOnly { @@ -256,6 +292,7 @@ func (ae *AppArmorEnforcer) AllowedFileMatchPatterns(pat tp.FilePatternType, fil } else { // !pat.ReadOnly && !pat.OwnerOnly line = fmt.Sprintf(" %s rw,\n", pat.Pattern) } + if !kl.ContainsElement(*fileWhiteList, line) { *fileWhiteList = append(*fileWhiteList, line) } @@ -268,20 +305,22 @@ func (ae *AppArmorEnforcer) AllowedNetworkMatchProtocols(proto tp.NetworkProtoco if !kl.ContainsElement(*networkWhiteList, line) { *networkWhiteList = append(*networkWhiteList, line) } - } else { - for _, src := range proto.FromSource { - if len(src.Path) <= 0 { - continue - } - source := src.Path - if _, ok := fromSources[source]; !ok { - fromSources[source] = []string{} - } + return + } - line := fmt.Sprintf(" network %s,\n", proto.Protocol) - if !kl.ContainsElement(fromSources[source], line) { - fromSources[source] = append(fromSources[source], line) - } + for _, src := range proto.FromSource { + if len(src.Path) == 0 { + continue + } + + source := src.Path + if _, ok := fromSources[source]; !ok { + fromSources[source] = []string{} + } + + line := fmt.Sprintf(" network %s,\n", proto.Protocol) + if !kl.ContainsElement(fromSources[source], line) { + fromSources[source] = append(fromSources[source], line) } } } @@ -293,288 +332,75 @@ func (ae *AppArmorEnforcer) AllowedCapabilitiesMatchCapabilities(cap tp.Capabili if !kl.ContainsElement(*capabilityWhiteList, line) { *capabilityWhiteList = append(*capabilityWhiteList, line) } - } else { - for _, src := range cap.FromSource { - if len(src.Path) <= 0 { - continue - } - source := src.Path - if _, ok := fromSources[source]; !ok { - fromSources[source] = []string{} - } - - line := fmt.Sprintf(" capability %s,\n", cap.Capability) - if !kl.ContainsElement(fromSources[source], line) { - fromSources[source] = append(fromSources[source], line) - } - } + return } -} - -// - -// AuditedProcessMatchPaths Function -func (ae *AppArmorEnforcer) AuditedProcessMatchPaths(path tp.ProcessPathType, processAuditList *[]string, fromSources map[string][]string) { - var line string - if len(path.FromSource) == 0 { - if path.OwnerOnly { - line = fmt.Sprintf(" owner %s ix,\n", path.Path) - } else { // !path.OwnerOnly - line = fmt.Sprintf(" %s ix,\n", path.Path) - } - if !kl.ContainsElement(*processAuditList, line) { - *processAuditList = append(*processAuditList, line) - } - } else { - for _, src := range path.FromSource { - if len(src.Path) <= 0 { - continue - } - source := src.Path - if _, ok := fromSources[source]; !ok { - fromSources[source] = []string{} - } - if path.OwnerOnly { - line = fmt.Sprintf(" owner %s ix,\n", path.Path) - } else { // !path.OwnerOnly - line = fmt.Sprintf(" %s ix,\n", path.Path) - } - if !kl.ContainsElement(fromSources[source], line) { - fromSources[source] = append(fromSources[source], line) - } + for _, src := range cap.FromSource { + if len(src.Path) == 0 { + continue } - } -} -// AuditedProcessMatchDirectories Function -func (ae *AppArmorEnforcer) AuditedProcessMatchDirectories(dir tp.ProcessDirectoryType, processAuditList *[]string, fromSources map[string][]string) { - var line string - if len(dir.FromSource) == 0 { - if dir.Recursive && dir.OwnerOnly { - line = fmt.Sprintf(" owner %s{*,**} ix,\n", dir.Directory) - } else if dir.Recursive && !dir.OwnerOnly { - line = fmt.Sprintf(" %s{*,**} ix,\n", dir.Directory) - } else if !dir.Recursive && dir.OwnerOnly { - line = fmt.Sprintf(" owner %s* ix,\n", dir.Directory) - } else { // !dir.Recursive && !dir.OwnerOnly - line = fmt.Sprintf(" %s* ix,\n", dir.Directory) - } - if !kl.ContainsElement(*processAuditList, line) { - *processAuditList = append(*processAuditList, line) + source := src.Path + if _, ok := fromSources[source]; !ok { + fromSources[source] = []string{} } - } else { - for _, src := range dir.FromSource { - if len(src.Path) <= 0 { - continue - } - source := src.Path - if _, ok := fromSources[source]; !ok { - fromSources[source] = []string{} - } - if dir.Recursive && dir.OwnerOnly { - line = fmt.Sprintf(" owner %s{*,**} ix,\n", dir.Directory) - } else if dir.Recursive && !dir.OwnerOnly { - line = fmt.Sprintf(" %s{*,**} ix,\n", dir.Directory) - } else if !dir.Recursive && dir.OwnerOnly { - line = fmt.Sprintf(" owner %s* ix,\n", dir.Directory) - } else { // !dir.Recursive && !dir.OwnerOnly - line = fmt.Sprintf(" %s* ix,\n", dir.Directory) - } - if !kl.ContainsElement(fromSources[source], line) { - fromSources[source] = append(fromSources[source], line) - } + line := fmt.Sprintf(" capability %s,\n", cap.Capability) + if !kl.ContainsElement(fromSources[source], line) { + fromSources[source] = append(fromSources[source], line) } } } -// AuditedProcessMatchPatterns Function -func (ae *AppArmorEnforcer) AuditedProcessMatchPatterns(pat tp.ProcessPatternType, processAuditList *[]string) { - var line string - if pat.OwnerOnly { - line = fmt.Sprintf(" owner %s ix,\n", pat.Pattern) - } else { // !pat.OwnerOnly - line = fmt.Sprintf(" %s* ix,\n", pat.Pattern) - } - if !kl.ContainsElement(*processAuditList, line) { - *processAuditList = append(*processAuditList, line) - } -} +// -// AuditedFileMatchPaths Function -func (ae *AppArmorEnforcer) AuditedFileMatchPaths(path tp.FilePathType, fileAuditList *[]string, fromSources map[string][]string) { - var line string +// BlockedProcessMatchPaths Function +func (ae *AppArmorEnforcer) BlockedProcessMatchPaths(path tp.ProcessPathType, processBlackList *[]string, fromSources map[string][]string) { if len(path.FromSource) == 0 { - if path.ReadOnly && path.OwnerOnly { - line = fmt.Sprintf(" owner %s r,\n", path.Path) - } else if path.ReadOnly && !path.OwnerOnly { - line = fmt.Sprintf(" %s r,\n", path.Path) - } else if !path.ReadOnly && path.OwnerOnly { - line = fmt.Sprintf(" owner %s rw,\n", path.Path) - } else { // !path.ReadOnly && !path.OwnerOnly - line = fmt.Sprintf(" %s rw,\n", path.Path) - } - if !kl.ContainsElement(*fileAuditList, line) { - *fileAuditList = append(*fileAuditList, line) - } - } else { - for _, src := range path.FromSource { - if len(src.Path) <= 0 { - continue - } - source := src.Path - if _, ok := fromSources[source]; !ok { - fromSources[source] = []string{} - } + line := "" - if path.ReadOnly && path.OwnerOnly { - line = fmt.Sprintf(" owner %s r,\n", path.Path) - } else if path.ReadOnly && !path.OwnerOnly { - line = fmt.Sprintf(" %s r,\n", path.Path) - } else if !path.ReadOnly && path.OwnerOnly { - line = fmt.Sprintf(" owner %s rw,\n", path.Path) - } else { // !path.ReadOnly && !path.OwnerOnly - line = fmt.Sprintf(" %s rw,\n", path.Path) - } - if !kl.ContainsElement(fromSources[source], line) { - fromSources[source] = append(fromSources[source], line) - } + if path.OwnerOnly { + line = fmt.Sprintf(" owner %s ix,\n deny other %s x,\n", path.Path, path.Path) + } else { // !path.OwnerOnly + line = fmt.Sprintf(" deny %s x,\n", path.Path) } - } -} -// AuditedFileMatchDirectories Function -func (ae *AppArmorEnforcer) AuditedFileMatchDirectories(dir tp.FileDirectoryType, fileAuditList *[]string, fromSources map[string][]string) { - var line string - if len(dir.FromSource) == 0 { - if dir.ReadOnly && dir.OwnerOnly { - if dir.Recursive { - line = fmt.Sprintf(" owner %s{*,**} r,\n", dir.Directory) - } else { - line = fmt.Sprintf(" owner %s* r,\n", dir.Directory) - } - } else if dir.ReadOnly && !dir.OwnerOnly { - if dir.Recursive { - line = fmt.Sprintf(" %s{*,**} r,\n", dir.Directory) - } else { - line = fmt.Sprintf(" %s* r,\n", dir.Directory) - } - } else if !dir.ReadOnly && dir.OwnerOnly { - if dir.Recursive { - line = fmt.Sprintf(" owner %s{*,**} rw,\n", dir.Directory) - } else { - line = fmt.Sprintf(" owner %s* rw,\n", dir.Directory) - } - } else { // !dir.ReadOnly && !dir.OwnerOnly - if dir.Recursive { - line = fmt.Sprintf(" %s{*,**} rw,\n", dir.Directory) - } else { - line = fmt.Sprintf(" %s* rw,\n", dir.Directory) - } - } - if !kl.ContainsElement(*fileAuditList, line) { - *fileAuditList = append(*fileAuditList, line) + if !kl.ContainsElement(*processBlackList, line) { + *processBlackList = append(*processBlackList, line) } - } else { - for _, src := range dir.FromSource { - if len(src.Path) <= 0 { - continue - } - source := src.Path - if _, ok := fromSources[source]; !ok { - fromSources[source] = []string{} - } - if dir.ReadOnly && dir.OwnerOnly { - if dir.Recursive { - line = fmt.Sprintf(" owner %s{*,**} r,\n", dir.Directory) - } else { - line = fmt.Sprintf(" owner %s* r,\n", dir.Directory) - } - } else if dir.ReadOnly && !dir.OwnerOnly { - if dir.Recursive { - line = fmt.Sprintf(" %s{*,**} r,\n", dir.Directory) - } else { - line = fmt.Sprintf(" %s* r,\n", dir.Directory) - } - } else if !dir.ReadOnly && dir.OwnerOnly { - if dir.Recursive { - line = fmt.Sprintf(" owner %s{*,**} rw,\n", dir.Directory) - } else { - line = fmt.Sprintf(" owner %s* rw,\n", dir.Directory) - } - } else { // !dir.ReadOnly && !dir.OwnerOnly - if dir.Recursive { - line = fmt.Sprintf(" %s{*,**} rw,\n", dir.Directory) - } else { - line = fmt.Sprintf(" %s* rw,\n", dir.Directory) - } - } - if !kl.ContainsElement(fromSources[source], line) { - fromSources[source] = append(fromSources[source], line) - } - } + return } -} -// AuditedFileMatchPatterns Function -func (ae *AppArmorEnforcer) AuditedFileMatchPatterns(pat tp.FilePatternType, fileAuditList *[]string) { - var line string - if pat.ReadOnly && pat.OwnerOnly { - line = fmt.Sprintf(" owner %s r,\n", pat.Pattern) - } else if pat.ReadOnly && !pat.OwnerOnly { - line = fmt.Sprintf(" %s r,\n", pat.Pattern) - } else if !pat.ReadOnly && pat.OwnerOnly { - line = fmt.Sprintf(" owner %s rw,\n", pat.Pattern) - } else { // !pat.ReadOnly && !pat.OwnerOnly - line = fmt.Sprintf(" %s rw,\n", pat.Pattern) - } - if !kl.ContainsElement(*fileAuditList, line) { - *fileAuditList = append(*fileAuditList, line) - } -} + for _, src := range path.FromSource { + line := "" -// + if len(src.Path) == 0 { + continue + } + + source := src.Path + if _, ok := fromSources[source]; !ok { + fromSources[source] = []string{} + } -// BlockedProcessMatchPaths Function -func (ae *AppArmorEnforcer) BlockedProcessMatchPaths(path tp.ProcessPathType, processBlackList *[]string, fromSources map[string][]string) { - var line string - if len(path.FromSource) == 0 { if path.OwnerOnly { line = fmt.Sprintf(" owner %s ix,\n deny other %s x,\n", path.Path, path.Path) } else { // !path.OwnerOnly line = fmt.Sprintf(" deny %s x,\n", path.Path) } - if !kl.ContainsElement(*processBlackList, line) { - *processBlackList = append(*processBlackList, line) - } - } else { - for _, src := range path.FromSource { - if len(src.Path) <= 0 { - continue - } - source := src.Path - if _, ok := fromSources[source]; !ok { - fromSources[source] = []string{} - } - if path.OwnerOnly { - line = fmt.Sprintf(" owner %s ix,\n deny other %s x,\n", path.Path, path.Path) - } else { // !path.OwnerOnly - line = fmt.Sprintf(" deny %s x,\n", path.Path) - } - if !kl.ContainsElement(fromSources[source], line) { - fromSources[source] = append(fromSources[source], line) - } + if !kl.ContainsElement(fromSources[source], line) { + fromSources[source] = append(fromSources[source], line) } } } // BlockedProcessMatchDirectories Function func (ae *AppArmorEnforcer) BlockedProcessMatchDirectories(dir tp.ProcessDirectoryType, processBlackList *[]string, fromSources map[string][]string) { - var line string if len(dir.FromSource) == 0 { + line := "" + if dir.Recursive && dir.OwnerOnly { line = fmt.Sprintf(" owner %s{*,**} ix,\n deny other %s{*,**} x,\n", dir.Directory, dir.Directory) } else if dir.Recursive && !dir.OwnerOnly { @@ -584,43 +410,52 @@ func (ae *AppArmorEnforcer) BlockedProcessMatchDirectories(dir tp.ProcessDirecto } else { // !dir.Recursive && !dir.OwnerOnly line = fmt.Sprintf(" deny %s* x,\n", dir.Directory) } + if !kl.ContainsElement(*processBlackList, line) { *processBlackList = append(*processBlackList, line) } - } else { - for _, src := range dir.FromSource { - if len(src.Path) <= 0 { - continue - } - source := src.Path - if _, ok := fromSources[source]; !ok { - fromSources[source] = []string{} - } - if dir.Recursive && dir.OwnerOnly { - line = fmt.Sprintf(" owner %s{*,**} ix,\n deny other %s{*,**} x,\n", dir.Directory, dir.Directory) - } else if dir.Recursive && !dir.OwnerOnly { - line = fmt.Sprintf(" deny %s{*,**} x,\n", dir.Directory) - } else if !dir.Recursive && dir.OwnerOnly { - line = fmt.Sprintf(" owner %s* ix,\n deny other %s* x,\n", dir.Directory, dir.Directory) - } else { // !dir.Recursive && !dir.OwnerOnly - line = fmt.Sprintf(" deny %s* x,\n", dir.Directory) - } - if !kl.ContainsElement(fromSources[source], line) { - fromSources[source] = append(fromSources[source], line) - } + return + } + + for _, src := range dir.FromSource { + line := "" + + if len(src.Path) == 0 { + continue + } + + source := src.Path + if _, ok := fromSources[source]; !ok { + fromSources[source] = []string{} + } + + if dir.Recursive && dir.OwnerOnly { + line = fmt.Sprintf(" owner %s{*,**} ix,\n deny other %s{*,**} x,\n", dir.Directory, dir.Directory) + } else if dir.Recursive && !dir.OwnerOnly { + line = fmt.Sprintf(" deny %s{*,**} x,\n", dir.Directory) + } else if !dir.Recursive && dir.OwnerOnly { + line = fmt.Sprintf(" owner %s* ix,\n deny other %s* x,\n", dir.Directory, dir.Directory) + } else { // !dir.Recursive && !dir.OwnerOnly + line = fmt.Sprintf(" deny %s* x,\n", dir.Directory) + } + + if !kl.ContainsElement(fromSources[source], line) { + fromSources[source] = append(fromSources[source], line) } } } // BlockedProcessMatchPatterns Function func (ae *AppArmorEnforcer) BlockedProcessMatchPatterns(pat tp.ProcessPatternType, processBlackList *[]string) { - var line string + line := "" + if pat.OwnerOnly { line = fmt.Sprintf(" owner %s ix,\n deny other %s x,\n", pat.Pattern, pat.Pattern) } else { // !path.OwnerOnly line = fmt.Sprintf(" deny %s x,\n", pat.Pattern) } + if !kl.ContainsElement(*processBlackList, line) { *processBlackList = append(*processBlackList, line) } @@ -628,8 +463,9 @@ func (ae *AppArmorEnforcer) BlockedProcessMatchPatterns(pat tp.ProcessPatternTyp // BlockedFileMatchPaths Function func (ae *AppArmorEnforcer) BlockedFileMatchPaths(path tp.FilePathType, fileBlackList *[]string, fromSources map[string][]string) { - var line string if len(path.FromSource) == 0 { + line := "" + if path.ReadOnly && path.OwnerOnly { line = fmt.Sprintf(" deny owner %s w,\n deny other %s rw,\n", path.Path, path.Path) } else if path.ReadOnly && !path.OwnerOnly { @@ -639,39 +475,47 @@ func (ae *AppArmorEnforcer) BlockedFileMatchPaths(path tp.FilePathType, fileBlac } else { // !path.ReadOnly && !path.OwnerOnly line = fmt.Sprintf(" deny %s rw,\n", path.Path) } + if !kl.ContainsElement(*fileBlackList, line) { *fileBlackList = append(*fileBlackList, line) } - } else { - for _, src := range path.FromSource { - if len(src.Path) <= 0 { - continue - } - source := src.Path - if _, ok := fromSources[source]; !ok { - fromSources[source] = []string{} - } - if path.ReadOnly && path.OwnerOnly { - line = fmt.Sprintf(" deny owner %s w,\n deny other %s rw,\n", path.Path, path.Path) - } else if path.ReadOnly && !path.OwnerOnly { - line = fmt.Sprintf(" deny %s w,\n", path.Path) - } else if !path.ReadOnly && path.OwnerOnly { - line = fmt.Sprintf(" owner %s rw,\n deny other %s rw,\n", path.Path, path.Path) - } else { // !path.ReadOnly && !path.OwnerOnly - line = fmt.Sprintf(" deny %s rw,\n", path.Path) - } - if !kl.ContainsElement(fromSources[source], line) { - fromSources[source] = append(fromSources[source], line) - } + return + } + + for _, src := range path.FromSource { + line := "" + + if len(src.Path) == 0 { + continue + } + + source := src.Path + if _, ok := fromSources[source]; !ok { + fromSources[source] = []string{} + } + + if path.ReadOnly && path.OwnerOnly { + line = fmt.Sprintf(" deny owner %s w,\n deny other %s rw,\n", path.Path, path.Path) + } else if path.ReadOnly && !path.OwnerOnly { + line = fmt.Sprintf(" deny %s w,\n", path.Path) + } else if !path.ReadOnly && path.OwnerOnly { + line = fmt.Sprintf(" owner %s rw,\n deny other %s rw,\n", path.Path, path.Path) + } else { // !path.ReadOnly && !path.OwnerOnly + line = fmt.Sprintf(" deny %s rw,\n", path.Path) + } + + if !kl.ContainsElement(fromSources[source], line) { + fromSources[source] = append(fromSources[source], line) } } } // BlockedFileMatchDirectories Function func (ae *AppArmorEnforcer) BlockedFileMatchDirectories(dir tp.FileDirectoryType, fileBlackList *[]string, fromSources map[string][]string) { - var line string if len(dir.FromSource) == 0 { + line := "" + if dir.ReadOnly && dir.OwnerOnly { if dir.Recursive { line = fmt.Sprintf(" deny owner %s{*,**} w,\n deny other %s{*,**} rw,\n", dir.Directory, dir.Directory) @@ -697,54 +541,62 @@ func (ae *AppArmorEnforcer) BlockedFileMatchDirectories(dir tp.FileDirectoryType line = fmt.Sprintf(" deny %s* rw,\n", dir.Directory) } } + if !kl.ContainsElement(*fileBlackList, line) { *fileBlackList = append(*fileBlackList, line) } - } else { - for _, src := range dir.FromSource { - if len(src.Path) <= 0 { - continue + + return + } + + for _, src := range dir.FromSource { + line := "" + + if len(src.Path) == 0 { + continue + } + + source := src.Path + if _, ok := fromSources[source]; !ok { + fromSources[source] = []string{} + } + + if dir.ReadOnly && dir.OwnerOnly { + if dir.Recursive { + line = fmt.Sprintf(" deny owner %s{*,**} w,\n deny other %s{*,**} rw,\n", dir.Directory, dir.Directory) + } else { + line = fmt.Sprintf(" deny owner %s* w,\n deny other %s* rw,\n", dir.Directory, dir.Directory) } - source := src.Path - if _, ok := fromSources[source]; !ok { - fromSources[source] = []string{} + } else if dir.ReadOnly && !dir.OwnerOnly { + if dir.Recursive { + line = fmt.Sprintf(" deny %s{*,**} w,\n", dir.Directory) + } else { + line = fmt.Sprintf(" deny %s* w,\n", dir.Directory) } - - if dir.ReadOnly && dir.OwnerOnly { - if dir.Recursive { - line = fmt.Sprintf(" deny owner %s{*,**} w,\n deny other %s{*,**} rw,\n", dir.Directory, dir.Directory) - } else { - line = fmt.Sprintf(" deny owner %s* w,\n deny other %s* rw,\n", dir.Directory, dir.Directory) - } - } else if dir.ReadOnly && !dir.OwnerOnly { - if dir.Recursive { - line = fmt.Sprintf(" deny %s{*,**} w,\n", dir.Directory) - } else { - line = fmt.Sprintf(" deny %s* w,\n", dir.Directory) - } - } else if !dir.ReadOnly && dir.OwnerOnly { - if dir.Recursive { - line = fmt.Sprintf(" owner %s{*,**} rw,\n deny other %s{*,**} rw,\n", dir.Directory, dir.Directory) - } else { - line = fmt.Sprintf(" owner %s* rw,\n deny other %s* w,\n", dir.Directory, dir.Directory) - } - } else { // !dir.ReadOnly && !dir.OwnerOnly - if dir.Recursive { - line = fmt.Sprintf(" deny %s{*,**} rw,\n", dir.Directory) - } else { - line = fmt.Sprintf(" deny %s* rw,\n", dir.Directory) - } + } else if !dir.ReadOnly && dir.OwnerOnly { + if dir.Recursive { + line = fmt.Sprintf(" owner %s{*,**} rw,\n deny other %s{*,**} rw,\n", dir.Directory, dir.Directory) + } else { + line = fmt.Sprintf(" owner %s* rw,\n deny other %s* w,\n", dir.Directory, dir.Directory) } - if !kl.ContainsElement(fromSources[source], line) { - fromSources[source] = append(fromSources[source], line) + } else { // !dir.ReadOnly && !dir.OwnerOnly + if dir.Recursive { + line = fmt.Sprintf(" deny %s{*,**} rw,\n", dir.Directory) + } else { + line = fmt.Sprintf(" deny %s* rw,\n", dir.Directory) } } + + if !kl.ContainsElement(fromSources[source], line) { + fromSources[source] = append(fromSources[source], line) + } } } // BlockedFileMatchPatterns Function func (ae *AppArmorEnforcer) BlockedFileMatchPatterns(pat tp.FilePatternType, fileBlackList *[]string) { - var line string + line := "" + if pat.ReadOnly && pat.OwnerOnly { line = fmt.Sprintf(" deny owner %s w,\n deny other %s rw,\n", pat.Pattern, pat.Pattern) } else if pat.ReadOnly && !pat.OwnerOnly { @@ -754,6 +606,7 @@ func (ae *AppArmorEnforcer) BlockedFileMatchPatterns(pat tp.FilePatternType, fil } else { // !pat.ReadOnly && !pat.OwnerOnly line = fmt.Sprintf(" deny %s rw,\n", pat.Pattern) } + if !kl.ContainsElement(*fileBlackList, line) { *fileBlackList = append(*fileBlackList, line) } @@ -768,10 +621,12 @@ func (ae *AppArmorEnforcer) BlockedNetworkMatchProtocols(proto tp.NetworkProtoco } return } + for _, src := range proto.FromSource { - if len(src.Path) <= 0 { + if len(src.Path) == 0 { continue } + source := src.Path if _, ok := fromSources[source]; !ok { fromSources[source] = []string{} @@ -791,20 +646,22 @@ func (ae *AppArmorEnforcer) BlockedCapabilitiesMatchCapabilities(cap tp.Capabili if !kl.ContainsElement(*capabilityBlackList, line) { *capabilityBlackList = append(*capabilityBlackList, line) } - } else { - for _, src := range cap.FromSource { - if len(src.Path) <= 0 { - continue - } - source := src.Path - if _, ok := fromSources[source]; !ok { - fromSources[source] = []string{} - } + return + } - line := fmt.Sprintf(" deny capability %s,\n", cap.Capability) - if !kl.ContainsElement(fromSources[source], line) { - fromSources[source] = append(fromSources[source], line) - } + for _, src := range cap.FromSource { + if len(src.Path) <= 0 { + continue + } + + source := src.Path + if _, ok := fromSources[source]; !ok { + fromSources[source] = []string{} + } + + line := fmt.Sprintf(" deny capability %s,\n", cap.Capability) + if !kl.ContainsElement(fromSources[source], line) { + fromSources[source] = append(fromSources[source], line) } } } @@ -812,27 +669,19 @@ func (ae *AppArmorEnforcer) BlockedCapabilitiesMatchCapabilities(cap tp.Capabili // == // // GenerateProfileHead Function -func (ae *AppArmorEnforcer) GenerateProfileHead(processWhiteList, fileWhiteList, networkWhiteList, capabilityWhiteList []string, file, network, capability bool, defaultPosture tp.DefaultPosture) string { +func (ae *AppArmorEnforcer) GenerateProfileHead(processWhiteList, fileWhiteList, networkWhiteList, capabilityWhiteList []string, defaultPosture tp.DefaultPosture) string { profileHead := " #include \n" profileHead = profileHead + " umount,\n" - // Block Access to Resource when - // -> Default Posture is Block - // AND - // -> Atleast one allow policy OR from source allow policy - - if defaultPosture.FileAction == "block" && ((len(processWhiteList) > 0 || len(fileWhiteList) > 0) || !file) { - } else { + if !(defaultPosture.FileAction == "block" && (len(processWhiteList) > 0 || len(fileWhiteList) > 0)) { profileHead = profileHead + " file,\n" } - if defaultPosture.NetworkAction == "block" && (len(networkWhiteList) > 0 || !network) { - } else { + if !(defaultPosture.NetworkAction == "block" && len(networkWhiteList) > 0) { profileHead = profileHead + " network,\n" } - if defaultPosture.CapabilitiesAction == "block" && (len(capabilityWhiteList) > 0 || !capability) { - } else { + if !(defaultPosture.CapabilitiesAction == "block" && len(capabilityWhiteList) > 0) { profileHead = profileHead + " capability,\n" } @@ -865,17 +714,15 @@ func (ae *AppArmorEnforcer) GenerateProfileFoot() string { // == // // GenerateProfileBody Function -func (ae *AppArmorEnforcer) GenerateProfileBody(defaultPosture tp.DefaultPosture, securityPolicies []tp.SecurityPolicy) (int, string) { +func (ae *AppArmorEnforcer) GenerateProfileBody(securityPolicies []tp.SecurityPolicy, defaultPosture tp.DefaultPosture) (int, string) { // preparation count := 0 processWhiteList := []string{} - processAuditList := []string{} processBlackList := []string{} fileWhiteList := []string{} - fileAuditList := []string{} fileBlackList := []string{} networkWhiteList := []string{} @@ -890,10 +737,6 @@ func (ae *AppArmorEnforcer) GenerateProfileBody(defaultPosture tp.DefaultPosture fusionProcessWhiteList := []string{} - globalFile := true - globalNetwork := true - globalCapability := true - // preparation for _, secPolicy := range securityPolicies { @@ -910,7 +753,7 @@ func (ae *AppArmorEnforcer) GenerateProfileBody(defaultPosture tp.DefaultPosture if path.Action == "Allow" { ae.AllowedProcessMatchPaths(path, &processWhiteList, fromSources) } else if path.Action == "Audit" { - ae.AuditedProcessMatchPaths(path, &processAuditList, fromSources) + // } else if path.Action == "Block" { ae.BlockedProcessMatchPaths(path, &processBlackList, fromSources) } @@ -921,7 +764,7 @@ func (ae *AppArmorEnforcer) GenerateProfileBody(defaultPosture tp.DefaultPosture if dir.Action == "Allow" { ae.AllowedProcessMatchDirectories(dir, &processWhiteList, fromSources) } else if dir.Action == "Audit" { - ae.AuditedProcessMatchDirectories(dir, &processAuditList, fromSources) + // } else if dir.Action == "Block" { ae.BlockedProcessMatchDirectories(dir, &processBlackList, fromSources) } @@ -932,7 +775,7 @@ func (ae *AppArmorEnforcer) GenerateProfileBody(defaultPosture tp.DefaultPosture if pat.Action == "Allow" { ae.AllowedProcessMatchPatterns(pat, &processWhiteList) } else if pat.Action == "Audit" { - ae.AuditedProcessMatchPatterns(pat, &processAuditList) + // } else if pat.Action == "Block" { ae.BlockedProcessMatchPatterns(pat, &processBlackList) } @@ -944,7 +787,7 @@ func (ae *AppArmorEnforcer) GenerateProfileBody(defaultPosture tp.DefaultPosture if path.Action == "Allow" { ae.AllowedFileMatchPaths(path, &fileWhiteList, fromSources) } else if path.Action == "Audit" { - ae.AuditedFileMatchPaths(path, &fileAuditList, fromSources) + // } else if path.Action == "Block" { ae.BlockedFileMatchPaths(path, &fileBlackList, fromSources) } @@ -955,7 +798,7 @@ func (ae *AppArmorEnforcer) GenerateProfileBody(defaultPosture tp.DefaultPosture if dir.Action == "Allow" { ae.AllowedFileMatchDirectories(dir, &fileWhiteList, fromSources) } else if dir.Action == "Audit" { - ae.AuditedFileMatchDirectories(dir, &fileAuditList, fromSources) + // } else if dir.Action == "Block" { ae.BlockedFileMatchDirectories(dir, &fileBlackList, fromSources) } @@ -966,7 +809,7 @@ func (ae *AppArmorEnforcer) GenerateProfileBody(defaultPosture tp.DefaultPosture if pat.Action == "Allow" { ae.AllowedFileMatchPatterns(pat, &fileWhiteList) } else if pat.Action == "Audit" { - ae.AuditedFileMatchPatterns(pat, &fileAuditList) + // } else if pat.Action == "Block" { ae.BlockedFileMatchPatterns(pat, &fileBlackList) } @@ -1027,20 +870,6 @@ func (ae *AppArmorEnforcer) GenerateProfileBody(defaultPosture tp.DefaultPosture count = count + len(capabilityWhiteList) - // body - audit list - - for _, line := range processAuditList { - profileBody = profileBody + line - } - - count = count + len(processAuditList) - - for _, line := range fileAuditList { - profileBody = profileBody + line - } - - count = count + len(fileAuditList) - // body - black list for _, line := range processBlackList { @@ -1095,17 +924,15 @@ func (ae *AppArmorEnforcer) GenerateProfileBody(defaultPosture tp.DefaultPosture for _, line := range lines { if strings.Contains(line, " network") { network = false - globalNetwork = false continue } if strings.Contains(line, " capability") { capability = false - globalCapability = false continue } - if strings.Contains(line, " owner") { + if strings.Contains(line, " owner") && strings.Contains(line, "deny") { continue } @@ -1114,7 +941,6 @@ func (ae *AppArmorEnforcer) GenerateProfileBody(defaultPosture tp.DefaultPosture } file = false - globalFile = false } if defaultPosture.FileAction == "block" && ((len(processWhiteList) > 0 || len(fileWhiteList) > 0) || !file) { @@ -1162,7 +988,7 @@ func (ae *AppArmorEnforcer) GenerateProfileBody(defaultPosture tp.DefaultPosture // head - profileHead := " ## == PRE START == ##\n" + ae.GenerateProfileHead(processWhiteList, fileWhiteList, networkWhiteList, capabilityWhiteList, globalFile, globalNetwork, globalCapability, defaultPosture) + " ## == PRE END == ##\n\n" + profileHead := " ## == PRE START == ##\n" + ae.GenerateProfileHead(processWhiteList, fileWhiteList, networkWhiteList, capabilityWhiteList, defaultPosture) + " ## == PRE END == ##\n\n" // body - together @@ -1192,7 +1018,7 @@ func (ae *AppArmorEnforcer) GenerateProfileBody(defaultPosture tp.DefaultPosture // == // // GenerateAppArmorProfile Function -func (ae *AppArmorEnforcer) GenerateAppArmorProfile(appArmorProfile string, defaultPosture tp.DefaultPosture, securityPolicies []tp.SecurityPolicy) (int, string, bool) { +func (ae *AppArmorEnforcer) GenerateAppArmorProfile(appArmorProfile string, securityPolicies []tp.SecurityPolicy, defaultPosture tp.DefaultPosture) (int, string, bool) { // check apparmor profile if _, err := os.Stat(filepath.Clean("/etc/apparmor.d/" + appArmorProfile)); os.IsNotExist(err) { @@ -1209,7 +1035,7 @@ func (ae *AppArmorEnforcer) GenerateAppArmorProfile(appArmorProfile string, defa // generate a profile body - count, newProfileBody := ae.GenerateProfileBody(defaultPosture, securityPolicies) + count, newProfileBody := ae.GenerateProfileBody(securityPolicies, defaultPosture) newProfile := "## == Managed by KubeArmor == ##\n" + "\n" + diff --git a/KubeArmor/enforcer/runtimeEnforcer.go b/KubeArmor/enforcer/runtimeEnforcer.go index 6b2850bb94..c738ff75d6 100644 --- a/KubeArmor/enforcer/runtimeEnforcer.go +++ b/KubeArmor/enforcer/runtimeEnforcer.go @@ -62,26 +62,22 @@ func NewRuntimeEnforcer(node tp.Node, logger *fd.Feeder) *RuntimeEnforcer { if re.appArmorEnforcer != nil { re.Logger.Print("Initialized AppArmor Enforcer") re.EnforcerType = "AppArmor" - } else { - return nil + logger.UpdateEnforcer(re.EnforcerType) + return re } } else if strings.Contains(re.EnforcerType, "selinux") { - if kl.IsK8sLocal() { + if !kl.IsInK8sCluster() { re.seLinuxEnforcer = NewSELinuxEnforcer(node, logger) if re.seLinuxEnforcer != nil { re.Logger.Print("Initialized SELinux Enforcer") re.EnforcerType = "SELinux" - } else { - return nil + logger.UpdateEnforcer(re.EnforcerType) + return re } - } else { - return nil } - } else { - return nil } - return re + return nil } // UpdateAppArmorProfiles Function diff --git a/KubeArmor/feeder/feeder.go b/KubeArmor/feeder/feeder.go index c5187e4577..69e5df782f 100644 --- a/KubeArmor/feeder/feeder.go +++ b/KubeArmor/feeder/feeder.go @@ -286,12 +286,15 @@ type Feeder struct { SecurityPolicies map[string]tp.MatchPolicies SecurityPoliciesLock *sync.RWMutex - //DefaultPosture (namespace -> postures) + // DefaultPosture (namespace -> postures) DefaultPostures map[string]tp.DefaultPosture DefaultPosturesLock *sync.Mutex // GKE IsGKE bool + + // Activated Enforcer + Enforcer string } // NewFeeder Function @@ -352,6 +355,7 @@ func NewFeeder(node *tp.Node) *Feeder { fd.SecurityPolicies = map[string]tp.MatchPolicies{} fd.SecurityPoliciesLock = new(sync.RWMutex) + // initialize default postures fd.DefaultPostures = map[string]tp.DefaultPosture{} fd.DefaultPosturesLock = new(sync.Mutex) @@ -365,6 +369,9 @@ func NewFeeder(node *tp.Node) *Feeder { } } + // default enforcer + fd.Enforcer = "eBPF Monitor" + return fd } @@ -473,6 +480,15 @@ func (fd *Feeder) Warnf(message string, args ...interface{}) { kg.Warnf(str) } +// ===================== // +// == Enforcer Update == // +// ===================== // + +// UpdateEnforcer Function +func (fd *Feeder) UpdateEnforcer(enforcer string) { + fd.Enforcer = enforcer +} + // =============== // // == Log Feeds == // // =============== // @@ -549,7 +565,7 @@ func (fd *Feeder) PushLog(log tp.Log) { } // gRPC output - if log.Type == "MatchedPolicy" || log.Type == "MatchedHostPolicy" || log.Type == "MatchedNativePolicy" { + if log.Type == "MatchedPolicy" || log.Type == "MatchedHostPolicy" { pbAlert := pb.Alert{} pbAlert.Timestamp = log.Timestamp @@ -574,6 +590,10 @@ func (fd *Feeder) PushLog(log tp.Log) { pbAlert.ParentProcessName = log.ParentProcessName pbAlert.ProcessName = log.ProcessName + if len(log.Enforcer) > 0 { + pbAlert.Enforcer = log.Enforcer + } + if len(log.PolicyName) > 0 { pbAlert.PolicyName = log.PolicyName } diff --git a/KubeArmor/feeder/policyMatcher.go b/KubeArmor/feeder/policyMatcher.go index 2a3af81319..e12b001c87 100644 --- a/KubeArmor/feeder/policyMatcher.go +++ b/KubeArmor/feeder/policyMatcher.go @@ -28,9 +28,9 @@ func getProtocolFromName(proto string) string { case "udp": return "type=SOCK_DGRAM" case "icmp": - return "type=SOCK_RAW protocol=1" + return "type=SOCK_RAW" default: - return "" + return "unknown" } } @@ -51,9 +51,9 @@ func getOperationAndCapabilityFromName(capName string) (op, cap string) { switch strings.ToLower(capName) { case "net_raw": op = "Network" - cap = "type=SOCK_RAW protocol=1" + cap = "type=SOCK_RAW" default: - return "", "" + return "", "unknown" } return op, cap @@ -66,9 +66,6 @@ func (fd *Feeder) newMatchPolicy(policyEnabled int, policyName, src string, mp i Source: src, } - match.OwnerOnly = false - match.ReadOnly = false - if ppt, ok := mp.(tp.ProcessPathType); ok { match.Severity = strconv.Itoa(ppt.Severity) match.Tags = ppt.Tags @@ -95,6 +92,7 @@ func (fd *Feeder) newMatchPolicy(policyEnabled int, policyName, src string, mp i match.ResourceType = "Directory" match.OwnerOnly = pdt.OwnerOnly + match.Recursive = pdt.Recursive if policyEnabled == tp.KubeArmorPolicyAudited && strings.HasPrefix(pdt.Action, "Block") { match.Action = "Audit (" + pdt.Action + ")" @@ -145,6 +143,7 @@ func (fd *Feeder) newMatchPolicy(policyEnabled int, policyName, src string, mp i match.OwnerOnly = fdt.OwnerOnly match.ReadOnly = fdt.ReadOnly + match.Recursive = fdt.Recursive if policyEnabled == tp.KubeArmorPolicyAudited && strings.HasPrefix(fdt.Action, "Block") { match.Action = "Audit (" + fdt.Action + ")" @@ -176,9 +175,9 @@ func (fd *Feeder) newMatchPolicy(policyEnabled int, policyName, src string, mp i match.Resource = getProtocolFromName(npt.Protocol) match.ResourceType = "Protocol" - if policyEnabled == tp.KubeArmorPolicyAudited && strings.HasPrefix(npt.Action, "Block") { + if policyEnabled == tp.KubeArmorPolicyEnabled && fd.IsGKE && strings.HasPrefix(npt.Action, "Block") { match.Action = "Audit (" + npt.Action + ")" - } else if policyEnabled == tp.KubeArmorPolicyEnabled && fd.IsGKE && strings.HasPrefix(npt.Action, "Block") { + } else if policyEnabled == tp.KubeArmorPolicyAudited && strings.HasPrefix(npt.Action, "Block") { match.Action = "Audit (" + npt.Action + ")" } else { match.Action = npt.Action @@ -206,20 +205,6 @@ func (fd *Feeder) newMatchPolicy(policyEnabled int, policyName, src string, mp i return match } -// UpdateDefaultPosture Function -func (fd *Feeder) UpdateDefaultPosture(action string, namespace string, defaultPosture tp.DefaultPosture) { - - fd.DefaultPosturesLock.Lock() - defer fd.DefaultPosturesLock.Unlock() - - if action == "DELETED" { - delete(fd.DefaultPostures, namespace) - } - - fd.DefaultPostures[namespace] = defaultPosture - -} - // UpdateSecurityPolicies Function func (fd *Feeder) UpdateSecurityPolicies(action string, endPoint tp.EndPoint) { name := endPoint.NamespaceName + "_" + endPoint.EndPointName @@ -236,12 +221,7 @@ func (fd *Feeder) UpdateSecurityPolicies(action string, endPoint tp.EndPoint) { policyName := secPolicy.Metadata["policyName"] if len(secPolicy.Spec.AppArmor) > 0 { - match := tp.MatchPolicy{} - - match.PolicyName = policyName - match.Native = true - - matches.Policies = append(matches.Policies, match) + continue } for _, path := range secPolicy.Spec.Process.MatchPaths { @@ -467,12 +447,7 @@ func (fd *Feeder) UpdateHostSecurityPolicies(action string, secPolicies []tp.Hos policyName := secPolicy.Metadata["policyName"] if len(secPolicy.Spec.AppArmor) > 0 { - match := tp.MatchPolicy{} - - match.PolicyName = policyName - match.Native = true - - matches.Policies = append(matches.Policies, match) + continue } for _, path := range secPolicy.Spec.Process.MatchPaths { @@ -679,33 +654,58 @@ func (fd *Feeder) UpdateHostSecurityPolicies(action string, secPolicies []tp.Hos fd.SecurityPoliciesLock.Unlock() } -// ==================== // -// == Policy Matches == // -// ==================== // +// ===================== // +// == Default Posture == // +// ===================== // + +// UpdateDefaultPosture Function +func (fd *Feeder) UpdateDefaultPosture(action string, namespace string, defaultPosture tp.DefaultPosture) { + + fd.DefaultPosturesLock.Lock() + defer fd.DefaultPosturesLock.Unlock() -func lastString(ss []string) string { - return ss[len(ss)-1] + if action == "DELETED" { + delete(fd.DefaultPostures, namespace) + } else { // ADDED or MODIFIED + fd.DefaultPostures[namespace] = defaultPosture + } } // Update Log Fields based on default posture and visibility configuration and return false if no updates -func setLogFields(action string, visibility bool, log *tp.Log, considerPosture bool) bool { +func setLogFields(log *tp.Log, action string, considerPosture, visibility, containerLog bool) bool { if considerPosture && action == "block" { - (*log).Type = "MatchedPolicy" + if containerLog { + (*log).Type = "MatchedPolicy" + } else { + (*log).Type = "MatchedHostPolicy" + } (*log).PolicyName = "DefaultPosture" (*log).Action = "Block" return true } else if considerPosture && action == "audit" { - (*log).Type = "MatchedPolicy" + if containerLog { + (*log).Type = "MatchedPolicy" + } else { + (*log).Type = "MatchedHostPolicy" + } (*log).PolicyName = "DefaultPosture" (*log).Action = "Audit" return true } else if visibility { - (*log).Type = "ContainerLog" + if containerLog { + (*log).Type = "ContainerLog" + } else { + (*log).Type = "HostLog" + } return true } return false } +// ==================== // +// == Policy Matches == // +// ==================== // + // UpdateMatchedPolicy Function func (fd *Feeder) UpdateMatchedPolicy(log tp.Log) tp.Log { allowProcPolicy := "" @@ -723,7 +723,6 @@ func (fd *Feeder) UpdateMatchedPolicy(log tp.Log) tp.Log { allowNetworkTags := []string{} allowNetworkMessage := "" - mightBeNative := false considerFilePosture := false considerNetworkPosture := false @@ -738,8 +737,14 @@ func (fd *Feeder) UpdateMatchedPolicy(log tp.Log) tp.Log { secPolicies := fd.SecurityPolicies[key].Policies for _, secPolicy := range secPolicies { - if secPolicy.Source == "" || (secPolicy.IsFromSource && strings.Contains(secPolicy.Source, strings.Split(log.Source, " ")[0])) || (log.Source == "runc:[2:INIT]" && strings.Contains(secPolicy.Source, strings.Split(log.Resource, " ")[0])) { - if secPolicy.Action == "Allow" { + firstLogSource := strings.Replace(strings.Split(log.Source, " ")[0], "./", "", 1) + firstLogResource := strings.Replace(strings.Split(log.Resource, " ")[0], "./", "", 1) + + if secPolicy.Action == "Allow" { + if secPolicy.Source == "" || (secPolicy.IsFromSource && + ((secPolicy.Operation == "Process" && (secPolicy.Source == log.ParentProcessName || secPolicy.Source == log.ProcessName)) || // ./bash -> xxx || ./bash -c xxx + (secPolicy.Operation != "Process" && (secPolicy.Source == log.ProcessName || strings.Contains(secPolicy.Source, firstLogSource))))) { + if secPolicy.Operation == "Process" { if allowProcPolicy == "" { allowProcPolicy = secPolicy.PolicyName @@ -832,120 +837,115 @@ func (fd *Feeder) UpdateMatchedPolicy(log tp.Log) tp.Log { } } - if matched || strings.Contains(log.Resource, secPolicy.Resource) || log.Resource == lastString(strings.Split(secPolicy.Resource, "/")) { - if (secPolicy.Action == "Allow" && log.Result != "Passed") || secPolicy.Source == "" || - (secPolicy.Source != "" && strings.Contains(secPolicy.Source, strings.Split(log.Source, " ")[0])) || - (log.Source == "runc:[2:INIT]" && strings.Contains(secPolicy.Source, strings.Split(log.Resource, " ")[0])) { + if secPolicy.Source == "" || (secPolicy.IsFromSource && + ((secPolicy.Operation == "Process" && (secPolicy.Source == log.ParentProcessName || secPolicy.Source == log.ProcessName)) || // ./bash -> xxx || ./bash -c xxx + (secPolicy.Operation == "File" && (secPolicy.Source == log.ProcessName || strings.Contains(secPolicy.Source, firstLogSource))))) { - if log.PolicyEnabled == tp.KubeArmorPolicyEnabled && log.Result == "Passed" { - if log.Resource != "" && secPolicy.ReadOnly && log.MergedDir != "" && secPolicy.OwnerOnly { - // read only - preLogData := strings.Split(log.Data, " ") - logData := strings.Split(preLogData[len(preLogData)-1], "=") - flags := logData[len(logData)-1] + if matched || secPolicy.Resource == log.Resource || (secPolicy.ResourceType == "Path" && strings.HasSuffix(secPolicy.Resource, firstLogResource)) || + (secPolicy.ResourceType == "Directory" && strings.HasPrefix(firstLogResource, secPolicy.Resource) && !strings.Contains(strings.Replace(firstLogResource, secPolicy.Resource, "", 1), "/")) || + (secPolicy.ResourceType == "Directory" && secPolicy.Recursive && strings.HasPrefix(firstLogResource, secPolicy.Resource) && strings.Contains(strings.Replace(firstLogResource, secPolicy.Resource, "", 1), "/")) { - // owner only - fileProcessUID := getFileProcessUID(log.MergedDir + log.Resource) + if secPolicy.Action == "Audit" && log.Result == "Passed" { + matchedFlags := false - if flags == "O_RDONLY" && strconv.Itoa(int(log.UID)) == fileProcessUID { - continue + if secPolicy.ReadOnly && log.Resource != "" && secPolicy.OwnerOnly && log.MergedDir != "" { + // read only && owner only + if strings.Contains(log.Data, "O_RDONLY") && strconv.Itoa(int(log.UID)) == getFileProcessUID(log.MergedDir+log.Resource) { + matchedFlags = true } - } else if log.Resource != "" && secPolicy.ReadOnly { + } else if secPolicy.ReadOnly && log.Resource != "" { // read only - preLogData := strings.Split(log.Data, " ") - logData := strings.Split(preLogData[len(preLogData)-1], "=") - flags := logData[len(logData)-1] - - if flags == "O_RDONLY" { - continue + if strings.Contains(log.Data, "O_RDONLY") { + matchedFlags = true } - } else if log.MergedDir != "" && secPolicy.OwnerOnly { + } else if secPolicy.OwnerOnly && log.MergedDir != "" { // owner only - fileProcessUID := getFileProcessUID(log.MergedDir + log.Resource) - - if strconv.Itoa(int(log.UID)) == fileProcessUID { - continue + if strconv.Itoa(int(log.UID)) == getFileProcessUID(log.MergedDir+log.Resource) { + matchedFlags = true } + } else { + // ! read only && ! owner only + matchedFlags = true } - } - log.PolicyName = secPolicy.PolicyName - log.Severity = secPolicy.Severity + if matchedFlags { + log.PolicyName = secPolicy.PolicyName + log.Severity = secPolicy.Severity - if len(secPolicy.Tags) > 0 { - log.Tags = strings.Join(secPolicy.Tags[:], ",") - } + if len(secPolicy.Tags) > 0 { + log.Tags = strings.Join(secPolicy.Tags[:], ",") + } + + if len(secPolicy.Message) > 0 { + log.Message = secPolicy.Message + } - if len(secPolicy.Message) > 0 { - log.Message = secPolicy.Message + log.Type = "MatchedPolicy" + log.Action = secPolicy.Action + + continue + } } - log.Type = "MatchedPolicy" - log.Action = secPolicy.Action + if log.Result != "Passed" { + log.PolicyName = secPolicy.PolicyName + log.Severity = secPolicy.Severity - continue - } - } + if len(secPolicy.Tags) > 0 { + log.Tags = strings.Join(secPolicy.Tags[:], ",") + } + + if len(secPolicy.Message) > 0 { + log.Message = secPolicy.Message + } - if !matched { - if secPolicy.Action == "Allow" { - considerFilePosture = true + log.Type = "MatchedPolicy" + log.Action = secPolicy.Action + + continue + } } } } case "Network": if secPolicy.Operation == log.Operation { - if strings.Contains(log.Resource, secPolicy.Resource) { - if secPolicy.Source == "" || (secPolicy.Source != "" && strings.Contains(secPolicy.Source, strings.Split(log.Source, " ")[0])) { - log.PolicyName = secPolicy.PolicyName - log.Severity = secPolicy.Severity + if (secPolicy.Source == "" || (secPolicy.IsFromSource && (secPolicy.Source == log.ProcessName || strings.Contains(secPolicy.Source, firstLogSource)))) && strings.Contains(log.Resource, secPolicy.Resource) { - if len(secPolicy.Tags) > 0 { - log.Tags = strings.Join(secPolicy.Tags[:], ",") - } - - if len(secPolicy.Message) > 0 { - log.Message = secPolicy.Message - } + log.PolicyName = secPolicy.PolicyName + log.Severity = secPolicy.Severity - log.Type = "MatchedPolicy" - log.Action = secPolicy.Action + if len(secPolicy.Tags) > 0 { + log.Tags = strings.Join(secPolicy.Tags[:], ",") + } - continue + if len(secPolicy.Message) > 0 { + log.Message = secPolicy.Message } - } - if secPolicy.Action == "Allow" { - considerNetworkPosture = true - } + log.Type = "MatchedPolicy" + log.Action = secPolicy.Action + continue + } } } - - if secPolicy.Native && log.Result != "Passed" { - mightBeNative = true - continue - } } fd.SecurityPoliciesLock.RUnlock() + + if log.Result != "Passed" { + if log.Operation == "Process" && allowProcPolicy == "" { + considerFilePosture = true + } else if log.Operation == "File" && allowFilePolicy == "" { + considerFilePosture = true + } else if log.Operation == "Network" && allowNetworkPolicy == "" { + considerNetworkPosture = true + } + } } if log.ContainerID != "" { // container if log.Type == "" { - if mightBeNative && log.Result != "Passed" { - log.PolicyName = "NativePolicy" - - log.Severity = "1" - log.Tags = "" - log.Message = "KubeArmor detected a native policy violation" - - log.Type = "MatchedNativePolicy" - log.Action = "Block" - - return log - } - if log.PolicyEnabled == tp.KubeArmorPolicyEnabled && log.Result != "Passed" { if log.Operation == "Process" && allowProcPolicy != "" { log.PolicyName = allowProcPolicy @@ -960,6 +960,7 @@ func (fd *Feeder) UpdateMatchedPolicy(log tp.Log) tp.Log { } log.Type = "MatchedPolicy" + log.Enforcer = fd.Enforcer log.Action = "Allow" return log @@ -977,6 +978,7 @@ func (fd *Feeder) UpdateMatchedPolicy(log tp.Log) tp.Log { } log.Type = "MatchedPolicy" + log.Enforcer = fd.Enforcer log.Action = "Allow" return log @@ -994,6 +996,7 @@ func (fd *Feeder) UpdateMatchedPolicy(log tp.Log) tp.Log { } log.Type = "MatchedPolicy" + log.Enforcer = fd.Enforcer log.Action = "Allow" return log @@ -1014,6 +1017,7 @@ func (fd *Feeder) UpdateMatchedPolicy(log tp.Log) tp.Log { } log.Type = "MatchedPolicy" + log.Enforcer = "eBPF Monitor" log.Action = "Audit (Allow)" return log @@ -1031,6 +1035,7 @@ func (fd *Feeder) UpdateMatchedPolicy(log tp.Log) tp.Log { } log.Type = "MatchedPolicy" + log.Enforcer = "eBPF Monitor" log.Action = "Audit (Allow)" return log @@ -1048,6 +1053,7 @@ func (fd *Feeder) UpdateMatchedPolicy(log tp.Log) tp.Log { } log.Type = "MatchedPolicy" + log.Enforcer = "eBPF Monitor" log.Action = "Audit (Allow)" return log @@ -1067,19 +1073,19 @@ func (fd *Feeder) UpdateMatchedPolicy(log tp.Log) tp.Log { } if log.Operation == "Process" { - if setLogFields(fd.DefaultPostures[log.NamespaceName].FileAction, log.ProcessVisibilityEnabled, &log, considerFilePosture) { + if setLogFields(&log, fd.DefaultPostures[log.NamespaceName].FileAction, considerFilePosture, log.ProcessVisibilityEnabled, true) { return log } } else if log.Operation == "File" { - if setLogFields(fd.DefaultPostures[log.NamespaceName].FileAction, log.FileVisibilityEnabled, &log, considerFilePosture) { + if setLogFields(&log, fd.DefaultPostures[log.NamespaceName].FileAction, considerFilePosture, log.FileVisibilityEnabled, true) { return log } } else if log.Operation == "Network" { - if setLogFields(fd.DefaultPostures[log.NamespaceName].NetworkAction, log.NetworkVisibilityEnabled, &log, considerNetworkPosture) { + if setLogFields(&log, fd.DefaultPostures[log.NamespaceName].NetworkAction, considerNetworkPosture, log.NetworkVisibilityEnabled, true) { return log } } else if log.Operation == "Capabilities" { - if setLogFields(fd.DefaultPostures[log.NamespaceName].CapabilitiesAction, log.CapabilitiesVisibilityEnabled, &log, false) { + if setLogFields(&log, fd.DefaultPostures[log.NamespaceName].CapabilitiesAction, false, log.CapabilitiesVisibilityEnabled, true) { return log } } @@ -1087,6 +1093,7 @@ func (fd *Feeder) UpdateMatchedPolicy(log tp.Log) tp.Log { } else if log.Type == "MatchedPolicy" { if log.PolicyEnabled == tp.KubeArmorPolicyAudited { if log.Action == "Block" { + log.Enforcer = "eBPF Monitor" log.Action = "Audit (Block)" } } @@ -1095,21 +1102,73 @@ func (fd *Feeder) UpdateMatchedPolicy(log tp.Log) tp.Log { return tp.Log{} } + if log.Enforcer == "" { + if log.Action == "Audit" { + log.Enforcer = "eBPF Monitor" + } else { + log.Enforcer = fd.Enforcer + } + } + return log } } else { // host if log.Type == "" { - if mightBeNative && log.Result != "Passed" { - log.PolicyName = "NativePolicy" + if fd.Node.PolicyEnabled == tp.KubeArmorPolicyEnabled && log.Result != "Passed" { + if log.Operation == "Process" && allowProcPolicy != "" { + log.PolicyName = allowProcPolicy + log.Severity = allowProcPolicySeverity + + if len(allowProcTags) > 0 { + log.Tags = strings.Join(allowProcTags[:], ",") + } + + if len(allowProcMessage) > 0 { + log.Message = allowProcMessage + } + + log.Type = "MatchedHostPolicy" + log.Enforcer = fd.Enforcer + log.Action = "Allow" + + return log + + } else if log.Operation == "File" && allowFilePolicy != "" { + log.PolicyName = allowFilePolicy + log.Severity = allowFilePolicySeverity + + if len(allowFileTags) > 0 { + log.Tags = strings.Join(allowFileTags[:], ",") + } + + if len(allowFileMessage) > 0 { + log.Message = allowFileMessage + } - log.Severity = "1" - log.Tags = "" - log.Message = "KubeArmor detected a native policy violation" + log.Type = "MatchedHostPolicy" + log.Enforcer = fd.Enforcer + log.Action = "Allow" - log.Type = "MatchedNativePolicy" - log.Action = "Block" + return log + + } else if log.Operation == "Network" && allowNetworkPolicy != "" { + log.PolicyName = allowNetworkPolicy + log.Severity = allowNetworkPolicySeverity - return log + if len(allowNetworkTags) > 0 { + log.Tags = strings.Join(allowNetworkTags[:], ",") + } + + if len(allowNetworkMessage) > 0 { + log.Message = allowNetworkMessage + } + + log.Type = "MatchedHostPolicy" + log.Enforcer = fd.Enforcer + log.Action = "Allow" + + return log + } } if fd.Node.PolicyEnabled == tp.KubeArmorPolicyAudited { @@ -1126,6 +1185,7 @@ func (fd *Feeder) UpdateMatchedPolicy(log tp.Log) tp.Log { } log.Type = "MatchedHostPolicy" + log.Enforcer = "eBPF Monitor" log.Action = "Audit (Allow)" return log @@ -1143,6 +1203,7 @@ func (fd *Feeder) UpdateMatchedPolicy(log tp.Log) tp.Log { } log.Type = "MatchedHostPolicy" + log.Enforcer = "eBPF Monitor" log.Action = "Audit (Allow)" return log @@ -1160,29 +1221,45 @@ func (fd *Feeder) UpdateMatchedPolicy(log tp.Log) tp.Log { } log.Type = "MatchedHostPolicy" + log.Enforcer = "eBPF Monitor" log.Action = "Audit (Allow)" return log } } - if fd.Node.ProcessVisibilityEnabled && log.Operation == "Process" { - log.Type = "HostLog" - return log - } else if fd.Node.FileVisibilityEnabled && log.Operation == "File" { - log.Type = "HostLog" - return log - } else if fd.Node.NetworkVisibilityEnabled && log.Operation == "Network" { - log.Type = "HostLog" - return log - } else if fd.Node.CapabilitiesVisibilityEnabled && log.Operation == "Capabilities" { - log.Type = "HostLog" - return log + if log.Result != "Passed" { + if log.Operation == "Process" && allowProcPolicy == "" { + considerFilePosture = true + } else if log.Operation == "File" && allowFilePolicy == "" { + considerFilePosture = true + } else if log.Operation == "Network" && allowNetworkPolicy == "" { + considerNetworkPosture = true + } + } + + if log.Operation == "Process" { + if setLogFields(&log, "block", considerFilePosture, fd.Node.ProcessVisibilityEnabled, false) { + return log + } + } else if log.Operation == "File" { + if setLogFields(&log, "block", considerFilePosture, fd.Node.FileVisibilityEnabled, false) { + return log + } + } else if log.Operation == "Network" { + if setLogFields(&log, "block", considerNetworkPosture, fd.Node.NetworkVisibilityEnabled, false) { + return log + } + } else if log.Operation == "Capabilities" { + if setLogFields(&log, "block", false, fd.Node.CapabilitiesVisibilityEnabled, false) { + return log + } } } else if log.Type == "MatchedPolicy" { if log.PolicyEnabled == tp.KubeArmorPolicyAudited { if log.Action == "Block" { + log.Enforcer = "eBPF Monitor" log.Action = "Audit (Block)" } } @@ -1192,6 +1269,10 @@ func (fd *Feeder) UpdateMatchedPolicy(log tp.Log) tp.Log { } log.Type = "MatchedHostPolicy" + if log.Enforcer == "" { + log.Enforcer = fd.Enforcer + } + return log } } diff --git a/KubeArmor/go.mod b/KubeArmor/go.mod index a59e44fe72..c8b21a55c9 100644 --- a/KubeArmor/go.mod +++ b/KubeArmor/go.mod @@ -23,7 +23,6 @@ require ( github.com/containerd/typeurl v1.0.2 github.com/docker/docker v20.10.7+incompatible github.com/docker/go-connections v0.4.0 // indirect - github.com/golang/protobuf v1.5.2 // indirect github.com/google/gofuzz v1.2.0 // indirect github.com/google/uuid v1.3.0 github.com/gorilla/mux v1.8.0 // indirect @@ -35,10 +34,9 @@ require ( github.com/spf13/viper v1.4.0 go.uber.org/zap v1.18.1 golang.org/x/lint v0.0.0-20210508222113-6edffad5e616 // indirect - golang.org/x/tools v0.1.7 // indirect + golang.org/x/tools v0.1.10 // indirect google.golang.org/appengine v1.6.6 // indirect - google.golang.org/genproto v0.0.0-20210108203827-ffc7fda8c3d7 // indirect - google.golang.org/grpc v1.34.0 + google.golang.org/grpc v1.45.0 k8s.io/api v0.21.2 k8s.io/apimachinery v0.21.2 k8s.io/client-go v0.21.2 diff --git a/KubeArmor/go.sum b/KubeArmor/go.sum index 82d21eb899..dbe01d809d 100644 --- a/KubeArmor/go.sum +++ b/KubeArmor/go.sum @@ -66,6 +66,7 @@ github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuy github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= github.com/alexflint/go-filemutex v0.0.0-20171022225611-72bdc8eae2ae/go.mod h1:CgnQgUtFrFz9mxFNtED3jI5tLDjKlOM+oUF/sTk6ps0= +github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= github.com/asaskevich/govalidator v0.0.0-20190424111038-f61b66f89f4a/go.mod h1:lB+ZfQJz7igIIfQNfa7Ml4HSf2uFQQRzpGGRXenZAgY= github.com/aws/aws-sdk-go v1.15.11/go.mod h1:mFuSZ37Z9YOHbQEwBWztmVzqXrEkub65tZoCYDt7FT0= @@ -98,7 +99,11 @@ github.com/cilium/ebpf v0.2.0/go.mod h1:To2CFviqOWL/M0gIMsvSMlqe7em/l1ALkX1PyjrX github.com/cilium/ebpf v0.4.0/go.mod h1:4tRaxcgiL706VnOzHOdBlY8IEAIdxINsQBcU4xJJXRs= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= -github.com/cncf/udpa/go v0.0.0-20200629203442-efcf912fb354/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= +github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= +github.com/cncf/udpa/go v0.0.0-20210930031921-04548b0d99d4/go.mod h1:6pvJx4me5XPnfI9Z40ddWsdw2W/uZgQLFXToKeRcDiI= +github.com/cncf/xds/go v0.0.0-20210805033703-aa0b78936158/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= +github.com/cncf/xds/go v0.0.0-20210922020428-25de7278fc84/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= +github.com/cncf/xds/go v0.0.0-20211011173535-cb28da3451f1/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= github.com/cockroachdb/datadriven v0.0.0-20190809214429-80d97fb3cbaa/go.mod h1:zn76sxSg3SzpJ0PPJaLDCu+Bu0Lg3sKTORVIj19EIF8= github.com/containerd/aufs v0.0.0-20200908144142-dab0cbea06f4/go.mod h1:nukgQABAEopAHvB6j7cnP5zJ+/3aVcE7hCYqvIwAHyE= github.com/containerd/aufs v0.0.0-20201003224125-76a6863f2989/go.mod h1:AkGGQs9NM2vtYHaUen+NljV0/baGCAPELGm2q9ZXpWU= @@ -242,7 +247,8 @@ github.com/emicklei/go-restful v2.9.5+incompatible/go.mod h1:otzb+WCGbkyDHkqmQmT github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= -github.com/envoyproxy/go-control-plane v0.9.7/go.mod h1:cwu0lG7PUMfa9snN8LXBig5ynNVH9qI8YYLbd1fK2po= +github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= +github.com/envoyproxy/go-control-plane v0.9.10-0.20210907150352-cf90f659a021/go.mod h1:AFq3mo9L8Lqqiid3OhADV3RfLJnjiw63cSpi+fDTRC0= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= github.com/evanphx/json-patch v4.9.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk= github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= @@ -363,6 +369,7 @@ github.com/grpc-ecosystem/go-grpc-middleware v1.0.1-0.20190118093823-f849b5445de github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= github.com/grpc-ecosystem/grpc-gateway v1.9.0/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= github.com/grpc-ecosystem/grpc-gateway v1.9.5/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= +github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= github.com/hashicorp/errwrap v0.0.0-20141028054710-7554cd9344ce/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= github.com/hashicorp/go-multierror v0.0.0-20161216184304-ed905158d874/go.mod h1:JMRHfdO9jKNzS/+BTlxCjKNQHg/jZAft8U7LloJvN7I= @@ -534,6 +541,7 @@ github.com/prometheus/procfs v0.6.0 h1:mxy4L2jP6qMonqmq+aTtOx1ifVWUgG/TAmntgbh3x github.com/prometheus/procfs v0.6.0/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA= github.com/prometheus/tsdb v0.7.1/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU= github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg= +github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/safchain/ethtool v0.0.0-20190326074333-42ed695e3de8/go.mod h1:Z0q5wiBQGYcxhMZ6gUqHn6pYNLypFAvaL3UvgZLR0U4= @@ -609,7 +617,7 @@ github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/yuin/goldmark v1.4.0/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= +github.com/yuin/goldmark v1.4.1/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= github.com/yvasiyarov/go-metrics v0.0.0-20140926110328-57bccd1ccd43/go.mod h1:aX5oPXxHm3bOH+xeAttToC8pqch2ScQN/JoXYupl6xs= github.com/yvasiyarov/gorelic v0.0.0-20141212073537-a9bba5b9ab50/go.mod h1:NUSPSUX/bi6SeDMUh6brw0nXpxHnc96TguQh0+r/ssA= github.com/yvasiyarov/newrelic_platform_go v0.0.0-20140908184405-b21fdbd4370f/go.mod h1:GlGEuHIJweS1mbCqG+7vt2nvWLzLLnRHbXz5JKd/Qbg= @@ -622,6 +630,7 @@ go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= go.opencensus.io v0.22.3/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= +go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqeYNgFYFoEGnI= go.uber.org/atomic v1.3.2/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= go.uber.org/atomic v1.7.0 h1:ADUqmZGgLDDfbSL9ZmPxKTybcoEYHgpYfELNoN+7hsw= @@ -648,6 +657,7 @@ golang.org/x/crypto v0.0.0-20200728195943-123391ffb6de/go.mod h1:LzIPMQfyMNhhGPh golang.org/x/crypto v0.0.0-20201002170205-7f63de1d35b0/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20210220033148-5ea612d1eb83/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I= golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= @@ -680,8 +690,8 @@ golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzB golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.4.2 h1:Gz96sIWK3OalVv/I/qNygP42zyoKp3xptRVCWRFEBvo= -golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3 h1:kQgndtyPBW/JIYERgdxfwMYh3AVStj88WQTlNDi2a+o= +golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3/go.mod h1:3p9vT2HGsQu2K1YbXdKPJLVgG5VJdoTa1poYQBtP1AY= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -711,14 +721,15 @@ golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLL golang.org/x/net v0.0.0-20200301022130-244492dfa37a/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= golang.org/x/net v0.0.0-20200707034311-ab3426394381/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= +golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20201006153459-a7d1128ccaa0/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20201224014010-6772e930b67b/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210224082022-3d97a244fca7/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= -golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d h1:20cMwl2fHAzkJMEA+8J4JgqBQcQGzbisXo31MIeenXI= -golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f h1:OfiFi4JbukWwe3lzw+xunroH1mnC1e2Gy5cxNJApiSY= +golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= @@ -797,8 +808,9 @@ golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20210324051608-47abb6519492/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210426230700-d19ff857e887/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e h1:WUoyKPm6nCo1BnNUvPGnFG3T5DUVem42yDJZZ4CNxMA= -golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211019181941-9d821ace8654 h1:id054HUawV2/6IGm2IV8KZQjqtwAOo2CYlOToYqa0d0= +golang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210220032956-6a3ed077a48d h1:SZxvLBoTP5yHO3Frd4z4vrF+DBX9vMVanchswa69toE= @@ -809,8 +821,9 @@ golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3 golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.6 h1:aRYxNxv6iGQlyVaZmk6ZgYEDa+Jg18DxebPSrd6bg1M= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= @@ -856,8 +869,8 @@ golang.org/x/tools v0.0.0-20200224181240-023911ca70b2/go.mod h1:TB2adYChydJhpapK golang.org/x/tools v0.0.0-20200304193943-95d2e580d8eb/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw= golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.1.7 h1:6j8CgantCy3yc8JGBqkDLMKWqZ0RDU2g1HVgacojGWQ= -golang.org/x/tools v0.1.7/go.mod h1:LGqMHiF4EqQNHR1JncWGqT5BVaXmza+X+BDGol+dOxo= +golang.org/x/tools v0.1.10 h1:QjFRCZxdOhBJ/UNgnBZLbNV13DlbnK0quyivTnXJM20= +golang.org/x/tools v0.1.10/go.mod h1:Uh6Zz+xoGYZom868N8YTex3t7RhtHDBrE8Gzo9bV56E= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -902,10 +915,10 @@ google.golang.org/genproto v0.0.0-20200204135345-fa8e72b47b90/go.mod h1:GmwEX6Z4 google.golang.org/genproto v0.0.0-20200212174721-66ed5ce911ce/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= google.golang.org/genproto v0.0.0-20200224152610-e50cd9704f63/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= google.golang.org/genproto v0.0.0-20200305110556-506484158171/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200513103714-09dca8ec2884/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= +google.golang.org/genproto v0.0.0-20201110150050-8816d57aaa9a h1:pOwg4OoaRYScjmR4LlLgdtnyoHYTSAVhhqe5uPdpII8= google.golang.org/genproto v0.0.0-20201110150050-8816d57aaa9a/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20210108203827-ffc7fda8c3d7 h1:n7yjMkxUgbEahYENvAGVlxMUW8TF/KEavLez31znfDw= -google.golang.org/genproto v0.0.0-20210108203827-ffc7fda8c3d7/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/grpc v0.0.0-20160317175043-d3ddb4469d5a/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= @@ -919,9 +932,11 @@ google.golang.org/grpc v1.26.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8 google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= google.golang.org/grpc v1.27.1/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= google.golang.org/grpc v1.30.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= +google.golang.org/grpc v1.33.1/go.mod h1:fr5YgcSWrqhRRxogOsw7RzIpsmvOZ6IcH4kBYTpR3n0= google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc= -google.golang.org/grpc v1.34.0 h1:raiipEjMOIC/TO2AvyTxP25XFdLxNIBwzDh3FM3XztI= -google.golang.org/grpc v1.34.0/go.mod h1:WotjhfgOW/POjDeRt8vscBtXq+2VjORFy659qA51WJ8= +google.golang.org/grpc v1.36.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= +google.golang.org/grpc v1.45.0 h1:NEpgUqV3Z+ZjkqMsxMg11IaDrXY4RY6CQukSGK0uI1M= +google.golang.org/grpc v1.45.0/go.mod h1:lN7owxKUQEqMfSyQikvvk5tf/6zMPsrK+ONuO11+0rQ= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= @@ -934,8 +949,8 @@ google.golang.org/protobuf v1.24.0/go.mod h1:r/3tXBNzIEhYS9I1OUVjXDlt8tc493IdKGj google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= -google.golang.org/protobuf v1.27.1 h1:SnqbnDw1V7RiZcXPx5MEeqPv2s79L9i7BJUlG/+RurQ= -google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= +google.golang.org/protobuf v1.28.0 h1:w43yiav+6bVFTBQFZX0r7ipe9JQ1QsbMgHwbBziscLw= +google.golang.org/protobuf v1.28.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= gopkg.in/airbrake/gobrake.v2 v2.0.9/go.mod h1:/h5ZAUhDkGaJfjzjKLSjv6zCL6O0LLBxU4K+aSYdM/U= gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= @@ -959,6 +974,7 @@ gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWD gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74= gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.5/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/KubeArmor/monitor/logUpdate.go b/KubeArmor/monitor/logUpdate.go index f288646468..486bcbd68c 100644 --- a/KubeArmor/monitor/logUpdate.go +++ b/KubeArmor/monitor/logUpdate.go @@ -4,9 +4,9 @@ package monitor import ( - "bytes" "fmt" "strconv" + "strings" kl "github.com/kubearmor/KubeArmor/KubeArmor/common" tp "github.com/kubearmor/KubeArmor/KubeArmor/types" @@ -68,15 +68,7 @@ func (mon *SystemMonitor) BuildLogBase(msg ContextCombined) tp.Log { log.PID = int32(msg.ContextSys.PID) log.UID = int32(msg.ContextSys.UID) - if msg.ContextSys.EventID == SysExecve || msg.ContextSys.EventID == SysExecveAt { - log.Source = mon.GetCommand(msg.ContainerID, msg.ContextSys.HostPPID) - } else { // otherwise - log.Source = mon.GetCommand(msg.ContainerID, msg.ContextSys.HostPID) - } - - if log.Source == "" { - log.Source = string(msg.ContextSys.Comm[:bytes.IndexByte(msg.ContextSys.Comm[:], 0)]) - } + log.Source = mon.GetCommand(msg.ContainerID, msg.ContextSys.HostPID) log.ParentProcessName = mon.GetExecPath(msg.ContainerID, msg.ContextSys.HostPPID) log.ProcessName = mon.GetExecPath(msg.ContainerID, msg.ContextSys.HostPID) @@ -86,13 +78,35 @@ func (mon *SystemMonitor) BuildLogBase(msg ContextCombined) tp.Log { // UpdateLogBase Function (SYS_EXECVE, SYS_EXECVEAT) func (mon *SystemMonitor) UpdateLogBase(eventID int32, log tp.Log) tp.Log { - source := mon.GetCommand(log.ContainerID, uint32(log.HostPPID)) - if source != "" { - log.Source = source + if log.ParentProcessName == "" || strings.HasPrefix(log.ParentProcessName, "/") { + parentProcessName := mon.GetExecPath(log.ContainerID, uint32(log.HostPPID)) + if parentProcessName != "" { + log.ParentProcessName = parentProcessName + } + } + + if log.ProcessName == "" || strings.HasPrefix(log.ProcessName, "/") { + processName := mon.GetExecPath(log.ContainerID, uint32(log.HostPID)) + if processName != "" { + log.ProcessName = processName + } + } + + if log.Source == "" || strings.HasPrefix(log.Source, "/") { + source := mon.GetCommand(log.ContainerID, uint32(log.HostPID)) + if source != "" { + log.Source = source + } } - log.ParentProcessName = mon.GetExecPath(log.ContainerID, uint32(log.HostPPID)) - log.ProcessName = mon.GetExecPath(log.ContainerID, uint32(log.HostPID)) + if !strings.HasPrefix(log.Resource, "/") { + resource := strings.Split(log.Resource, " ") + if len(resource) == 1 { + log.Resource = log.Source + } else { + log.Resource = log.Source + " " + strings.Join(resource[1:], " ") + } + } return log } diff --git a/KubeArmor/monitor/processTree.go b/KubeArmor/monitor/processTree.go index 38afe39cb9..7932c8d295 100644 --- a/KubeArmor/monitor/processTree.go +++ b/KubeArmor/monitor/processTree.go @@ -6,6 +6,7 @@ package monitor import ( "os" "strconv" + "strings" "time" tp "github.com/kubearmor/KubeArmor/KubeArmor/types" @@ -63,7 +64,7 @@ func (mon *SystemMonitor) DeleteContainerIDFromNsMap(containerID string) { // ================== // // BuildPidNode Function -func (mon *SystemMonitor) BuildPidNode(ctx SyscallContext, execPath string, args []string) tp.PidNode { +func (mon *SystemMonitor) BuildPidNode(containerID string, ctx SyscallContext, execPath string, args []string) tp.PidNode { node := tp.PidNode{} node.HostPPID = ctx.HostPPID @@ -73,7 +74,10 @@ func (mon *SystemMonitor) BuildPidNode(ctx SyscallContext, execPath string, args node.PID = ctx.PID node.UID = ctx.UID + node.ParentExecPath = mon.GetExecPath(containerID, ctx.HostPPID) node.ExecPath = execPath + + node.Source = execPath node.Args = "" for idx, arg := range args { @@ -110,6 +114,10 @@ func (mon *SystemMonitor) AddActivePid(containerID string, node tp.PidNode) { // UpdateExecPath Function func (mon *SystemMonitor) UpdateExecPath(containerID string, hostPid uint32, execPath string) { + if execPath == "/" || !strings.HasPrefix(execPath, "/") { + return + } + ActiveHostPidMap := *(mon.ActiveHostPidMap) ActivePidMapLock := *(mon.ActivePidMapLock) @@ -117,10 +125,18 @@ func (mon *SystemMonitor) UpdateExecPath(containerID string, hostPid uint32, exe defer ActivePidMapLock.Unlock() if pidMap, ok := ActiveHostPidMap[containerID]; ok { - if node, ok := pidMap[hostPid]; ok { - newNode := node - newNode.ExecPath = execPath - ActiveHostPidMap[containerID][hostPid] = newNode + if node, ok := pidMap[hostPid]; ok && node.ExecPath != execPath { + originalPath := strings.Replace(node.Source, "./", "", 1) + if strings.Contains(execPath, originalPath) { + newNode := node + newNode.Source = execPath // full path + newNode.ExecPath = execPath // full path + ActiveHostPidMap[containerID][hostPid] = newNode + } else { + newNode := node + newNode.ExecPath = execPath // full path + ActiveHostPidMap[containerID][hostPid] = newNode + } } } } @@ -130,25 +146,19 @@ func (mon *SystemMonitor) GetExecPath(containerID string, hostPid uint32) string ActiveHostPidMap := *(mon.ActiveHostPidMap) ActivePidMapLock := *(mon.ActivePidMapLock) - ActivePidMapLock.RLock() - defer ActivePidMapLock.RUnlock() + ActivePidMapLock.Lock() + defer ActivePidMapLock.Unlock() - // container side if pidMap, ok := ActiveHostPidMap[containerID]; ok { if node, ok := pidMap[hostPid]; ok { - return node.ExecPath - } - } - - // host side or between host and container - if pidMap, ok := ActiveHostPidMap[""]; ok { - if node, ok := pidMap[hostPid]; ok { - return node.ExecPath + if node.ExecPath != "/" && strings.HasPrefix(node.ExecPath, "/") { + return node.ExecPath + } } } // just in case that it couldn't still get the full path - if data, err := os.Readlink("/proc/" + strconv.FormatUint(uint64(hostPid), 10) + "/exe"); err == nil && data != "" { + if data, err := os.Readlink("/proc/" + strconv.FormatUint(uint64(hostPid), 10) + "/exe"); err == nil && data != "" && data != "/" { return data } @@ -160,34 +170,18 @@ func (mon *SystemMonitor) GetCommand(containerID string, hostPid uint32) string ActiveHostPidMap := *(mon.ActiveHostPidMap) ActivePidMapLock := *(mon.ActivePidMapLock) - ActivePidMapLock.RLock() - defer ActivePidMapLock.RUnlock() - - // container side - if pidMap, ok := ActiveHostPidMap[containerID]; ok { - if node, ok := pidMap[hostPid]; ok { - if node.Args != "" { - return node.ExecPath + " " + node.Args - } - return node.ExecPath - } - } + ActivePidMapLock.Lock() + defer ActivePidMapLock.Unlock() - // host side or between host and container if pidMap, ok := ActiveHostPidMap[containerID]; ok { if node, ok := pidMap[hostPid]; ok { if node.Args != "" { - return node.ExecPath + " " + node.Args + return node.Source + " " + node.Args } - return node.ExecPath + return node.Source } } - // just in case that it couldn't still get the full path - if data, err := os.Readlink("/proc/" + strconv.FormatUint(uint64(hostPid), 10) + "/exe"); err == nil && data != "" { - return data - } - return "" } @@ -223,10 +217,6 @@ func (mon *SystemMonitor) CleanUpExitedHostPids() { for _, pidMap := range ActiveHostPidMap { for pid, pidNode := range pidMap { if pidNode.Exited { - if _, err := os.Readlink("/proc/" + strconv.FormatUint(uint64(pidNode.HostPID), 10) + "/exe"); err == nil { - continue - } - if now.After(pidNode.ExitedTime.Add(time.Second * 5)) { delete(pidMap, pid) } diff --git a/KubeArmor/monitor/syscallParser.go b/KubeArmor/monitor/syscallParser.go index f315df0f25..a76a8ea7bf 100644 --- a/KubeArmor/monitor/syscallParser.go +++ b/KubeArmor/monitor/syscallParser.go @@ -281,59 +281,59 @@ func getExecFlags(flags uint32) string { return strings.Join(f, "|") } +var socketDomains = map[uint32]string{ + 0: "AF_UNSPEC", + 1: "AF_UNIX", + 2: "AF_INET", + 3: "AF_AX25", + 4: "AF_IPX", + 5: "AF_APPLETALK", + 6: "AF_NETROM", + 7: "AF_BRIDGE", + 8: "AF_ATMPVC", + 9: "AF_X25", + 10: "AF_INET6", + 11: "AF_ROSE", + 12: "AF_DECnet", + 13: "AF_NETBEUI", + 14: "AF_SECURITY", + 15: "AF_KEY", + 16: "AF_NETLINK", + 17: "AF_PACKET", + 18: "AF_ASH", + 19: "AF_ECONET", + 20: "AF_ATMSVC", + 21: "AF_RDS", + 22: "AF_SNA", + 23: "AF_IRDA", + 24: "AF_PPPOX", + 25: "AF_WANPIPE", + 26: "AF_LLC", + 27: "AF_IB", + 28: "AF_MPLS", + 29: "AF_CAN", + 30: "AF_TIPC", + 31: "AF_BLUETOOTH", + 32: "AF_IUCV", + 33: "AF_RXRPC", + 34: "AF_ISDN", + 35: "AF_PHONET", + 36: "AF_IEEE802154", + 37: "AF_CAIF", + 38: "AF_ALG", + 39: "AF_NFC", + 40: "AF_VSOCK", + 41: "AF_KCM", + 42: "AF_QIPCRTR", + 43: "AF_SMC", + 44: "AF_XDP", +} + // getSocketDomain Function func getSocketDomain(sd uint32) string { // readSocketDomain prints the `domain` bitmask argument of the `socket` syscall // http://man7.org/linux/man-pages/man2/socket.2.html - var socketDomains = map[uint32]string{ - 0: "AF_UNSPEC", - 1: "AF_UNIX", - 2: "AF_INET", - 3: "AF_AX25", - 4: "AF_IPX", - 5: "AF_APPLETALK", - 6: "AF_NETROM", - 7: "AF_BRIDGE", - 8: "AF_ATMPVC", - 9: "AF_X25", - 10: "AF_INET6", - 11: "AF_ROSE", - 12: "AF_DECnet", - 13: "AF_NETBEUI", - 14: "AF_SECURITY", - 15: "AF_KEY", - 16: "AF_NETLINK", - 17: "AF_PACKET", - 18: "AF_ASH", - 19: "AF_ECONET", - 20: "AF_ATMSVC", - 21: "AF_RDS", - 22: "AF_SNA", - 23: "AF_IRDA", - 24: "AF_PPPOX", - 25: "AF_WANPIPE", - 26: "AF_LLC", - 27: "AF_IB", - 28: "AF_MPLS", - 29: "AF_CAN", - 30: "AF_TIPC", - 31: "AF_BLUETOOTH", - 32: "AF_IUCV", - 33: "AF_RXRPC", - 34: "AF_ISDN", - 35: "AF_PHONET", - 36: "AF_IEEE802154", - 37: "AF_CAIF", - 38: "AF_ALG", - 39: "AF_NFC", - 40: "AF_VSOCK", - 41: "AF_KCM", - 42: "AF_QIPCRTR", - 43: "AF_SMC", - 44: "AF_XDP", - } - var res string if sdName, ok := socketDomains[sd]; ok { @@ -345,22 +345,22 @@ func getSocketDomain(sd uint32) string { return res } +var socketTypes = map[uint32]string{ + 1: "SOCK_STREAM", + 2: "SOCK_DGRAM", + 3: "SOCK_RAW", + 4: "SOCK_RDM", + 5: "SOCK_SEQPACKET", + 6: "SOCK_DCCP", + 10: "SOCK_PACKET", +} + // getSocketType Function func getSocketType(st uint32) string { // readSocketType prints the `type` bitmask argument of the `socket` syscall // http://man7.org/linux/man-pages/man2/socket.2.html // https://elixir.bootlin.com/linux/v5.5.3/source/arch/mips/include/asm/socket.h - var socketTypes = map[uint32]string{ - 1: "SOCK_STREAM", - 2: "SOCK_DGRAM", - 3: "SOCK_RAW", - 4: "SOCK_RDM", - 5: "SOCK_SEQPACKET", - 6: "SOCK_DCCP", - 10: "SOCK_PACKET", - } - var f []string if stName, ok := socketTypes[st&0xf]; ok { @@ -378,52 +378,52 @@ func getSocketType(st uint32) string { return strings.Join(f, "|") } +var capabilities = map[int32]string{ + 0: "CAP_CHOWN", + 1: "CAP_DAC_OVERRIDE", + 2: "CAP_DAC_READ_SEARCH", + 3: "CAP_FOWNER", + 4: "CAP_FSETID", + 5: "CAP_KILL", + 6: "CAP_SETGID", + 7: "CAP_SETUID", + 8: "CAP_SETPCAP", + 9: "CAP_LINUX_IMMUTABLE", + 10: "CAP_NET_BIND_SERVICE", + 11: "CAP_NET_BROADCAST", + 12: "CAP_NET_ADMIN", + 13: "CAP_NET_RAW", + 14: "CAP_IPC_LOCK", + 15: "CAP_IPC_OWNER", + 16: "CAP_SYS_MODULE", + 17: "CAP_SYS_RAWIO", + 18: "CAP_SYS_CHROOT", + 19: "CAP_SYS_PTRACE", + 20: "CAP_SYS_PACCT", + 21: "CAP_SYS_ADMIN", + 22: "CAP_SYS_BOOT", + 23: "CAP_SYS_NICE", + 24: "CAP_SYS_RESOURCE", + 25: "CAP_SYS_TIME", + 26: "CAP_SYS_TTY_CONFIG", + 27: "CAP_MKNOD", + 28: "CAP_LEASE", + 29: "CAP_AUDIT_WRITE", + 30: "CAP_AUDIT_CONTROL", + 31: "CAP_SETFCAP", + 32: "CAP_MAC_OVERRIDE", + 33: "CAP_MAC_ADMIN", + 34: "CAP_SYSLOG", + 35: "CAP_WAKE_ALARM", + 36: "CAP_BLOCK_SUSPEND", + 37: "CAP_AUDIT_READ", +} + // getCapabilityName Function func getCapabilityName(cap int32) string { // getCapabilityName prints the `capability` bitmask argument of the `cap_capable` function // include/uapi/linux/capability.h - var capabilities = map[int32]string{ - 0: "CAP_CHOWN", - 1: "CAP_DAC_OVERRIDE", - 2: "CAP_DAC_READ_SEARCH", - 3: "CAP_FOWNER", - 4: "CAP_FSETID", - 5: "CAP_KILL", - 6: "CAP_SETGID", - 7: "CAP_SETUID", - 8: "CAP_SETPCAP", - 9: "CAP_LINUX_IMMUTABLE", - 10: "CAP_NET_BIND_SERVICE", - 11: "CAP_NET_BROADCAST", - 12: "CAP_NET_ADMIN", - 13: "CAP_NET_RAW", - 14: "CAP_IPC_LOCK", - 15: "CAP_IPC_OWNER", - 16: "CAP_SYS_MODULE", - 17: "CAP_SYS_RAWIO", - 18: "CAP_SYS_CHROOT", - 19: "CAP_SYS_PTRACE", - 20: "CAP_SYS_PACCT", - 21: "CAP_SYS_ADMIN", - 22: "CAP_SYS_BOOT", - 23: "CAP_SYS_NICE", - 24: "CAP_SYS_RESOURCE", - 25: "CAP_SYS_TIME", - 26: "CAP_SYS_TTY_CONFIG", - 27: "CAP_MKNOD", - 28: "CAP_LEASE", - 29: "CAP_AUDIT_WRITE", - 30: "CAP_AUDIT_CONTROL", - 31: "CAP_SETFCAP", - 32: "CAP_MAC_OVERRIDE", - 33: "CAP_MAC_ADMIN", - 34: "CAP_SYSLOG", - 35: "CAP_WAKE_ALARM", - 36: "CAP_BLOCK_SUSPEND", - 37: "CAP_AUDIT_READ", - } - var res string if capName, ok := capabilities[cap]; ok { @@ -435,349 +435,349 @@ func getCapabilityName(cap int32) string { return res } +var syscalls = map[int32]string{ + 0: "SYS_READ", + 1: "SYS_WRITE", + 2: "SYS_OPEN", + 3: "SYS_CLOSE", + 4: "SYS_STAT", + 5: "SYS_FSTAT", + 6: "SYS_LSTAT", + 7: "SYS_POLL", + 8: "SYS_LSEEK", + 9: "SYS_MMAP", + 10: "SYS_MPROTECT", + 11: "SYS_MUNMAP", + 12: "SYS_BRK", + 13: "SYS_RT_SIGACTION", + 14: "SYS_RT_SIGPROCMASK", + 15: "SYS_RT_SIGRETURN", + 16: "SYS_IOCTL", + 17: "SYS_PREAD64", + 18: "SYS_PWRITE64", + 19: "SYS_READV", + 20: "SYS_WRITEV", + 21: "SYS_ACCESS", + 22: "SYS_PIPE", + 23: "SYS_SELECT", + 24: "SYS_SCHED_YIELD", + 25: "SYS_MREMAP", + 26: "SYS_MSYNC", + 27: "SYS_MINCORE", + 28: "SYS_MADVISE", + 29: "SYS_SHMGET", + 30: "SYS_SHMAT", + 31: "SYS_SHMCTL", + 32: "SYS_DUP", + 33: "SYS_DUP2", + 34: "SYS_PAUSE", + 35: "SYS_NANOSLEEP", + 36: "SYS_GETITIMER", + 37: "SYS_ALARM", + 38: "SYS_SETITIMER", + 39: "SYS_GETPID", + 40: "SYS_SENDFILE", + 41: "SYS_SOCKET", + 42: "SYS_CONNECT", + 43: "SYS_ACCEPT", + 44: "SYS_SENDTO", + 45: "SYS_RECVFROM", + 46: "SYS_SENDMSG", + 47: "SYS_RECVMSG", + 48: "SYS_SHUTDOWN", + 49: "SYS_BIND", + 50: "SYS_LISTEN", + 51: "SYS_GETSOCKNAME", + 52: "SYS_GETPEERNAME", + 53: "SYS_SOCKETPAIR", + 54: "SYS_SETSOCKOPT", + 55: "SYS_GETSOCKOPT", + 56: "SYS_CLONE", + 57: "SYS_FORK", + 58: "SYS_VFORK", + 59: "SYS_EXECVE", + 60: "SYS_EXIT", + 61: "SYS_WAIT4", + 62: "SYS_KILL", + 63: "SYS_UNAME", + 64: "SYS_SEMGET", + 65: "SYS_SEMOP", + 66: "SYS_SEMCTL", + 67: "SYS_SHMDT", + 68: "SYS_MSGGET", + 69: "SYS_MSGSND", + 70: "SYS_MSGRCV", + 71: "SYS_MSGCTL", + 72: "SYS_FCNTL", + 73: "SYS_FLOCK", + 74: "SYS_FSYNC", + 75: "SYS_FDATASYNC", + 76: "SYS_TRUNCATE", + 77: "SYS_FTRUNCATE", + 78: "SYS_GETDENTS", + 79: "SYS_GETCWD", + 80: "SYS_CHDIR", + 81: "SYS_FCHDIR", + 82: "SYS_RENAME", + 83: "SYS_MKDIR", + 84: "SYS_RMDIR", + 85: "SYS_CREAT", + 86: "SYS_LINK", + 87: "SYS_UNLINK", + 88: "SYS_SYMLINK", + 89: "SYS_READLINK", + 90: "SYS_CHMOD", + 91: "SYS_FCHMOD", + 92: "SYS_CHOWN", + 93: "SYS_FCHOWN", + 94: "SYS_LCHOWN", + 95: "SYS_UMASK", + 96: "SYS_GETTIMEOFDAY", + 97: "SYS_GETRLIMIT", + 98: "SYS_GETRUSAGE", + 99: "SYS_SYSINFO", + 100: "SYS_TIMES", + 101: "SYS_PTRACE", + 102: "SYS_GETUID", + 103: "SYS_SYSLOG", + 104: "SYS_GETGID", + 105: "SYS_SETUID", + 106: "SYS_SETGID", + 107: "SYS_GETEUID", + 108: "SYS_GETEGID", + 109: "SYS_SETPGID", + 110: "SYS_GETPPID", + 111: "SYS_GETPGRP", + 112: "SYS_SETSID", + 113: "SYS_SETREUID", + 114: "SYS_SETREGID", + 115: "SYS_GETGROUPS", + 116: "SYS_SETGROUPS", + 117: "SYS_SETRESUID", + 118: "SYS_GETRESUID", + 119: "SYS_SETRESGID", + 120: "SYS_GETRESGID", + 121: "SYS_GETPGID", + 122: "SYS_SETFSUID", + 123: "SYS_SETFSGID", + 124: "SYS_GETSID", + 125: "SYS_CAPGET", + 126: "SYS_CAPSET", + 127: "SYS_RT_SIGPENDING", + 128: "SYS_RT_SIGTIMEDWAIT", + 129: "SYS_RT_SIGQUEUEINFO", + 130: "SYS_RT_SIGSUSPEND", + 131: "SYS_SIGALTSTACK", + 132: "SYS_UTIME", + 133: "SYS_MKNOD", + 134: "SYS_USELIB", + 135: "SYS_PERSONALITY", + 136: "SYS_USTAT", + 137: "SYS_STATFS", + 138: "SYS_FSTATFS", + 139: "SYS_SYSFS", + 140: "SYS_GETPRIORITY", + 141: "SYS_SETPRIORITY", + 142: "SYS_SCHED_SETPARAM", + 143: "SYS_SCHED_GETPARAM", + 144: "SYS_SCHED_SETSCHEDULER", + 145: "SYS_SCHED_GETSCHEDULER", + 146: "SYS_SCHED_GET_PRIORITY_MAX", + 147: "SYS_SCHED_GET_PRIORITY_MIN", + 148: "SYS_SCHED_RR_GET_INTERVAL", + 149: "SYS_MLOCK", + 150: "SYS_MUNLOCK", + 151: "SYS_MLOCKALL", + 152: "SYS_MUNLOCKALL", + 153: "SYS_VHANGUP", + 154: "SYS_MODIFY_LDT", + 155: "SYS_PIVOT_ROOT", + 156: "SYS__SYSCTL", + 157: "SYS_PRCTL", + 158: "SYS_ARCH_PRCTL", + 159: "SYS_ADJTIMEX", + 160: "SYS_SETRLIMIT", + 161: "SYS_CHROOT", + 162: "SYS_SYNC", + 163: "SYS_ACCT", + 164: "SYS_SETTIMEOFDAY", + 165: "SYS_MOUNT", + 166: "SYS_UMOUNT2", + 167: "SYS_SWAPON", + 168: "SYS_SWAPOFF", + 169: "SYS_REBOOT", + 170: "SYS_SETHOSTNAME", + 171: "SYS_SETDOMAINNAME", + 172: "SYS_IOPL", + 173: "SYS_IOPERM", + 174: "SYS_CREATE_MODULE", + 175: "SYS_INIT_MODULE", + 176: "SYS_DELETE_MODULE", + 177: "SYS_GET_KERNEL_SYMS", + 178: "SYS_QUERY_MODULE", + 179: "SYS_QUOTACTL", + 180: "SYS_NFSSERVCTL", + 181: "SYS_GETPMSG", + 182: "SYS_PUTPMSG", + 183: "SYS_AFS_SYSCALL", + 184: "SYS_TUXCALL", + 185: "SYS_SECURITY", + 186: "SYS_GETTID", + 187: "SYS_READAHEAD", + 188: "SYS_SETXATTR", + 189: "SYS_LSETXATTR", + 190: "SYS_FSETXATTR", + 191: "SYS_GETXATTR", + 192: "SYS_LGETXATTR", + 193: "SYS_FGETXATTR", + 194: "SYS_LISTXATTR", + 195: "SYS_LLISTXATTR", + 196: "SYS_FLISTXATTR", + 197: "SYS_REMOVEXATTR", + 198: "SYS_LREMOVEXATTR", + 199: "SYS_FREMOVEXATTR", + 200: "SYS_TKILL", + 201: "SYS_TIME", + 202: "SYS_FUTEX", + 203: "SYS_SCHED_SETAFFINITY", + 204: "SYS_SCHED_GETAFFINITY", + 205: "SYS_SET_THREAD_AREA", + 206: "SYS_IO_SETUP", + 207: "SYS_IO_DESTROY", + 208: "SYS_IO_GETEVENTS", + 209: "SYS_IO_SUBMIT", + 210: "SYS_IO_CANCEL", + 211: "SYS_GET_THREAD_AREA", + 212: "SYS_LOOKUP_DCOOKIE", + 213: "SYS_EPOLL_CREATE", + 214: "SYS_EPOLL_CTL_OLD", + 215: "SYS_EPOLL_WAIT_OLD", + 216: "SYS_REMAP_FILE_PAGES", + 217: "SYS_GETDENTS64", + 218: "SYS_SET_TID_ADDRESS", + 219: "SYS_RESTART_SYSCALL", + 220: "SYS_SEMTIMEDOP", + 221: "SYS_FADVISE64", + 222: "SYS_TIMER_CREATE", + 223: "SYS_TIMER_SETTIME", + 224: "SYS_TIMER_GETTIME", + 225: "SYS_TIMER_GETOVERRUN", + 226: "SYS_TIMER_DELETE", + 227: "SYS_CLOCK_SETTIME", + 228: "SYS_CLOCK_GETTIME", + 229: "SYS_CLOCK_GETRES", + 230: "SYS_CLOCK_NANOSLEEP", + 231: "SYS_EXIT_GROUP", + 232: "SYS_EPOLL_WAIT", + 233: "SYS_EPOLL_CTL", + 234: "SYS_TGKILL", + 235: "SYS_UTIMES", + 236: "SYS_VSERVER", + 237: "SYS_MBIND", + 238: "SYS_SET_MEMPOLICY", + 239: "SYS_GET_MEMPOLICY", + 240: "SYS_MQ_OPEN", + 241: "SYS_MQ_UNLINK", + 242: "SYS_MQ_TIMEDSEND", + 243: "SYS_MQ_TIMEDRECEIVE", + 244: "SYS_MQ_NOTIFY", + 245: "SYS_MQ_GETSETATTR", + 246: "SYS_KEXEC_LOAD", + 247: "SYS_WAITID", + 248: "SYS_ADD_KEY", + 249: "SYS_REQUEST_KEY", + 250: "SYS_KEYCTL", + 251: "SYS_IOPRIO_SET", + 252: "SYS_IOPRIO_GET", + 253: "SYS_INOTIFY_INIT", + 254: "SYS_INOTIFY_ADD_WATCH", + 255: "SYS_INOTIFY_RM_WATCH", + 256: "SYS_MIGRATE_PAGES", + 257: "SYS_OPENAT", + 258: "SYS_MKDIRAT", + 259: "SYS_MKNODAT", + 260: "SYS_FCHOWNAT", + 261: "SYS_FUTIMESAT", + 262: "SYS_NEWFSTATAT", + 263: "SYS_UNLINKAT", + 264: "SYS_RENAMEAT", + 265: "SYS_LINKAT", + 266: "SYS_SYMLINKAT", + 267: "SYS_READLINKAT", + 268: "SYS_FCHMODAT", + 269: "SYS_FACCESSAT", + 270: "SYS_PSELECT6", + 271: "SYS_PPOLL", + 272: "SYS_UNSHARE", + 273: "SYS_SET_ROBUST_LIST", + 274: "SYS_GET_ROBUST_LIST", + 275: "SYS_SPLICE", + 276: "SYS_TEE", + 277: "SYS_SYNC_FILE_RANGE", + 278: "SYS_VMSPLICE", + 279: "SYS_MOVE_PAGES", + 280: "SYS_UTIMENSAT", + 281: "SYS_EPOLL_PWAIT", + 282: "SYS_SIGNALFD", + 283: "SYS_TIMERFD_CREATE", + 284: "SYS_EVENTFD", + 285: "SYS_FALLOCATE", + 286: "SYS_TIMERFD_SETTIME", + 287: "SYS_TIMERFD_GETTIME", + 288: "SYS_ACCEPT4", + 289: "SYS_SIGNALFD4", + 290: "SYS_EVENTFD2", + 291: "SYS_EPOLL_CREATE1", + 292: "SYS_DUP3", + 293: "SYS_PIPE2", + 294: "SYS_INOTIFY_INIT1", + 295: "SYS_PREADV", + 296: "SYS_PWRITEV", + 297: "SYS_RT_TGSIGQUEUEINFO", + 298: "SYS_PERF_EVENT_OPEN", + 299: "SYS_RECVMMSG", + 300: "SYS_FANOTIFY_INIT", + 301: "SYS_FANOTIFY_MARK", + 302: "SYS_PRLIMIT64", + 303: "SYS_NAME_TO_HANDLE_AT", + 304: "SYS_OPEN_BY_HANDLE_AT", + 305: "SYS_CLOCK_ADJTIME", + 306: "SYS_SYNCFS", + 307: "SYS_SENDMMSG", + 308: "SYS_SETNS", + 309: "SYS_GETCPU", + 310: "SYS_PROCESS_VM_READV", + 311: "SYS_PROCESS_VM_WRITEV", + 312: "SYS_KCMP", + 313: "SYS_FINIT_MODULE", + 314: "SYS_SCHED_SETATTR", + 315: "SYS_SCHED_GETATTR", + 316: "SYS_RENAMEAT2", + 317: "SYS_SECCOMP", + 318: "SYS_GETRANDOM", + 319: "SYS_MEMFD_CREATE", + 320: "SYS_KEXEC_FILE_LOAD", + 321: "SYS_BPF", + 322: "SYS_EXECVEAT", + 323: "SYS_USERFAULTFD", + 324: "SYS_MEMBARRIER", + 325: "SYS_MLOCK2", + 326: "SYS_COPY_FILE_RANGE", + 327: "SYS_PREADV2", + 328: "SYS_PWRITEV2", + 329: "SYS_PKEY_MPROTECT", + 330: "SYS_PKEY_ALLOC", + 331: "SYS_PKEY_FREE", + 332: "SYS_STATX", + + 351: "DO_EXIT", + 352: "SECURITY_BPRM_CHECK", +} + // getSyscallName Function func getSyscallName(sc int32) string { // source: /usr/include/x86_64-linux-gnu/asm/unistd_64.h - var syscalls = map[int32]string{ - 0: "SYS_READ", - 1: "SYS_WRITE", - 2: "SYS_OPEN", - 3: "SYS_CLOSE", - 4: "SYS_STAT", - 5: "SYS_FSTAT", - 6: "SYS_LSTAT", - 7: "SYS_POLL", - 8: "SYS_LSEEK", - 9: "SYS_MMAP", - 10: "SYS_MPROTECT", - 11: "SYS_MUNMAP", - 12: "SYS_BRK", - 13: "SYS_RT_SIGACTION", - 14: "SYS_RT_SIGPROCMASK", - 15: "SYS_RT_SIGRETURN", - 16: "SYS_IOCTL", - 17: "SYS_PREAD64", - 18: "SYS_PWRITE64", - 19: "SYS_READV", - 20: "SYS_WRITEV", - 21: "SYS_ACCESS", - 22: "SYS_PIPE", - 23: "SYS_SELECT", - 24: "SYS_SCHED_YIELD", - 25: "SYS_MREMAP", - 26: "SYS_MSYNC", - 27: "SYS_MINCORE", - 28: "SYS_MADVISE", - 29: "SYS_SHMGET", - 30: "SYS_SHMAT", - 31: "SYS_SHMCTL", - 32: "SYS_DUP", - 33: "SYS_DUP2", - 34: "SYS_PAUSE", - 35: "SYS_NANOSLEEP", - 36: "SYS_GETITIMER", - 37: "SYS_ALARM", - 38: "SYS_SETITIMER", - 39: "SYS_GETPID", - 40: "SYS_SENDFILE", - 41: "SYS_SOCKET", - 42: "SYS_CONNECT", - 43: "SYS_ACCEPT", - 44: "SYS_SENDTO", - 45: "SYS_RECVFROM", - 46: "SYS_SENDMSG", - 47: "SYS_RECVMSG", - 48: "SYS_SHUTDOWN", - 49: "SYS_BIND", - 50: "SYS_LISTEN", - 51: "SYS_GETSOCKNAME", - 52: "SYS_GETPEERNAME", - 53: "SYS_SOCKETPAIR", - 54: "SYS_SETSOCKOPT", - 55: "SYS_GETSOCKOPT", - 56: "SYS_CLONE", - 57: "SYS_FORK", - 58: "SYS_VFORK", - 59: "SYS_EXECVE", - 60: "SYS_EXIT", - 61: "SYS_WAIT4", - 62: "SYS_KILL", - 63: "SYS_UNAME", - 64: "SYS_SEMGET", - 65: "SYS_SEMOP", - 66: "SYS_SEMCTL", - 67: "SYS_SHMDT", - 68: "SYS_MSGGET", - 69: "SYS_MSGSND", - 70: "SYS_MSGRCV", - 71: "SYS_MSGCTL", - 72: "SYS_FCNTL", - 73: "SYS_FLOCK", - 74: "SYS_FSYNC", - 75: "SYS_FDATASYNC", - 76: "SYS_TRUNCATE", - 77: "SYS_FTRUNCATE", - 78: "SYS_GETDENTS", - 79: "SYS_GETCWD", - 80: "SYS_CHDIR", - 81: "SYS_FCHDIR", - 82: "SYS_RENAME", - 83: "SYS_MKDIR", - 84: "SYS_RMDIR", - 85: "SYS_CREAT", - 86: "SYS_LINK", - 87: "SYS_UNLINK", - 88: "SYS_SYMLINK", - 89: "SYS_READLINK", - 90: "SYS_CHMOD", - 91: "SYS_FCHMOD", - 92: "SYS_CHOWN", - 93: "SYS_FCHOWN", - 94: "SYS_LCHOWN", - 95: "SYS_UMASK", - 96: "SYS_GETTIMEOFDAY", - 97: "SYS_GETRLIMIT", - 98: "SYS_GETRUSAGE", - 99: "SYS_SYSINFO", - 100: "SYS_TIMES", - 101: "SYS_PTRACE", - 102: "SYS_GETUID", - 103: "SYS_SYSLOG", - 104: "SYS_GETGID", - 105: "SYS_SETUID", - 106: "SYS_SETGID", - 107: "SYS_GETEUID", - 108: "SYS_GETEGID", - 109: "SYS_SETPGID", - 110: "SYS_GETPPID", - 111: "SYS_GETPGRP", - 112: "SYS_SETSID", - 113: "SYS_SETREUID", - 114: "SYS_SETREGID", - 115: "SYS_GETGROUPS", - 116: "SYS_SETGROUPS", - 117: "SYS_SETRESUID", - 118: "SYS_GETRESUID", - 119: "SYS_SETRESGID", - 120: "SYS_GETRESGID", - 121: "SYS_GETPGID", - 122: "SYS_SETFSUID", - 123: "SYS_SETFSGID", - 124: "SYS_GETSID", - 125: "SYS_CAPGET", - 126: "SYS_CAPSET", - 127: "SYS_RT_SIGPENDING", - 128: "SYS_RT_SIGTIMEDWAIT", - 129: "SYS_RT_SIGQUEUEINFO", - 130: "SYS_RT_SIGSUSPEND", - 131: "SYS_SIGALTSTACK", - 132: "SYS_UTIME", - 133: "SYS_MKNOD", - 134: "SYS_USELIB", - 135: "SYS_PERSONALITY", - 136: "SYS_USTAT", - 137: "SYS_STATFS", - 138: "SYS_FSTATFS", - 139: "SYS_SYSFS", - 140: "SYS_GETPRIORITY", - 141: "SYS_SETPRIORITY", - 142: "SYS_SCHED_SETPARAM", - 143: "SYS_SCHED_GETPARAM", - 144: "SYS_SCHED_SETSCHEDULER", - 145: "SYS_SCHED_GETSCHEDULER", - 146: "SYS_SCHED_GET_PRIORITY_MAX", - 147: "SYS_SCHED_GET_PRIORITY_MIN", - 148: "SYS_SCHED_RR_GET_INTERVAL", - 149: "SYS_MLOCK", - 150: "SYS_MUNLOCK", - 151: "SYS_MLOCKALL", - 152: "SYS_MUNLOCKALL", - 153: "SYS_VHANGUP", - 154: "SYS_MODIFY_LDT", - 155: "SYS_PIVOT_ROOT", - 156: "SYS__SYSCTL", - 157: "SYS_PRCTL", - 158: "SYS_ARCH_PRCTL", - 159: "SYS_ADJTIMEX", - 160: "SYS_SETRLIMIT", - 161: "SYS_CHROOT", - 162: "SYS_SYNC", - 163: "SYS_ACCT", - 164: "SYS_SETTIMEOFDAY", - 165: "SYS_MOUNT", - 166: "SYS_UMOUNT2", - 167: "SYS_SWAPON", - 168: "SYS_SWAPOFF", - 169: "SYS_REBOOT", - 170: "SYS_SETHOSTNAME", - 171: "SYS_SETDOMAINNAME", - 172: "SYS_IOPL", - 173: "SYS_IOPERM", - 174: "SYS_CREATE_MODULE", - 175: "SYS_INIT_MODULE", - 176: "SYS_DELETE_MODULE", - 177: "SYS_GET_KERNEL_SYMS", - 178: "SYS_QUERY_MODULE", - 179: "SYS_QUOTACTL", - 180: "SYS_NFSSERVCTL", - 181: "SYS_GETPMSG", - 182: "SYS_PUTPMSG", - 183: "SYS_AFS_SYSCALL", - 184: "SYS_TUXCALL", - 185: "SYS_SECURITY", - 186: "SYS_GETTID", - 187: "SYS_READAHEAD", - 188: "SYS_SETXATTR", - 189: "SYS_LSETXATTR", - 190: "SYS_FSETXATTR", - 191: "SYS_GETXATTR", - 192: "SYS_LGETXATTR", - 193: "SYS_FGETXATTR", - 194: "SYS_LISTXATTR", - 195: "SYS_LLISTXATTR", - 196: "SYS_FLISTXATTR", - 197: "SYS_REMOVEXATTR", - 198: "SYS_LREMOVEXATTR", - 199: "SYS_FREMOVEXATTR", - 200: "SYS_TKILL", - 201: "SYS_TIME", - 202: "SYS_FUTEX", - 203: "SYS_SCHED_SETAFFINITY", - 204: "SYS_SCHED_GETAFFINITY", - 205: "SYS_SET_THREAD_AREA", - 206: "SYS_IO_SETUP", - 207: "SYS_IO_DESTROY", - 208: "SYS_IO_GETEVENTS", - 209: "SYS_IO_SUBMIT", - 210: "SYS_IO_CANCEL", - 211: "SYS_GET_THREAD_AREA", - 212: "SYS_LOOKUP_DCOOKIE", - 213: "SYS_EPOLL_CREATE", - 214: "SYS_EPOLL_CTL_OLD", - 215: "SYS_EPOLL_WAIT_OLD", - 216: "SYS_REMAP_FILE_PAGES", - 217: "SYS_GETDENTS64", - 218: "SYS_SET_TID_ADDRESS", - 219: "SYS_RESTART_SYSCALL", - 220: "SYS_SEMTIMEDOP", - 221: "SYS_FADVISE64", - 222: "SYS_TIMER_CREATE", - 223: "SYS_TIMER_SETTIME", - 224: "SYS_TIMER_GETTIME", - 225: "SYS_TIMER_GETOVERRUN", - 226: "SYS_TIMER_DELETE", - 227: "SYS_CLOCK_SETTIME", - 228: "SYS_CLOCK_GETTIME", - 229: "SYS_CLOCK_GETRES", - 230: "SYS_CLOCK_NANOSLEEP", - 231: "SYS_EXIT_GROUP", - 232: "SYS_EPOLL_WAIT", - 233: "SYS_EPOLL_CTL", - 234: "SYS_TGKILL", - 235: "SYS_UTIMES", - 236: "SYS_VSERVER", - 237: "SYS_MBIND", - 238: "SYS_SET_MEMPOLICY", - 239: "SYS_GET_MEMPOLICY", - 240: "SYS_MQ_OPEN", - 241: "SYS_MQ_UNLINK", - 242: "SYS_MQ_TIMEDSEND", - 243: "SYS_MQ_TIMEDRECEIVE", - 244: "SYS_MQ_NOTIFY", - 245: "SYS_MQ_GETSETATTR", - 246: "SYS_KEXEC_LOAD", - 247: "SYS_WAITID", - 248: "SYS_ADD_KEY", - 249: "SYS_REQUEST_KEY", - 250: "SYS_KEYCTL", - 251: "SYS_IOPRIO_SET", - 252: "SYS_IOPRIO_GET", - 253: "SYS_INOTIFY_INIT", - 254: "SYS_INOTIFY_ADD_WATCH", - 255: "SYS_INOTIFY_RM_WATCH", - 256: "SYS_MIGRATE_PAGES", - 257: "SYS_OPENAT", - 258: "SYS_MKDIRAT", - 259: "SYS_MKNODAT", - 260: "SYS_FCHOWNAT", - 261: "SYS_FUTIMESAT", - 262: "SYS_NEWFSTATAT", - 263: "SYS_UNLINKAT", - 264: "SYS_RENAMEAT", - 265: "SYS_LINKAT", - 266: "SYS_SYMLINKAT", - 267: "SYS_READLINKAT", - 268: "SYS_FCHMODAT", - 269: "SYS_FACCESSAT", - 270: "SYS_PSELECT6", - 271: "SYS_PPOLL", - 272: "SYS_UNSHARE", - 273: "SYS_SET_ROBUST_LIST", - 274: "SYS_GET_ROBUST_LIST", - 275: "SYS_SPLICE", - 276: "SYS_TEE", - 277: "SYS_SYNC_FILE_RANGE", - 278: "SYS_VMSPLICE", - 279: "SYS_MOVE_PAGES", - 280: "SYS_UTIMENSAT", - 281: "SYS_EPOLL_PWAIT", - 282: "SYS_SIGNALFD", - 283: "SYS_TIMERFD_CREATE", - 284: "SYS_EVENTFD", - 285: "SYS_FALLOCATE", - 286: "SYS_TIMERFD_SETTIME", - 287: "SYS_TIMERFD_GETTIME", - 288: "SYS_ACCEPT4", - 289: "SYS_SIGNALFD4", - 290: "SYS_EVENTFD2", - 291: "SYS_EPOLL_CREATE1", - 292: "SYS_DUP3", - 293: "SYS_PIPE2", - 294: "SYS_INOTIFY_INIT1", - 295: "SYS_PREADV", - 296: "SYS_PWRITEV", - 297: "SYS_RT_TGSIGQUEUEINFO", - 298: "SYS_PERF_EVENT_OPEN", - 299: "SYS_RECVMMSG", - 300: "SYS_FANOTIFY_INIT", - 301: "SYS_FANOTIFY_MARK", - 302: "SYS_PRLIMIT64", - 303: "SYS_NAME_TO_HANDLE_AT", - 304: "SYS_OPEN_BY_HANDLE_AT", - 305: "SYS_CLOCK_ADJTIME", - 306: "SYS_SYNCFS", - 307: "SYS_SENDMMSG", - 308: "SYS_SETNS", - 309: "SYS_GETCPU", - 310: "SYS_PROCESS_VM_READV", - 311: "SYS_PROCESS_VM_WRITEV", - 312: "SYS_KCMP", - 313: "SYS_FINIT_MODULE", - 314: "SYS_SCHED_SETATTR", - 315: "SYS_SCHED_GETATTR", - 316: "SYS_RENAMEAT2", - 317: "SYS_SECCOMP", - 318: "SYS_GETRANDOM", - 319: "SYS_MEMFD_CREATE", - 320: "SYS_KEXEC_FILE_LOAD", - 321: "SYS_BPF", - 322: "SYS_EXECVEAT", - 323: "SYS_USERFAULTFD", - 324: "SYS_MEMBARRIER", - 325: "SYS_MLOCK2", - 326: "SYS_COPY_FILE_RANGE", - 327: "SYS_PREADV2", - 328: "SYS_PWRITEV2", - 329: "SYS_PKEY_MPROTECT", - 330: "SYS_PKEY_ALLOC", - 331: "SYS_PKEY_FREE", - 332: "SYS_STATX", - - 351: "DO_EXIT", - 352: "SECURITY_BPRM_CHECK", - } - var res string if syscallName, ok := syscalls[sc]; ok { @@ -789,144 +789,144 @@ func getSyscallName(sc int32) string { return res } +var errMsg = map[int64]string{ + 1: "Operation not permitted", + 2: "No such file or directory", + 3: "No such process", + 4: "Interrupted system call", + 5: "Input/output error", + 6: "No such device or address", + 7: "Argument list too long", + 8: "Exec format error", + 9: "Bad file descriptor", + 10: "No child processes", + 11: "Resource temporarily unavailable", + 12: "Cannot allocate memory", + 13: "Permission denied", + 14: "Bad address", + 15: "Block device required", + 16: "Device or resource busy", + 17: "File exists", + 18: "Invalid cross-device link", + 19: "No such device", + 20: "Not a directory", + 21: "Is a directory", + 22: "Invalid argument", + 23: "Too many open files in system", + 24: "Too many open files", + 25: "Inappropriate ioctl for device", + 26: "Text file busy", + 27: "File too large", + 28: "No space left on device", + 29: "Illegal seek", + 30: "Read-only file system", + 31: "Too many links", + 32: "Broken pipe", + 33: "Numerical argument out of domain", + 34: "Numerical result out of range", + 35: "Resource deadlock avoided", + 36: "File name too long", + 37: "No locks available", + 38: "Function not implemented", + 39: "Directory not empty", + 40: "Too many levels of symbolic links", + 42: "No message of desired type", + 43: "Identifier removed", + 44: "Channel number out of range", + 45: "Level 2 not synchronized", + 46: "Level 3 halted", + 47: "Level 3 reset", + 48: "Link number out of range", + 49: "Protocol driver not attached", + 50: "No CSI structure available", + 51: "Level 2 halted", + 52: "Invalid exchange", + 53: "Invalid request descriptor", + 54: "Exchange full", + 55: "No anode", + 56: "Invalid request code", + 57: "Invalid slot", + 59: "Bad font file format", + 60: "Device not a stream", + 61: "No data available", + 62: "Timer expired", + 63: "Out of streams resources", + 64: "Machine is not on the network", + 65: "Package not installed", + 66: "Object is remote", + 67: "Link has been severed", + 68: "Advertise error", + 69: "Srmount error", + 70: "Communication error on send", + 71: "Protocol error", + 72: "Multihop attempted", + 73: "RFS specific error", + 74: "Bad message", + 75: "Value too large for defined data type", + 76: "Name not unique on network", + 77: "File descriptor in bad state", + 78: "Remote address changed", + 79: "Can not access a needed shared library", + 80: "Accessing a corrupted shared library", + 81: ".lib section in a.out corrupted", + 82: "Attempting to link in too many shared libraries", + 83: "Cannot exec a shared library directly", + 84: "Invalid or incomplete multibyte or wide character", + 85: "Interrupted system call should be restarted", + 86: "Streams pipe error", + 87: "Too many users", + 88: "Socket operation on non-socket", + 89: "Destination address required", + 90: "Message too long", + 91: "Protocol wrong type for socket", + 92: "Protocol not available", + 93: "Protocol not supported", + 94: "Socket type not supported", + 95: "Operation not supported", + 96: "Protocol family not supported", + 97: "Address family not supported by protocol", + 98: "Address already in use", + 99: "Cannot assign requested address", + 100: "Network is down", + 101: "Network is unreachable", + 102: "Network dropped connection on reset", + 103: "Software caused connection abort", + 104: "Connection reset by peer", + 105: "No buffer space available", + 106: "Transport endpoint is already connected", + 107: "Transport endpoint is not connected", + 108: "Cannot send after transport endpoint shutdown", + 109: "Too many references: cannot splice", + 110: "Connection timed out", + 111: "Connection refused", + 112: "Host is down", + 113: "No route to host", + 114: "Operation already in progress", + 115: "Operation now in progress", + 116: "Stale file handle", + 117: "Structure needs cleaning", + 118: "Not a XENIX named type file", + 119: "No XENIX semaphores available", + 120: "Is a named type file", + 121: "Remote I/O error", + 122: "Disk quota exceeded", + 123: "No medium found", + 124: "Wrong medium type", + 125: "Operation canceled", + 126: "Required key not available", + 127: "Key has expired", + 128: "Key has been revoked", + 129: "Key was rejected by service", + 130: "Owner died", + 131: "State not recoverable", + 132: "Operation not possible due to RF-kill", + 133: "Memory page has hardware error", +} + // getErrorMessage Function func getErrorMessage(errno int64) string { // errno -l - var errMsg = map[int64]string{ - 1: "Operation not permitted", - 2: "No such file or directory", - 3: "No such process", - 4: "Interrupted system call", - 5: "Input/output error", - 6: "No such device or address", - 7: "Argument list too long", - 8: "Exec format error", - 9: "Bad file descriptor", - 10: "No child processes", - 11: "Resource temporarily unavailable", - 12: "Cannot allocate memory", - 13: "Permission denied", - 14: "Bad address", - 15: "Block device required", - 16: "Device or resource busy", - 17: "File exists", - 18: "Invalid cross-device link", - 19: "No such device", - 20: "Not a directory", - 21: "Is a directory", - 22: "Invalid argument", - 23: "Too many open files in system", - 24: "Too many open files", - 25: "Inappropriate ioctl for device", - 26: "Text file busy", - 27: "File too large", - 28: "No space left on device", - 29: "Illegal seek", - 30: "Read-only file system", - 31: "Too many links", - 32: "Broken pipe", - 33: "Numerical argument out of domain", - 34: "Numerical result out of range", - 35: "Resource deadlock avoided", - 36: "File name too long", - 37: "No locks available", - 38: "Function not implemented", - 39: "Directory not empty", - 40: "Too many levels of symbolic links", - 42: "No message of desired type", - 43: "Identifier removed", - 44: "Channel number out of range", - 45: "Level 2 not synchronized", - 46: "Level 3 halted", - 47: "Level 3 reset", - 48: "Link number out of range", - 49: "Protocol driver not attached", - 50: "No CSI structure available", - 51: "Level 2 halted", - 52: "Invalid exchange", - 53: "Invalid request descriptor", - 54: "Exchange full", - 55: "No anode", - 56: "Invalid request code", - 57: "Invalid slot", - 59: "Bad font file format", - 60: "Device not a stream", - 61: "No data available", - 62: "Timer expired", - 63: "Out of streams resources", - 64: "Machine is not on the network", - 65: "Package not installed", - 66: "Object is remote", - 67: "Link has been severed", - 68: "Advertise error", - 69: "Srmount error", - 70: "Communication error on send", - 71: "Protocol error", - 72: "Multihop attempted", - 73: "RFS specific error", - 74: "Bad message", - 75: "Value too large for defined data type", - 76: "Name not unique on network", - 77: "File descriptor in bad state", - 78: "Remote address changed", - 79: "Can not access a needed shared library", - 80: "Accessing a corrupted shared library", - 81: ".lib section in a.out corrupted", - 82: "Attempting to link in too many shared libraries", - 83: "Cannot exec a shared library directly", - 84: "Invalid or incomplete multibyte or wide character", - 85: "Interrupted system call should be restarted", - 86: "Streams pipe error", - 87: "Too many users", - 88: "Socket operation on non-socket", - 89: "Destination address required", - 90: "Message too long", - 91: "Protocol wrong type for socket", - 92: "Protocol not available", - 93: "Protocol not supported", - 94: "Socket type not supported", - 95: "Operation not supported", - 96: "Protocol family not supported", - 97: "Address family not supported by protocol", - 98: "Address already in use", - 99: "Cannot assign requested address", - 100: "Network is down", - 101: "Network is unreachable", - 102: "Network dropped connection on reset", - 103: "Software caused connection abort", - 104: "Connection reset by peer", - 105: "No buffer space available", - 106: "Transport endpoint is already connected", - 107: "Transport endpoint is not connected", - 108: "Cannot send after transport endpoint shutdown", - 109: "Too many references: cannot splice", - 110: "Connection timed out", - 111: "Connection refused", - 112: "Host is down", - 113: "No route to host", - 114: "Operation already in progress", - 115: "Operation now in progress", - 116: "Stale file handle", - 117: "Structure needs cleaning", - 118: "Not a XENIX named type file", - 119: "No XENIX semaphores available", - 120: "Is a named type file", - 121: "Remote I/O error", - 122: "Disk quota exceeded", - 123: "No medium found", - 124: "Wrong medium type", - 125: "Operation canceled", - 126: "Required key not available", - 127: "Key has expired", - 128: "Key has been revoked", - 129: "Key was rejected by service", - 130: "Owner died", - 131: "State not recoverable", - 132: "Operation not possible due to RF-kill", - 133: "Memory page has hardware error", - } - var res string if msg, ok := errMsg[-errno]; ok { diff --git a/KubeArmor/monitor/systemMonitor.go b/KubeArmor/monitor/systemMonitor.go index 34988aad84..60ae89ed10 100644 --- a/KubeArmor/monitor/systemMonitor.go +++ b/KubeArmor/monitor/systemMonitor.go @@ -242,7 +242,6 @@ func (mon *SystemMonitor) InitBPF() error { bpfPath := homeDir + "/BPF/system_monitor.c" if _, err := os.Stat(filepath.Clean(bpfPath)); err != nil { // go test - bpfPath = os.Getenv("PWD") + "/../BPF/system_monitor.c" if _, err := os.Stat(filepath.Clean(bpfPath)); err != nil { return err @@ -508,7 +507,7 @@ func (mon *SystemMonitor) TraceSyscall() { } else if ctx.EventID == SysExecve { if len(args) == 2 { // enter // build a pid node - pidNode := mon.BuildPidNode(ctx, args[0].(string), args[1].([]string)) + pidNode := mon.BuildPidNode(containerID, ctx, args[0].(string), args[1].([]string)) mon.AddActivePid(containerID, pidNode) // generate a log with the base information @@ -542,9 +541,7 @@ func (mon *SystemMonitor) TraceSyscall() { delete(execLogMap, ctx.HostPID) // update the log again - if !strings.HasPrefix(log.Source, "/") { - log = mon.UpdateLogBase(ctx.EventID, log) - } + log = mon.UpdateLogBase(ctx.EventID, log) // get error message if ctx.Retval < 0 { @@ -568,7 +565,7 @@ func (mon *SystemMonitor) TraceSyscall() { } else if ctx.EventID == SysExecveAt { if len(args) == 4 { // enter // build a pid node - pidNode := mon.BuildPidNode(ctx, args[1].(string), args[2].([]string)) + pidNode := mon.BuildPidNode(containerID, ctx, args[1].(string), args[2].([]string)) mon.AddActivePid(containerID, pidNode) // generate a log with the base information @@ -611,9 +608,7 @@ func (mon *SystemMonitor) TraceSyscall() { delete(execLogMap, ctx.HostPID) // update the log again - if !strings.HasPrefix(log.Source, "/") { - log = mon.UpdateLogBase(ctx.EventID, log) - } + log = mon.UpdateLogBase(ctx.EventID, log) // get error message if ctx.Retval < 0 { @@ -695,7 +690,7 @@ func (mon *SystemMonitor) TraceHostSyscall() { } else if ctx.EventID == SysExecve { if len(args) == 2 { // enter // build a pid node - pidNode := mon.BuildPidNode(ctx, args[0].(string), args[1].([]string)) + pidNode := mon.BuildPidNode("", ctx, args[0].(string), args[1].([]string)) mon.AddActivePid("", pidNode) // generate a log with the base information @@ -755,7 +750,7 @@ func (mon *SystemMonitor) TraceHostSyscall() { } else if ctx.EventID == SysExecveAt { if len(args) == 4 { // enter // build a pid node - pidNode := mon.BuildPidNode(ctx, args[1].(string), args[2].([]string)) + pidNode := mon.BuildPidNode("", ctx, args[1].(string), args[2].([]string)) mon.AddActivePid("", pidNode) // generate a log with the base information diff --git a/KubeArmor/types/types.go b/KubeArmor/types/types.go index 446d62e95e..a2024f3a8c 100644 --- a/KubeArmor/types/types.go +++ b/KubeArmor/types/types.go @@ -59,8 +59,7 @@ type EndPoint struct { // == // - PolicyEnabled int `json:"policyEnabled"` - + PolicyEnabled int `json:"policyEnabled"` DefaultPosture DefaultPosture `json:"defaultPosture"` ProcessVisibilityEnabled bool `json:"processVisibilityEnabled"` @@ -199,6 +198,9 @@ type Log struct { ParentProcessName string `json:"parentProcessName"` ProcessName string `json:"processName"` + // enforcer + Enforcer string `json:"enforcer,omitempty"` + // policy PolicyName string `json:"policyName,omitempty"` @@ -242,6 +244,7 @@ type MatchPolicy struct { IsFromSource bool OwnerOnly bool ReadOnly bool + Recursive bool Regexp *regexp.Regexp Native bool @@ -519,8 +522,11 @@ type PidNode struct { PID uint32 UID uint32 - ExecPath string - Args string + ParentExecPath string + ExecPath string + + Source string + Args string Exited bool ExitedTime time.Time diff --git a/protobuf/Makefile b/protobuf/Makefile index 8f0a815685..b113076ace 100644 --- a/protobuf/Makefile +++ b/protobuf/Makefile @@ -13,7 +13,8 @@ go.sum: go.mod go get . %.pb.go: %.proto - protoc --proto_path=. --go_opt=paths=source_relative --go_out=plugins=grpc:. $< + go mod tidy + protoc --go_out=. --go_opt=paths=source_relative --go-grpc_out=. --go-grpc_opt=paths=source_relative,require_unimplemented_servers=false $< .PHONY: clean clean: diff --git a/protobuf/go.mod b/protobuf/go.mod index 45a7439db9..4ae97fc762 100644 --- a/protobuf/go.mod +++ b/protobuf/go.mod @@ -8,6 +8,6 @@ replace ( ) require ( - google.golang.org/grpc v1.34.0 - google.golang.org/protobuf v1.27.1 + google.golang.org/grpc v1.45.0 + google.golang.org/protobuf v1.28.0 ) diff --git a/protobuf/kubearmor.pb.go b/protobuf/kubearmor.pb.go index e5414dbea0..f2a9783a39 100644 --- a/protobuf/kubearmor.pb.go +++ b/protobuf/kubearmor.pb.go @@ -1,16 +1,12 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.27.1 -// protoc v3.14.0 +// protoc v3.19.4 // source: kubearmor.proto package protobuf import ( - context "context" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" @@ -209,6 +205,7 @@ type Alert struct { ParentProcessName string `protobuf:"bytes,25,opt,name=ParentProcessName,proto3" json:"ParentProcessName,omitempty"` ProcessName string `protobuf:"bytes,26,opt,name=ProcessName,proto3" json:"ProcessName,omitempty"` HostPPID int32 `protobuf:"varint,27,opt,name=HostPPID,proto3" json:"HostPPID,omitempty"` + Enforcer string `protobuf:"bytes,28,opt,name=Enforcer,proto3" json:"Enforcer,omitempty"` } func (x *Alert) Reset() { @@ -432,6 +429,13 @@ func (x *Alert) GetHostPPID() int32 { return 0 } +func (x *Alert) GetEnforcer() string { + if x != nil { + return x.Enforcer + } + return "" +} + // log struct type Log struct { state protoimpl.MessageState @@ -765,7 +769,7 @@ var file_kubearmor_proto_rawDesc = []byte{ 0x04, 0x54, 0x79, 0x70, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x4c, 0x65, 0x76, 0x65, 0x6c, 0x18, 0x07, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x4c, 0x65, 0x76, 0x65, 0x6c, 0x12, 0x18, 0x0a, 0x07, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, 0x08, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x4d, 0x65, - 0x73, 0x73, 0x61, 0x67, 0x65, 0x22, 0x87, 0x06, 0x0a, 0x05, 0x41, 0x6c, 0x65, 0x72, 0x74, 0x12, + 0x73, 0x73, 0x61, 0x67, 0x65, 0x22, 0xa3, 0x06, 0x0a, 0x05, 0x41, 0x6c, 0x65, 0x72, 0x74, 0x12, 0x1c, 0x0a, 0x09, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x09, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x12, 0x20, 0x0a, 0x0b, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x64, 0x54, 0x69, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, @@ -813,71 +817,73 @@ var file_kubearmor_proto_rawDesc = []byte{ 0x65, 0x12, 0x20, 0x0a, 0x0b, 0x50, 0x72, 0x6f, 0x63, 0x65, 0x73, 0x73, 0x4e, 0x61, 0x6d, 0x65, 0x18, 0x1a, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x50, 0x72, 0x6f, 0x63, 0x65, 0x73, 0x73, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x1a, 0x0a, 0x08, 0x48, 0x6f, 0x73, 0x74, 0x50, 0x50, 0x49, 0x44, 0x18, - 0x1b, 0x20, 0x01, 0x28, 0x05, 0x52, 0x08, 0x48, 0x6f, 0x73, 0x74, 0x50, 0x50, 0x49, 0x44, 0x22, - 0x83, 0x05, 0x0a, 0x03, 0x4c, 0x6f, 0x67, 0x12, 0x1c, 0x0a, 0x09, 0x54, 0x69, 0x6d, 0x65, 0x73, - 0x74, 0x61, 0x6d, 0x70, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x09, 0x54, 0x69, 0x6d, 0x65, - 0x73, 0x74, 0x61, 0x6d, 0x70, 0x12, 0x20, 0x0a, 0x0b, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x64, - 0x54, 0x69, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x55, 0x70, 0x64, 0x61, - 0x74, 0x65, 0x64, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x20, 0x0a, 0x0b, 0x43, 0x6c, 0x75, 0x73, 0x74, - 0x65, 0x72, 0x4e, 0x61, 0x6d, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x43, 0x6c, - 0x75, 0x73, 0x74, 0x65, 0x72, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x1a, 0x0a, 0x08, 0x48, 0x6f, 0x73, - 0x74, 0x4e, 0x61, 0x6d, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x48, 0x6f, 0x73, - 0x74, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x24, 0x0a, 0x0d, 0x4e, 0x61, 0x6d, 0x65, 0x73, 0x70, 0x61, - 0x63, 0x65, 0x4e, 0x61, 0x6d, 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0d, 0x4e, 0x61, - 0x6d, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x50, - 0x6f, 0x64, 0x4e, 0x61, 0x6d, 0x65, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x50, 0x6f, - 0x64, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x20, 0x0a, 0x0b, 0x43, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, - 0x65, 0x72, 0x49, 0x44, 0x18, 0x07, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x43, 0x6f, 0x6e, 0x74, - 0x61, 0x69, 0x6e, 0x65, 0x72, 0x49, 0x44, 0x12, 0x24, 0x0a, 0x0d, 0x43, 0x6f, 0x6e, 0x74, 0x61, - 0x69, 0x6e, 0x65, 0x72, 0x4e, 0x61, 0x6d, 0x65, 0x18, 0x08, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0d, - 0x43, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x18, 0x0a, - 0x07, 0x48, 0x6f, 0x73, 0x74, 0x50, 0x49, 0x44, 0x18, 0x09, 0x20, 0x01, 0x28, 0x05, 0x52, 0x07, - 0x48, 0x6f, 0x73, 0x74, 0x50, 0x49, 0x44, 0x12, 0x12, 0x0a, 0x04, 0x50, 0x50, 0x49, 0x44, 0x18, - 0x0a, 0x20, 0x01, 0x28, 0x05, 0x52, 0x04, 0x50, 0x50, 0x49, 0x44, 0x12, 0x10, 0x0a, 0x03, 0x50, - 0x49, 0x44, 0x18, 0x0b, 0x20, 0x01, 0x28, 0x05, 0x52, 0x03, 0x50, 0x49, 0x44, 0x12, 0x10, 0x0a, - 0x03, 0x55, 0x49, 0x44, 0x18, 0x0c, 0x20, 0x01, 0x28, 0x05, 0x52, 0x03, 0x55, 0x49, 0x44, 0x12, - 0x12, 0x0a, 0x04, 0x54, 0x79, 0x70, 0x65, 0x18, 0x0d, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x54, - 0x79, 0x70, 0x65, 0x12, 0x16, 0x0a, 0x06, 0x53, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x18, 0x0e, 0x20, - 0x01, 0x28, 0x09, 0x52, 0x06, 0x53, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x12, 0x1c, 0x0a, 0x09, 0x4f, - 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x0f, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, - 0x4f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x1a, 0x0a, 0x08, 0x52, 0x65, 0x73, - 0x6f, 0x75, 0x72, 0x63, 0x65, 0x18, 0x10, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x52, 0x65, 0x73, - 0x6f, 0x75, 0x72, 0x63, 0x65, 0x12, 0x12, 0x0a, 0x04, 0x44, 0x61, 0x74, 0x61, 0x18, 0x11, 0x20, - 0x01, 0x28, 0x09, 0x52, 0x04, 0x44, 0x61, 0x74, 0x61, 0x12, 0x16, 0x0a, 0x06, 0x52, 0x65, 0x73, - 0x75, 0x6c, 0x74, 0x18, 0x12, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x52, 0x65, 0x73, 0x75, 0x6c, - 0x74, 0x12, 0x26, 0x0a, 0x0e, 0x43, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x49, 0x6d, - 0x61, 0x67, 0x65, 0x18, 0x13, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0e, 0x43, 0x6f, 0x6e, 0x74, 0x61, - 0x69, 0x6e, 0x65, 0x72, 0x49, 0x6d, 0x61, 0x67, 0x65, 0x12, 0x2c, 0x0a, 0x11, 0x50, 0x61, 0x72, - 0x65, 0x6e, 0x74, 0x50, 0x72, 0x6f, 0x63, 0x65, 0x73, 0x73, 0x4e, 0x61, 0x6d, 0x65, 0x18, 0x14, - 0x20, 0x01, 0x28, 0x09, 0x52, 0x11, 0x50, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x50, 0x72, 0x6f, 0x63, - 0x65, 0x73, 0x73, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x20, 0x0a, 0x0b, 0x50, 0x72, 0x6f, 0x63, 0x65, - 0x73, 0x73, 0x4e, 0x61, 0x6d, 0x65, 0x18, 0x15, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x50, 0x72, - 0x6f, 0x63, 0x65, 0x73, 0x73, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x1a, 0x0a, 0x08, 0x48, 0x6f, 0x73, - 0x74, 0x50, 0x50, 0x49, 0x44, 0x18, 0x16, 0x20, 0x01, 0x28, 0x05, 0x52, 0x08, 0x48, 0x6f, 0x73, - 0x74, 0x50, 0x50, 0x49, 0x44, 0x22, 0x28, 0x0a, 0x0e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, - 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x12, 0x16, 0x0a, 0x06, 0x46, 0x69, 0x6c, 0x74, 0x65, - 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x46, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x22, - 0x26, 0x0a, 0x0c, 0x52, 0x65, 0x70, 0x6c, 0x79, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x12, - 0x16, 0x0a, 0x06, 0x52, 0x65, 0x74, 0x76, 0x61, 0x6c, 0x18, 0x01, 0x20, 0x01, 0x28, 0x05, 0x52, - 0x06, 0x52, 0x65, 0x74, 0x76, 0x61, 0x6c, 0x32, 0xef, 0x01, 0x0a, 0x0a, 0x4c, 0x6f, 0x67, 0x53, - 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x39, 0x0a, 0x0b, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, - 0x43, 0x68, 0x65, 0x63, 0x6b, 0x12, 0x14, 0x2e, 0x66, 0x65, 0x65, 0x64, 0x65, 0x72, 0x2e, 0x4e, - 0x6f, 0x6e, 0x63, 0x65, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x1a, 0x14, 0x2e, 0x66, 0x65, - 0x65, 0x64, 0x65, 0x72, 0x2e, 0x52, 0x65, 0x70, 0x6c, 0x79, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, - 0x65, 0x12, 0x3a, 0x0a, 0x0d, 0x57, 0x61, 0x74, 0x63, 0x68, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, - 0x65, 0x73, 0x12, 0x16, 0x2e, 0x66, 0x65, 0x65, 0x64, 0x65, 0x72, 0x2e, 0x52, 0x65, 0x71, 0x75, - 0x65, 0x73, 0x74, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x1a, 0x0f, 0x2e, 0x66, 0x65, 0x65, - 0x64, 0x65, 0x72, 0x2e, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x30, 0x01, 0x12, 0x36, 0x0a, - 0x0b, 0x57, 0x61, 0x74, 0x63, 0x68, 0x41, 0x6c, 0x65, 0x72, 0x74, 0x73, 0x12, 0x16, 0x2e, 0x66, - 0x65, 0x65, 0x64, 0x65, 0x72, 0x2e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x4d, 0x65, 0x73, - 0x73, 0x61, 0x67, 0x65, 0x1a, 0x0d, 0x2e, 0x66, 0x65, 0x65, 0x64, 0x65, 0x72, 0x2e, 0x41, 0x6c, - 0x65, 0x72, 0x74, 0x30, 0x01, 0x12, 0x32, 0x0a, 0x09, 0x57, 0x61, 0x74, 0x63, 0x68, 0x4c, 0x6f, - 0x67, 0x73, 0x12, 0x16, 0x2e, 0x66, 0x65, 0x65, 0x64, 0x65, 0x72, 0x2e, 0x52, 0x65, 0x71, 0x75, - 0x65, 0x73, 0x74, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x1a, 0x0b, 0x2e, 0x66, 0x65, 0x65, - 0x64, 0x65, 0x72, 0x2e, 0x4c, 0x6f, 0x67, 0x30, 0x01, 0x42, 0x29, 0x5a, 0x27, 0x67, 0x69, 0x74, - 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x6b, 0x75, 0x62, 0x65, 0x61, 0x72, 0x6d, 0x6f, - 0x72, 0x2f, 0x4b, 0x75, 0x62, 0x65, 0x41, 0x72, 0x6d, 0x6f, 0x72, 0x2f, 0x70, 0x72, 0x6f, 0x74, - 0x6f, 0x62, 0x75, 0x66, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, + 0x1b, 0x20, 0x01, 0x28, 0x05, 0x52, 0x08, 0x48, 0x6f, 0x73, 0x74, 0x50, 0x50, 0x49, 0x44, 0x12, + 0x1a, 0x0a, 0x08, 0x45, 0x6e, 0x66, 0x6f, 0x72, 0x63, 0x65, 0x72, 0x18, 0x1c, 0x20, 0x01, 0x28, + 0x09, 0x52, 0x08, 0x45, 0x6e, 0x66, 0x6f, 0x72, 0x63, 0x65, 0x72, 0x22, 0x83, 0x05, 0x0a, 0x03, + 0x4c, 0x6f, 0x67, 0x12, 0x1c, 0x0a, 0x09, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, + 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x09, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, + 0x70, 0x12, 0x20, 0x0a, 0x0b, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x64, 0x54, 0x69, 0x6d, 0x65, + 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x64, 0x54, + 0x69, 0x6d, 0x65, 0x12, 0x20, 0x0a, 0x0b, 0x43, 0x6c, 0x75, 0x73, 0x74, 0x65, 0x72, 0x4e, 0x61, + 0x6d, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x43, 0x6c, 0x75, 0x73, 0x74, 0x65, + 0x72, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x1a, 0x0a, 0x08, 0x48, 0x6f, 0x73, 0x74, 0x4e, 0x61, 0x6d, + 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x48, 0x6f, 0x73, 0x74, 0x4e, 0x61, 0x6d, + 0x65, 0x12, 0x24, 0x0a, 0x0d, 0x4e, 0x61, 0x6d, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x4e, 0x61, + 0x6d, 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0d, 0x4e, 0x61, 0x6d, 0x65, 0x73, 0x70, + 0x61, 0x63, 0x65, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x50, 0x6f, 0x64, 0x4e, 0x61, + 0x6d, 0x65, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x50, 0x6f, 0x64, 0x4e, 0x61, 0x6d, + 0x65, 0x12, 0x20, 0x0a, 0x0b, 0x43, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x49, 0x44, + 0x18, 0x07, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x43, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, + 0x72, 0x49, 0x44, 0x12, 0x24, 0x0a, 0x0d, 0x43, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, + 0x4e, 0x61, 0x6d, 0x65, 0x18, 0x08, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0d, 0x43, 0x6f, 0x6e, 0x74, + 0x61, 0x69, 0x6e, 0x65, 0x72, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x48, 0x6f, 0x73, + 0x74, 0x50, 0x49, 0x44, 0x18, 0x09, 0x20, 0x01, 0x28, 0x05, 0x52, 0x07, 0x48, 0x6f, 0x73, 0x74, + 0x50, 0x49, 0x44, 0x12, 0x12, 0x0a, 0x04, 0x50, 0x50, 0x49, 0x44, 0x18, 0x0a, 0x20, 0x01, 0x28, + 0x05, 0x52, 0x04, 0x50, 0x50, 0x49, 0x44, 0x12, 0x10, 0x0a, 0x03, 0x50, 0x49, 0x44, 0x18, 0x0b, + 0x20, 0x01, 0x28, 0x05, 0x52, 0x03, 0x50, 0x49, 0x44, 0x12, 0x10, 0x0a, 0x03, 0x55, 0x49, 0x44, + 0x18, 0x0c, 0x20, 0x01, 0x28, 0x05, 0x52, 0x03, 0x55, 0x49, 0x44, 0x12, 0x12, 0x0a, 0x04, 0x54, + 0x79, 0x70, 0x65, 0x18, 0x0d, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x54, 0x79, 0x70, 0x65, 0x12, + 0x16, 0x0a, 0x06, 0x53, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x18, 0x0e, 0x20, 0x01, 0x28, 0x09, 0x52, + 0x06, 0x53, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x12, 0x1c, 0x0a, 0x09, 0x4f, 0x70, 0x65, 0x72, 0x61, + 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x0f, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x4f, 0x70, 0x65, 0x72, + 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x1a, 0x0a, 0x08, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, + 0x65, 0x18, 0x10, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, + 0x65, 0x12, 0x12, 0x0a, 0x04, 0x44, 0x61, 0x74, 0x61, 0x18, 0x11, 0x20, 0x01, 0x28, 0x09, 0x52, + 0x04, 0x44, 0x61, 0x74, 0x61, 0x12, 0x16, 0x0a, 0x06, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x18, + 0x12, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x12, 0x26, 0x0a, + 0x0e, 0x43, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x49, 0x6d, 0x61, 0x67, 0x65, 0x18, + 0x13, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0e, 0x43, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, + 0x49, 0x6d, 0x61, 0x67, 0x65, 0x12, 0x2c, 0x0a, 0x11, 0x50, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x50, + 0x72, 0x6f, 0x63, 0x65, 0x73, 0x73, 0x4e, 0x61, 0x6d, 0x65, 0x18, 0x14, 0x20, 0x01, 0x28, 0x09, + 0x52, 0x11, 0x50, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x50, 0x72, 0x6f, 0x63, 0x65, 0x73, 0x73, 0x4e, + 0x61, 0x6d, 0x65, 0x12, 0x20, 0x0a, 0x0b, 0x50, 0x72, 0x6f, 0x63, 0x65, 0x73, 0x73, 0x4e, 0x61, + 0x6d, 0x65, 0x18, 0x15, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x50, 0x72, 0x6f, 0x63, 0x65, 0x73, + 0x73, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x1a, 0x0a, 0x08, 0x48, 0x6f, 0x73, 0x74, 0x50, 0x50, 0x49, + 0x44, 0x18, 0x16, 0x20, 0x01, 0x28, 0x05, 0x52, 0x08, 0x48, 0x6f, 0x73, 0x74, 0x50, 0x50, 0x49, + 0x44, 0x22, 0x28, 0x0a, 0x0e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x4d, 0x65, 0x73, 0x73, + 0x61, 0x67, 0x65, 0x12, 0x16, 0x0a, 0x06, 0x46, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x18, 0x01, 0x20, + 0x01, 0x28, 0x09, 0x52, 0x06, 0x46, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x22, 0x26, 0x0a, 0x0c, 0x52, + 0x65, 0x70, 0x6c, 0x79, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x12, 0x16, 0x0a, 0x06, 0x52, + 0x65, 0x74, 0x76, 0x61, 0x6c, 0x18, 0x01, 0x20, 0x01, 0x28, 0x05, 0x52, 0x06, 0x52, 0x65, 0x74, + 0x76, 0x61, 0x6c, 0x32, 0xef, 0x01, 0x0a, 0x0a, 0x4c, 0x6f, 0x67, 0x53, 0x65, 0x72, 0x76, 0x69, + 0x63, 0x65, 0x12, 0x39, 0x0a, 0x0b, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, + 0x6b, 0x12, 0x14, 0x2e, 0x66, 0x65, 0x65, 0x64, 0x65, 0x72, 0x2e, 0x4e, 0x6f, 0x6e, 0x63, 0x65, + 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x1a, 0x14, 0x2e, 0x66, 0x65, 0x65, 0x64, 0x65, 0x72, + 0x2e, 0x52, 0x65, 0x70, 0x6c, 0x79, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x12, 0x3a, 0x0a, + 0x0d, 0x57, 0x61, 0x74, 0x63, 0x68, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x73, 0x12, 0x16, + 0x2e, 0x66, 0x65, 0x65, 0x64, 0x65, 0x72, 0x2e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x4d, + 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x1a, 0x0f, 0x2e, 0x66, 0x65, 0x65, 0x64, 0x65, 0x72, 0x2e, + 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x30, 0x01, 0x12, 0x36, 0x0a, 0x0b, 0x57, 0x61, 0x74, + 0x63, 0x68, 0x41, 0x6c, 0x65, 0x72, 0x74, 0x73, 0x12, 0x16, 0x2e, 0x66, 0x65, 0x65, 0x64, 0x65, + 0x72, 0x2e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, + 0x1a, 0x0d, 0x2e, 0x66, 0x65, 0x65, 0x64, 0x65, 0x72, 0x2e, 0x41, 0x6c, 0x65, 0x72, 0x74, 0x30, + 0x01, 0x12, 0x32, 0x0a, 0x09, 0x57, 0x61, 0x74, 0x63, 0x68, 0x4c, 0x6f, 0x67, 0x73, 0x12, 0x16, + 0x2e, 0x66, 0x65, 0x65, 0x64, 0x65, 0x72, 0x2e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x4d, + 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x1a, 0x0b, 0x2e, 0x66, 0x65, 0x65, 0x64, 0x65, 0x72, 0x2e, + 0x4c, 0x6f, 0x67, 0x30, 0x01, 0x42, 0x29, 0x5a, 0x27, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, + 0x63, 0x6f, 0x6d, 0x2f, 0x6b, 0x75, 0x62, 0x65, 0x61, 0x72, 0x6d, 0x6f, 0x72, 0x2f, 0x4b, 0x75, + 0x62, 0x65, 0x41, 0x72, 0x6d, 0x6f, 0x72, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, + 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( @@ -1015,273 +1021,3 @@ func file_kubearmor_proto_init() { file_kubearmor_proto_goTypes = nil file_kubearmor_proto_depIdxs = nil } - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConnInterface - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion6 - -// LogServiceClient is the client API for LogService service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type LogServiceClient interface { - HealthCheck(ctx context.Context, in *NonceMessage, opts ...grpc.CallOption) (*ReplyMessage, error) - WatchMessages(ctx context.Context, in *RequestMessage, opts ...grpc.CallOption) (LogService_WatchMessagesClient, error) - WatchAlerts(ctx context.Context, in *RequestMessage, opts ...grpc.CallOption) (LogService_WatchAlertsClient, error) - WatchLogs(ctx context.Context, in *RequestMessage, opts ...grpc.CallOption) (LogService_WatchLogsClient, error) -} - -type logServiceClient struct { - cc grpc.ClientConnInterface -} - -func NewLogServiceClient(cc grpc.ClientConnInterface) LogServiceClient { - return &logServiceClient{cc} -} - -func (c *logServiceClient) HealthCheck(ctx context.Context, in *NonceMessage, opts ...grpc.CallOption) (*ReplyMessage, error) { - out := new(ReplyMessage) - err := c.cc.Invoke(ctx, "/feeder.LogService/HealthCheck", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *logServiceClient) WatchMessages(ctx context.Context, in *RequestMessage, opts ...grpc.CallOption) (LogService_WatchMessagesClient, error) { - stream, err := c.cc.NewStream(ctx, &_LogService_serviceDesc.Streams[0], "/feeder.LogService/WatchMessages", opts...) - if err != nil { - return nil, err - } - x := &logServiceWatchMessagesClient{stream} - if err := x.ClientStream.SendMsg(in); err != nil { - return nil, err - } - if err := x.ClientStream.CloseSend(); err != nil { - return nil, err - } - return x, nil -} - -type LogService_WatchMessagesClient interface { - Recv() (*Message, error) - grpc.ClientStream -} - -type logServiceWatchMessagesClient struct { - grpc.ClientStream -} - -func (x *logServiceWatchMessagesClient) Recv() (*Message, error) { - m := new(Message) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func (c *logServiceClient) WatchAlerts(ctx context.Context, in *RequestMessage, opts ...grpc.CallOption) (LogService_WatchAlertsClient, error) { - stream, err := c.cc.NewStream(ctx, &_LogService_serviceDesc.Streams[1], "/feeder.LogService/WatchAlerts", opts...) - if err != nil { - return nil, err - } - x := &logServiceWatchAlertsClient{stream} - if err := x.ClientStream.SendMsg(in); err != nil { - return nil, err - } - if err := x.ClientStream.CloseSend(); err != nil { - return nil, err - } - return x, nil -} - -type LogService_WatchAlertsClient interface { - Recv() (*Alert, error) - grpc.ClientStream -} - -type logServiceWatchAlertsClient struct { - grpc.ClientStream -} - -func (x *logServiceWatchAlertsClient) Recv() (*Alert, error) { - m := new(Alert) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func (c *logServiceClient) WatchLogs(ctx context.Context, in *RequestMessage, opts ...grpc.CallOption) (LogService_WatchLogsClient, error) { - stream, err := c.cc.NewStream(ctx, &_LogService_serviceDesc.Streams[2], "/feeder.LogService/WatchLogs", opts...) - if err != nil { - return nil, err - } - x := &logServiceWatchLogsClient{stream} - if err := x.ClientStream.SendMsg(in); err != nil { - return nil, err - } - if err := x.ClientStream.CloseSend(); err != nil { - return nil, err - } - return x, nil -} - -type LogService_WatchLogsClient interface { - Recv() (*Log, error) - grpc.ClientStream -} - -type logServiceWatchLogsClient struct { - grpc.ClientStream -} - -func (x *logServiceWatchLogsClient) Recv() (*Log, error) { - m := new(Log) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -// LogServiceServer is the server API for LogService service. -type LogServiceServer interface { - HealthCheck(context.Context, *NonceMessage) (*ReplyMessage, error) - WatchMessages(*RequestMessage, LogService_WatchMessagesServer) error - WatchAlerts(*RequestMessage, LogService_WatchAlertsServer) error - WatchLogs(*RequestMessage, LogService_WatchLogsServer) error -} - -// UnimplementedLogServiceServer can be embedded to have forward compatible implementations. -type UnimplementedLogServiceServer struct { -} - -func (*UnimplementedLogServiceServer) HealthCheck(context.Context, *NonceMessage) (*ReplyMessage, error) { - return nil, status.Errorf(codes.Unimplemented, "method HealthCheck not implemented") -} -func (*UnimplementedLogServiceServer) WatchMessages(*RequestMessage, LogService_WatchMessagesServer) error { - return status.Errorf(codes.Unimplemented, "method WatchMessages not implemented") -} -func (*UnimplementedLogServiceServer) WatchAlerts(*RequestMessage, LogService_WatchAlertsServer) error { - return status.Errorf(codes.Unimplemented, "method WatchAlerts not implemented") -} -func (*UnimplementedLogServiceServer) WatchLogs(*RequestMessage, LogService_WatchLogsServer) error { - return status.Errorf(codes.Unimplemented, "method WatchLogs not implemented") -} - -func RegisterLogServiceServer(s *grpc.Server, srv LogServiceServer) { - s.RegisterService(&_LogService_serviceDesc, srv) -} - -func _LogService_HealthCheck_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(NonceMessage) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(LogServiceServer).HealthCheck(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/feeder.LogService/HealthCheck", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(LogServiceServer).HealthCheck(ctx, req.(*NonceMessage)) - } - return interceptor(ctx, in, info, handler) -} - -func _LogService_WatchMessages_Handler(srv interface{}, stream grpc.ServerStream) error { - m := new(RequestMessage) - if err := stream.RecvMsg(m); err != nil { - return err - } - return srv.(LogServiceServer).WatchMessages(m, &logServiceWatchMessagesServer{stream}) -} - -type LogService_WatchMessagesServer interface { - Send(*Message) error - grpc.ServerStream -} - -type logServiceWatchMessagesServer struct { - grpc.ServerStream -} - -func (x *logServiceWatchMessagesServer) Send(m *Message) error { - return x.ServerStream.SendMsg(m) -} - -func _LogService_WatchAlerts_Handler(srv interface{}, stream grpc.ServerStream) error { - m := new(RequestMessage) - if err := stream.RecvMsg(m); err != nil { - return err - } - return srv.(LogServiceServer).WatchAlerts(m, &logServiceWatchAlertsServer{stream}) -} - -type LogService_WatchAlertsServer interface { - Send(*Alert) error - grpc.ServerStream -} - -type logServiceWatchAlertsServer struct { - grpc.ServerStream -} - -func (x *logServiceWatchAlertsServer) Send(m *Alert) error { - return x.ServerStream.SendMsg(m) -} - -func _LogService_WatchLogs_Handler(srv interface{}, stream grpc.ServerStream) error { - m := new(RequestMessage) - if err := stream.RecvMsg(m); err != nil { - return err - } - return srv.(LogServiceServer).WatchLogs(m, &logServiceWatchLogsServer{stream}) -} - -type LogService_WatchLogsServer interface { - Send(*Log) error - grpc.ServerStream -} - -type logServiceWatchLogsServer struct { - grpc.ServerStream -} - -func (x *logServiceWatchLogsServer) Send(m *Log) error { - return x.ServerStream.SendMsg(m) -} - -var _LogService_serviceDesc = grpc.ServiceDesc{ - ServiceName: "feeder.LogService", - HandlerType: (*LogServiceServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "HealthCheck", - Handler: _LogService_HealthCheck_Handler, - }, - }, - Streams: []grpc.StreamDesc{ - { - StreamName: "WatchMessages", - Handler: _LogService_WatchMessages_Handler, - ServerStreams: true, - }, - { - StreamName: "WatchAlerts", - Handler: _LogService_WatchAlerts_Handler, - ServerStreams: true, - }, - { - StreamName: "WatchLogs", - Handler: _LogService_WatchLogs_Handler, - ServerStreams: true, - }, - }, - Metadata: "kubearmor.proto", -} diff --git a/protobuf/kubearmor.proto b/protobuf/kubearmor.proto index c8593a2ba7..494b2420eb 100644 --- a/protobuf/kubearmor.proto +++ b/protobuf/kubearmor.proto @@ -64,6 +64,8 @@ message Alert { string ProcessName = 26; int32 HostPPID = 27; + + string Enforcer = 28; } // log struct diff --git a/protobuf/kubearmor_grpc.pb.go b/protobuf/kubearmor_grpc.pb.go new file mode 100644 index 0000000000..84acf9eb85 --- /dev/null +++ b/protobuf/kubearmor_grpc.pb.go @@ -0,0 +1,293 @@ +// Code generated by protoc-gen-go-grpc. DO NOT EDIT. +// versions: +// - protoc-gen-go-grpc v1.2.0 +// - protoc v3.19.4 +// source: kubearmor.proto + +package protobuf + +import ( + context "context" + grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" +) + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +// Requires gRPC-Go v1.32.0 or later. +const _ = grpc.SupportPackageIsVersion7 + +// LogServiceClient is the client API for LogService service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. +type LogServiceClient interface { + HealthCheck(ctx context.Context, in *NonceMessage, opts ...grpc.CallOption) (*ReplyMessage, error) + WatchMessages(ctx context.Context, in *RequestMessage, opts ...grpc.CallOption) (LogService_WatchMessagesClient, error) + WatchAlerts(ctx context.Context, in *RequestMessage, opts ...grpc.CallOption) (LogService_WatchAlertsClient, error) + WatchLogs(ctx context.Context, in *RequestMessage, opts ...grpc.CallOption) (LogService_WatchLogsClient, error) +} + +type logServiceClient struct { + cc grpc.ClientConnInterface +} + +func NewLogServiceClient(cc grpc.ClientConnInterface) LogServiceClient { + return &logServiceClient{cc} +} + +func (c *logServiceClient) HealthCheck(ctx context.Context, in *NonceMessage, opts ...grpc.CallOption) (*ReplyMessage, error) { + out := new(ReplyMessage) + err := c.cc.Invoke(ctx, "/feeder.LogService/HealthCheck", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *logServiceClient) WatchMessages(ctx context.Context, in *RequestMessage, opts ...grpc.CallOption) (LogService_WatchMessagesClient, error) { + stream, err := c.cc.NewStream(ctx, &LogService_ServiceDesc.Streams[0], "/feeder.LogService/WatchMessages", opts...) + if err != nil { + return nil, err + } + x := &logServiceWatchMessagesClient{stream} + if err := x.ClientStream.SendMsg(in); err != nil { + return nil, err + } + if err := x.ClientStream.CloseSend(); err != nil { + return nil, err + } + return x, nil +} + +type LogService_WatchMessagesClient interface { + Recv() (*Message, error) + grpc.ClientStream +} + +type logServiceWatchMessagesClient struct { + grpc.ClientStream +} + +func (x *logServiceWatchMessagesClient) Recv() (*Message, error) { + m := new(Message) + if err := x.ClientStream.RecvMsg(m); err != nil { + return nil, err + } + return m, nil +} + +func (c *logServiceClient) WatchAlerts(ctx context.Context, in *RequestMessage, opts ...grpc.CallOption) (LogService_WatchAlertsClient, error) { + stream, err := c.cc.NewStream(ctx, &LogService_ServiceDesc.Streams[1], "/feeder.LogService/WatchAlerts", opts...) + if err != nil { + return nil, err + } + x := &logServiceWatchAlertsClient{stream} + if err := x.ClientStream.SendMsg(in); err != nil { + return nil, err + } + if err := x.ClientStream.CloseSend(); err != nil { + return nil, err + } + return x, nil +} + +type LogService_WatchAlertsClient interface { + Recv() (*Alert, error) + grpc.ClientStream +} + +type logServiceWatchAlertsClient struct { + grpc.ClientStream +} + +func (x *logServiceWatchAlertsClient) Recv() (*Alert, error) { + m := new(Alert) + if err := x.ClientStream.RecvMsg(m); err != nil { + return nil, err + } + return m, nil +} + +func (c *logServiceClient) WatchLogs(ctx context.Context, in *RequestMessage, opts ...grpc.CallOption) (LogService_WatchLogsClient, error) { + stream, err := c.cc.NewStream(ctx, &LogService_ServiceDesc.Streams[2], "/feeder.LogService/WatchLogs", opts...) + if err != nil { + return nil, err + } + x := &logServiceWatchLogsClient{stream} + if err := x.ClientStream.SendMsg(in); err != nil { + return nil, err + } + if err := x.ClientStream.CloseSend(); err != nil { + return nil, err + } + return x, nil +} + +type LogService_WatchLogsClient interface { + Recv() (*Log, error) + grpc.ClientStream +} + +type logServiceWatchLogsClient struct { + grpc.ClientStream +} + +func (x *logServiceWatchLogsClient) Recv() (*Log, error) { + m := new(Log) + if err := x.ClientStream.RecvMsg(m); err != nil { + return nil, err + } + return m, nil +} + +// LogServiceServer is the server API for LogService service. +// All implementations should embed UnimplementedLogServiceServer +// for forward compatibility +type LogServiceServer interface { + HealthCheck(context.Context, *NonceMessage) (*ReplyMessage, error) + WatchMessages(*RequestMessage, LogService_WatchMessagesServer) error + WatchAlerts(*RequestMessage, LogService_WatchAlertsServer) error + WatchLogs(*RequestMessage, LogService_WatchLogsServer) error +} + +// UnimplementedLogServiceServer should be embedded to have forward compatible implementations. +type UnimplementedLogServiceServer struct { +} + +func (UnimplementedLogServiceServer) HealthCheck(context.Context, *NonceMessage) (*ReplyMessage, error) { + return nil, status.Errorf(codes.Unimplemented, "method HealthCheck not implemented") +} +func (UnimplementedLogServiceServer) WatchMessages(*RequestMessage, LogService_WatchMessagesServer) error { + return status.Errorf(codes.Unimplemented, "method WatchMessages not implemented") +} +func (UnimplementedLogServiceServer) WatchAlerts(*RequestMessage, LogService_WatchAlertsServer) error { + return status.Errorf(codes.Unimplemented, "method WatchAlerts not implemented") +} +func (UnimplementedLogServiceServer) WatchLogs(*RequestMessage, LogService_WatchLogsServer) error { + return status.Errorf(codes.Unimplemented, "method WatchLogs not implemented") +} + +// UnsafeLogServiceServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to LogServiceServer will +// result in compilation errors. +type UnsafeLogServiceServer interface { + mustEmbedUnimplementedLogServiceServer() +} + +func RegisterLogServiceServer(s grpc.ServiceRegistrar, srv LogServiceServer) { + s.RegisterService(&LogService_ServiceDesc, srv) +} + +func _LogService_HealthCheck_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(NonceMessage) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(LogServiceServer).HealthCheck(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/feeder.LogService/HealthCheck", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(LogServiceServer).HealthCheck(ctx, req.(*NonceMessage)) + } + return interceptor(ctx, in, info, handler) +} + +func _LogService_WatchMessages_Handler(srv interface{}, stream grpc.ServerStream) error { + m := new(RequestMessage) + if err := stream.RecvMsg(m); err != nil { + return err + } + return srv.(LogServiceServer).WatchMessages(m, &logServiceWatchMessagesServer{stream}) +} + +type LogService_WatchMessagesServer interface { + Send(*Message) error + grpc.ServerStream +} + +type logServiceWatchMessagesServer struct { + grpc.ServerStream +} + +func (x *logServiceWatchMessagesServer) Send(m *Message) error { + return x.ServerStream.SendMsg(m) +} + +func _LogService_WatchAlerts_Handler(srv interface{}, stream grpc.ServerStream) error { + m := new(RequestMessage) + if err := stream.RecvMsg(m); err != nil { + return err + } + return srv.(LogServiceServer).WatchAlerts(m, &logServiceWatchAlertsServer{stream}) +} + +type LogService_WatchAlertsServer interface { + Send(*Alert) error + grpc.ServerStream +} + +type logServiceWatchAlertsServer struct { + grpc.ServerStream +} + +func (x *logServiceWatchAlertsServer) Send(m *Alert) error { + return x.ServerStream.SendMsg(m) +} + +func _LogService_WatchLogs_Handler(srv interface{}, stream grpc.ServerStream) error { + m := new(RequestMessage) + if err := stream.RecvMsg(m); err != nil { + return err + } + return srv.(LogServiceServer).WatchLogs(m, &logServiceWatchLogsServer{stream}) +} + +type LogService_WatchLogsServer interface { + Send(*Log) error + grpc.ServerStream +} + +type logServiceWatchLogsServer struct { + grpc.ServerStream +} + +func (x *logServiceWatchLogsServer) Send(m *Log) error { + return x.ServerStream.SendMsg(m) +} + +// LogService_ServiceDesc is the grpc.ServiceDesc for LogService service. +// It's only intended for direct use with grpc.RegisterService, +// and not to be introspected or modified (even as a copy) +var LogService_ServiceDesc = grpc.ServiceDesc{ + ServiceName: "feeder.LogService", + HandlerType: (*LogServiceServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "HealthCheck", + Handler: _LogService_HealthCheck_Handler, + }, + }, + Streams: []grpc.StreamDesc{ + { + StreamName: "WatchMessages", + Handler: _LogService_WatchMessages_Handler, + ServerStreams: true, + }, + { + StreamName: "WatchAlerts", + Handler: _LogService_WatchAlerts_Handler, + ServerStreams: true, + }, + { + StreamName: "WatchLogs", + Handler: _LogService_WatchLogs_Handler, + ServerStreams: true, + }, + }, + Metadata: "kubearmor.proto", +} diff --git a/protobuf/kvm.pb.go b/protobuf/kvm.pb.go index 10618960e5..82f3d71efe 100644 --- a/protobuf/kvm.pb.go +++ b/protobuf/kvm.pb.go @@ -1,16 +1,12 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.27.1 -// protoc v3.14.0 +// protoc v3.19.4 // source: kvm.proto package protobuf import ( - context "context" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" @@ -282,152 +278,3 @@ func file_kvm_proto_init() { file_kvm_proto_goTypes = nil file_kvm_proto_depIdxs = nil } - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConnInterface - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion6 - -// KVMClient is the client API for KVM service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type KVMClient interface { - RegisterAgentIdentity(ctx context.Context, in *AgentIdentity, opts ...grpc.CallOption) (*Status, error) - SendPolicy(ctx context.Context, opts ...grpc.CallOption) (KVM_SendPolicyClient, error) -} - -type kVMClient struct { - cc grpc.ClientConnInterface -} - -func NewKVMClient(cc grpc.ClientConnInterface) KVMClient { - return &kVMClient{cc} -} - -func (c *kVMClient) RegisterAgentIdentity(ctx context.Context, in *AgentIdentity, opts ...grpc.CallOption) (*Status, error) { - out := new(Status) - err := c.cc.Invoke(ctx, "/kvm.KVM/registerAgentIdentity", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *kVMClient) SendPolicy(ctx context.Context, opts ...grpc.CallOption) (KVM_SendPolicyClient, error) { - stream, err := c.cc.NewStream(ctx, &_KVM_serviceDesc.Streams[0], "/kvm.KVM/sendPolicy", opts...) - if err != nil { - return nil, err - } - x := &kVMSendPolicyClient{stream} - return x, nil -} - -type KVM_SendPolicyClient interface { - Send(*Status) error - Recv() (*PolicyData, error) - grpc.ClientStream -} - -type kVMSendPolicyClient struct { - grpc.ClientStream -} - -func (x *kVMSendPolicyClient) Send(m *Status) error { - return x.ClientStream.SendMsg(m) -} - -func (x *kVMSendPolicyClient) Recv() (*PolicyData, error) { - m := new(PolicyData) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -// KVMServer is the server API for KVM service. -type KVMServer interface { - RegisterAgentIdentity(context.Context, *AgentIdentity) (*Status, error) - SendPolicy(KVM_SendPolicyServer) error -} - -// UnimplementedKVMServer can be embedded to have forward compatible implementations. -type UnimplementedKVMServer struct { -} - -func (*UnimplementedKVMServer) RegisterAgentIdentity(context.Context, *AgentIdentity) (*Status, error) { - return nil, status.Errorf(codes.Unimplemented, "method RegisterAgentIdentity not implemented") -} -func (*UnimplementedKVMServer) SendPolicy(KVM_SendPolicyServer) error { - return status.Errorf(codes.Unimplemented, "method SendPolicy not implemented") -} - -func RegisterKVMServer(s *grpc.Server, srv KVMServer) { - s.RegisterService(&_KVM_serviceDesc, srv) -} - -func _KVM_RegisterAgentIdentity_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(AgentIdentity) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(KVMServer).RegisterAgentIdentity(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kvm.KVM/RegisterAgentIdentity", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(KVMServer).RegisterAgentIdentity(ctx, req.(*AgentIdentity)) - } - return interceptor(ctx, in, info, handler) -} - -func _KVM_SendPolicy_Handler(srv interface{}, stream grpc.ServerStream) error { - return srv.(KVMServer).SendPolicy(&kVMSendPolicyServer{stream}) -} - -type KVM_SendPolicyServer interface { - Send(*PolicyData) error - Recv() (*Status, error) - grpc.ServerStream -} - -type kVMSendPolicyServer struct { - grpc.ServerStream -} - -func (x *kVMSendPolicyServer) Send(m *PolicyData) error { - return x.ServerStream.SendMsg(m) -} - -func (x *kVMSendPolicyServer) Recv() (*Status, error) { - m := new(Status) - if err := x.ServerStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -var _KVM_serviceDesc = grpc.ServiceDesc{ - ServiceName: "kvm.KVM", - HandlerType: (*KVMServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "registerAgentIdentity", - Handler: _KVM_RegisterAgentIdentity_Handler, - }, - }, - Streams: []grpc.StreamDesc{ - { - StreamName: "sendPolicy", - Handler: _KVM_SendPolicy_Handler, - ServerStreams: true, - ClientStreams: true, - }, - }, - Metadata: "kvm.proto", -} diff --git a/protobuf/kvm_grpc.pb.go b/protobuf/kvm_grpc.pb.go new file mode 100644 index 0000000000..8e3e365f6c --- /dev/null +++ b/protobuf/kvm_grpc.pb.go @@ -0,0 +1,172 @@ +// Code generated by protoc-gen-go-grpc. DO NOT EDIT. +// versions: +// - protoc-gen-go-grpc v1.2.0 +// - protoc v3.19.4 +// source: kvm.proto + +package protobuf + +import ( + context "context" + grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" +) + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +// Requires gRPC-Go v1.32.0 or later. +const _ = grpc.SupportPackageIsVersion7 + +// KVMClient is the client API for KVM service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. +type KVMClient interface { + RegisterAgentIdentity(ctx context.Context, in *AgentIdentity, opts ...grpc.CallOption) (*Status, error) + SendPolicy(ctx context.Context, opts ...grpc.CallOption) (KVM_SendPolicyClient, error) +} + +type kVMClient struct { + cc grpc.ClientConnInterface +} + +func NewKVMClient(cc grpc.ClientConnInterface) KVMClient { + return &kVMClient{cc} +} + +func (c *kVMClient) RegisterAgentIdentity(ctx context.Context, in *AgentIdentity, opts ...grpc.CallOption) (*Status, error) { + out := new(Status) + err := c.cc.Invoke(ctx, "/kvm.KVM/registerAgentIdentity", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *kVMClient) SendPolicy(ctx context.Context, opts ...grpc.CallOption) (KVM_SendPolicyClient, error) { + stream, err := c.cc.NewStream(ctx, &KVM_ServiceDesc.Streams[0], "/kvm.KVM/sendPolicy", opts...) + if err != nil { + return nil, err + } + x := &kVMSendPolicyClient{stream} + return x, nil +} + +type KVM_SendPolicyClient interface { + Send(*Status) error + Recv() (*PolicyData, error) + grpc.ClientStream +} + +type kVMSendPolicyClient struct { + grpc.ClientStream +} + +func (x *kVMSendPolicyClient) Send(m *Status) error { + return x.ClientStream.SendMsg(m) +} + +func (x *kVMSendPolicyClient) Recv() (*PolicyData, error) { + m := new(PolicyData) + if err := x.ClientStream.RecvMsg(m); err != nil { + return nil, err + } + return m, nil +} + +// KVMServer is the server API for KVM service. +// All implementations should embed UnimplementedKVMServer +// for forward compatibility +type KVMServer interface { + RegisterAgentIdentity(context.Context, *AgentIdentity) (*Status, error) + SendPolicy(KVM_SendPolicyServer) error +} + +// UnimplementedKVMServer should be embedded to have forward compatible implementations. +type UnimplementedKVMServer struct { +} + +func (UnimplementedKVMServer) RegisterAgentIdentity(context.Context, *AgentIdentity) (*Status, error) { + return nil, status.Errorf(codes.Unimplemented, "method RegisterAgentIdentity not implemented") +} +func (UnimplementedKVMServer) SendPolicy(KVM_SendPolicyServer) error { + return status.Errorf(codes.Unimplemented, "method SendPolicy not implemented") +} + +// UnsafeKVMServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to KVMServer will +// result in compilation errors. +type UnsafeKVMServer interface { + mustEmbedUnimplementedKVMServer() +} + +func RegisterKVMServer(s grpc.ServiceRegistrar, srv KVMServer) { + s.RegisterService(&KVM_ServiceDesc, srv) +} + +func _KVM_RegisterAgentIdentity_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(AgentIdentity) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(KVMServer).RegisterAgentIdentity(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/kvm.KVM/registerAgentIdentity", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(KVMServer).RegisterAgentIdentity(ctx, req.(*AgentIdentity)) + } + return interceptor(ctx, in, info, handler) +} + +func _KVM_SendPolicy_Handler(srv interface{}, stream grpc.ServerStream) error { + return srv.(KVMServer).SendPolicy(&kVMSendPolicyServer{stream}) +} + +type KVM_SendPolicyServer interface { + Send(*PolicyData) error + Recv() (*Status, error) + grpc.ServerStream +} + +type kVMSendPolicyServer struct { + grpc.ServerStream +} + +func (x *kVMSendPolicyServer) Send(m *PolicyData) error { + return x.ServerStream.SendMsg(m) +} + +func (x *kVMSendPolicyServer) Recv() (*Status, error) { + m := new(Status) + if err := x.ServerStream.RecvMsg(m); err != nil { + return nil, err + } + return m, nil +} + +// KVM_ServiceDesc is the grpc.ServiceDesc for KVM service. +// It's only intended for direct use with grpc.RegisterService, +// and not to be introspected or modified (even as a copy) +var KVM_ServiceDesc = grpc.ServiceDesc{ + ServiceName: "kvm.KVM", + HandlerType: (*KVMServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "registerAgentIdentity", + Handler: _KVM_RegisterAgentIdentity_Handler, + }, + }, + Streams: []grpc.StreamDesc{ + { + StreamName: "sendPolicy", + Handler: _KVM_SendPolicy_Handler, + ServerStreams: true, + ClientStreams: true, + }, + }, + Metadata: "kvm.proto", +} diff --git a/protobuf/policy.pb.go b/protobuf/policy.pb.go index 9ff3738a40..7389efb899 100644 --- a/protobuf/policy.pb.go +++ b/protobuf/policy.pb.go @@ -1,16 +1,12 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.27.1 -// protoc v3.14.0 +// protoc v3.19.4 // source: policy.proto package protobuf import ( - context "context" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" @@ -213,83 +209,3 @@ func file_policy_proto_init() { file_policy_proto_goTypes = nil file_policy_proto_depIdxs = nil } - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConnInterface - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion6 - -// PolicyServiceClient is the client API for PolicyService service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type PolicyServiceClient interface { - HostPolicy(ctx context.Context, in *Policy, opts ...grpc.CallOption) (*Response, error) -} - -type policyServiceClient struct { - cc grpc.ClientConnInterface -} - -func NewPolicyServiceClient(cc grpc.ClientConnInterface) PolicyServiceClient { - return &policyServiceClient{cc} -} - -func (c *policyServiceClient) HostPolicy(ctx context.Context, in *Policy, opts ...grpc.CallOption) (*Response, error) { - out := new(Response) - err := c.cc.Invoke(ctx, "/policy.PolicyService/hostPolicy", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// PolicyServiceServer is the server API for PolicyService service. -type PolicyServiceServer interface { - HostPolicy(context.Context, *Policy) (*Response, error) -} - -// UnimplementedPolicyServiceServer can be embedded to have forward compatible implementations. -type UnimplementedPolicyServiceServer struct { -} - -func (*UnimplementedPolicyServiceServer) HostPolicy(context.Context, *Policy) (*Response, error) { - return nil, status.Errorf(codes.Unimplemented, "method HostPolicy not implemented") -} - -func RegisterPolicyServiceServer(s *grpc.Server, srv PolicyServiceServer) { - s.RegisterService(&_PolicyService_serviceDesc, srv) -} - -func _PolicyService_HostPolicy_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(Policy) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(PolicyServiceServer).HostPolicy(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/policy.PolicyService/HostPolicy", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(PolicyServiceServer).HostPolicy(ctx, req.(*Policy)) - } - return interceptor(ctx, in, info, handler) -} - -var _PolicyService_serviceDesc = grpc.ServiceDesc{ - ServiceName: "policy.PolicyService", - HandlerType: (*PolicyServiceServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "hostPolicy", - Handler: _PolicyService_HostPolicy_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "policy.proto", -} diff --git a/protobuf/policy_grpc.pb.go b/protobuf/policy_grpc.pb.go new file mode 100644 index 0000000000..f92fbc257e --- /dev/null +++ b/protobuf/policy_grpc.pb.go @@ -0,0 +1,103 @@ +// Code generated by protoc-gen-go-grpc. DO NOT EDIT. +// versions: +// - protoc-gen-go-grpc v1.2.0 +// - protoc v3.19.4 +// source: policy.proto + +package protobuf + +import ( + context "context" + grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" +) + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +// Requires gRPC-Go v1.32.0 or later. +const _ = grpc.SupportPackageIsVersion7 + +// PolicyServiceClient is the client API for PolicyService service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. +type PolicyServiceClient interface { + HostPolicy(ctx context.Context, in *Policy, opts ...grpc.CallOption) (*Response, error) +} + +type policyServiceClient struct { + cc grpc.ClientConnInterface +} + +func NewPolicyServiceClient(cc grpc.ClientConnInterface) PolicyServiceClient { + return &policyServiceClient{cc} +} + +func (c *policyServiceClient) HostPolicy(ctx context.Context, in *Policy, opts ...grpc.CallOption) (*Response, error) { + out := new(Response) + err := c.cc.Invoke(ctx, "/policy.PolicyService/hostPolicy", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +// PolicyServiceServer is the server API for PolicyService service. +// All implementations should embed UnimplementedPolicyServiceServer +// for forward compatibility +type PolicyServiceServer interface { + HostPolicy(context.Context, *Policy) (*Response, error) +} + +// UnimplementedPolicyServiceServer should be embedded to have forward compatible implementations. +type UnimplementedPolicyServiceServer struct { +} + +func (UnimplementedPolicyServiceServer) HostPolicy(context.Context, *Policy) (*Response, error) { + return nil, status.Errorf(codes.Unimplemented, "method HostPolicy not implemented") +} + +// UnsafePolicyServiceServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to PolicyServiceServer will +// result in compilation errors. +type UnsafePolicyServiceServer interface { + mustEmbedUnimplementedPolicyServiceServer() +} + +func RegisterPolicyServiceServer(s grpc.ServiceRegistrar, srv PolicyServiceServer) { + s.RegisterService(&PolicyService_ServiceDesc, srv) +} + +func _PolicyService_HostPolicy_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(Policy) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(PolicyServiceServer).HostPolicy(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/policy.PolicyService/hostPolicy", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(PolicyServiceServer).HostPolicy(ctx, req.(*Policy)) + } + return interceptor(ctx, in, info, handler) +} + +// PolicyService_ServiceDesc is the grpc.ServiceDesc for PolicyService service. +// It's only intended for direct use with grpc.RegisterService, +// and not to be introspected or modified (even as a copy) +var PolicyService_ServiceDesc = grpc.ServiceDesc{ + ServiceName: "policy.PolicyService", + HandlerType: (*PolicyServiceServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "hostPolicy", + Handler: _PolicyService_HostPolicy_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "policy.proto", +} From 24a304adef23ba2a4246d0df90a5261856416975 Mon Sep 17 00:00:00 2001 From: Jaehyun Nam Date: Mon, 11 Apr 2022 07:21:43 +0000 Subject: [PATCH 2/4] update test scenarios Signed-off-by: Jaehyun Nam --- tests/scenarios/github_test_01/cmd1 | 4 +- tests/scenarios/github_test_02/cmd1 | 2 +- tests/scenarios/github_test_02/cmd2 | 7 + ....yaml => ksp-ubuntu-1-proc-dir-audit.yaml} | 9 +- tests/scenarios/github_test_03/cmd2 | 7 + tests/scenarios/github_test_03/cmd3 | 7 + .../ksp-ubuntu-1-file-pattern-block.yaml | 2 +- tests/scenarios/github_test_04/cmd1 | 4 +- tests/scenarios/github_test_04/cmd2 | 6 +- ...ubuntu-1-file-path-block-from-source.yaml} | 8 +- tests/scenarios/github_test_05/cmd1 | 2 +- tests/scenarios/github_test_05/cmd2 | 4 +- ...tu-1-file-path-allow-from-source-path.yaml | 24 --- ...-ubuntu-1-file-path-allow-from-source.yaml | 18 ++ tests/scenarios/github_test_06/cmd1 | 2 +- tests/scenarios/github_test_06/cmd3 | 2 +- ...untu-1-file-path-owner-readonly-allow.yaml | 16 +- tests/scenarios/github_test_07/cmd3 | 2 +- tests/scenarios/github_test_07/cmd4 | 2 +- ...le-dir-recursive-owner-readonly-block.yaml | 8 +- tests/scenarios/github_test_08/cmd3 | 2 +- tests/scenarios/github_test_08/cmd4 | 2 +- tests/scenarios/github_test_08/cmd5 | 2 +- tests/scenarios/github_test_08/cmd6 | 2 +- ...u-1-file-pattern-owner-readonly-block.yaml | 8 +- tests/scenarios/github_test_11/cmd1 | 2 +- tests/scenarios/github_test_11/cmd2 | 2 +- ...nsp-ubuntu-1-file-dir-recursive-block.yaml | 2 +- tests/scenarios/github_test_12/cmd3 | 4 +- ...sp-ubuntu-1-net-tcp-from-source-allow.yaml | 19 +- tests/test-scenarios-github.sh | 172 ++++++++-------- tests/test-scenarios-in-runtime.sh | 194 +++++++++--------- tests/test-scenarios-local.sh | 170 +++++++-------- 33 files changed, 375 insertions(+), 342 deletions(-) create mode 100644 tests/scenarios/github_test_02/cmd2 rename tests/scenarios/github_test_02/{ksp-ubuntu-1-proc-dir-allow.yaml => ksp-ubuntu-1-proc-dir-audit.yaml} (52%) create mode 100644 tests/scenarios/github_test_03/cmd2 create mode 100644 tests/scenarios/github_test_03/cmd3 rename tests/scenarios/github_test_04/{ksp-ubuntu-1-file-path-block-from-source-path.yaml => ksp-ubuntu-1-file-path-block-from-source.yaml} (57%) delete mode 100644 tests/scenarios/github_test_05/ksp-ubuntu-1-file-path-allow-from-source-path.yaml create mode 100644 tests/scenarios/github_test_05/ksp-ubuntu-1-file-path-allow-from-source.yaml diff --git a/tests/scenarios/github_test_01/cmd1 b/tests/scenarios/github_test_01/cmd1 index 4ae4de37a0..11bb54bf98 100644 --- a/tests/scenarios/github_test_01/cmd1 +++ b/tests/scenarios/github_test_01/cmd1 @@ -1,7 +1,7 @@ source: ubuntu-1-deployment -cmd: dash -c "sleep 1" +cmd: dash -c "uname -r" result: passed --- operation: Process -condition: sleep +condition: uname action: Block diff --git a/tests/scenarios/github_test_02/cmd1 b/tests/scenarios/github_test_02/cmd1 index e27b018afa..bc439bbf90 100644 --- a/tests/scenarios/github_test_02/cmd1 +++ b/tests/scenarios/github_test_02/cmd1 @@ -3,5 +3,5 @@ cmd: cat /credentials/password result: passed --- operation: File -condition: password +condition: /credentials/password action: Audit diff --git a/tests/scenarios/github_test_02/cmd2 b/tests/scenarios/github_test_02/cmd2 new file mode 100644 index 0000000000..6800886623 --- /dev/null +++ b/tests/scenarios/github_test_02/cmd2 @@ -0,0 +1,7 @@ +source: ubuntu-1-deployment +cmd: cat /credentials/keys/priv.key +result: passed +--- +operation: File +condition: /credentials/keys/priv.key +action: Audit diff --git a/tests/scenarios/github_test_02/ksp-ubuntu-1-proc-dir-allow.yaml b/tests/scenarios/github_test_02/ksp-ubuntu-1-proc-dir-audit.yaml similarity index 52% rename from tests/scenarios/github_test_02/ksp-ubuntu-1-proc-dir-allow.yaml rename to tests/scenarios/github_test_02/ksp-ubuntu-1-proc-dir-audit.yaml index 868be80de6..e0bfd01d01 100644 --- a/tests/scenarios/github_test_02/ksp-ubuntu-1-proc-dir-allow.yaml +++ b/tests/scenarios/github_test_02/ksp-ubuntu-1-proc-dir-audit.yaml @@ -1,20 +1,17 @@ apiVersion: security.kubearmor.com/v1 kind: KubeArmorPolicy metadata: - name: ksp-ubuntu-1-proc-dir-allow + name: ksp-ubuntu-1-proc-dir-audit namespace: github spec: severity: 5 - message: "allow credentials only" + message: "audit credentials" selector: matchLabels: container: ubuntu-1 - process: - matchDirectories: - - dir: /bin/ file: matchDirectories: - - dir: /credentials/ # allow accessing the files in this directory; otherwise, deny all + - dir: /credentials/ recursive: true action: Audit diff --git a/tests/scenarios/github_test_03/cmd2 b/tests/scenarios/github_test_03/cmd2 new file mode 100644 index 0000000000..0ebfd09436 --- /dev/null +++ b/tests/scenarios/github_test_03/cmd2 @@ -0,0 +1,7 @@ +source: ubuntu-1-deployment +cmd: cat /etc/gshadow +result: failed +--- +operation: File +condition: /etc/gshadow +action: Block diff --git a/tests/scenarios/github_test_03/cmd3 b/tests/scenarios/github_test_03/cmd3 new file mode 100644 index 0000000000..2b533505d0 --- /dev/null +++ b/tests/scenarios/github_test_03/cmd3 @@ -0,0 +1,7 @@ +source: ubuntu-1-deployment +cmd: cat /etc/hostname +result: passed +--- +operation: File +condition: /etc/hostname +action: Block diff --git a/tests/scenarios/github_test_03/ksp-ubuntu-1-file-pattern-block.yaml b/tests/scenarios/github_test_03/ksp-ubuntu-1-file-pattern-block.yaml index db3aace7ea..6d5e46cd51 100644 --- a/tests/scenarios/github_test_03/ksp-ubuntu-1-file-pattern-block.yaml +++ b/tests/scenarios/github_test_03/ksp-ubuntu-1-file-pattern-block.yaml @@ -11,6 +11,6 @@ spec: container: ubuntu-1 file: matchPatterns: - - pattern: /etc/*hado? # try open /etc/shadow or /etc/gshadow (permission denied) + - pattern: /etc/*hado? action: Block diff --git a/tests/scenarios/github_test_04/cmd1 b/tests/scenarios/github_test_04/cmd1 index 8289eaa85b..f9cef439d4 100644 --- a/tests/scenarios/github_test_04/cmd1 +++ b/tests/scenarios/github_test_04/cmd1 @@ -1,6 +1,6 @@ source: ubuntu-1-deployment -cmd: head /secret.txt -result: passed +cmd: cat /secret.txt +result: failed --- operation: File condition: /secret.txt diff --git a/tests/scenarios/github_test_04/cmd2 b/tests/scenarios/github_test_04/cmd2 index c0f2086c56..2b533505d0 100644 --- a/tests/scenarios/github_test_04/cmd2 +++ b/tests/scenarios/github_test_04/cmd2 @@ -1,7 +1,7 @@ source: ubuntu-1-deployment -cmd: cat /secret.txt -result: failed +cmd: cat /etc/hostname +result: passed --- operation: File -condition: /secret.txt +condition: /etc/hostname action: Block diff --git a/tests/scenarios/github_test_04/ksp-ubuntu-1-file-path-block-from-source-path.yaml b/tests/scenarios/github_test_04/ksp-ubuntu-1-file-path-block-from-source.yaml similarity index 57% rename from tests/scenarios/github_test_04/ksp-ubuntu-1-file-path-block-from-source-path.yaml rename to tests/scenarios/github_test_04/ksp-ubuntu-1-file-path-block-from-source.yaml index 8e0a738bbf..1e0d8bd93c 100644 --- a/tests/scenarios/github_test_04/ksp-ubuntu-1-file-path-block-from-source-path.yaml +++ b/tests/scenarios/github_test_04/ksp-ubuntu-1-file-path-block-from-source.yaml @@ -1,7 +1,7 @@ apiVersion: security.kubearmor.com/v1 kind: KubeArmorPolicy metadata: - name: ksp-ubutnu-1-file-path-block-from-source-path + name: ksp-ubutnu-1-file-path-block-from-source namespace: github spec: severity: 5 @@ -11,8 +11,8 @@ spec: container: ubuntu-1 file: matchPaths: - - path: /secret.txt # /bin/cat /secret.txt (permission denied) - fromSource: # head /secret.txt (success) - - path: /bin/cat # + - path: /secret.txt + fromSource: + - path: /bin/cat action: Block diff --git a/tests/scenarios/github_test_05/cmd1 b/tests/scenarios/github_test_05/cmd1 index 537270361f..332818e976 100644 --- a/tests/scenarios/github_test_05/cmd1 +++ b/tests/scenarios/github_test_05/cmd1 @@ -1,5 +1,5 @@ source: ubuntu-1-deployment -cmd: /bin/cat /secret.txt +cmd: cat /secret.txt result: passed --- operation: File diff --git a/tests/scenarios/github_test_05/cmd2 b/tests/scenarios/github_test_05/cmd2 index b404fcde73..2a35604c67 100644 --- a/tests/scenarios/github_test_05/cmd2 +++ b/tests/scenarios/github_test_05/cmd2 @@ -1,7 +1,7 @@ source: ubuntu-1-deployment -cmd: head /secret.txt +cmd: cat /etc/hosts result: failed --- operation: File -condition: /secret.txt +condition: /etc/hosts action: Allow diff --git a/tests/scenarios/github_test_05/ksp-ubuntu-1-file-path-allow-from-source-path.yaml b/tests/scenarios/github_test_05/ksp-ubuntu-1-file-path-allow-from-source-path.yaml deleted file mode 100644 index 66542ebdc2..0000000000 --- a/tests/scenarios/github_test_05/ksp-ubuntu-1-file-path-allow-from-source-path.yaml +++ /dev/null @@ -1,24 +0,0 @@ -apiVersion: security.kubearmor.com/v1 -kind: KubeArmorPolicy -metadata: - name: ksp-ubuntu-1-file-path-allow-from-source-path - namespace: github -spec: - severity: 5 - message: "allow /bin/cat to access /secret.txt" - selector: - matchLabels: - container: ubuntu-1 - process: # base bin rules - matchDirectories: - - dir: /bin/ - recursive: true - - dir: /usr/bin/ - recursive: true - file: - matchPaths: - - path: /secret.txt # /bin/cat /secret.txt (success) - fromSource: # /bin/cat /etc/hosts (permission denied) - - path: /bin/cat # /bin/head /secret.txt (permission denied) - action: - Allow diff --git a/tests/scenarios/github_test_05/ksp-ubuntu-1-file-path-allow-from-source.yaml b/tests/scenarios/github_test_05/ksp-ubuntu-1-file-path-allow-from-source.yaml new file mode 100644 index 0000000000..0ca46b42b9 --- /dev/null +++ b/tests/scenarios/github_test_05/ksp-ubuntu-1-file-path-allow-from-source.yaml @@ -0,0 +1,18 @@ +apiVersion: security.kubearmor.com/v1 +kind: KubeArmorPolicy +metadata: + name: ksp-ubuntu-1-file-path-allow-from-source + namespace: github +spec: + severity: 5 + message: "allow /bin/cat to access /secret.txt" + selector: + matchLabels: + container: ubuntu-1 + file: + matchPaths: + - path: /secret.txt + fromSource: + - path: /bin/cat + action: + Allow diff --git a/tests/scenarios/github_test_06/cmd1 b/tests/scenarios/github_test_06/cmd1 index baaa14e9ac..4f3d227bd8 100644 --- a/tests/scenarios/github_test_06/cmd1 +++ b/tests/scenarios/github_test_06/cmd1 @@ -1,5 +1,5 @@ source: ubuntu-1-deployment -cmd: su - user1 -c "/bin/cat /home/user1/secret_data1.txt" +cmd: su - user1 -c "cat /home/user1/secret_data1.txt" result: passed --- operation: File diff --git a/tests/scenarios/github_test_06/cmd3 b/tests/scenarios/github_test_06/cmd3 index d3a0657a02..51b4e54f48 100644 --- a/tests/scenarios/github_test_06/cmd3 +++ b/tests/scenarios/github_test_06/cmd3 @@ -1,5 +1,5 @@ source: ubuntu-1-deployment -cmd: /bin/cat /home/user1/secret_data1.txt +cmd: cat /home/user1/secret_data1.txt result: failed --- operation: File diff --git a/tests/scenarios/github_test_06/ksp-ubuntu-1-file-path-owner-readonly-allow.yaml b/tests/scenarios/github_test_06/ksp-ubuntu-1-file-path-owner-readonly-allow.yaml index 424de641b1..073a13b683 100644 --- a/tests/scenarios/github_test_06/ksp-ubuntu-1-file-path-owner-readonly-allow.yaml +++ b/tests/scenarios/github_test_06/ksp-ubuntu-1-file-path-owner-readonly-allow.yaml @@ -11,29 +11,27 @@ spec: selector: matchLabels: container: ubuntu-1 - process: # base whitelisting rules + process: matchDirectories: - - dir: /bin/ # required to change root to user1 / try 'su - user1' + - dir: /bin/ # required to change root to user1 recursive: true - dir: /usr/bin/ # used in changing accounts recursive: true file: matchPaths: - - path: /dev/tty - readOnly: false - path: /home/user1/secret_data1.txt - readOnly: true # su - user1 -c /bin/cat /home/user1/secret_data1.txt (success) - ownerOnly: true # su - user1 -c echo "test" >> /home/user1/secret_data1.txt (permission denied) - - path: /run/utmp # required to change root to user1 + readOnly: true + ownerOnly: true - path: /root/.bashrc # used by root + - path: /root/.bash_history # used by root - path: /home/user1/.profile # used by user1 - path: /home/user1/.bashrc # used by user1 + - path: /run/utmp # required to change root to user1 + - path: /dev/tty matchDirectories: - dir: /etc/ # required to change root to user1 (coarse-grained way) recursive: true - dir: /proc/ # required to change root to user1 (coarse-grained way) recursive: true - - dir: /dev/pts/ - recursive: true action: Allow diff --git a/tests/scenarios/github_test_07/cmd3 b/tests/scenarios/github_test_07/cmd3 index 9e0b6f0b62..622a0e57c8 100644 --- a/tests/scenarios/github_test_07/cmd3 +++ b/tests/scenarios/github_test_07/cmd3 @@ -1,5 +1,5 @@ source: ubuntu-1-deployment -cmd: su - user1 -c "echo test >> /home/user1/dir1/key1.txt" +cmd: echo test >> /home/user1/dir1/key1.txt result: failed --- operation: File diff --git a/tests/scenarios/github_test_07/cmd4 b/tests/scenarios/github_test_07/cmd4 index 622a0e57c8..9e0b6f0b62 100644 --- a/tests/scenarios/github_test_07/cmd4 +++ b/tests/scenarios/github_test_07/cmd4 @@ -1,5 +1,5 @@ source: ubuntu-1-deployment -cmd: echo test >> /home/user1/dir1/key1.txt +cmd: su - user1 -c "echo test >> /home/user1/dir1/key1.txt" result: failed --- operation: File diff --git a/tests/scenarios/github_test_07/ksp-ubuntu-1-file-dir-recursive-owner-readonly-block.yaml b/tests/scenarios/github_test_07/ksp-ubuntu-1-file-dir-recursive-owner-readonly-block.yaml index 12fdaee32c..15d9bad35c 100644 --- a/tests/scenarios/github_test_07/ksp-ubuntu-1-file-dir-recursive-owner-readonly-block.yaml +++ b/tests/scenarios/github_test_07/ksp-ubuntu-1-file-dir-recursive-owner-readonly-block.yaml @@ -9,10 +9,10 @@ spec: matchLabels: container: ubuntu-1 file: - matchDirectories: # cat /home/user1/dir1/key1.txt (permission denied) - - dir: /home/user1/ # su - user1 -c "cat /home/user1/dir1/key1.txt" (success) - recursive: true # su - user1 -c "echo test >> /home/user1/secret_data1.txt" (permission denied) - ownerOnly: true # echo testroot >> /home/user1/secret_data1.txt (permission denied) + matchDirectories: + - dir: /home/user1/ + recursive: true + ownerOnly: true readOnly: true action: Block diff --git a/tests/scenarios/github_test_08/cmd3 b/tests/scenarios/github_test_08/cmd3 index 4502a4c606..79dd87a518 100644 --- a/tests/scenarios/github_test_08/cmd3 +++ b/tests/scenarios/github_test_08/cmd3 @@ -1,5 +1,5 @@ source: ubuntu-1-deployment -cmd: su - user1 -c "echo test >> /home/user1/otherfile.txt" +cmd: su - user1 -c "cat /home/user1/otherfile.txt" result: passed --- operation: File diff --git a/tests/scenarios/github_test_08/cmd4 b/tests/scenarios/github_test_08/cmd4 index c814a0609c..4502a4c606 100644 --- a/tests/scenarios/github_test_08/cmd4 +++ b/tests/scenarios/github_test_08/cmd4 @@ -1,5 +1,5 @@ source: ubuntu-1-deployment -cmd: echo test >> /home/user1/otherfile.txt +cmd: su - user1 -c "echo test >> /home/user1/otherfile.txt" result: passed --- operation: File diff --git a/tests/scenarios/github_test_08/cmd5 b/tests/scenarios/github_test_08/cmd5 index 906d09da38..f4b69acb6a 100644 --- a/tests/scenarios/github_test_08/cmd5 +++ b/tests/scenarios/github_test_08/cmd5 @@ -1,5 +1,5 @@ source: ubuntu-1-deployment -cmd: echo test >> /home/user1/secret_data1.txt +cmd: cat /home/user1/secret_data1.txt result: failed --- operation: File diff --git a/tests/scenarios/github_test_08/cmd6 b/tests/scenarios/github_test_08/cmd6 index f4b69acb6a..906d09da38 100644 --- a/tests/scenarios/github_test_08/cmd6 +++ b/tests/scenarios/github_test_08/cmd6 @@ -1,5 +1,5 @@ source: ubuntu-1-deployment -cmd: cat /home/user1/secret_data1.txt +cmd: echo test >> /home/user1/secret_data1.txt result: failed --- operation: File diff --git a/tests/scenarios/github_test_08/ksp-ubuntu-1-file-pattern-owner-readonly-block.yaml b/tests/scenarios/github_test_08/ksp-ubuntu-1-file-pattern-owner-readonly-block.yaml index 26ea55ce75..8ed237474b 100644 --- a/tests/scenarios/github_test_08/ksp-ubuntu-1-file-pattern-owner-readonly-block.yaml +++ b/tests/scenarios/github_test_08/ksp-ubuntu-1-file-pattern-owner-readonly-block.yaml @@ -10,9 +10,9 @@ spec: matchLabels: container: ubuntu-1 file: - matchPatterns: # echo testroot >> /home/user1/secret_data1.txt (permission denied) - - pattern: /home/user1/secret_data* # su - user1 -c "echo test >> /home/user1/secret_data1.txt" (permission denied) - ownerOnly: true # cat /home/user1/secret_data1.txt (permission denied) - readOnly: true # su - user1 -c "cat /home/user1/secret_data1.txt" (success) + matchPatterns: + - pattern: /home/user1/secret_data* + ownerOnly: true + readOnly: true action: Block diff --git a/tests/scenarios/github_test_11/cmd1 b/tests/scenarios/github_test_11/cmd1 index 3a804587b9..751a25b3c4 100644 --- a/tests/scenarios/github_test_11/cmd1 +++ b/tests/scenarios/github_test_11/cmd1 @@ -3,5 +3,5 @@ cmd: cat /etc/shells result: failed --- operation: File -condition: "/etc/shells" +condition: /etc/shells action: Block diff --git a/tests/scenarios/github_test_11/cmd2 b/tests/scenarios/github_test_11/cmd2 index b8b1ca383c..351ab50255 100644 --- a/tests/scenarios/github_test_11/cmd2 +++ b/tests/scenarios/github_test_11/cmd2 @@ -3,5 +3,5 @@ cmd: cat /etc/hostname result: failed --- operation: File -condition: "/etc/hostname" +condition: /etc/hostname action: Block diff --git a/tests/scenarios/github_test_11/nsp-ubuntu-1-file-dir-recursive-block.yaml b/tests/scenarios/github_test_11/nsp-ubuntu-1-file-dir-recursive-block.yaml index 5545d9096c..ff1bec441d 100644 --- a/tests/scenarios/github_test_11/nsp-ubuntu-1-file-dir-recursive-block.yaml +++ b/tests/scenarios/github_test_11/nsp-ubuntu-1-file-dir-recursive-block.yaml @@ -1,7 +1,7 @@ apiVersion: security.kubearmor.com/v1 kind: KubeArmorPolicy metadata: - name: nap-ubuntu-1-file-dir-recursive-block + name: nsp-ubuntu-1-file-dir-recursive-block namespace: github spec: selector: diff --git a/tests/scenarios/github_test_12/cmd3 b/tests/scenarios/github_test_12/cmd3 index c9483388b5..c6017dfdb1 100644 --- a/tests/scenarios/github_test_12/cmd3 +++ b/tests/scenarios/github_test_12/cmd3 @@ -1,7 +1,7 @@ source: ubuntu-1-deployment cmd: wget --tries=1 142.250.193.46 -result: failed +result: passed --- operation: Network condition: SOCK_STREAM -action: Block +action: Allow diff --git a/tests/scenarios/github_test_12/ksp-ubuntu-1-net-tcp-from-source-allow.yaml b/tests/scenarios/github_test_12/ksp-ubuntu-1-net-tcp-from-source-allow.yaml index cfeb8bd1ad..1e18c36043 100644 --- a/tests/scenarios/github_test_12/ksp-ubuntu-1-net-tcp-from-source-allow.yaml +++ b/tests/scenarios/github_test_12/ksp-ubuntu-1-net-tcp-from-source-allow.yaml @@ -1,7 +1,7 @@ apiVersion: security.kubearmor.com/v1 kind: KubeArmorPolicy metadata: - name: ksp-ubuntu-1-net-tcp-from-source-allow-curl + name: ksp-ubuntu-1-net-tcp-from-source-allow namespace: github spec: severity: 8 @@ -10,7 +10,18 @@ spec: container: ubuntu-1 network: matchProtocols: - - protocol: tcp - fromSource: - - path: /usr/bin/curl + - protocol: tcp + fromSource: + - path: /usr/bin/curl action: Allow + +# test +# curl 172.217.175.36 +# +# 301 Moved +#

301 Moved

+# The document has moved +# here. +# +# $ curl www.google.com +# curl: (6) Could not resolve host: www.google.com diff --git a/tests/test-scenarios-github.sh b/tests/test-scenarios-github.sh index db07257552..880299a64a 100755 --- a/tests/test-scenarios-github.sh +++ b/tests/test-scenarios-github.sh @@ -23,36 +23,80 @@ TEST_HOME=`dirname $(realpath "$0")` CRD_HOME=`dirname $(realpath "$0")`/../deployments/CRD ARMOR_HOME=`dirname $(realpath "$0")`/../KubeArmor +LSM="none" + +cat /sys/kernel/security/lsm | grep selinux > /dev/null 2>&1 +if [ $? == 0 ]; then + LSM="selinux" +fi + +cat /sys/kernel/security/lsm | grep apparmor > /dev/null 2>&1 +if [ $? == 0 ]; then + LSM="apparmor" +fi + ARMOR_OPTIONS=() -SKIP_CONTAINER_POLICY=0 -SKIP_NATIVE_POLICY=0 +SKIP_CONTAINER_POLICY=1 +SKIP_NATIVE_POLICY=1 SKIP_HOST_POLICY=1 -SKIP_NATIVE_HOST_POLICY=1 case $1 in - "-testHostPolicy") - SKIP_CONTAINER_POLICY=1 - SKIP_HOST_POLICY=0 + "-testPolicy") + if [ "$LSM" == "selinux" ]; then + echo "KubeArmor does not support container policies in SELinux-enabled environments" + exit + fi + + SKIP_CONTAINER_POLICY=0 + SKIP_NATIVE_POLICY=1 + SKIP_HOST_POLICY=1 + ARMOR_OPTIONS=${@:2} - ARMOR_OPTIONS=(${ARMOR_OPTIONS[@]} "-enableKubeArmorHostPolicy") ;; + + "-testHostPolicy") + echo "If you want to test host policies, please run KubeArmor separately and use test-scenarios-in-runtime.sh" + exit + ;; + "-testNativePolicy") + if [ "$LSM" != "apparmor" ]; then + echo "KubeArmor does not support native policies if AppArmor is not enabled" + exit + fi + SKIP_CONTAINER_POLICY=1 SKIP_NATIVE_POLICY=0 - SKIP_NATIVE_HOST_POLICY=0 - ARMOR_OPTIONS=${@:2} - ;; - "-testAll") - SKIP_CONTAINER_POLICY=0 - SKIP_HOST_POLICY=0 - SKIP_NATIVE_POLICY=0 - SKIP_NATIVE_HOST_POLICY=0 + SKIP_HOST_POLICY=1 + ARMOR_OPTIONS=${@:2} - ARMOR_OPTIONS=(${ARMOR_OPTIONS[@]} "-enableKubeArmorHostPolicy") ;; + *) - ARMOR_OPTIONS=$@ + if [ "$LSM" == "selinux" ]; then + echo "KubeArmor only supports host policies in SELinux-enabled environments" + echo "If you want to test host policies, please run KubeArmor separately and use test-scenarios-in-runtime.sh" + exit + + elif [ "$LSM" == "apparmor" ]; then + echo "If you want to test host policies, please run KubeArmor separately and use test-scenarios-in-runtime.sh" + + SKIP_CONTAINER_POLICY=0 + SKIP_NATIVE_POLICY=0 + SKIP_HOST_POLICY=1 + + ARMOR_OPTIONS=$@ + + else # none + echo "KubeArmor does not support native policies if AppArmor is not enabled" + + SKIP_CONTAINER_POLICY=0 + SKIP_NATIVE_POLICY=1 + SKIP_HOST_POLICY=0 + + ARMOR_OPTIONS=$@ + fi ;; esac @@ -60,12 +104,6 @@ ARMOR_MSG=/tmp/kubearmor.msg ARMOR_LOG=/tmp/kubearmor.log TEST_LOG=/tmp/kubearmor.test -APPARMOR=0 -cat /sys/kernel/security/lsm | grep apparmor > /dev/null 2>&1 -if [ $? == 0 ]; then - APPARMOR=1 -fi - RED='\033[0;31m' GREEN='\033[0;32m' ORANGE='\033[0;33m' @@ -114,7 +152,6 @@ function start_and_wait_for_kubearmor_initialization() { echo "Options: -logPath=$ARMOR_LOG ${ARMOR_OPTIONS[@]}" if [[ ! " ${ARMOR_OPTIONS[@]} " =~ "-enableKubeArmorHostPolicy" ]]; then SKIP_HOST_POLICY=1 - SKIP_NATIVE_HOST_POLICY=1 fi ka_podname=`kubectl get pods -n kube-system -l kubearmor-app=kubearmor -o custom-columns=":metadata.name" --no-headers` @@ -228,7 +265,7 @@ function should_not_find_any_log() { sleep 5 - audit_log=$($CAT_LOG | grep -E "$1.*policyName.*\"$2\".*MatchedPolicy.*\"$6\".*$3.*resource.*$4.*$5" | tail -n 1 | grep -v Passed) + audit_log=$($CAT_LOG | grep -E "$1.*policyName.*$2.*MatchedPolicy.*$6.*operation.*$3.*resource.*$4.*data.*action.*$5" | grep -v grep | tail -n 1 | grep -v Passed) if [ $? == 0 ]; then echo $audit_log FAIL "Found the log from logs" @@ -244,7 +281,7 @@ function should_find_passed_log() { sleep 5 - audit_log=$($CAT_LOG | grep -E "$1.*policyName.*\"$2\".*MatchedPolicy.*$3.*resource.*$4.*$5" | tail -n 1 | grep Passed) + audit_log=$($CAT_LOG | grep -E "$1.*policyName.*$2.*MatchedPolicy.*operation.*$3.*resource.*$4.*data.*action.*$5" | grep -v grep | tail -n 1 | grep Passed) if [ $? != 0 ]; then audit_log="" FAIL "Failed to find the log from logs" @@ -260,16 +297,7 @@ function should_find_blocked_log() { sleep 5 - match_type="MatchedPolicy" - if [[ $6 -eq 1 ]]; then - match_type="MatchedNativePolicy" - fi - - if [[ $6 -eq 0 ]]; then - audit_log=$($CAT_LOG | grep -E "$1.*policyName.*\"$2|DefaultPosture\".*$match_type.*$3.*resource.*$4.*$5" | tail -n 1 | grep -v Passed) - else - audit_log=$($CAT_LOG | grep -E "$1.*policyName.*\"NativePolicy\".*$match_type.*$3.*resource.*$4.*$5" | tail -n 1 | grep -v Passed) - fi + audit_log=$($CAT_LOG | grep -E "$1.*policyName.*$2|DefaultPosture.*MatchedPolicy.*operation.*$3.*resource.*$4.*data.*action.*$5" | grep -v grep | tail -n 1 | grep -v Passed) if [ $? != 0 ]; then audit_log="" FAIL "Failed to find the log from logs" @@ -285,7 +313,7 @@ function should_not_find_any_host_log() { sleep 5 - audit_log=$($CAT_LOG | grep -E "$HOST_NAME.*policyName.*\"$1\".*MatchedHostPolicy.*\"$5\".*$2.*resource.*$3.*$4" | tail -n 1 | grep -v Passed) + audit_log=$($CAT_LOG | grep -E "$HOST_NAME.*policyName.*$1.*MatchedHostPolicy.*$5.*operation.*$2.*resource.*$3.*data.*action.*$4" | grep -v grep | tail -n 1 | grep -v Passed) if [ $? == 0 ]; then echo $audit_log FAIL "Found the log from logs" @@ -301,7 +329,7 @@ function should_find_passed_host_log() { sleep 5 - audit_log=$($CAT_LOG | grep -E "$HOST_NAME.*policyName.*\"$1\".*MatchedHostPolicy.*$2.*resource.*$3.*$4" | tail -n 1 | grep Passed) + audit_log=$($CAT_LOG | grep -E "$HOST_NAME.*policyName.*$1.*MatchedHostPolicy.*operation.*$2.*resource.*$3.*data.*action.*$4" | grep -v grep | tail -n 1 | grep Passed) if [ $? != 0 ]; then audit_log="" FAIL "Failed to find the log from logs" @@ -317,16 +345,7 @@ function should_find_blocked_host_log() { sleep 5 - match_type="MatchedHostPolicy" - if [[ $5 -eq 1 ]]; then - match_type="MatchedNativePolicy" - fi - - if [[ $5 -eq 0 ]]; then - audit_log=$($CAT_LOG | grep -E "$HOST_NAME.*policyName.*\"$1\".*$match_type.*$2.*resource.*$3.*$4" | tail -n 1 | grep -v Passed) - else - audit_log=$($CAT_LOG | grep -E "$HOST_NAME.*policyName.*\"NativePolicy\".*$match_type.*$2.*resource.*$3.*$4" | tail -n 1 | grep -v Passed) - fi + audit_log=$($CAT_LOG | grep -E "$HOST_NAME.*policyName.*$1|DefaultPosture.*MatchedHostPolicy.*operation.*$2.*resource.*$3.*data.*action.*$4" | grep -v grep | tail -n 1 | grep -v Passed) if [ $? != 0 ]; then audit_log="" FAIL "Failed to find the log from logs" @@ -341,51 +360,36 @@ function run_test_scenario() { cd $1 YAML_FILE=$(ls *.yaml) - policy_type=$(echo $YAML_FILE | awk '{split($0,a,"-"); print a[1]}') + POLICY_TYPE=$(echo $YAML_FILE | awk '{split($0,a,"-"); print a[1]}') POLICY=$(grep "name:" $YAML_FILE | head -n1 | awk '{ print $2}') - NATIVE=0 + NATIVE_POLICY=0 HOST_POLICY=0 - NATIVE_HOST=0 - if [[ $policy_type == "ksp" ]]; then + if [[ $POLICY_TYPE == "ksp" ]]; then if [ $SKIP_CONTAINER_POLICY == 1 ]; then WARN "Skipped $3" skipped_testcases+=("$3") return fi - elif [[ $policy_type == "nsp" ]]; then + elif [[ $POLICY_TYPE == "nsp" ]]; then # skip a policy with a native profile unless AppArmor is enabled - if [ $APPARMOR == 0 ]; then + if [ "$LSM" != "apparmor" ]; then WARN "Skipped $3" skipped_testcases+=("$3") return - fi - if [ $SKIP_NATIVE_POLICY == 1 ]; then + elif [ $SKIP_NATIVE_POLICY == 1 ]; then WARN "Skipped $3" skipped_testcases+=("$3") return fi - NATIVE=1 - elif [[ $policy_type == "hsp" ]]; then + NATIVE_POLICY=1 + elif [[ $POLICY_TYPE == "hsp" ]]; then if [ $SKIP_HOST_POLICY == 1 ]; then WARN "Skipped $3" skipped_testcases+=("$3") return fi HOST_POLICY=1 - elif [[ $policy_type == "nhp" ]]; then - # skip a policy with a native profile unless AppArmor is enabled - if [ $APPARMOR == 0 ]; then - WARN "Skipped $3" - skipped_testcases+=("$3") - return - fi - if [ $SKIP_NATIVE_HOST_POLICY == 1 ]; then - WARN "Skipped $3" - skipped_testcases+=("$3") - return - fi - NATIVE_HOST=1 else WARN "Skipped unknown testcase $3" skipped_testcases+=("$3") @@ -393,7 +397,7 @@ function run_test_scenario() { fi DBG "Applying $YAML_FILE into $2" - if [[ $HOST_POLICY -eq 1 ]] || [[ $NATIVE_HOST -eq 1 ]]; then + if [[ $HOST_POLICY -eq 1 ]]; then kubectl apply -f $YAML_FILE else kubectl apply -n $2 -f $YAML_FILE @@ -415,7 +419,7 @@ function run_test_scenario() { SOURCE=$(cat $cmd | grep "^source" | awk '{print $2}') POD="" - if [[ $HOST_POLICY -eq 0 ]] && [[ $NATIVE_HOST -eq 0 ]]; then + if [[ $HOST_POLICY -eq 0 ]]; then POD=$(kubectl get pods -n $2 | grep $SOURCE | awk '{print $1}') fi CMD=$(cat $cmd | grep "^cmd" | cut -d' ' -f2-) @@ -425,8 +429,8 @@ function run_test_scenario() { COND=$(cat $cmd | grep "^condition" | cut -d' ' -f2-) ACTION=$(cat $cmd | grep "^action" | awk '{print $2}') - # if AppArmor is not enabled - if [ $APPARMOR == 0 ]; then + # if AppArmor and SELinux are not enabled + if [ "$LSM" == "none" ]; then # replace Block with Audit if [ "$ACTION" == "Block" ]; then if [ "$RESULT" == "failed" ]; then @@ -447,7 +451,7 @@ function run_test_scenario() { actual_res="passed" DBG "Running \"$CMD\"" - if [[ $HOST_POLICY -eq 1 ]] || [[ $NATIVE_HOST -eq 1 ]]; then + if [[ $HOST_POLICY -eq 1 ]]; then bash -c ''"${CMD}"'' else echo kubectl exec -n $2 $POD -- bash -c ''"${CMD}"'' @@ -464,7 +468,7 @@ function run_test_scenario() { should_not_find_any_log $POD $POLICY $OP $COND $ACTION $CMD else DBG "$ACTION action, but the command should be failed" - should_find_blocked_log $POD $POLICY $OP $COND $ACTION $NATIVE + should_find_blocked_log $POD $POLICY $OP $COND $ACTION fi elif [ "$ACTION" == "Audit" ]; then if [ "$RESULT" == "passed" ]; then @@ -472,7 +476,7 @@ function run_test_scenario() { should_find_passed_log $POD $POLICY $OP $COND $ACTION else DBG "$ACTION action, but the command should be failed" - should_find_blocked_log $POD $POLICY $OP $COND $ACTION $NATIVE + should_find_blocked_log $POD $POLICY $OP $COND $ACTION fi elif [ "$ACTION" == "Block" ]; then if [ "$RESULT" == "passed" ]; then @@ -480,7 +484,7 @@ function run_test_scenario() { should_not_find_any_log $POD $POLICY $OP $COND $ACTION $CMD else DBG "$ACTION action, and the command should be failed" - should_find_blocked_log $POD $POLICY $OP $COND $ACTION $NATIVE + should_find_blocked_log $POD $POLICY $OP $COND $ACTION fi fi else @@ -490,7 +494,7 @@ function run_test_scenario() { should_not_find_any_host_log $POLICY $OP $COND $ACTION $CMD else DBG "$ACTION action, but the command should be failed" - should_find_blocked_host_log $POLICY $OP $COND $ACTION $NATIVE_HOST + should_find_blocked_host_log $POLICY $OP $COND $ACTION fi elif [ "$ACTION" == "Audit" ]; then if [ "$RESULT" == "passed" ]; then @@ -498,7 +502,7 @@ function run_test_scenario() { should_find_passed_host_log $POLICY $OP $COND $ACTION else DBG "$ACTION action, but the command should be failed" - should_find_blocked_host_log $POLICY $OP $COND $ACTION $NATIVE_HOST + should_find_blocked_host_log $POLICY $OP $COND $ACTION fi elif [ "$ACTION" == "Block" ]; then if [ "$RESULT" == "passed" ]; then @@ -506,7 +510,7 @@ function run_test_scenario() { should_not_find_any_host_log $POLICY $OP $COND $ACTION $CMD else DBG "$ACTION action, and the command should be failed" - should_find_blocked_host_log $POLICY $OP $COND $ACTION $NATIVE_HOST + should_find_blocked_host_log $POLICY $OP $COND $ACTION fi fi fi @@ -552,7 +556,7 @@ function run_test_scenario() { fi DBG "Deleting $YAML_FILE from $2" - if [[ $HOST_POLICY -eq 1 ]] || [[ $NATIVE_HOST -eq 1 ]]; then + if [[ $HOST_POLICY -eq 1 ]]; then kubectl delete -f $YAML_FILE else kubectl delete -n $2 -f $YAML_FILE @@ -655,7 +659,7 @@ fi HOST_NAME=$(hostname) res_host=0 -if [[ $SKIP_HOST_POLICY -eq 0 || $SKIP_NATIVE_HOST_POLICY -eq 0 ]]; then +if [[ $SKIP_HOST_POLICY -eq 0 ]]; then INFO "Running Host Scenarios" cd $TEST_HOME/host_scenarios diff --git a/tests/test-scenarios-in-runtime.sh b/tests/test-scenarios-in-runtime.sh index 1b905b1ae4..1bba2beee1 100755 --- a/tests/test-scenarios-in-runtime.sh +++ b/tests/test-scenarios-in-runtime.sh @@ -21,45 +21,91 @@ realpath() { TEST_HOME=`dirname $(realpath "$0")` -SKIP_CONTAINER_POLICY=0 +LSM="none" + +cat /sys/kernel/security/lsm | grep selinux > /dev/null 2>&1 +if [ $? == 0 ]; then + LSM="selinux" +fi + +cat /sys/kernel/security/lsm | grep apparmor > /dev/null 2>&1 +if [ $? == 0 ]; then + LSM="apparmor" +fi + +SKIP_CONTAINER_POLICY=1 SKIP_NATIVE_POLICY=1 SKIP_HOST_POLICY=1 -SKIP_NATIVE_HOST_POLICY=1 case $1 in + "-testPolicy") + if [ "$LSM" == "selinux" ]; then + echo "KubeArmor does not support container policies in SELinux-enabled environments" + exit + fi + + SKIP_CONTAINER_POLICY=0 + SKIP_NATIVE_POLICY=1 + SKIP_HOST_POLICY=1 + + ARMOR_OPTIONS=${@:2} + ;; + "-testHostPolicy") SKIP_CONTAINER_POLICY=1 + SKIP_NATIVE_POLICY=1 SKIP_HOST_POLICY=0 + + ARMOR_OPTIONS=${@:2} + ARMOR_OPTIONS=(${ARMOR_OPTIONS[@]} "-enableKubeArmorHostPolicy") ;; + "-testNativePolicy") + if [ "$LSM" != "apparmor" ]; then + echo "KubeArmor does not support native policies if AppArmor is not enabled" + exit + fi + SKIP_CONTAINER_POLICY=1 SKIP_NATIVE_POLICY=0 - SKIP_NATIVE_HOST_POLICY=0 - ;; - "-testAll") - SKIP_CONTAINER_POLICY=0 - SKIP_HOST_POLICY=0 - SKIP_NATIVE_POLICY=0 - SKIP_NATIVE_HOST_POLICY=0 + SKIP_HOST_POLICY=1 + + ARMOR_OPTIONS=${@:2} ;; + *) + if [ "$LSM" == "selinux" ]; then + echo "KubeArmor only supports host policies in SELinux-enabled environments" + + SKIP_CONTAINER_POLICY=1 + SKIP_NATIVE_POLICY=1 + SKIP_HOST_POLICY=0 + + ARMOR_OPTIONS=$@ + ARMOR_OPTIONS=(${ARMOR_OPTIONS[@]} "-enableKubeArmorHostPolicy") + + elif [ "$LSM" == "apparmor" ]; then + SKIP_CONTAINER_POLICY=0 + SKIP_NATIVE_POLICY=0 + SKIP_HOST_POLICY=0 + + ARMOR_OPTIONS=$@ + + else # none + echo "KubeArmor does not support native policies if AppArmor is not enabled" + + SKIP_CONTAINER_POLICY=0 + SKIP_NATIVE_POLICY=1 + SKIP_HOST_POLICY=0 + + ARMOR_OPTIONS=$@ + fi ;; esac ARMOR_LOG=/tmp/kubearmor.log TEST_LOG=/tmp/kubearmor.test -APPARMOR=0 -cat /sys/kernel/security/lsm | grep apparmor > /dev/null 2>&1 -if [ $? == 0 ]; then - APPARMOR=1 -fi - -MINIKUBE=$(kubectl get nodes -l kubernetes.io/hostname=minikube 2> /dev/null | wc -l) -if [ $MINIKUBE == 2 ]; then - APPARMOR=0 -fi - RED='\033[0;31m' GREEN='\033[0;32m' ORANGE='\033[0;33m' @@ -140,7 +186,7 @@ function should_not_find_any_log() { KUBEARMOR=$(kubectl get pods -n kube-system -l kubearmor-app=kubearmor -o wide 2> /dev/null | grep $NODE | grep kubearmor | awk '{print $1}') if [[ $KUBEARMOR = "kubearmor"* ]]; then - audit_log=$(kubectl -n kube-system exec $KUBEARMOR -- grep -E "$1.*policyName.*\"$2\".*MatchedPolicy.*\"$6\".*$3.*resource.*$4.*$5" $ARMOR_LOG | tail -n 1 | grep -v Passed) + audit_log=$(kubectl -n kube-system exec $KUBEARMOR -- grep -E "$1.*policyName.*$2.*MatchedPolicy.*$6.*operation.*$3.*resource.*$4.*data.*action.*$5" $ARMOR_LOG | grep -v grep | tail -n 1 | grep -v Passed) if [ $? == 0 ]; then echo $audit_log FAIL "Found the log from logs" @@ -150,7 +196,7 @@ function should_not_find_any_log() { DBG "Found no log from logs" fi else # local - audit_log=$(grep -E "$1.*policyName.*\"$2\".*MatchedPolicy.*\"$6\".*$3.*resource.*$4.*$5" $ARMOR_LOG | tail -n 1 | grep -v Passed) + audit_log=$(grep -E "$1.*policyName.*$2.*MatchedPolicy.*$6.*operation.*$3.*resource.*$4.*data.*action.*$5" $ARMOR_LOG | grep -v grep | tail -n 1 | grep -v Passed) if [ $? == 0 ]; then echo $audit_log FAIL "Found the log from logs" @@ -171,7 +217,7 @@ function should_find_passed_log() { KUBEARMOR=$(kubectl get pods -n kube-system -l kubearmor-app=kubearmor -o wide 2> /dev/null | grep $NODE | grep kubearmor | awk '{print $1}') if [[ $KUBEARMOR = "kubearmor"* ]]; then - audit_log=$(kubectl -n kube-system exec $KUBEARMOR -- grep -E "$1.*policyName.*\"$2\".*MatchedPolicy.*$3.*resource.*$4.*$5" $ARMOR_LOG | tail -n 1 | grep Passed) + audit_log=$(kubectl -n kube-system exec $KUBEARMOR -- grep -E "$1.*policyName.*$2.*MatchedPolicy.*operation.*$3.*resource.*$4.*data.*action.*$5" $ARMOR_LOG | grep -v grep | tail -n 1 | grep Passed) if [ $? != 0 ]; then audit_log="" FAIL "Failed to find the log from logs" @@ -181,7 +227,7 @@ function should_find_passed_log() { DBG "[INFO] Found the log from logs" fi else # local - audit_log=$(grep -E "$1.*policyName.*\"$2\".*MatchedPolicy.*$3.*resource.*$4.*$5" $ARMOR_LOG | tail -n 1 | grep Passed) + audit_log=$(grep -E "$1.*policyName.*$2.*MatchedPolicy.*operation.*$3.*resource.*$4.*data.*action.*$5" $ARMOR_LOG | grep -v grep | tail -n 1 | grep Passed) if [ $? != 0 ]; then audit_log="" FAIL "Failed to find the log from logs" @@ -201,17 +247,8 @@ function should_find_blocked_log() { NODE=$(kubectl get pods -A -o wide | grep $1 | awk '{print $8}') KUBEARMOR=$(kubectl get pods -n kube-system -l kubearmor-app=kubearmor -o wide 2> /dev/null | grep $NODE | grep kubearmor | awk '{print $1}') - match_type="MatchedPolicy" - if [[ $6 -eq 1 ]]; then - match_type="MatchedNativePolicy" - fi - if [[ $KUBEARMOR = "kubearmor"* ]]; then - if [[ $6 -eq 0 ]]; then - audit_log=$(kubectl -n kube-system exec $KUBEARMOR -- grep -E "$1.*policyName.*\"$2|DefaultPosture\".*$match_type.*$3.*resource.*$4.*$5" $ARMOR_LOG | tail -n 1 | grep -v Passed) - else - audit_log=$(kubectl -n kube-system exec $KUBEARMOR -- grep -E "$1.*policyName.*\"NativePolicy\".*$match_type.*$3.*resource.*$4.*$5" $ARMOR_LOG | tail -n 1 | grep -v Passed) - fi + audit_log=$(kubectl -n kube-system exec $KUBEARMOR -- grep -E "$1.*policyName.*$2|DefaultPosture.*MatchedPolicy.*operation.*$3.*resource.*$4.*data.*action.*$5" $ARMOR_LOG | grep -v grep | tail -n 1 | grep -v Passed) if [ $? != 0 ]; then audit_log="" FAIL "Failed to find the log from logs" @@ -221,11 +258,7 @@ function should_find_blocked_log() { DBG "Found the log from logs" fi else # local - if [[ $6 -eq 0 ]]; then - audit_log=$(grep -E "$1.*policyName.*\"$2|DefaultPosture\".*$match_type.*$3.*resource.*$4.*$5" $ARMOR_LOG | tail -n 1 | grep -v Passed) - else - audit_log=$(grep -E "$1.*policyName.*\"NativePolicy\".*$match_type.*$3.*resource.*$4.*$5" $ARMOR_LOG | tail -n 1 | grep -v Passed) - fi + audit_log=$(grep -E "$1.*policyName.*$2|DefaultPosture.*MatchedPolicy.*operation.*$3.*resource.*$4.*data.*action.*$5" $ARMOR_LOG | grep -v grep | tail -n 1 | grep -v Passed) if [ $? != 0 ]; then audit_log="" FAIL "Failed to find the log from logs" @@ -246,7 +279,7 @@ function should_not_find_any_host_log() { KUBEARMOR=$(kubectl get pods -n kube-system -l kubearmor-app=kubearmor -o wide 2> /dev/null | grep $NODE | grep kubearmor | awk '{print $1}') if [[ $KUBEARMOR = "kubearmor"* ]]; then - audit_log=$(kubectl -n kube-system exec $KUBEARMOR -- grep -E "$HOST_NAME.*policyName.*\"$1\".*MatchedHostPolicy.*\"$5\".*$2.*resource.*$3.*$4" $ARMOR_LOG | tail -n 1 | grep -v Passed) + audit_log=$(kubectl -n kube-system exec $KUBEARMOR -- grep -E "$HOST_NAME.*policyName.*$1.*MatchedHostPolicy.*$5.*operation.*$2.*resource.*$3.*data.*action.*$4" $ARMOR_LOG | grep -v grep | tail -n 1 | grep -v Passed) if [ $? == 0 ]; then echo $audit_log FAIL "Found the log from logs" @@ -256,7 +289,7 @@ function should_not_find_any_host_log() { DBG "[INFO] Found no log from logs" fi else # local - audit_log=$(grep -E "$HOST_NAME.*policyName.*\"$1\".*MatchedHostPolicy.*\"$5\".*$2.*resource.*$3.*$4" $ARMOR_LOG | tail -n 1 | grep -v Passed) + audit_log=$(grep -E "$HOST_NAME.*policyName.*$1.*MatchedHostPolicy.*$5.*operation.*$2.*resource.*$3.*data.*action.*$4" $ARMOR_LOG | grep -v grep | tail -n 1 | grep -v Passed) if [ $? == 0 ]; then echo $audit_log FAIL "Found the log from logs" @@ -277,7 +310,7 @@ function should_find_passed_host_log() { KUBEARMOR=$(kubectl get pods -n kube-system -l kubearmor-app=kubearmor -o wide 2> /dev/null | grep $NODE | grep kubearmor | awk '{print $1}') if [[ $KUBEARMOR = "kubearmor"* ]]; then - audit_log=$(kubectl -n kube-system exec $KUBEARMOR -- grep -E "$HOST_NAME.*policyName.*\"$1\".*MatchedHostPolicy.*$2.*resource.*$3.*$4" $ARMOR_LOG | tail -n 1 | grep Passed) + audit_log=$(kubectl -n kube-system exec $KUBEARMOR -- grep -E "$HOST_NAME.*policyName.*$1.*MatchedHostPolicy.*operation.*$2.*resource.*$3.*data.*action.*$4" $ARMOR_LOG | grep -v grep | tail -n 1 | grep Passed) if [ $? != 0 ]; then audit_log="" FAIL "Failed to find the log from logs" @@ -287,7 +320,7 @@ function should_find_passed_host_log() { DBG "[INFO] Found the log from logs" fi else # local - audit_log=$(grep -E "$HOST_NAME.*policyName.*\"$1\".*MatchedHostPolicy.*$2.*resource.*$3.*$4" $ARMOR_LOG | tail -n 1 | grep Passed) + audit_log=$(grep -E "$HOST_NAME.*policyName.*$1.*MatchedHostPolicy.*operation.*$2.*resource.*$3.*data.*action.*$4" $ARMOR_LOG | grep -v grep | tail -n 1 | grep Passed) if [ $? != 0 ]; then audit_log="" FAIL "Failed to find the log from logs" @@ -307,17 +340,8 @@ function should_find_blocked_host_log() { NODE=$(hostname) KUBEARMOR=$(kubectl get pods -n kube-system -l kubearmor-app=kubearmor -o wide 2> /dev/null | grep $NODE | grep kubearmor | awk '{print $1}') - match_type="MatchedHostPolicy" - if [[ $5 -eq 1 ]]; then - match_type="MatchedNativePolicy" - fi - if [[ $KUBEARMOR = "kubearmor"* ]]; then - if [[ $5 -eq 0 ]]; then - audit_log=$(kubectl -n kube-system exec $KUBEARMOR -- grep -E "$HOST_NAME.*policyName.*\"$1\".*$match_type.*$2.*resource.*$3.*$4" $ARMOR_LOG | tail -n 1 | grep -v Passed) - else - audit_log=$(kubectl -n kube-system exec $KUBEARMOR -- grep -E "$HOST_NAME.*policyName.*\"NativePolicy\".*$match_type.*$2.*resource.*$3.*$4" $ARMOR_LOG | tail -n 1 | grep -v Passed) - fi + audit_log=$(kubectl -n kube-system exec $KUBEARMOR -- grep -E "$HOST_NAME.*policyName.*$1|DefaultPosture.*MatchedHostPolicy.*operation.*$2.*resource.*$3.*data.*action.*$4" $ARMOR_LOG | grep -v grep | tail -n 1 | grep -v Passed) if [ $? != 0 ]; then audit_log="" FAIL "Failed to find the log from logs" @@ -327,11 +351,7 @@ function should_find_blocked_host_log() { DBG "Found the log from logs" fi else # local - if [[ $5 -eq 0 ]]; then - audit_log=$(grep -E "$HOST_NAME.*policyName.*\"$1\".*$match_type.*$2.*resource.*$3.*$4" $ARMOR_LOG | tail -n 1 | grep -v Passed) - else - audit_log=$(grep -E "$HOST_NAME.*policyName.*\"NativePolicy\".*$match_type.*$2.*resource.*$3.*$4" $ARMOR_LOG | tail -n 1 | grep -v Passed) - fi + audit_log=$(grep -E "$HOST_NAME.*policyName.*$1|DefaultPosture.*MatchedHostPolicy.*operation.*$2.*resource.*$3.*data.*action.*$4" $ARMOR_LOG | grep -v grep | tail -n 1 | grep -v Passed) if [ $? != 0 ]; then audit_log="" FAIL "Failed to find the log from logs" @@ -347,51 +367,36 @@ function run_test_scenario() { cd $1 YAML_FILE=$(ls *.yaml) - policy_type=$(echo $YAML_FILE | awk '{split($0,a,"-"); print a[1]}') + POLICY_TYPE=$(echo $YAML_FILE | awk '{split($0,a,"-"); print a[1]}') POLICY=$(grep "name:" $YAML_FILE | head -n1 | awk '{ print $2}') - NATIVE=0 + NATIVE_POLICY=0 HOST_POLICY=0 - NATIVE_HOST=0 - if [[ $policy_type == "ksp" ]]; then + if [[ $POLICY_TYPE == "ksp" ]]; then if [ $SKIP_CONTAINER_POLICY == 1 ]; then WARN "Skipped $3" skipped_testcases+=("$3") return fi - elif [[ $policy_type == "nsp" ]]; then + elif [[ $POLICY_TYPE == "nsp" ]]; then # skip a policy with a native profile unless AppArmor is enabled - if [ $APPARMOR == 0 ]; then + if [ "$LSM" != "apparmor" ]; then WARN "Skipped $3" skipped_testcases+=("$3") return - fi - if [ $SKIP_NATIVE_POLICY == 1 ]; then + elif [ $SKIP_NATIVE_POLICY == 1 ]; then WARN "Skipped $3" skipped_testcases+=("$3") return fi - NATIVE=1 - elif [[ $policy_type == "hsp" ]]; then + NATIVE_POLICY=1 + elif [[ $POLICY_TYPE == "hsp" ]]; then if [ $SKIP_HOST_POLICY == 1 ]; then WARN "Skipped $3" skipped_testcases+=("$3") return fi HOST_POLICY=1 - elif [[ $policy_type == "nhp" ]]; then - # skip a policy with a native profile unless AppArmor is enabled - if [ $APPARMOR == 0 ]; then - WARN "Skipped $3" - skipped_testcases+=("$3") - return - fi - if [ $SKIP_NATIVE_HOST_POLICY == 1 ]; then - WARN "Skipped $3" - skipped_testcases+=("$3") - return - fi - NATIVE_HOST=1 else WARN "Skipped unknown testcase $3" skipped_testcases+=("$3") @@ -399,7 +404,7 @@ function run_test_scenario() { fi DBG "Applying $YAML_FILE into $2" - if [[ $HOST_POLICY -eq 1 ]] || [[ $NATIVE_HOST -eq 1 ]]; then + if [[ $HOST_POLICY -eq 1 ]]; then kubectl apply -f $YAML_FILE else kubectl apply -n $2 -f $YAML_FILE @@ -421,7 +426,7 @@ function run_test_scenario() { SOURCE=$(cat $cmd | grep "^source" | awk '{print $2}') POD="" - if [[ $HOST_POLICY -eq 0 ]] && [[ $NATIVE_HOST -eq 0 ]]; then + if [[ $HOST_POLICY -eq 0 ]]; then POD=$(kubectl get pods -n $2 | grep $SOURCE | awk '{print $1}') fi CMD=$(cat $cmd | grep "^cmd" | cut -d' ' -f2-) @@ -431,8 +436,8 @@ function run_test_scenario() { COND=$(cat $cmd | grep "^condition" | cut -d' ' -f2-) ACTION=$(cat $cmd | grep "^action" | awk '{print $2}') - # if AppArmor is not enabled - if [ $APPARMOR == 0 ]; then + # if AppArmor and SELinux are not enabled + if [ "$LSM" == "none" ]; then # replace Block with Audit if [ "$ACTION" == "Block" ]; then if [ "$RESULT" == "failed" ]; then @@ -453,7 +458,7 @@ function run_test_scenario() { actual_res="passed" DBG "Running \"$CMD\"" - if [[ $HOST_POLICY -eq 1 ]] || [[ $NATIVE_HOST -eq 1 ]]; then + if [[ $HOST_POLICY -eq 1 ]]; then bash -c ''"${CMD}"'' else echo kubectl exec -n $2 $POD -- bash -c ''"${CMD}"'' @@ -470,7 +475,7 @@ function run_test_scenario() { should_not_find_any_log $POD $POLICY $OP $COND $ACTION $CMD else DBG "$ACTION action, but the command should be failed" - should_find_blocked_log $POD $POLICY $OP $COND $ACTION $NATIVE + should_find_blocked_log $POD $POLICY $OP $COND $ACTION fi elif [ "$ACTION" == "Audit" ]; then if [ "$RESULT" == "passed" ]; then @@ -478,7 +483,7 @@ function run_test_scenario() { should_find_passed_log $POD $POLICY $OP $COND $ACTION else DBG "$ACTION action, but the command should be failed" - should_find_blocked_log $POD $POLICY $OP $COND $ACTION $NATIVE + should_find_blocked_log $POD $POLICY $OP $COND $ACTION fi elif [ "$ACTION" == "Block" ]; then if [ "$RESULT" == "passed" ]; then @@ -486,7 +491,7 @@ function run_test_scenario() { should_not_find_any_log $POD $POLICY $OP $COND $ACTION $CMD else DBG "$ACTION action, and the command should be failed" - should_find_blocked_log $POD $POLICY $OP $COND $ACTION $NATIVE + should_find_blocked_log $POD $POLICY $OP $COND $ACTION fi fi else @@ -496,7 +501,7 @@ function run_test_scenario() { should_not_find_any_host_log $POLICY $OP $COND $ACTION $CMD else DBG "$ACTION action, but the command should be failed" - should_find_blocked_host_log $POLICY $OP $COND $ACTION $NATIVE_HOST + should_find_blocked_host_log $POLICY $OP $COND $ACTION fi elif [ "$ACTION" == "Audit" ]; then if [ "$RESULT" == "passed" ]; then @@ -504,7 +509,7 @@ function run_test_scenario() { should_find_passed_host_log $POLICY $OP $COND $ACTION else DBG "$ACTION action, but the command should be failed" - should_find_blocked_host_log $POLICY $OP $COND $ACTION $NATIVE_HOST + should_find_blocked_host_log $POLICY $OP $COND $ACTION fi elif [ "$ACTION" == "Block" ]; then if [ "$RESULT" == "passed" ]; then @@ -512,7 +517,7 @@ function run_test_scenario() { should_not_find_any_host_log $POLICY $OP $COND $ACTION $CMD else DBG "$ACTION action, and the command should be failed" - should_find_blocked_host_log $POLICY $OP $COND $ACTION $NATIVE_HOST + should_find_blocked_host_log $POLICY $OP $COND $ACTION fi fi fi @@ -558,7 +563,7 @@ function run_test_scenario() { fi DBG "Deleting $YAML_FILE from $2" - if [[ $HOST_POLICY -eq 1 ]] || [[ $NATIVE_HOST -eq 1 ]]; then + if [[ $HOST_POLICY -eq 1 ]]; then kubectl delete -f $YAML_FILE else kubectl delete -n $2 -f $YAML_FILE @@ -577,7 +582,6 @@ function run_test_scenario() { if [[ ! "$(ps -f --pid $(pidof kubearmor) 2> /dev/null | cat | grep enableKubeArmorHostPolicy)" != "" ]]; then SKIP_HOST_POLICY=1 - SKIP_NATIVE_HOST_POLICY=1 fi total_testcases=$(expr $(ls -l $TEST_HOME/scenarios | grep ^d | wc -l) + $(ls -ld $TEST_HOME/host_scenarios/$(hostname)_* 2> /dev/null | grep ^d | wc -l)) @@ -701,7 +705,7 @@ fi HOST_NAME="$(hostname)" res_host=0 -if [[ $SKIP_HOST_POLICY -eq 0 || $SKIP_NATIVE_HOST_POLICY -eq 0 ]]; then +if [[ $SKIP_HOST_POLICY -eq 0 ]]; then INFO "Running Host Scenarios" cd $TEST_HOME/host_scenarios diff --git a/tests/test-scenarios-local.sh b/tests/test-scenarios-local.sh index 4e05973fc3..b5774eb631 100755 --- a/tests/test-scenarios-local.sh +++ b/tests/test-scenarios-local.sh @@ -23,36 +23,80 @@ TEST_HOME=`dirname $(realpath "$0")` CRD_HOME=`dirname $(realpath "$0")`/../deployments/CRD ARMOR_HOME=`dirname $(realpath "$0")`/../KubeArmor +LSM="none" + +cat /sys/kernel/security/lsm | grep selinux > /dev/null 2>&1 +if [ $? == 0 ]; then + LSM="selinux" +fi + +cat /sys/kernel/security/lsm | grep apparmor > /dev/null 2>&1 +if [ $? == 0 ]; then + LSM="apparmor" +fi + ARMOR_OPTIONS=() -SKIP_CONTAINER_POLICY=0 +SKIP_CONTAINER_POLICY=1 SKIP_NATIVE_POLICY=1 SKIP_HOST_POLICY=1 -SKIP_NATIVE_HOST_POLICY=1 case $1 in - "-testHostPolicy") - SKIP_CONTAINER_POLICY=1 - SKIP_HOST_POLICY=0 + "-testPolicy") + if [ "$LSM" == "selinux" ]; then + echo "KubeArmor does not support container policies in SELinux-enabled environments" + exit + fi + + SKIP_CONTAINER_POLICY=0 + SKIP_NATIVE_POLICY=1 + SKIP_HOST_POLICY=1 + ARMOR_OPTIONS=${@:2} - ARMOR_OPTIONS=(${ARMOR_OPTIONS[@]} "-enableKubeArmorHostPolicy") ;; + + "-testHostPolicy") + echo "If you want to test host policies, please run KubeArmor separately and use test-scenarios-in-runtime.sh" + exit + ;; + "-testNativePolicy") + if [ "$LSM" != "apparmor" ]; then + echo "KubeArmor does not support native policies if AppArmor is not enabled" + exit + fi + SKIP_CONTAINER_POLICY=1 SKIP_NATIVE_POLICY=0 - SKIP_NATIVE_HOST_POLICY=0 - ARMOR_OPTIONS=${@:2} - ;; - "-testAll") - SKIP_CONTAINER_POLICY=0 - SKIP_HOST_POLICY=0 - SKIP_NATIVE_POLICY=0 - SKIP_NATIVE_HOST_POLICY=0 + SKIP_HOST_POLICY=1 + ARMOR_OPTIONS=${@:2} - ARMOR_OPTIONS=(${ARMOR_OPTIONS[@]} "-enableKubeArmorHostPolicy") ;; + *) - ARMOR_OPTIONS=$@ + if [ "$LSM" == "selinux" ]; then + echo "KubeArmor only supports host policies in SELinux-enabled environments" + echo "If you want to test host policies, please run KubeArmor separately and use test-scenarios-in-runtime.sh" + exit + + elif [ "$LSM" == "apparmor" ]; then + echo "If you want to test host policies, please run KubeArmor separately and use test-scenarios-in-runtime.sh" + + SKIP_CONTAINER_POLICY=0 + SKIP_NATIVE_POLICY=0 + SKIP_HOST_POLICY=1 + + ARMOR_OPTIONS=$@ + + else # none + echo "KubeArmor does not support native policies if AppArmor is not enabled" + + SKIP_CONTAINER_POLICY=0 + SKIP_NATIVE_POLICY=1 + SKIP_HOST_POLICY=0 + + ARMOR_OPTIONS=$@ + fi ;; esac @@ -60,12 +104,6 @@ ARMOR_MSG=/tmp/kubearmor.msg ARMOR_LOG=/tmp/kubearmor.log TEST_LOG=/tmp/kubearmor.test -APPARMOR=0 -cat /sys/kernel/security/lsm | grep apparmor > /dev/null 2>&1 -if [ $? == 0 ]; then - APPARMOR=1 -fi - RED='\033[0;31m' GREEN='\033[0;32m' ORANGE='\033[0;33m' @@ -120,7 +158,6 @@ function start_and_wait_for_kubearmor_initialization() { echo "Options: -logPath=$ARMOR_LOG ${ARMOR_OPTIONS[@]}" if [[ ! " ${ARMOR_OPTIONS[@]} " =~ "-enableKubeArmorHostPolicy" ]]; then SKIP_HOST_POLICY=1 - SKIP_NATIVE_HOST_POLICY=1 fi sudo -E ./kubearmor -logPath=$ARMOR_LOG ${ARMOR_OPTIONS[@]} > $ARMOR_MSG & @@ -187,7 +224,7 @@ function should_not_find_any_log() { sleep 5 - audit_log=$(grep -E "$1.*policyName.*\"$2\".*MatchedPolicy.*\"$6\".*$3.*resource.*$4.*$5" $ARMOR_LOG | tail -n 1 | grep -v Passed) + audit_log=$(grep -E "$1.*policyName.*$2.*MatchedPolicy.*$6.*operation.*$3.*resource.*$4.*data.*action.*$5" $ARMOR_LOG | grep -v grep | tail -n 1 | grep -v Passed) if [ $? == 0 ]; then echo $audit_log FAIL "Found the log from logs" @@ -203,7 +240,7 @@ function should_find_passed_log() { sleep 5 - audit_log=$(grep -E "$1.*policyName.*\"$2\".*MatchedPolicy.*$3.*resource.*$4.*$5" $ARMOR_LOG | tail -n 1 | grep Passed) + audit_log=$(grep -E "$1.*policyName.*$2.*MatchedPolicy.*operation.*$3.*resource.*$4.*data.*action.*$5" $ARMOR_LOG | grep -v grep | tail -n 1 | grep Passed) if [ $? != 0 ]; then audit_log="" FAIL "Failed to find the log from logs" @@ -219,16 +256,7 @@ function should_find_blocked_log() { sleep 5 - match_type="MatchedPolicy" - if [[ $6 -eq 1 ]]; then - match_type="MatchedNativePolicy" - fi - - if [[ $6 -eq 0 ]]; then - audit_log=$(grep -E "$1.*policyName.*\"$2|DefaultPosture\".*$match_type.*$3.*resource.*$4.*$5" $ARMOR_LOG | tail -n 1 | grep -v Passed) - else - audit_log=$(grep -E "$1.*policyName.*\"NativePolicy\".*$match_type.*$3.*resource.*$4.*$5" $ARMOR_LOG | tail -n 1 | grep -v Passed) - fi + audit_log=$(grep -E "$1.*policyName.*$2|DefaultPosture.*MatchedPolicy.*operation.*$3.*resource.*$4.*data.*action.*$5" $ARMOR_LOG | grep -v grep | tail -n 1 | grep -v Passed) if [ $? != 0 ]; then audit_log="" FAIL "Failed to find the log from logs" @@ -244,7 +272,7 @@ function should_not_find_any_host_log() { sleep 5 - audit_log=$(grep -E "$HOST_NAME.*policyName.*\"$1\".*MatchedHostPolicy.*\"$5\".*$2.*resource.*$3.*$4" $ARMOR_LOG | tail -n 1 | grep -v Passed) + audit_log=$(grep -E "$HOST_NAME.*policyName.*$1.*MatchedHostPolicy.*$5.*operation.*$2.*resource.*$3.*data.*action.*$4" $ARMOR_LOG | grep -v grep | tail -n 1 | grep -v Passed) if [ $? == 0 ]; then echo $audit_log FAIL "Found the log from logs" @@ -260,7 +288,7 @@ function should_find_passed_host_log() { sleep 5 - audit_log=$(grep -E "$HOST_NAME.*policyName.*\"$1\".*MatchedHostPolicy.*$2.*resource.*$3.*$4" $ARMOR_LOG | tail -n 1 | grep Passed) + audit_log=$(grep -E "$HOST_NAME.*policyName.*$1.*MatchedHostPolicy.*operation.*$2.*resource.*$3.*data.*action.*$4" $ARMOR_LOG | grep -v grep | tail -n 1 | grep Passed) if [ $? != 0 ]; then audit_log="" FAIL "Failed to find the log from logs" @@ -276,16 +304,7 @@ function should_find_blocked_host_log() { sleep 5 - match_type="MatchedHostPolicy" - if [[ $5 -eq 1 ]]; then - match_type="MatchedNativePolicy" - fi - - if [[ $5 -eq 0 ]]; then - audit_log=$(grep -E "$HOST_NAME.*policyName.*\"$1\".*$match_type.*$2.*resource.*$3.*$4" $ARMOR_LOG | tail -n 1 | grep -v Passed) - else - audit_log=$(grep -E "$HOST_NAME.*policyName.*\"NativePolicy\".*$match_type.*$2.*resource.*$3.*$4" $ARMOR_LOG | tail -n 1 | grep -v Passed) - fi + audit_log=$(grep -E "$HOST_NAME.*policyName.*$1|DefaultPosture.*MatchedHostPolicy.*operation.*$2.*resource.*$3.*data.*action.*$4" $ARMOR_LOG | grep -v grep | tail -n 1 | grep -v Passed) if [ $? != 0 ]; then audit_log="" FAIL "Failed to find the log from logs" @@ -300,51 +319,36 @@ function run_test_scenario() { cd $1 YAML_FILE=$(ls *.yaml) - policy_type=$(echo $YAML_FILE | awk '{split($0,a,"-"); print a[1]}') + POLICY_TYPE=$(echo $YAML_FILE | awk '{split($0,a,"-"); print a[1]}') POLICY=$(grep "name:" $YAML_FILE | head -n1 | awk '{ print $2}') - NATIVE=0 + NATIVE_POLICY=0 HOST_POLICY=0 - NATIVE_HOST=0 - if [[ $policy_type == "ksp" ]]; then + if [[ $POLICY_TYPE == "ksp" ]]; then if [ $SKIP_CONTAINER_POLICY == 1 ]; then WARN "Skipped $3" skipped_testcases+=("$3") return fi - elif [[ $policy_type == "nsp" ]]; then + elif [[ $POLICY_TYPE == "nsp" ]]; then # skip a policy with a native profile unless AppArmor is enabled - if [ $APPARMOR == 0 ]; then + if [ "$LSM" != "apparmor" ]; then WARN "Skipped $3" skipped_testcases+=("$3") return - fi - if [ $SKIP_NATIVE_POLICY == 1 ]; then + elif [ $SKIP_NATIVE_POLICY == 1 ]; then WARN "Skipped $3" skipped_testcases+=("$3") return fi - NATIVE=1 - elif [[ $policy_type == "hsp" ]]; then + NATIVE_POLICY=1 + elif [[ $POLICY_TYPE == "hsp" ]]; then if [ $SKIP_HOST_POLICY == 1 ]; then WARN "Skipped $3" skipped_testcases+=("$3") return fi HOST_POLICY=1 - elif [[ $policy_type == "nhp" ]]; then - # skip a policy with a native profile unless AppArmor is enabled - if [ $APPARMOR == 0 ]; then - WARN "Skipped $3" - skipped_testcases+=("$3") - return - fi - if [ $SKIP_NATIVE_HOST_POLICY == 1 ]; then - WARN "Skipped $3" - skipped_testcases+=("$3") - return - fi - NATIVE_HOST=1 else WARN "Skipped unknown testcase $3" skipped_testcases+=("$3") @@ -352,7 +356,7 @@ function run_test_scenario() { fi DBG "Applying $YAML_FILE into $2" - if [[ $HOST_POLICY -eq 1 ]] || [[ $NATIVE_HOST -eq 1 ]]; then + if [[ $HOST_POLICY -eq 1 ]]; then kubectl apply -f $YAML_FILE else kubectl apply -n $2 -f $YAML_FILE @@ -374,7 +378,7 @@ function run_test_scenario() { SOURCE=$(cat $cmd | grep "^source" | awk '{print $2}') POD="" - if [[ $HOST_POLICY -eq 0 ]] && [[ $NATIVE_HOST -eq 0 ]]; then + if [[ $HOST_POLICY -eq 0 ]]; then POD=$(kubectl get pods -n $2 | grep $SOURCE | awk '{print $1}') fi CMD=$(cat $cmd | grep "^cmd" | cut -d' ' -f2-) @@ -384,8 +388,8 @@ function run_test_scenario() { COND=$(cat $cmd | grep "^condition" | cut -d' ' -f2-) ACTION=$(cat $cmd | grep "^action" | awk '{print $2}') - # if AppArmor is not enabled - if [ $APPARMOR == 0 ]; then + # if AppArmor and SELinux are not enabled + if [ "$LSM" == "none" ]; then # replace Block with Audit if [ "$ACTION" == "Block" ]; then if [ "$RESULT" == "failed" ]; then @@ -406,7 +410,7 @@ function run_test_scenario() { actual_res="passed" DBG "Running \"$CMD\"" - if [[ $HOST_POLICY -eq 1 ]] || [[ $NATIVE_HOST -eq 1 ]]; then + if [[ $HOST_POLICY -eq 1 ]]; then bash -c ''"${CMD}"'' else echo kubectl exec -n $2 $POD -- bash -c ''"${CMD}"'' @@ -423,7 +427,7 @@ function run_test_scenario() { should_not_find_any_log $POD $POLICY $OP $COND $ACTION $CMD else DBG "$ACTION action, but the command should be failed" - should_find_blocked_log $POD $POLICY $OP $COND $ACTION $NATIVE + should_find_blocked_log $POD $POLICY $OP $COND $ACTION fi elif [ "$ACTION" == "Audit" ]; then if [ "$RESULT" == "passed" ]; then @@ -431,7 +435,7 @@ function run_test_scenario() { should_find_passed_log $POD $POLICY $OP $COND $ACTION else DBG "$ACTION action, but the command should be failed" - should_find_blocked_log $POD $POLICY $OP $COND $ACTION $NATIVE + should_find_blocked_log $POD $POLICY $OP $COND $ACTION fi elif [ "$ACTION" == "Block" ]; then if [ "$RESULT" == "passed" ]; then @@ -439,7 +443,7 @@ function run_test_scenario() { should_not_find_any_log $POD $POLICY $OP $COND $ACTION $CMD else DBG "$ACTION action, and the command should be failed" - should_find_blocked_log $POD $POLICY $OP $COND $ACTION $NATIVE + should_find_blocked_log $POD $POLICY $OP $COND $ACTION fi fi else @@ -449,7 +453,7 @@ function run_test_scenario() { should_not_find_any_host_log $POLICY $OP $COND $ACTION $CMD else DBG "$ACTION action, but the command should be failed" - should_find_blocked_host_log $POLICY $OP $COND $ACTION $NATIVE_HOST + should_find_blocked_host_log $POLICY $OP $COND $ACTION fi elif [ "$ACTION" == "Audit" ]; then if [ "$RESULT" == "passed" ]; then @@ -457,7 +461,7 @@ function run_test_scenario() { should_find_passed_host_log $POLICY $OP $COND $ACTION else DBG "$ACTION action, but the command should be failed" - should_find_blocked_host_log $POLICY $OP $COND $ACTION $NATIVE_HOST + should_find_blocked_host_log $POLICY $OP $COND $ACTION fi elif [ "$ACTION" == "Block" ]; then if [ "$RESULT" == "passed" ]; then @@ -465,7 +469,7 @@ function run_test_scenario() { should_not_find_any_host_log $POLICY $OP $COND $ACTION $CMD else DBG "$ACTION action, and the command should be failed" - should_find_blocked_host_log $POLICY $OP $COND $ACTION $NATIVE_HOST + should_find_blocked_host_log $POLICY $OP $COND $ACTION fi fi fi @@ -511,7 +515,7 @@ function run_test_scenario() { fi DBG "Deleting $YAML_FILE from $2" - if [[ $HOST_POLICY -eq 1 ]] || [[ $NATIVE_HOST -eq 1 ]]; then + if [[ $HOST_POLICY -eq 1 ]]; then kubectl delete -f $YAML_FILE else kubectl delete -n $2 -f $YAML_FILE @@ -665,7 +669,7 @@ fi HOST_NAME=$(hostname) res_host=0 -if [[ $SKIP_HOST_POLICY -eq 0 || $SKIP_NATIVE_HOST_POLICY -eq 0 ]]; then +if [[ $SKIP_HOST_POLICY -eq 0 ]]; then INFO "Running Host Scenarios" cd $TEST_HOME/host_scenarios From ce8eb656bf495e93c8db82fcb3c436b8fa8346ea Mon Sep 17 00:00:00 2001 From: Jaehyun Nam Date: Mon, 11 Apr 2022 07:22:24 +0000 Subject: [PATCH 3/4] update setup scripts Signed-off-by: Jaehyun Nam --- .../self-managed-k8s-selinux/setup.sh | 8 +- contribution/self-managed-k8s/setup.sh | 8 +- contribution/technical_roadmap.md | 130 ------------------ contribution/testing_guide.md | 4 +- contribution/trouble_shooting_guide.md | 3 - 5 files changed, 10 insertions(+), 143 deletions(-) delete mode 100644 contribution/technical_roadmap.md delete mode 100644 contribution/trouble_shooting_guide.md diff --git a/contribution/self-managed-k8s-selinux/setup.sh b/contribution/self-managed-k8s-selinux/setup.sh index 3f4094c1c2..3e11ea706c 100755 --- a/contribution/self-managed-k8s-selinux/setup.sh +++ b/contribution/self-managed-k8s-selinux/setup.sh @@ -66,10 +66,10 @@ fi # download protoc mkdir -p /tmp/build/protoc; cd /tmp/build/protoc -wget --quiet https://github.com/protocolbuffers/protobuf/releases/download/v3.14.0/protoc-3.14.0-linux-x86_64.zip -O /tmp/build/protoc/protoc-3.14.0-linux-x86_64.zip +wget --quiet https://github.com/protocolbuffers/protobuf/releases/download/v3.19.4/protoc-3.19.4-linux-x86_64.zip -O /tmp/build/protoc/protoc-3.19.4-linux-x86_64.zip # install protoc -unzip protoc-3.14.0-linux-x86_64.zip +unzip protoc-3.19.4-linux-x86_64.zip sudo mv bin/protoc /usr/local/bin/ sudo chmod 755 /usr/local/bin/protoc @@ -85,8 +85,8 @@ elif [ -z "$GOPATH" ]; then fi # download protoc-gen-go -go get -u google.golang.org/grpc -go get -u github.com/golang/protobuf/protoc-gen-go +go install google.golang.org/protobuf/cmd/protoc-gen-go@v1.27.1 +go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@v1.2.0 # install kubebuilder wget --quiet https://github.com/kubernetes-sigs/kubebuilder/releases/download/v3.1.0/kubebuilder_linux_amd64 -O /tmp/build/kubebuilder diff --git a/contribution/self-managed-k8s/setup.sh b/contribution/self-managed-k8s/setup.sh index e171e482a1..0375d60e19 100755 --- a/contribution/self-managed-k8s/setup.sh +++ b/contribution/self-managed-k8s/setup.sh @@ -63,10 +63,10 @@ sudo apt-get install -y unzip # download protoc mkdir -p /tmp/build/protoc; cd /tmp/build/protoc -wget --quiet https://github.com/protocolbuffers/protobuf/releases/download/v3.14.0/protoc-3.14.0-linux-x86_64.zip -O /tmp/build/protoc/protoc-3.14.0-linux-x86_64.zip +wget --quiet https://github.com/protocolbuffers/protobuf/releases/download/v3.19.4/protoc-3.19.4-linux-x86_64.zip -O /tmp/build/protoc/protoc-3.19.4-linux-x86_64.zip # install protoc -unzip protoc-3.14.0-linux-x86_64.zip +unzip protoc-3.19.4-linux-x86_64.zip sudo mv bin/protoc /usr/local/bin/ sudo chmod 755 /usr/local/bin/protoc @@ -82,8 +82,8 @@ elif [ -z "$GOPATH" ]; then fi # download protoc-gen-go -go get -u google.golang.org/grpc -go get -u github.com/golang/protobuf/protoc-gen-go +go install google.golang.org/protobuf/cmd/protoc-gen-go@v1.27.1 +go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@v1.2.0 # install kubebuilder wget --quiet https://github.com/kubernetes-sigs/kubebuilder/releases/download/v3.1.0/kubebuilder_linux_amd64 -O /tmp/build/kubebuilder diff --git a/contribution/technical_roadmap.md b/contribution/technical_roadmap.md deleted file mode 100644 index 4d4e3a28c2..0000000000 --- a/contribution/technical_roadmap.md +++ /dev/null @@ -1,130 +0,0 @@ -# Technical Roadmap - -* KubeArmor v1.1 - - * Kubernetes Environments - * Self-managed Kubernetes \(using kubeadm\), MicroK8s, K3s*, Minikube* - * Google Kubernetes Engine \(GKE\), Amazon Elastic Kubernetes Service \(EKS\)\*, Azure Kubernetes Service \(AKS\)\* - - * Container Platforms - * Docker, Containerd - - * LSM Supports - * AppArmor - - * Features - * (KubeArmorPolicy) Add a new field, "apparmor" in KubeArmorPolicy* - ```text - (AppArmor) Apply native AppArmor profiles using KubeArmorPolicy - ``` - - * (KubeArmorHostPolicy) Support security policies for hosts* - ```text - Apply security policies to restrict host resources (e.g., processes and files in hosts) - ``` - - * (Audit Mode) Provide the audit mode if no LSM is enabled in hosts* - ```textg - Keep auditing the behavior of containers based on given policies - In the audit mode, actions are changed as follows: - - Allow -> Audit (Allow) - - Audit -> Audit - - Block -> Audit (Block) - ``` - - * Monitor container behaviors at the system level - - * Enforce security policies against: - ```text - Process executions - File accesses - Network operations - Capabilities permitted - ``` - - * Produce container-aware alerts and system logs and write them into: - ```text - Standard output - Log file - gRPC - ``` - - * Provide gRPC clients* - ```text - kubearmor-log-client (https://github.com/kubearmor/kubearmor-log-client) - kubearmor-mysql-client* (https://github.com/kubearmor/kubearmor-mysql-client) - kubearmor-kafka-client* (https://github.com/kubearmor/kubearmor-kafka-client) - ``` - - * Produce telemetry data to monitoring systems* - ```text - Prometheus integration* (https://github.com/kubearmor/kubearmor-prometheus-exporter) - ``` - - Node that we add a symbol (*) for new features. - -* KubeArmor v1.0 - - * Kubernetes Environments - * Self-managed Kubernetes \(using kubeadm\), MicroK8s - * Google Kubernetes Engine \(GKE\) - - * Container Platforms - * Docker, Containerd - - * LSM Support - * AppArmor - - * Features - * Monitor container behaviors at the system level - - * Enforce security policies against: - ```text - Process executions - File accesses - Network operations - Capabilities permitted - ``` - - * Produce container-aware alerts and system logs and write them into: - ```text - Standard output - Log file - gRPC - ``` - - * Provide gRPC clients - ```text - kubearmor-log-client (https://github.com/kubearmor/kubearmor-log-client) - ``` - -* KubeArmor Roadmap for future releases - * Container Platforms - * OpenShift, PodMan - - * LSM Supports - * LSM eBPF (KRSI), SELinux - - * Features - * Automatically generate security policies for given containers against: - ```text - Process executions - Files accesses - ``` - - * Enforce security policies \(using LSM eBPF\) against: - ```text - Process executions - File accesses - Network operations - Capabilities permitted - ``` - - * Enforce security policies against inter-container communications at the network level - ```text - Integration with network security solutions (e.g., Cilium) - ``` - - * Advanced in-kernel event auditing system - - Current event auditing systems such as Falco/Tracee provide event-auditing on an individual event basis. They take into account the event context such as process-context, task context etc. With [KubeArmor's event auditing system](https://docs.google.com/document/d/17ozYdpimFV6Mag2rtIvITI8lVRL_kBp7bCwhSlu2hvM/edit?usp=sharing) we intend to take this to the next level. KubeArmor's in-kernel event auditing system will allow one to specify rules based on rate-limiting of events, correlation of multiple system events. As an example, consider that the security team is interested only if the number of system call connects happen at more than 10 events per second. Or consider if there are connects happening in parallel with file-read operations where the file is in critical/sensitive path. With KubeArmor's event auditor system, a security team can pinpoint the rule to a greater granularity and thus avoid false positives to a greater extent. diff --git a/contribution/testing_guide.md b/contribution/testing_guide.md index 702b472fd9..7f1becf124 100644 --- a/contribution/testing_guide.md +++ b/contribution/testing_guide.md @@ -163,7 +163,7 @@ The auto-testing framework operates based on two things: microservices and testc ```text $ cd KubeArmor/tests - ~/KubeArmor/tests$ ./test-scenarios-local.sh -testAll + ~/KubeArmor/tests$ ./test-scenarios-local.sh ``` Check the test report @@ -178,7 +178,7 @@ The auto-testing framework operates based on two things: microservices and testc ```text $ cd KubeArmor/tests - ~/KubeArmor/tests$ ./test-scenarios-in-runtime.sh -testAll + ~/KubeArmor/tests$ ./test-scenarios-in-runtime.sh ``` Check the test report diff --git a/contribution/trouble_shooting_guide.md b/contribution/trouble_shooting_guide.md deleted file mode 100644 index 8c46f54306..0000000000 --- a/contribution/trouble_shooting_guide.md +++ /dev/null @@ -1,3 +0,0 @@ -# Troubleshooting Guide - -TBF From 9f2816dbde963621ee1274120b2e82a080b62b86 Mon Sep 17 00:00:00 2001 From: Jaehyun Nam Date: Tue, 12 Apr 2022 03:36:51 +0000 Subject: [PATCH 4/4] update kubeArmor.go Signed-off-by: Jaehyun Nam --- KubeArmor/core/kubeArmor.go | 58 ++++++++++++++++++------------------- 1 file changed, 28 insertions(+), 30 deletions(-) diff --git a/KubeArmor/core/kubeArmor.go b/KubeArmor/core/kubeArmor.go index 03b112c924..ef696763bf 100644 --- a/KubeArmor/core/kubeArmor.go +++ b/KubeArmor/core/kubeArmor.go @@ -341,49 +341,47 @@ func KubeArmor() { kg.Print("Updated the node information") } else if cfg.GlobalCfg.K8sEnv { - if K8s.InitK8sClient() { - kg.Print("Initialized Kubernetes client") + if !K8s.InitK8sClient() { + kg.Err("Failed to initialize Kubernetes client") - // set the flag - dm.K8sEnabled = true + // destroy the daemon + dm.DestroyKubeArmorDaemon() - // watch k8s nodes - go dm.WatchK8sNodes() - kg.Print("Started to monitor node events") + return + } - // == // + kg.Print("Initialized Kubernetes client") - // wait for a while - time.Sleep(time.Second * 1) + // set the flag + dm.K8sEnabled = true - if dm.Node.NodeIP == "" { - for timeout := 0; timeout <= 60; timeout++ { - if dm.Node.NodeIP != "" { - break - } + // watch k8s nodes + go dm.WatchK8sNodes() + kg.Print("Started to monitor node events") - if dm.Node.NodeIP == "" && timeout == 60 { - kg.Print("The node information is not available, terminating KubeArmor") + // == // - // destroy the daemon - dm.DestroyKubeArmorDaemon() + // wait for a while + time.Sleep(time.Second * 1) - return - } + for timeout := 0; timeout <= 60; timeout++ { + if dm.Node.NodeIP != "" { + break + } - kg.Print("The node information is not available") + if dm.Node.NodeIP == "" && timeout == 60 { + kg.Print("The node information is not available, terminating KubeArmor") - // wait for a while - time.Sleep(time.Second * 1) - } + // destroy the daemon + dm.DestroyKubeArmorDaemon() + + return } - } else { - kg.Err("Failed to initialize Kubernetes client") - // destroy the daemon - dm.DestroyKubeArmorDaemon() + kg.Print("The node information is not available") - return + // wait for a while + time.Sleep(time.Second * 1) } }