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

Improving rule r0006 #410

Merged
merged 7 commits into from
Nov 24, 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
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ require (
k8s.io/apimachinery v0.31.1
k8s.io/client-go v0.31.1
k8s.io/kubectl v0.31.0
k8s.io/kubelet v0.31.1
k8s.io/utils v0.0.0-20240711033017-18e509b52bc8
sigs.k8s.io/yaml v1.4.0
)
Expand Down Expand Up @@ -252,7 +253,6 @@ require (
k8s.io/cri-api v0.31.1 // indirect
k8s.io/klog/v2 v2.130.1 // indirect
k8s.io/kube-openapi v0.0.0-20240812233141-91dab695df6f // indirect
k8s.io/kubelet v0.31.1 // indirect
oras.land/oras-go/v2 v2.4.0 // indirect
sigs.k8s.io/controller-runtime v0.19.0 // indirect
sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd // indirect
Expand Down
125 changes: 82 additions & 43 deletions pkg/ruleengine/v1/r0006_unexpected_service_account_token_access.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package ruleengine

import (
"fmt"
"path/filepath"
"strings"

"github.com/kubescape/node-agent/pkg/objectcache"
Expand All @@ -10,17 +11,14 @@ import (

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

"github.com/kubescape/storage/pkg/apis/softwarecomposition/v1beta1"
)

const (
R0006ID = "R0006"
R0006Name = "Unexpected Service Account Token Access"
)

// ServiceAccountTokenPathsPrefixs is a list because of symlinks.
var serviceAccountTokenPathsPrefix = []string{
var serviceAccountTokenPathsPrefixes = []string{
"/run/secrets/kubernetes.io/serviceaccount",
"/var/run/secrets/kubernetes.io/serviceaccount",
"/run/secrets/eks.amazonaws.com/serviceaccount",
Expand All @@ -31,7 +29,7 @@ var R0006UnexpectedServiceAccountTokenAccessRuleDescriptor = ruleengine.RuleDesc
ID: R0006ID,
Name: R0006Name,
Description: "Detecting unexpected access to service account token.",
Tags: []string{"token", "malicious", "whitelisted"},
Tags: []string{"token", "malicious", "security", "kubernetes"},
Priority: RulePriorityHigh,
Requirements: &RuleRequirements{
EventTypes: []utils.EventType{
Expand All @@ -42,15 +40,68 @@ var R0006UnexpectedServiceAccountTokenAccessRuleDescriptor = ruleengine.RuleDesc
return CreateRuleR0006UnexpectedServiceAccountTokenAccess()
},
}
var _ ruleengine.RuleEvaluator = (*R0006UnexpectedServiceAccountTokenAccess)(nil)

type R0006UnexpectedServiceAccountTokenAccess struct {
BaseRule
}

// getTokenBasePath returns the base service account token path if the path is a token path,
// otherwise returns an empty string. Using a single iteration through prefixes.
func getTokenBasePath(path string) string {
for _, prefix := range serviceAccountTokenPathsPrefixes {
if strings.HasPrefix(path, prefix) {
return prefix
}
}
return ""
}

// normalizeTokenPath removes timestamp directories from the path while maintaining
// the essential structure. Optimized for minimal allocations.
func normalizeTokenPath(path string) string {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do you have a time constraint on this? because splitting and joining strings are really wasteful
you can check how much fun we had with indexing strings in https://github.com/kubescape/storage/blob/2b75b33130a55255df7575dc473a49858e3e325d/pkg/registry/file/dynamicpathdetector/analyzer.go#L137

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you have a better suggestion? I am not that worried about performance because we first filter the prefix, wdyt?

// Get the base path - if not a token path, return original
basePath := getTokenBasePath(path)
if basePath == "" {
return path
}

// Get the final component (usually "token", "ca.crt", etc.)
finalComponent := filepath.Base(path)

// Split the middle part (between base path and final component)
middle := strings.TrimPrefix(filepath.Dir(path), basePath)
if middle == "" {
return filepath.Join(basePath, finalComponent)
}

// Process middle parts
var normalizedMiddle strings.Builder
parts := strings.Split(middle, "/")
for _, part := range parts {
if part == "" {
continue
}
// Skip timestamp directories (starting with ".." and containing "_")
if strings.HasPrefix(part, "..") && strings.Contains(part, "_") {
continue
}
normalizedMiddle.WriteString("/")
normalizedMiddle.WriteString(part)
}

// If no middle parts remain, join base and final
if normalizedMiddle.Len() == 0 {
return filepath.Join(basePath, finalComponent)
}

// Join all parts
return basePath + normalizedMiddle.String() + "/" + finalComponent
}

func CreateRuleR0006UnexpectedServiceAccountTokenAccess() *R0006UnexpectedServiceAccountTokenAccess {
return &R0006UnexpectedServiceAccountTokenAccess{}
}

func (rule *R0006UnexpectedServiceAccountTokenAccess) Name() string {
return R0006Name
}
Expand All @@ -59,24 +110,10 @@ func (rule *R0006UnexpectedServiceAccountTokenAccess) ID() string {
return R0006ID
}

func (rule *R0006UnexpectedServiceAccountTokenAccess) DeleteRule() {
}

func (rule *R0006UnexpectedServiceAccountTokenAccess) generatePatchCommand(event *traceropentype.Event, ap *v1beta1.ApplicationProfile) string {
flagList := "["
for _, arg := range event.Flags {
flagList += "\"" + arg + "\","
}
// remove the last comma
if len(flagList) > 1 {
flagList = flagList[:len(flagList)-1]
}
baseTemplate := "kubectl patch applicationprofile %s --namespace %s --type merge -p '{\"spec\": {\"containers\": [{\"name\": \"%s\", \"opens\": [{\"path\": \"%s\", \"flags\": %s}]}]}}'"
return fmt.Sprintf(baseTemplate, ap.GetName(), ap.GetNamespace(),
event.GetContainer(), event.FullPath, flagList)
}
func (rule *R0006UnexpectedServiceAccountTokenAccess) DeleteRule() {}

func (rule *R0006UnexpectedServiceAccountTokenAccess) ProcessEvent(eventType utils.EventType, event utils.K8sEvent, objCache objectcache.ObjectCache) ruleengine.RuleFailure {
// Quick type checks first
if eventType != utils.OpenEventType {
return nil
}
Expand All @@ -86,19 +123,12 @@ func (rule *R0006UnexpectedServiceAccountTokenAccess) ProcessEvent(eventType uti
return nil
}

shouldCheckEvent := false

for _, prefix := range serviceAccountTokenPathsPrefix {
if strings.HasPrefix(openEvent.FullPath, prefix) {
shouldCheckEvent = true
break
}
}

if !shouldCheckEvent {
// Check if this is a token path - using optimized check
if getTokenBasePath(openEvent.FullPath) == "" {
return nil
}

// Get the application profile
ap := objCache.ApplicationProfileCache().GetApplicationProfile(openEvent.Runtime.ContainerID)
if ap == nil {
return nil
Expand All @@ -109,24 +139,30 @@ func (rule *R0006UnexpectedServiceAccountTokenAccess) ProcessEvent(eventType uti
return nil
}

// Normalize the accessed path once
normalizedAccessedPath := normalizeTokenPath(openEvent.FullPath)
dirPath := filepath.Dir(normalizedAccessedPath)

// Check against whitelisted paths
for _, open := range appProfileOpenList.Opens {
for _, prefix := range serviceAccountTokenPathsPrefix {
if strings.HasPrefix(open.Path, prefix) {
return nil
}
if dirPath == filepath.Dir(normalizeTokenPath(open.Path)) {
return nil
}
}

ruleFailure := GenericRuleFailure{
// If we get here, the access was not whitelisted - create an alert
return &GenericRuleFailure{
BaseRuntimeAlert: apitypes.BaseRuntimeAlert{
AlertName: rule.Name(),
Arguments: map[string]interface{}{
"path": openEvent.FullPath,
"flags": openEvent.Flags,
},
InfectedPID: openEvent.Pid,
FixSuggestions: fmt.Sprintf("If this is a valid behavior, please add the open call \"%s\" to the whitelist in the application profile for the Pod \"%s\". You can use the following command: %s", openEvent.FullPath, openEvent.GetPod(), rule.generatePatchCommand(openEvent, ap)),
Severity: R0006UnexpectedServiceAccountTokenAccessRuleDescriptor.Priority,
InfectedPID: openEvent.Pid,
FixSuggestions: fmt.Sprintf(
"If this is a valid behavior, please add the open call to the whitelist in the application profile for the Pod %s",
openEvent.GetPod()),
Severity: R0006UnexpectedServiceAccountTokenAccessRuleDescriptor.Priority,
},
RuntimeProcessDetails: apitypes.ProcessTree{
ProcessTree: apitypes.Process{
Expand All @@ -139,16 +175,19 @@ func (rule *R0006UnexpectedServiceAccountTokenAccess) ProcessEvent(eventType uti
},
TriggerEvent: openEvent.Event,
RuleAlert: apitypes.RuleAlert{
RuleDescription: fmt.Sprintf("Unexpected access to service account token: %s with flags: %s in: %s", openEvent.FullPath, strings.Join(openEvent.Flags, ","), openEvent.GetContainer()),
RuleDescription: fmt.Sprintf(
"Unexpected access to service account token: %s with flags: %s in: %s",
openEvent.FullPath,
strings.Join(openEvent.Flags, ","),
openEvent.GetContainer(),
),
},
RuntimeAlertK8sDetails: apitypes.RuntimeAlertK8sDetails{
PodName: openEvent.GetPod(),
PodLabels: openEvent.K8s.PodLabels,
},
RuleID: rule.ID(),
}

return &ruleFailure
}

func (rule *R0006UnexpectedServiceAccountTokenAccess) Requirements() ruleengine.RuleSpec {
Expand Down
Loading
Loading