Production-grade guide to kubernetes security policies covering architecture patterns, implementation strategies, testing approaches, and operational best practices for enterprise engineering teams.
Kubernetes Security Policies define the rules that govern how workloads, networks, storage, and cluster resources behave securely across a Kubernetes cluster. They are essential when enforcing consistent security across teams, environments, and CI/CD pipelines, especially in regulated or high-risk deployments where misconfigurations must be both automated and auditable.
When deploying applications via kubectl apply -f, the cluster must enforce baseline security requirements on all pods. The primary mechanism is Pod Security Admission (PSA), a built-in Kubernetes admission controller that evaluates pod specifications against predefined security profiles.
The profiles—baseline, restricted, and privileged—are applied at the namespace level via a PodSecurity custom resource.
apiVersion: policy/v1beta1
kind: PodSecurity
metadata:
name: default-profile
spec:
defaults:
allowPrivilegeEscalation: true
runAsUser: { rule: "must" }
seccompProfile: { type: RuntimeDefault }
supplementalGroups: { rule: "must" }
fsGroup: { rule: "must" }
rules:
# Enforce baseline profile for all pods
- level: "baseline"
version: "v1beta1"
# Apply to all namespaces unless overridden
matchLabels:
pod-security.kubernetes.io/enforce: "baseline"
This configuration, when applied via kubectl apply -f pod-security.yaml, enables PSA for all pods. The admission controller validates every pod spec against the profile, rejecting pods that violate the rules.
A pod that fails validation returns an error in the pod's status.conditions:
{
"type": "PodSecurity",
"status": "False",
"reason": "PodSecurityViolation",
"message": "pod must have fsGroup and supplementalGroups, runAsUser must be specified"
}
The runAsUser rule includes two sub-options: rule: "must" enforces that runAsUser must be present in the pod spec, while rule: "must", range: [1000, 65535] would restrict the user ID to a specific range.
Common pitfalls:
runAsUser is rule: "must" but runAsNonRoot is rule: "must" — these are distinct and both must be configured.seccompProfile is type: RuntimeDefault but RuntimeDefault is not available in the node's seccomp profile — the admission controller fails silently if the profile is missing.fsGroup and supplementalGroups are both rule: "must" but the fsGroup must be a single integer, not a list — the admission controller expects fsGroup: { ranges: [] } for complex range-based policies, but fsGroup: 1000 is accepted as a single group.Network policies define how pods communicate within and between namespaces. The standard networking.k8s.io/v1/NetworkPolicy resource is used to control ingress and egress traffic.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-frontend-to-backend
namespace: app
spec:
podSelector:
matchLabels:
app: backend
policyTypes:
- Ingress
- Egress
ingress:
- from:
- podSelector:
matchLabels:
app: frontend
ports:
- protocol: TCP
port: 8080
egress:
- to:
- podSelector:
matchLabels:
app: database
ports:
- protocol: TCP
port: 5432
This policy allows only the frontend pods to reach backend pods on port 8080, and backend pods to connect to database pods on port 5432.
A silent failure occurs when from or to selectors are not properly resolved:
podSelector with matchLabels but no matchExpressions fails to match pods whose labels do not exactly match.from: { namespaceSelector: ... }, the namespace must have the correct label, and the networking.k8s.io/namespace label is not automatically applied.Another edge case: a pod is in the app namespace but app does not have the label networking.k8s.io/name: app — the networking.k8s.io/v1 controller does not automatically apply this label. The policy must be applied explicitly.
To verify policy enforcement, use kubectl get networkpolicies -A and inspect the status.conditions of each policy:
status:
conditions:
- type: Applied
status: "True"
lastTransitionTime: "2023-10-05T12:00:00Z"
reason: Applied
message: "All pod selectors matched"
A reason: "SelectorMismatch" indicates that some pods do not match the podSelector or namespaceSelector.
Security policies must ensure that only trusted container images are deployed. This is achieved via Image Policy, a feature of the image-policy admission controller in Kubernetes.
ImagePolicy is configured through a YAML file and registered with the Kubernetes API server via a ConfigMap in the kube-system namespace.
apiVersion: v1
kind: ConfigMap
metadata:
name: image-policy
namespace: kube-system
data:
policy: |
{
"version": "v1",
"imagePolicy": {
"registry": {
"match": [
{ "name": "gcr.io/*" },
{ "name": "docker.io/*" }
],
"auth": {
"secret": {
"name": "image-pull-secret",
"key": "config.json"
}
}
},
"signature": {
"type": "cosign",
"publicKeys": [
{
"key": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA...",
"name": "cosign-key"
}
]
},
"enforcement": {
"mode": "enforced",
"images": [
{
"name": "gcr.io/my-project/frontend:*",
"signature": {
"required": true,
"trusted": true
}
}
]
}
}
}
The image-policy ConfigMap is mounted into the admission controller via a Deployment:
apiVersion: apps/v1
kind: Deployment
metadata:
name: image-policy
namespace: kube-system
spec:
template:
spec:
containers:
- name: image-policy
image: gcr.io/k8s-staging-image-policy/image-policy:v0.1
args:
- --config=/etc/image-policy/config.yaml
volumeMounts:
- name: image-policy-config
mountPath: /etc/image-policy
volumes:
- name: image-policy-config
configMap:
name: image-policy
The admission controller evaluates every image pulled into the cluster. An image that fails policy validation is rejected with a detailed error:
{
"kind": "Status",
"apiVersion": "v1",
"metadata": {},
"status": "Failure",
"message": "Image gcr.io/my-project/frontend:v1.2.3 failed signature validation",
"reason": "ImagePolicyError",
"details": {
"causes": [
{
"message": "Signature not found for image gcr.io/my-project/frontend:v1.2.3",
"reason": "MissingSignature"
},
{
"message": "Signature verification failed: Invalid signature",
"reason": "SignatureVerificationFailed"
}
]
}
}
The most common failure is a missing config.json in the image-pull-secret secret, which contains the Docker registry credentials. If the config.json is malformed or missing the auths key, the registry authentication fails silently.
Another edge: the cosign signature verification requires the image’s index.json to be present in the registry, but the index.json is not automatically created when pushing an image with docker push. The policy assumes a multi-arch image with an index, and fails when a single-arch image is pushed.
Secrets must be versioned, rotated, and validated by policy. Kubernetes uses Secret resources, which are mounted into pods via volumeMounts.
To enforce secret policies, use a Secret custom resource with spec.validation and spec.rotation.
apiVersion: secrets.k8s.io/v1
kind: Secret
metadata:
name: db-credentials
namespace: app
spec:
type: kubernetes.io/tls
data:
tls.crt: <base64-encoded-certificate>
tls.key: <base64-encoded-private-key>
validation:
# Enforce that secrets are not used for more than 90 days
maxAgeDays: 90
# Require at least two versions of the secret
minVersions: 2
# Enforce that the secret is signed by a known key
signature: {
type: "cosign",
publicKey: "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA..."
}
rotation:
# Rotate every 30 days
interval: "30d"
# Rotate on new deployment
onDeployment: true
# Trigger rotation via a webhook
webhook: {
url: "https://secrets-app.example.com/rotate",
headers: {
"Authorization": "Bearer abc123"
}
}
When a new Secret is created or updated, the validation controller checks:
maxAgeDays is calculated from the metadata.creationTimestamp.minVersions counts the number of Secret objects in the same namespace with the same name but different data or annotations.signature is validated using the cosign tool, which checks the signature of the data field.Rotation is triggered by:
cron job that runs every 30 days.Deployment that updates the Secret and triggers onDeployment.webhook that is invoked when the Secret is updated via kubectl apply.A common failure: the webhook URL is unreachable, but the rotation controller does not log the failure. The Secret status includes:
status:
conditions:
- type: RotationReady
status: "True"
lastTransitionTime: "2023-10-05T12:00:00Z"
reason: WebhookSuccess
message: "Webhook triggered successfully"
When the webhook fails, the condition changes to:
- type: RotationReady
status: "False"
lastTransitionTime: "2023-10-05T12:15:00Z"
reason: WebhookFailure
message: "Failed to call https://secrets-app.example.com/rotate: 502 Bad Gateway"
Security policies must be auditable. Kubernetes provides Event resources and AuditLog files.
Enable audit logging via --audit-policy-file on the API server:
apiVersion: v1
kind: ConfigMap
metadata:
name: audit-policy
namespace: kube-system
data:
policy.yaml: |
apiVersion: audit.k8s.io/v1
kind: Policy
rules:
- level: Metadata
resources:
- group: ""
resources: ["pods"]
- group: "policy.k8s.io"
resources: ["podsecurity"]
verbs: ["create", "update", "delete"]
- level: Request
resources:
- group: "secrets.k8s.io"
resources: ["secrets"]
verbs: ["create", "update"]
- level: RequestResponse
resources:
- group: ""
resources: ["pods"]
namespaces: ["app", "prod"]
This policy logs metadata on all pod operations and full request/response bodies for secrets in app and prod.
Audit logs are written to a file or sent to a logging system via stdout. They include:
{
"kind": "Event",
"apiVersion": "audit.k8s.io/v1",
"level": "Request",
"requestURI": "/apis/policy.k8s.io/v1beta1/podsecurity",
"verb": "create",
"user": {
"username": "alice",
"groups": ["developers", "security"]
},
"sourceIPs": ["192.168.1.10"],
"userAgent": "kubectl apply",
"objectRef": {
"resource": "podsecurity",
"name": "app-profile"
},
"requestObject": {
"apiVersion": "policy/v1beta1",
"kind": "PodSecurity",
"metadata": { "name": "app-profile" },
"spec": { "defaults": { "runAsUser": { "rule": "must" } } }
},
"responseStatus": {
"code": 201,
"reason": "Created"
}
}
Auditing is silent when:
PodSecurity resource is created but the spec.rules field is missing.NetworkPolicy is applied but the spec.ingress field is null instead of an empty array.Secret is updated but the data field is not properly base64-encoded.The audit log is the primary source of truth for compliance checks. A policy is considered satisfied only if all relevant events exist with the expected structure and fields.
This page was rewritten on 12 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at [email protected] and we will correct it.
We use cookies for analytics (Google Analytics) and advertising (Google AdSense) to improve your experience and support free content. Privacy Policy