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

feat(core): add support for kata and confidential containers #1888

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
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
18 changes: 17 additions & 1 deletion KubeArmor/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,9 @@ type KubearmorConfig struct {
DefaultPostureLogs bool // Enable/Disable Default Posture logs for AppArmor LSM
InitTimeout string // Timeout for main thread init stages

StateAgent bool // enable KubeArmor state agent
UseOCIHooks bool // Use OCI hooks for container visibility instead of CRI socket
StateAgent bool // enable KubeArmor state agent
RestorePath string // Path to restore policies from

AlertThrottling bool // Enable/Disable Alert Throttling
MaxAlertPerSec int // Maximum alerts allowed per second
Expand Down Expand Up @@ -96,6 +98,8 @@ const (
ConfigCoverageTest string = "coverageTest"
ConfigK8sEnv string = "k8s"
ConfigDebug string = "debug"
UseOCIHooks string = "useOCIHooks"
RestorePath string = "restorePath"
ConfigUntrackedNs string = "untrackedNs"
LsmOrder string = "lsm"
BPFFsPath string = "bpfFsPath"
Expand Down Expand Up @@ -156,6 +160,10 @@ func readCmdLineParams() {

stateAgent := flag.Bool(ConfigStateAgent, false, "enabling KubeArmor State Agent client")

useOCIHooks := flag.Bool(UseOCIHooks, false, "Use OCI hooks to get new containers instead of using container runtime socket")

restorePath := flag.String(RestorePath, PolicyDir, "Path to restore policies from")

alertThrottling := flag.Bool(ConfigAlertThrottling, true, "enabling Alert Throttling")

maxAlertPerSec := flag.Int(ConfigMaxAlertPerSec, 10, "Maximum alerts allowed per second")
Expand Down Expand Up @@ -220,6 +228,10 @@ func readCmdLineParams() {

viper.SetDefault(ConfigStateAgent, *stateAgent)

viper.SetDefault(UseOCIHooks, *useOCIHooks)

viper.SetDefault(RestorePath, *restorePath)

viper.SetDefault(ConfigAlertThrottling, *alertThrottling)

viper.SetDefault(ConfigMaxAlertPerSec, *maxAlertPerSec)
Expand Down Expand Up @@ -324,6 +336,10 @@ func LoadConfig() error {

GlobalCfg.StateAgent = viper.GetBool(ConfigStateAgent)

GlobalCfg.UseOCIHooks = viper.GetBool(UseOCIHooks)

GlobalCfg.RestorePath = viper.GetString(RestorePath)

GlobalCfg.AlertThrottling = viper.GetBool(ConfigAlertThrottling)
GlobalCfg.MaxAlertPerSec = viper.GetInt(ConfigMaxAlertPerSec)
GlobalCfg.ThrottleSec = viper.GetInt(ConfigThrottleSec)
Expand Down
74 changes: 4 additions & 70 deletions KubeArmor/core/containerdHandler.go
Original file line number Diff line number Diff line change
Expand Up @@ -335,61 +335,11 @@ func (dm *KubeArmorDaemon) UpdateContainerdContainer(ctx context.Context, contai
}
}

switch endPointEvent {
case "ADDED":
endPoint.EndPointName = container.ContainerName
endPoint.ContainerName = container.ContainerName
endPoint.NamespaceName = container.NamespaceName

endPoint.Containers = []string{container.ContainerID}

endPoint.Labels = containerLabels
endPoint.Identities = containerIdentities

endPoint.PolicyEnabled = tp.KubeArmorPolicyEnabled
endPoint.ProcessVisibilityEnabled = true
endPoint.FileVisibilityEnabled = true
endPoint.NetworkVisibilityEnabled = true
endPoint.CapabilitiesVisibilityEnabled = true

endPoint.AppArmorProfiles = []string{"kubearmor_" + container.ContainerName}

globalDefaultPosture := tp.DefaultPosture{
FileAction: cfg.GlobalCfg.DefaultFilePosture,
NetworkAction: cfg.GlobalCfg.DefaultNetworkPosture,
CapabilitiesAction: cfg.GlobalCfg.DefaultCapabilitiesPosture,
}
endPoint.DefaultPosture = globalDefaultPosture

dm.SecurityPoliciesLock.RLock()
for _, secPol := range dm.SecurityPolicies {
if kl.MatchIdentities(secPol.Spec.Selector.Identities, endPoint.Identities) {
endPoint.SecurityPolicies = append(endPoint.SecurityPolicies, secPol)
}
}
dm.SecurityPoliciesLock.RUnlock()

dm.EndPoints = append(dm.EndPoints, endPoint)
case "UPDATED":
// in case of AppArmor enforcement when endPoint has to be created first
endPoint.Containers = append(endPoint.Containers, container.ContainerID)

// if this container has any additional identities, add them
endPoint.Identities = append(endPoint.Identities, containerIdentities...)
endPoint.Identities = slices.Compact(endPoint.Identities)

// add other policies
endPoint.SecurityPolicies = []tp.SecurityPolicy{}
dm.SecurityPoliciesLock.RLock()
for _, secPol := range dm.SecurityPolicies {
if kl.MatchIdentities(secPol.Spec.Selector.Identities, endPoint.Identities) {
endPoint.SecurityPolicies = append(endPoint.SecurityPolicies, secPol)
}
}
dm.SecurityPoliciesLock.RUnlock()

dm.CreateEndpoint(&endPoint, container, containerLabels, containerIdentities, endPointEvent)
if endPointEvent == "UPDATED" {
dm.EndPoints[endPointIdx] = endPoint
}

dm.EndPointsLock.Unlock()
}

Expand Down Expand Up @@ -457,23 +407,7 @@ func (dm *KubeArmorDaemon) UpdateContainerdContainer(ctx context.Context, contai
}

if dm.SystemMonitor != nil && cfg.GlobalCfg.Policy {
// for throttling
dm.SystemMonitor.Logger.ContainerNsKey[containerID] = common.OuterKey{
MntNs: container.MntNS,
PidNs: container.PidNS,
}

// update NsMap
dm.SystemMonitor.AddContainerIDToNsMap(containerID, container.NamespaceName, container.PidNS, container.MntNS)
dm.RuntimeEnforcer.RegisterContainer(containerID, container.PidNS, container.MntNS)

if len(endPoint.SecurityPolicies) > 0 { // struct can be empty or no policies registered for the endPoint yet
dm.Logger.UpdateSecurityPolicies("ADDED", endPoint)
if dm.RuntimeEnforcer != nil && endPoint.PolicyEnabled == tp.KubeArmorPolicyEnabled {
// enforce security policies
dm.RuntimeEnforcer.UpdateSecurityPolicies(endPoint)
}
}
dm.PopulateMaps(endPoint, container)
}

if cfg.GlobalCfg.StateAgent {
Expand Down
74 changes: 4 additions & 70 deletions KubeArmor/core/dockerHandler.go
Original file line number Diff line number Diff line change
Expand Up @@ -496,61 +496,11 @@ func (dm *KubeArmorDaemon) UpdateDockerContainer(containerID, action string) {
}
}

switch endPointEvent {
case "ADDED":
endPoint.EndPointName = container.ContainerName
endPoint.ContainerName = container.ContainerName
endPoint.NamespaceName = container.NamespaceName

endPoint.Containers = []string{container.ContainerID}

endPoint.Labels = containerLabels
endPoint.Identities = containerIdentities

endPoint.PolicyEnabled = tp.KubeArmorPolicyEnabled
endPoint.ProcessVisibilityEnabled = true
endPoint.FileVisibilityEnabled = true
endPoint.NetworkVisibilityEnabled = true
endPoint.CapabilitiesVisibilityEnabled = true

endPoint.AppArmorProfiles = []string{"kubearmor_" + container.ContainerName}

globalDefaultPosture := tp.DefaultPosture{
FileAction: cfg.GlobalCfg.DefaultFilePosture,
NetworkAction: cfg.GlobalCfg.DefaultNetworkPosture,
CapabilitiesAction: cfg.GlobalCfg.DefaultCapabilitiesPosture,
}
endPoint.DefaultPosture = globalDefaultPosture

dm.SecurityPoliciesLock.RLock()
for _, secPol := range dm.SecurityPolicies {
if kl.MatchIdentities(secPol.Spec.Selector.Identities, endPoint.Identities) {
endPoint.SecurityPolicies = append(endPoint.SecurityPolicies, secPol)
}
}
dm.SecurityPoliciesLock.RUnlock()

dm.EndPoints = append(dm.EndPoints, endPoint)
case "UPDATED":
// in case of AppArmor enforcement when endpoint has to be created first
endPoint.Containers = append(endPoint.Containers, container.ContainerID)

// if this container has any additional identities, add them
endPoint.Identities = append(endPoint.Identities, containerIdentities...)
endPoint.Identities = slices.Compact(endPoint.Identities)

// add other policies
endPoint.SecurityPolicies = []tp.SecurityPolicy{}
dm.SecurityPoliciesLock.RLock()
for _, secPol := range dm.SecurityPolicies {
if kl.MatchIdentities(secPol.Spec.Selector.Identities, endPoint.Identities) {
endPoint.SecurityPolicies = append(endPoint.SecurityPolicies, secPol)
}
}
dm.SecurityPoliciesLock.RUnlock()

dm.CreateEndpoint(&endPoint, container, containerLabels, containerIdentities, endPointEvent)
if endPointEvent == "UPDATED" {
dm.EndPoints[endPointIdx] = endPoint
}

dm.EndPointsLock.Unlock()
}

Expand Down Expand Up @@ -607,23 +557,7 @@ func (dm *KubeArmorDaemon) UpdateDockerContainer(containerID, action string) {
}

if dm.SystemMonitor != nil && cfg.GlobalCfg.Policy {
// for throttling
dm.SystemMonitor.Logger.ContainerNsKey[containerID] = common.OuterKey{
MntNs: container.MntNS,
PidNs: container.PidNS,
}

// update NsMap
dm.SystemMonitor.AddContainerIDToNsMap(containerID, container.NamespaceName, container.PidNS, container.MntNS)
dm.RuntimeEnforcer.RegisterContainer(containerID, container.PidNS, container.MntNS)

if len(endPoint.SecurityPolicies) > 0 { // struct can be empty or no policies registered for the endpoint yet
dm.Logger.UpdateSecurityPolicies("ADDED", endPoint)
if dm.RuntimeEnforcer != nil && endPoint.PolicyEnabled == tp.KubeArmorPolicyEnabled {
// enforce security policies
dm.RuntimeEnforcer.UpdateSecurityPolicies(endPoint)
}
}
dm.PopulateMaps(endPoint, container)
}

if cfg.GlobalCfg.StateAgent {
Expand Down
160 changes: 160 additions & 0 deletions KubeArmor/core/hookHandler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
// SPDX-License-Identifier: Apache-2.0
// Copyright 2022 Authors of KubeArmor

package core

import (
"encoding/json"
"io"
"log"
"os"
"strings"

"github.com/fsnotify/fsnotify"
kl "github.com/kubearmor/KubeArmor/KubeArmor/common"
cfg "github.com/kubearmor/KubeArmor/KubeArmor/config"
"github.com/kubearmor/KubeArmor/KubeArmor/state"
tp "github.com/kubearmor/KubeArmor/KubeArmor/types"
)

func (dm *KubeArmorDaemon) HandleFile(file string) {
f, err := os.Open(file)
if err != nil {
log.Fatalln("Error opening file:", err)
}

decoder := json.NewDecoder(f)
for {
var containerData tp.Container

err = decoder.Decode(&containerData)
if err != nil {
dm.Logger.Warnf("Reached EOF")
}
dm.handleContainerCreate(containerData)
if err == io.EOF {
// End of file reached
break
}
}

defer f.Close()

w, err := fsnotify.NewWatcher()
if err != nil {
log.Fatal("Error creating new watcher:", err)
}
defer w.Close()

err = w.Add(file)
if err != nil {
log.Fatal("Error adding file to watcher:", err)
}

for {
select {
case err, ok := <-w.Errors:
if !ok {
dm.Logger.Warnf("Returning 1")
return
}
log.Println("Watcher error:", err)

case e, ok := <-w.Events:
if !ok {
dm.Logger.Warnf("Returning 2")
return
}

if e.Op&fsnotify.Write == fsnotify.Write {
f, err := os.Open(file)
if err != nil {
log.Println("Error opening file:", err)
continue
}
defer f.Close()

decoder := json.NewDecoder(f)
for {
var containerData tp.Container

err = decoder.Decode(&containerData)
if err != nil {
dm.Logger.Warnf("Reached EOF")
}
dm.handleContainerCreate(containerData)
if err == io.EOF {
// End of file reached
break
}
}
}
}
}
}

func (dm *KubeArmorDaemon) handleContainerCreate(container tp.Container) {
endPoint := tp.EndPoint{}

dm.ContainersLock.Lock()
defer dm.ContainersLock.Unlock()
if _, ok := dm.Containers[container.ContainerID]; !ok {
dm.Containers[container.ContainerID] = container

// create/update endpoint in non-k8s mode
if !dm.K8sEnabled {
// for policy matching
container.NamespaceName = "container_namespace"
labels := []string{}
labels = append(labels, "namespaceName="+container.NamespaceName)
labels = append(labels, "kubearmor.io/container.name="+container.ContainerName)
container.Labels = strings.Join(labels, ",")

containerLabels, containerIdentities := kl.GetLabelsFromString(container.Labels)
dm.EndPointsLock.Lock()
dm.CreateEndpoint(&endPoint, container, containerLabels, containerIdentities, "ADDED")
dm.EndPointsLock.Unlock()
}
} else if dm.Containers[container.ContainerID].PidNS == 0 && dm.Containers[container.ContainerID].MntNS == 0 {
c := dm.Containers[container.ContainerID]
c.MntNS = container.MntNS
c.PidNS = container.PidNS
c.AppArmorProfile = container.AppArmorProfile
dm.Containers[c.ContainerID] = c

dm.EndPointsLock.Lock()
for idx, endpoint := range dm.EndPoints {
if endpoint.NamespaceName == container.NamespaceName && endpoint.EndPointName == container.EndPointName && kl.ContainsElement(endPoint.Containers, container.ContainerID) {

// update apparmor profiles
if !kl.ContainsElement(endpoint.AppArmorProfiles, container.AppArmorProfile) {
dm.EndPoints[idx].AppArmorProfiles = append(dm.EndPoints[idx].AppArmorProfiles, container.AppArmorProfile)
}

if container.Privileged && dm.EndPoints[idx].PrivilegedContainers != nil {
dm.EndPoints[idx].PrivilegedContainers[container.ContainerName] = struct{}{}
}

endPoint = dm.EndPoints[idx]

break
}
}
dm.EndPointsLock.Unlock()
}

if len(dm.OwnerInfo) > 0 {
container.Owner = dm.OwnerInfo[container.EndPointName]
}

if dm.SystemMonitor != nil && cfg.GlobalCfg.Policy {
dm.PopulateMaps(endPoint, container)
}

if cfg.GlobalCfg.StateAgent {
container.Status = "running"
go dm.StateAgent.PushContainerEvent(container, state.EventAdded)
}

dm.Logger.Printf("Detected a container (added/%.12s/pidns=%d/mntns=%d)", container.ContainerID, container.PidNS, container.MntNS)
}
Loading
Loading