Skip to content

Commit

Permalink
add guard time when scanning naked pods
Browse files Browse the repository at this point in the history
Signed-off-by: Matthias Bertschy <matthias.bertschy@gmail.com>
  • Loading branch information
matthyx committed Sep 2, 2024
1 parent 4617c94 commit 9abe5a0
Show file tree
Hide file tree
Showing 5 changed files with 57 additions and 8 deletions.
9 changes: 9 additions & 0 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,8 @@ type Config struct {
HTTPExporterConfig *exporters.HTTPExporterConfig `mapstructure:"httpExporterConfig"`
ExcludeNamespaces []string `mapstructure:"excludeNamespaces"`
IncludeNamespaces []string `mapstructure:"includeNamespaces"`
// PodScanGuardTime specifies the minimum age a pod without a parent must have before it is scanned
PodScanGuardTime time.Duration `mapstructure:"podScanGuardTime"`
}

// IConfig is an interface for all config types used in the operator
Expand All @@ -121,6 +123,7 @@ type IConfig interface {
KubescapeURL() string
KubevulnURL() string
SkipNamespace(ns string) bool
GuardTime() time.Duration
}

// OperatorConfig implements IConfig
Expand Down Expand Up @@ -185,6 +188,7 @@ func (c *OperatorConfig) MatchingRulesFilename() string {
func (c *OperatorConfig) GatewayWebsocketURL() string {
return c.clusterConfig.GatewayWebsocketURL
}

func (c *OperatorConfig) ConcurrencyWorkers() int {
return c.serviceConfig.ConcurrencyWorkers
}
Expand Down Expand Up @@ -224,6 +228,10 @@ func (c *OperatorConfig) EventReceiverURL() string {
return c.eventReceiverRestURL
}

func (c *OperatorConfig) GuardTime() time.Duration {
return c.serviceConfig.PodScanGuardTime
}

func LoadConfig(path string) (Config, error) {
viper.AddConfigPath(path)
viper.SetConfigName("config")
Expand All @@ -236,6 +244,7 @@ func LoadConfig(path string) (Config, error) {
viper.SetDefault("triggerSecurityFramework", false)
viper.SetDefault("matchingRulesFilename", "/etc/config/matchingRules.json")
viper.SetDefault("eventDeduplicationInterval", 2*time.Minute)
viper.SetDefault("podScanGuardTime", 3*time.Hour)

viper.AutomaticEnv()

Expand Down
1 change: 1 addition & 0 deletions config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ func TestLoadConfig(t *testing.T) {
EventDeduplicationInterval: 2 * time.Minute,
ExcludeNamespaces: []string{"kube-system", "kubescape"},
IncludeNamespaces: []string{},
PodScanGuardTime: 3 * time.Hour,
},
},
}
Expand Down
16 changes: 15 additions & 1 deletion mainhandler/handlerequests.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import (
"time"

"github.com/kubescape/backend/pkg/versioncheck"
"github.com/kubescape/k8s-interface/workloadinterface"
"k8s.io/apimachinery/pkg/runtime"

core1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
Expand Down Expand Up @@ -384,12 +386,24 @@ func (mainHandler *MainHandler) HandleImageScanningScopedRequest(ctx context.Con
pod.Kind = "Pod"

// get pod instanceIDs
instanceIDs, err := instanceidhandlerv1.GenerateInstanceIDFromPod(&pod)
unstructuredObj, err := runtime.DefaultUnstructuredConverter.ToUnstructured(&pod)
if err != nil {
logger.L().Ctx(ctx).Error("failed to convert pod to unstructured", helpers.String("pod", pod.GetName()), helpers.String("namespace", pod.GetNamespace()), helpers.Error(err))
continue
}
wl := workloadinterface.NewWorkloadObj(unstructuredObj)
instanceIDs, err := instanceidhandlerv1.GenerateInstanceID(wl)
if err != nil {
logger.L().Ctx(ctx).Error("failed to generate instance ID for pod", helpers.String("pod", pod.GetName()), helpers.String("namespace", pod.GetNamespace()), helpers.Error(err))
continue
}

// for naked pods, only handle if pod is older than guard time
if !k8sinterface.WorkloadHasParent(wl) && time.Now().Before(pod.CreationTimestamp.Add(mainHandler.config.GuardTime())) {
logger.L().Debug("naked pod younger than guard time detected, skipping scan", helpers.String("pod", pod.GetName()), helpers.String("namespace", pod.GetNamespace()), helpers.String("creationTimestamp", pod.CreationTimestamp.String()))
continue
}

for _, instanceID := range instanceIDs {
s, _ := instanceID.GetSlug(false)
if ok := slugs[s]; ok {
Expand Down
31 changes: 26 additions & 5 deletions watcher/podwatcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@ package watcher
import (
"context"
"errors"
"time"

mapset "github.com/deckarep/golang-set/v2"
"github.com/kubescape/k8s-interface/workloadinterface"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/tools/pager"

Expand Down Expand Up @@ -68,26 +70,45 @@ func (wh *WatchHandler) PodWatch(ctx context.Context, workerPool *ants.PoolWithF
if !ok {
continue
}
// handle pod events
switch event.Type {
case watch.Modified, watch.Added:
wh.handlePodWatcher(ctx, pod, workerPool)
case watch.Deleted:
unstructuredObj, err := runtime.DefaultUnstructuredConverter.ToUnstructured(pod)
if err != nil {
logger.L().Ctx(ctx).Error("failed to convert pod to unstructured", helpers.String("pod", pod.GetName()), helpers.String("namespace", pod.GetNamespace()), helpers.Error(err))
continue
}
wl := workloadinterface.NewWorkloadObj(unstructuredObj)
if !k8sinterface.WorkloadHasParent(wl) && time.Now().Before(pod.CreationTimestamp.Add(wh.cfg.GuardTime())) {
// for naked pods, only handle if pod still exists when older than guard time
untilPodMature := time.Until(pod.CreationTimestamp.Add(wh.cfg.GuardTime()))
logger.L().Debug("naked pod detected, delaying scan", helpers.String("pod", pod.GetName()), helpers.String("namespace", pod.GetNamespace()), helpers.String("time", untilPodMature.String()))
time.AfterFunc(untilPodMature, func() {
// use get to check if pod still exists, and refresh the pod object
pod, err := wh.k8sAPI.KubernetesClient.CoreV1().Pods(pod.Namespace).Get(context.Background(), pod.Name, v1.GetOptions{})
if err == nil {
wh.handlePodWatcher(ctx, pod, wl, workerPool)
}
})
} else {
wh.handlePodWatcher(ctx, pod, wl, workerPool)
}
default:
continue
}

}
return nil
}

// handlePodWatcher handles the pod watch events
func (wh *WatchHandler) handlePodWatcher(ctx context.Context, pod *core1.Pod, workerPool *ants.PoolWithFunc) {
func (wh *WatchHandler) handlePodWatcher(ctx context.Context, pod *core1.Pod, wl *workloadinterface.Workload, workerPool *ants.PoolWithFunc) {

// check if we need to add
pod.APIVersion = "v1"
pod.Kind = "Pod"

// get pod instanceIDs
instanceIDs, err := instanceidhandlerv1.GenerateInstanceIDFromPod(pod)
instanceIDs, err := instanceidhandlerv1.GenerateInstanceID(wl)
if err != nil {
logger.L().Ctx(ctx).Error("failed to generate instance ID for pod", helpers.String("pod", pod.GetName()), helpers.String("namespace", pod.GetNamespace()), helpers.Error(err))
return
Expand Down
8 changes: 6 additions & 2 deletions watcher/podwatcher_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"sync"
"testing"

"github.com/kubescape/k8s-interface/workloadinterface"
dynamicfake "k8s.io/client-go/dynamic/fake"

"github.com/armosec/armoapi-go/apis"
Expand Down Expand Up @@ -383,8 +384,11 @@ func Test_handlePodWatcher(t *testing.T) {
resourcesCreatedWg.Done()
})

for i := range tc.pods {
wh.handlePodWatcher(ctx, tc.pods[i], pool)
for _, pod := range tc.pods {
unstructuredObj, err := runtime.DefaultUnstructuredConverter.ToUnstructured(pod)
assert.NoError(t, err)
wl := workloadinterface.NewWorkloadObj(unstructuredObj)
wh.handlePodWatcher(ctx, pod, wl, pool)
}
resourcesCreatedWg.Wait()

Expand Down

0 comments on commit 9abe5a0

Please sign in to comment.