Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding rules #300

Merged
merged 6 commits into from
May 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions pkg/ruleengine/v1/factory.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ func NewRuleCreator() *RuleCreatorImpl {
R0007KubernetesClientExecutedDescriptor,
R0008ReadEnvironmentVariablesProcFSRuleDescriptor,
R0009EbpfProgramLoadRuleDescriptor,
R0010UnexpectedSensitiveFileAccessRuleDescriptor,
R1000ExecFromMaliciousSourceDescriptor,
R1001ExecBinaryNotInBaseImageRuleDescriptor,
R1002LoadKernelModuleRuleDescriptor,
Expand All @@ -30,6 +31,8 @@ func NewRuleCreator() *RuleCreatorImpl {
R1007XMRCryptoMiningRuleDescriptor,
R1008CryptoMiningDomainCommunicationRuleDescriptor,
R1009CryptoMiningRelatedPortRuleDescriptor,
// R1010SymlinkCreatedOverSensitiveFileRuleDescriptor,
R1011LdPreloadHookRuleDescriptor,
},
}
}
Expand Down
23 changes: 23 additions & 0 deletions pkg/ruleengine/v1/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,17 @@ import (
"github.com/kubescape/storage/pkg/apis/softwarecomposition/v1beta1"
)

// SensitiveFiles is a list of sensitive files that should not be accessed by the application unexpectedly.
var SensitiveFiles = []string{
"/etc/shadow",
"/etc/passwd",
"/etc/sudoers",
"/etc/ssh/sshd_config",
"/etc/ssh/ssh_config",
"/etc/pam.d",
"/etc/group",
}

var (
ContainerNotFound = errors.New("container not found")
ProfileNotFound = errors.New("application profile not found")
Expand Down Expand Up @@ -130,3 +141,15 @@ func isExecEventInProfile(execEvent *tracerexectype.Event, objectCache objectcac
}
return false, nil
}

func interfaceToStringSlice(val interface{}) ([]string, bool) {
sliceOfInterfaces, ok := val.([]interface{})
if ok {
sliceOfStrings := []string{}
for _, interfaceVal := range sliceOfInterfaces {
sliceOfStrings = append(sliceOfStrings, fmt.Sprintf("%v", interfaceVal))
}
return sliceOfStrings, true
}
return nil, false
}
13 changes: 0 additions & 13 deletions pkg/ruleengine/v1/r0002_unexpected_file_access.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,18 +56,6 @@ func (rule *R0002UnexpectedFileAccess) ID() string {
return R0002ID
}

func interfaceToStringSlice(val interface{}) ([]string, bool) {
sliceOfInterfaces, ok := val.([]interface{})
if ok {
sliceOfStrings := []string{}
for _, interfaceVal := range sliceOfInterfaces {
sliceOfStrings = append(sliceOfStrings, fmt.Sprintf("%v", interfaceVal))
}
return sliceOfStrings, true
}
return nil, false
}

func (rule *R0002UnexpectedFileAccess) SetParameters(parameters map[string]interface{}) {
rule.BaseRule.SetParameters(parameters)

Expand All @@ -86,7 +74,6 @@ func (rule *R0002UnexpectedFileAccess) SetParameters(parameters map[string]inter
} else {
logger.L().Warning("failed to convert ignorePrefixes to []string", helpers.String("ruleID", rule.ID()))
}

}

