Skip to content

Commit

Permalink
fix,core: restore container policy
Browse files Browse the repository at this point in the history
We had a bug where we restored Backed Up container policy as host policy, this commit updates the restore logic to accomodate both container and host policies

Signed-off-by: daemon1024 <[email protected]>
  • Loading branch information
daemon1024 committed May 24, 2023
1 parent e8b4504 commit 69e0a8a
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 6 deletions.
2 changes: 1 addition & 1 deletion KubeArmor/core/kubeArmor.go
Original file line number Diff line number Diff line change
Expand Up @@ -660,7 +660,7 @@ func KubeArmor() {

if cfg.GlobalCfg.KVMAgent || !dm.K8sEnabled {
// Restore and apply all kubearmor host security policies
dm.restoreKubeArmorHostPolicies()
dm.restoreKubeArmorPolicies()
}

// == //
Expand Down
37 changes: 32 additions & 5 deletions KubeArmor/core/unorchestratedUpdates.go
Original file line number Diff line number Diff line change
Expand Up @@ -576,7 +576,7 @@ func (dm *KubeArmorDaemon) backupKubeArmorContainerPolicy(policy tp.SecurityPoli
}
}

func (dm *KubeArmorDaemon) restoreKubeArmorHostPolicies() {
func (dm *KubeArmorDaemon) restoreKubeArmorPolicies() {
if _, err := os.Stat(cfg.PolicyDir); err != nil {
kg.Warn("Policies dir not found for restoration")
return
Expand All @@ -586,15 +586,42 @@ func (dm *KubeArmorDaemon) restoreKubeArmorHostPolicies() {
if policyFiles, err := os.ReadDir(cfg.PolicyDir); err == nil {
for _, file := range policyFiles {
if data, err := os.ReadFile(cfg.PolicyDir + file.Name()); err == nil {
var hostPolicy tp.HostSecurityPolicy
if err := json.Unmarshal(data, &hostPolicy); err == nil {
dm.HostSecurityPolicies = append(dm.HostSecurityPolicies, hostPolicy)

var k struct {
Metadata map[string]string `json:"metadata"`
}

err := json.Unmarshal(data, &k)
if err != nil {
kg.Errf("Failed to unmarshal policy: %v", err)
continue
}

if _, ok := k.Metadata["namespaceName"]; ok { // ContainerPolicy contains namespaceName
var containerPolicy tp.K8sKubeArmorPolicy
if err := json.Unmarshal(data, &containerPolicy); err == nil {
containerPolicy.Metadata.Name = k.Metadata["policyName"]
dm.ParseAndUpdateContainerSecurityPolicy(tp.K8sKubeArmorPolicyEvent{
Type: "ADDED",
Object: containerPolicy,
})
}

} else { // HostSecurityPolicy
var hostPolicy tp.HostSecurityPolicy
if err := json.Unmarshal(data, &hostPolicy); err == nil {
dm.HostSecurityPolicies = append(dm.HostSecurityPolicies, hostPolicy)
} else {
kg.Errf("Failed to unmarshal host policy: %v", err)
}
}
}
}

if len(policyFiles) != 0 {
dm.UpdateHostSecurityPolicies()
if len(dm.HostSecurityPolicies) != 0 {
dm.UpdateHostSecurityPolicies()
}
} else {
kg.Warn("No policies found for restoration")
}
Expand Down

0 comments on commit 69e0a8a

Please sign in to comment.