Christian K.
Christian K.

Reputation: 21

OPA Gatekeeper Policy to block priviliged Pods

Since 2 days I try to create a simple OPA Gatekeeper Policy which blocks the creation of pods with "privileged:true" for some namespaces.

Some more details:

Im using opa-gatekeeper in version 3.13 installed by following these instructions.

To enable the policy, first I created a ConstraintTemplate:

apiVersion: templates.gatekeeper.sh/v1beta1
kind: ConstraintTemplate
metadata:
  name: disallowprivilegedpods
  annotations:
    description: "Disallow creation of privileged pods in alpha and beta namespaces"
spec:
  crd:
    spec:
      names:
        kind: DisallowPrivilegedPods
  targets:
    - target: admission.k8s.gatekeeper.sh
      rego: |
        package disallow_privileged_pods

        violation[{"msg": msg}] {
          input.request.kind.kind == "Pod"
          input.request.operation == "CREATE"
          input.request.namespace == ["alpha", "beta"]
          input.request.object.spec.securityContext.privileged == true
          msg := "Privileged pods are not allowed in the Alpha and Beta namespaces."
        }

Next I created the constraint:

apiVersion: constraints.gatekeeper.sh/v1beta1
kind: DisallowPrivilegedPods
metadata:
  name: disallow-privileged-pods-alpha-beta
spec:
  match:
    kinds:
      - apiGroups: [""]
        kinds: ["Pod"]
    namespaces:
      - alpha
      - beta

To test if the policy is working correctly, I tried to deploy this pod in one of these namespaces:

apiVersion: v1
kind: Pod
metadata:
  name: privileged-pod
  namespace: alpha
spec:
  containers:
    - name: my-container
      image: nginx
      securityContext:
        privileged: true
  restartPolicy: Never

Unfortunately the policy doesnt seem to work and the pod can be created.

Can anyone give me some hints, whats wrong with the policy?

Cheers,

Christian

Upvotes: 2

Views: 623

Answers (1)

Jason
Jason

Reputation: 734

This check - input.request.namespace == ["alpha", "beta"] will evaluate to true only if the input.request.namespace field is exactly identical to the array it is being compared to. i.e. - Only if input.request.namespace is an array with exactly two values, the first one being "alpha" and the second one "beta"

To check if an array input field holds one of two values, use incremental rules and array lookups:

namespace_alpha_or_beta {
    "alpha" = input.request.namespace[_]
}

namespace_alpha_or_beta {
    "beta" = input.request.namespace[_]
}

Upvotes: 1

Related Questions