func (rule *R0002UnexpectedFileAccess) DeleteRule() {
Expand Down
16 changes: 16 additions & 0 deletions pkg/ruleengine/v1/r0009_ebpf_program_load.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"node-agent/pkg/objectcache"
"node-agent/pkg/ruleengine"
"node-agent/pkg/utils"
"slices"

tracersyscallstype "github.com/inspektor-gadget/inspektor-gadget/pkg/gadgets/traceloop/types"

Expand Down Expand Up @@ -63,6 +64,21 @@ func (rule *R0009EbpfProgramLoad) ProcessEvent(eventType utils.EventType, event
return nil
}

ap := objCache.ApplicationProfileCache().GetApplicationProfile(syscallEvent.Runtime.ContainerID)
if ap == nil {
return nil
}

appProfileSyscallList, err := getContainerFromApplicationProfile(ap, syscallEvent.GetContainer())
if err != nil {
return nil
}

// Check if the syscall is in the list of allowed syscalls
if slices.Contains(appProfileSyscallList.Syscalls, syscallEvent.Syscall) {
return nil
}

if syscallEvent.Syscall == "bpf" && syscallEvent.Parameters[0].Name == "cmd" && syscallEvent.Parameters[0].Value == fmt.Sprintf("%d", BPF_PROG_LOAD) {
ruleFailure := GenericRuleFailure{
BaseRuntimeAlert: apitypes.BaseRuntimeAlert{
Expand Down
52 changes: 35 additions & 17 deletions pkg/ruleengine/v1/r0009_ebpf_program_load_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import (
"testing"

tracersyscallstype "github.com/inspektor-gadget/inspektor-gadget/pkg/gadgets/traceloop/types"
eventtypes "github.com/inspektor-gadget/inspektor-gadget/pkg/types"
"github.com/kubescape/storage/pkg/apis/softwarecomposition/v1beta1"
)

func TestR0009EbpfProgramLoad(t *testing.T) {
Expand All @@ -16,26 +18,49 @@ func TestR0009EbpfProgramLoad(t *testing.T) {
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",
Opens: []v1beta1.OpenCalls{
{
Path: "/test",
Flags: []string{"O_RDONLY"},
},
},
},
},
},
}
objCache.SetApplicationProfile(profile)
}

// Create a syscall event
e := &tracersyscallstype.Event{
Event: eventtypes.Event{
CommonData: eventtypes.CommonData{
K8s: eventtypes.K8sMetadata{
BasicK8sMetadata: eventtypes.BasicK8sMetadata{
ContainerName: "test",
},
},
},
},
Comm: "test",
Syscall: "test",
}

ruleResult := r.ProcessEvent(utils.SyscallEventType, e, &RuleObjectCacheMock{})
ruleResult := r.ProcessEvent(utils.SyscallEventType, e, &objCache)
if ruleResult != nil {
fmt.Printf("ruleResult: %v\n", ruleResult)
t.Errorf("Expected ruleResult to be nil since syscall is not bpf")
return
}

// Create a new rule
r2 := CreateRuleR0009EbpfProgramLoad()
// Assert r is not nil
if r2 == nil {
t.Errorf("Expected r to not be nil")
}

// Create a syscall event with bpf syscall
e.Syscall = "bpf"
e.Parameters = []tracersyscallstype.SyscallParam{
Expand All @@ -45,23 +70,16 @@ func TestR0009EbpfProgramLoad(t *testing.T) {
},
}

ruleResult = r2.ProcessEvent(utils.SyscallEventType, e, &RuleObjectCacheMock{})
ruleResult = r.ProcessEvent(utils.SyscallEventType, e, &objCache)
if ruleResult == nil {
fmt.Printf("ruleResult: %v\n", ruleResult)
t.Errorf("Expected ruleResult to be Failure because of bpf is used")
return
}

// Create a new rule
r3 := CreateRuleR0009EbpfProgramLoad()
// Assert r is not nil
if r3 == nil {
t.Errorf("Expected r to not be nil")
}

// Create a syscall event with bpf syscall but not BPF_PROG_LOAD
e.Parameters[0].Value = "1"
ruleResult = r3.ProcessEvent(utils.SyscallEventType, e, &RuleObjectCacheMock{})
ruleResult = r.ProcessEvent(utils.SyscallEventType, e, &objCache)
if ruleResult != nil {
fmt.Printf("ruleResult: %v\n", ruleResult)
t.Errorf("Expected ruleResult to be nil since syscall is bpf but not BPF_PROG_LOAD")
Expand Down
149 changes: 149 additions & 0 deletions pkg/ruleengine/v1/r0010_unexpected_sensitive_file_access.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
package ruleengine

import (
"fmt"
"node-agent/pkg/objectcache"
"node-agent/pkg/ruleengine"
"node-agent/pkg/utils"
"strings"

apitypes "github.com/armosec/armoapi-go/armotypes"
traceropentype "github.com/inspektor-gadget/inspektor-gadget/pkg/gadgets/trace/open/types"
"github.com/kubescape/go-logger"
"github.com/kubescape/go-logger/helpers"
)

const (
R0010ID = "R0010"
R0010Name = "Unexpected Sensitive File Access"
)

var R0010UnexpectedSensitiveFileAccessRuleDescriptor = RuleDescriptor{
ID: R0010ID,
Name: R0010Name,
Description: "Detecting access to sensitive files.",
Tags: []string{"files", "malicious", "whitelisted"},
Priority: RulePriorityMed,
Requirements: &RuleRequirements{
EventTypes: []utils.EventType{
utils.OpenEventType,
},
},
RuleCreationFunc: func() ruleengine.RuleEvaluator {
return CreateRuleR0010UnexpectedSensitiveFileAccess()
},
}
var _ ruleengine.RuleEvaluator = (*R0010UnexpectedSensitiveFileAccess)(nil)

type R0010UnexpectedSensitiveFileAccess struct {
BaseRule
additionalPaths []string
}

func CreateRuleR0010UnexpectedSensitiveFileAccess() *R0010UnexpectedSensitiveFileAccess {
return &R0010UnexpectedSensitiveFileAccess{
additionalPaths: SensitiveFiles,
}
}

func (rule *R0010UnexpectedSensitiveFileAccess) SetParameters(parameters map[string]interface{}) {
rule.BaseRule.SetParameters(parameters)

additionalPathsInterface := rule.GetParameters()["additionalPaths"]
if additionalPathsInterface == nil {
return
}

additionalPaths, ok := interfaceToStringSlice(additionalPathsInterface)
if ok {
for _, path := range additionalPaths {
rule.additionalPaths = append(rule.additionalPaths, fmt.Sprintf("%v", path))
}
} else {
logger.L().Warning("failed to convert additionalPaths to []string", helpers.String("ruleID", rule.ID()))
}
}

func (rule *R0010UnexpectedSensitiveFileAccess) Name() string {
return R0010Name
}

func (rule *R0010UnexpectedSensitiveFileAccess) ID() string {
return R0010ID
}

func (rule *R0010UnexpectedSensitiveFileAccess) DeleteRule() {
}

func (rule *R0010UnexpectedSensitiveFileAccess) ProcessEvent(eventType utils.EventType, event interface{}, objCache objectcache.ObjectCache) ruleengine.RuleFailure {
if eventType != utils.OpenEventType {
return nil
}

openEvent, ok := event.(*traceropentype.Event)
if !ok {
return nil
}

ap := objCache.ApplicationProfileCache().GetApplicationProfile(openEvent.Runtime.ContainerID)
if ap == nil {
return nil
}

appProfileOpenList, err := getContainerFromApplicationProfile(ap, openEvent.GetContainer())
if err != nil {
return nil
}

isSensitive := false
for _, path := range rule.additionalPaths {
if strings.HasPrefix(openEvent.FullPath, path) {
isSensitive = true
break
}
}

if !isSensitive {
return nil
}

for _, open := range appProfileOpenList.Opens {
if open.Path == openEvent.FullPath {
return nil
}
}

ruleFailure := GenericRuleFailure{
BaseRuntimeAlert: apitypes.BaseRuntimeAlert{
AlertName: rule.Name(),
InfectedPID: openEvent.Pid,
FixSuggestions: "If this is a legitimate action, please consider removing this workload from the binding of this rule.",
Severity: R0010UnexpectedSensitiveFileAccessRuleDescriptor.Priority,
},
RuntimeProcessDetails: apitypes.ProcessTree{
ProcessTree: apitypes.Process{
Comm: openEvent.Comm,
Gid: &openEvent.Gid,
PID: openEvent.Pid,
Uid: &openEvent.Uid,
},
ContainerID: openEvent.Runtime.ContainerID,
},
TriggerEvent: openEvent.Event,
RuleAlert: apitypes.RuleAlert{
RuleID: rule.ID(),
RuleDescription: fmt.Sprintf("Unexpected sensitive file access: %s in: %s", openEvent.FullPath, openEvent.GetContainer()),
},
RuntimeAlertK8sDetails: apitypes.RuntimeAlertK8sDetails{
PodName: openEvent.GetPod(),
},
}

return &ruleFailure
}

func (rule *R0010UnexpectedSensitiveFileAccess) Requirements() ruleengine.RuleSpec {
return &RuleRequirements{
EventTypes: R0010UnexpectedSensitiveFileAccessRuleDescriptor.Requirements.RequiredEventTypes(),
}
}
Loading
Loading