Skip to content

Commit

Permalink
fix(core): incorrect cluster policies matching
Browse files Browse the repository at this point in the history
Regular policies are mistakenly modified and applied at cluster level over time

Fixes: kubearmor#1780

Signed-off-by: Carlos Rodriguez-Fernandez <[email protected]>
  • Loading branch information
carlosrodfern committed Aug 13, 2024
1 parent 7e7b1c3 commit 5af978d
Showing 1 changed file with 1 addition and 43 deletions.
44 changes: 1 addition & 43 deletions KubeArmor/core/kubeUpdate.go
Original file line number Diff line number Diff line change
Expand Up @@ -959,48 +959,6 @@ func (dm *KubeArmorDaemon) WatchK8sPods() {
}
}

func matchClusterSecurityPolicyRule(policy tp.SecurityPolicy) bool {
hasInOperator := false
excludedNamespaces := make(map[string]bool)

for _, matchExpression := range policy.Spec.Selector.MatchExpressions {
if matchExpression.Key == "namespace" {
if matchExpression.Operator == "In" {
hasInOperator = true
for _, value := range matchExpression.Values {
if !kl.ContainsElement(policy.Spec.Selector.NamespaceList, value) {
policy.Spec.Selector.NamespaceList = append(policy.Spec.Selector.NamespaceList, value)
return true
}

}

} else if matchExpression.Operator == "NotIn" && !hasInOperator {
for _, value := range matchExpression.Values {
excludedNamespaces[value] = true
}
}
}
}

// this logic will also work when selector is not defined, and policy rule will be applied across all the namespaces
if !hasInOperator {
nsList, err := K8s.K8sClient.CoreV1().Namespaces().List(context.Background(), metav1.ListOptions{})
if err != nil {
kg.Err("unable to fetch namespace list")
return false
}

for _, ns := range nsList.Items {
if _, ok := excludedNamespaces[ns.Name]; !ok && !kl.ContainsElement(policy.Spec.Selector.NamespaceList, ns.Name) {
policy.Spec.Selector.NamespaceList = append(policy.Spec.Selector.NamespaceList, ns.Name)
return true
}
}
}
return false
}

// ============================ //
// == Security Policy Update == //
// ============================ //
Expand All @@ -1013,7 +971,7 @@ func (dm *KubeArmorDaemon) GetSecurityPolicies(identities []string, namespaceNam
secPolicies := []tp.SecurityPolicy{}

for _, policy := range dm.SecurityPolicies {
if kl.MatchIdentities(policy.Spec.Selector.Identities, identities) || kl.ContainsElement(policy.Spec.Selector.NamespaceList, namespaceName) || matchClusterSecurityPolicyRule(policy) {
if kl.MatchIdentities(policy.Spec.Selector.Identities, identities) || kl.ContainsElement(policy.Spec.Selector.NamespaceList, namespaceName) {
secPolicy := tp.SecurityPolicy{}
if err := kl.Clone(policy, &secPolicy); err != nil {
dm.Logger.Errf("Failed to clone a policy (%s)", err.Error())
Expand Down

0 comments on commit 5af978d

Please sign in to comment.