Skip to content

Commit

Permalink
Fixed rules test
Browse files Browse the repository at this point in the history
Signed-off-by: Afek Berger <[email protected]>
  • Loading branch information
afek854 committed Nov 7, 2024
1 parent 179544e commit e076c4e
Show file tree
Hide file tree
Showing 7 changed files with 118 additions and 60 deletions.
Empty file removed a
Empty file.
Empty file removed feature.txt
Empty file.
Original file line number Diff line number Diff line change
Expand Up @@ -26,18 +26,17 @@ func TestR1010SymlinkCreatedOverSensitiveFile(t *testing.T) {
Containers: []v1beta1.ApplicationProfileContainer{
{
Name: "test",
PolicyByRuleId: map[string]v1beta1.RulePolicy{
R1010ID: v1beta1.RulePolicy{
AllowedProcesses: []string{"/usr/sbin/groupadd"},
},
},
Opens: []v1beta1.OpenCalls{
{
Path: "/test",
Flags: []string{"O_RDONLY"},
},
},
Execs: []v1beta1.ExecCalls{
{
Path: "/usr/sbin/groupadd",
Args: []string{"test"},
},
},
},
},
},
Expand Down
2 changes: 2 additions & 0 deletions pkg/ruleengine/v1/r1011_ld_preload_hook.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ func (rule *R1011LdPreloadHook) ProcessEvent(eventType utils.EventType, event ut

if allowed, err := isAllowed(&execEvent.Event, objectCache, execEvent.Comm, R1011ID); err != nil {
logger.L().Error("failed to check if ld_preload is allowed", helpers.String("ruleID", rule.ID()), helpers.String("error", err.Error()))
return nil
} else if allowed {
return nil
}
Expand All @@ -89,6 +90,7 @@ func (rule *R1011LdPreloadHook) ProcessEvent(eventType utils.EventType, event ut

if allowed, err := isAllowed(&openEvent.Event, objectCache, openEvent.Comm, R1011ID); err != nil {
logger.L().Error("failed to check if ld_preload is allowed", helpers.String("ruleID", rule.ID()), helpers.String("error", err.Error()))
return nil
} else if allowed {
return nil
}
Expand Down
66 changes: 60 additions & 6 deletions pkg/ruleengine/v1/r1011_ld_preload_hook_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"testing"

"github.com/kubescape/node-agent/pkg/utils"
"github.com/kubescape/storage/pkg/apis/softwarecomposition/v1beta1"

tracerexectype "github.com/inspektor-gadget/inspektor-gadget/pkg/gadgets/trace/exec/types"
traceropentype "github.com/inspektor-gadget/inspektor-gadget/pkg/gadgets/trace/open/types"
Expand All @@ -13,12 +14,26 @@ import (

func TestR1011LdPreloadHook(t *testing.T) {
// Create a new rule
r := CreateRuleR1011LdPreloadHook()
// Assert r is not nil
r := CreateRuleR1011LdPreloadHook() // Assert r is not nil
if r == nil {
t.Errorf("Expected r to not be nil")
}

objCache := RuleObjectCacheMock{}
profile := objCache.ApplicationProfileCache().GetApplicationProfile("test")
if profile == nil {
profile = &v1beta1.ApplicationProfile{
Spec: v1beta1.ApplicationProfileSpec{
Containers: []v1beta1.ApplicationProfileContainer{
{
Name: "test",
},
},
},
}
objCache.SetApplicationProfile(profile)
}

// Create open event
e := &traceropentype.Event{
Event: eventtypes.Event{
Expand All @@ -36,20 +51,19 @@ func TestR1011LdPreloadHook(t *testing.T) {
}

// Test with existing ld_preload file
ruleResult := r.ProcessEvent(utils.OpenEventType, e, &RuleObjectCacheMock{})
ruleResult := r.ProcessEvent(utils.OpenEventType, e, &objCache)
if ruleResult == nil {
t.Errorf("Expected ruleResult to not be nil since ld_preload file is opened with write flag")
}

// Test with ld.so.preload file opened with read flag
e.FlagsRaw = 0
ruleResult = r.ProcessEvent(utils.OpenEventType, e, &RuleObjectCacheMock{})
ruleResult = r.ProcessEvent(utils.OpenEventType, e, &objCache)
if ruleResult != nil {
t.Errorf("Expected ruleResult to be nil since ld_preload file is opened with read flag")
}

// Test with pod spec
objCache := RuleObjectCacheMock{}
objCache.SetPodSpec(&corev1.PodSpec{
Containers: []corev1.Container{
{
Expand Down Expand Up @@ -99,7 +113,47 @@ func TestR1011LdPreloadHook(t *testing.T) {
Comm: "java",
}
// Test with exec event
ruleResult = r.ProcessEvent(utils.ExecveEventType, e2, &RuleObjectCacheMock{})
ruleResult = r.ProcessEvent(utils.ExecveEventType, e2, &objCache)
if ruleResult != nil {
t.Errorf("Expected ruleResult to be nil since exec event is on java")
}

e3 := &traceropentype.Event{
Event: eventtypes.Event{
CommonData: eventtypes.CommonData{
K8s: eventtypes.K8sMetadata{
BasicK8sMetadata: eventtypes.BasicK8sMetadata{
ContainerName: "test",
},
},
},
},
Comm: "test",
FullPath: "/etc/ld.so.preload",
FlagsRaw: 1,
}

objCache = RuleObjectCacheMock{}
profile = objCache.ApplicationProfileCache().GetApplicationProfile("test")
if profile == nil {
profile = &v1beta1.ApplicationProfile{
Spec: v1beta1.ApplicationProfileSpec{
Containers: []v1beta1.ApplicationProfileContainer{
{
Name: "test",
PolicyByRuleId: map[string]v1beta1.RulePolicy{
R1011ID: v1beta1.RulePolicy{
AllowedProcesses: []string{"test"},
},
},
},
},
},
}
objCache.SetApplicationProfile(profile)
}
// Test with exec event
ruleResult = r.ProcessEvent(utils.OpenEventType, e3, &objCache)
if ruleResult != nil {
t.Errorf("Expected ruleResult to be nil since exec event is on java")
}
Expand Down
87 changes: 46 additions & 41 deletions pkg/ruleengine/v1/r1012_hardlink_created_over_sensitive_file.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,58 +87,63 @@ func (rule *R1012HardlinkCreatedOverSensitiveFile) ProcessEvent(eventType utils.

if allowed, err := isAllowed(&hardlinkEvent.Event, objCache, hardlinkEvent.Comm, R1012ID); err != nil {
logger.L().Error("failed to check if hardlink is allowed", helpers.String("ruleID", rule.ID()), helpers.String("error", err.Error()))
return nil
} else if allowed {
return nil
}

for _, path := range rule.additionalPaths {
if strings.HasPrefix(hardlinkEvent.OldPath, path) {
return &GenericRuleFailure{
BaseRuntimeAlert: apitypes.BaseRuntimeAlert{
AlertName: rule.Name(),
Arguments: map[string]interface{}{
"oldPath": hardlinkEvent.OldPath,
"newPath": hardlinkEvent.NewPath,
},
InfectedPID: hardlinkEvent.Pid,
FixSuggestions: "If this is a legitimate action, please consider removing this workload from the binding of this rule.",
Severity: R1012HardlinkCreatedOverSensitiveFileRuleDescriptor.Priority,
},
RuntimeProcessDetails: apitypes.ProcessTree{
ProcessTree: apitypes.Process{
Comm: hardlinkEvent.Comm,
PPID: hardlinkEvent.PPid,
PID: hardlinkEvent.Pid,
UpperLayer: &hardlinkEvent.UpperLayer,
Uid: &hardlinkEvent.Uid,
Gid: &hardlinkEvent.Gid,
Path: hardlinkEvent.ExePath,
Hardlink: hardlinkEvent.ExePath,
},
ContainerID: hardlinkEvent.Runtime.ContainerID,
},
TriggerEvent: hardlinkEvent.Event,
RuleAlert: apitypes.RuleAlert{
RuleDescription: fmt.Sprintf("Hardlink created over sensitive file: %s - %s in: %s", hardlinkEvent.OldPath, hardlinkEvent.NewPath, hardlinkEvent.GetContainer()),
},
RuntimeAlertK8sDetails: apitypes.RuntimeAlertK8sDetails{
PodName: hardlinkEvent.GetPod(),
PodLabels: hardlinkEvent.K8s.PodLabels,
},
RuleID: rule.ID(),
}
}
return &GenericRuleFailure{
BaseRuntimeAlert: apitypes.BaseRuntimeAlert{
AlertName: rule.Name(),
Arguments: map[string]interface{}{
"oldPath": hardlinkEvent.OldPath,
"newPath": hardlinkEvent.NewPath,
},
InfectedPID: hardlinkEvent.Pid,
FixSuggestions: "If this is a legitimate action, please consider removing this workload from the binding of this rule.",
Severity: R1012HardlinkCreatedOverSensitiveFileRuleDescriptor.Priority,
},
RuntimeProcessDetails: apitypes.ProcessTree{
ProcessTree: apitypes.Process{
Comm: hardlinkEvent.Comm,
PPID: hardlinkEvent.PPid,
PID: hardlinkEvent.Pid,
UpperLayer: &hardlinkEvent.UpperLayer,
Uid: &hardlinkEvent.Uid,
Gid: &hardlinkEvent.Gid,
Path: hardlinkEvent.ExePath,
Hardlink: hardlinkEvent.ExePath,
},
ContainerID: hardlinkEvent.Runtime.ContainerID,
},
TriggerEvent: hardlinkEvent.Event,
RuleAlert: apitypes.RuleAlert{
RuleDescription: fmt.Sprintf("Hardlink created over sensitive file: %s - %s in: %s", hardlinkEvent.OldPath, hardlinkEvent.NewPath, hardlinkEvent.GetContainer()),
},
RuntimeAlertK8sDetails: apitypes.RuntimeAlertK8sDetails{
PodName: hardlinkEvent.GetPod(),
PodLabels: hardlinkEvent.K8s.PodLabels,
},
RuleID: rule.ID(),
}

return nil
}

func (rule *R1012HardlinkCreatedOverSensitiveFile) EvaluateRule(eventType utils.EventType, event utils.K8sEvent, _ objectcache.K8sObjectCache) bool {
if eventType != utils.HardlinkEventType {
return false
}
_, ok := event.(*tracerhardlinktype.Event)
return ok

hardlinkEvent, ok := event.(*tracerhardlinktype.Event)
if !ok {
return false
}

for _, path := range rule.additionalPaths {
if strings.HasPrefix(hardlinkEvent.OldPath, path) {
return true
}
}
return false
}

func (rule *R1012HardlinkCreatedOverSensitiveFile) Requirements() ruleengine.RuleSpec {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,18 +26,17 @@ func TestR1012HardlinkCreatedOverSensitiveFile(t *testing.T) {
Containers: []v1beta1.ApplicationProfileContainer{
{
Name: "test",
PolicyByRuleId: map[string]v1beta1.RulePolicy{
R1012ID: v1beta1.RulePolicy{
AllowedProcesses: []string{"/usr/sbin/groupadd"},
},
},
Opens: []v1beta1.OpenCalls{
{
Path: "/test",
Flags: []string{"O_RDONLY"},
},
},
Execs: []v1beta1.ExecCalls{
{
Path: "/usr/sbin/groupadd",
Args: []string{"test"},
},
},
},
},
},
Expand Down Expand Up @@ -90,7 +89,6 @@ func TestR1012HardlinkCreatedOverSensitiveFile(t *testing.T) {
e.Comm = "/usr/sbin/groupadd"
e.OldPath = "/etc/passwd"
e.NewPath = "/etc/abc"

ruleResult = r.ProcessEvent(utils.HardlinkEventType, e, &objCache)
if ruleResult != nil {
fmt.Printf("ruleResult: %v\n", ruleResult)
Expand Down

0 comments on commit e076c4e

Please sign in to comment.