Automation — automate Pod security policy enforcement.
1# Kyverno ClusterPolicy for PSS2apiVersion: kyverno.io/v13kind: ClusterPolicy4metadata:5 name: require-restricted6spec:7 validationFailureAction: Enforce8 background: true9 rules:10 - name: require-run-as-non-root11 match:12 any:13 - resources:14 kinds:15 - Pod16 validate:17 message: "Running as root is not allowed"18 pattern:19 spec:20 securityContext:21 runAsNonRoot: true22 - name: require-seccomp23 match:24 any:25 - resources:26 kinds:27 - Pod28 validate:29 message: "Seccomp profile is required"30 pattern:31 spec:32 securityContext:33 seccompProfile:34 type: RuntimeDefault35 - name: restrict-privilege-escalation36 match:37 any:38 - resources:39 kinds:40 - Pod41 validate:42 message: "Privilege escalation is not allowed"43 pattern:44 spec:45 containers:46 - securityContext:47 allowPrivilegeEscalation: false48---49# OPA Gatekeeper constraint50apiVersion: templates.gatekeeper.sh/v151kind: ConstraintTemplate52metadata:53 name: k8spspallowedusers54spec:55 crd:56 spec:57 names:58 kind: K8sPSPAllowedUsers59 targets:60 - target: admission.k8s.gatekeeper.sh61 rego: |62 package k8spspallowedusers63 violation[{"msg": msg}] {64 container := input.review.object.spec.containers[_]65 not container.securityContext.runAsNonRoot66 msg := sprintf("Container %v must run as non-root", [container.name])67 }68---69apiVersion: constraints.gatekeeper.sh/v1beta170kind: K8sPSPAllowedUsers71metadata:72 name: require-non-root73spec:74 match:75 kinds:76 - apiGroups: [""]77 kinds: ["Pod"]78 namespaces: ["production"]
1# Install Kyverno2helm install kyverno kyverno/kyverno -n kyverno --create-namespace34# Install Gatekeeper5kubectl apply -f https://raw.githubusercontent.com/open-policy-agent/gatekeeper/master/deploy/gatekeeper.yaml67# Check policies8kubectl get clusterpolicy9kubectl get constrainttemplates1011# Test policy12kubectl apply -f non-compliant-pod.yaml 2>&11314# View policy violations15kubectl get clusterpolicyreport16kubectl get policyreport -A1718# Check admission webhook19kubectl get validatingwebhookconfigurations | grep kyverno20kubectl get validatingwebhookconfigurations | grep gatekeeper
Automation Tools:
Best Practices: