Skip to content
iD
InfoDive Labs
Back to blog
CybersecurityKubernetesContainers

Kubernetes Security: Hardening Your Container Infrastructure

A comprehensive guide to Kubernetes security covering pod security, RBAC, network policies, image scanning, secrets management, and runtime protection strategies.

November 7, 20247 min read

Kubernetes Security: Hardening Your Container Infrastructure

Kubernetes has become the standard platform for running containerized workloads in production. Its flexibility and power come with a significant security surface area - a default Kubernetes installation is permissive by design, prioritizing ease of use over security. Without deliberate hardening, your cluster may allow container escapes, lateral movement between namespaces, unauthorized access to the Kubernetes API, and exposure of sensitive secrets.

This guide covers the most impactful security measures you should implement to protect your Kubernetes infrastructure, ordered from foundational controls to advanced runtime protections.

Securing the Kubernetes API Server

The API server is the front door to your cluster. Every interaction with Kubernetes - from kubectl commands to pod scheduling - goes through the API server. Compromising it means compromising everything.

API server hardening essentials:

  • Disable anonymous authentication. Set --anonymous-auth=false to require authentication for all API requests.
  • Use OIDC or webhook token authentication instead of static tokens or basic authentication. Integrate with your identity provider (Okta, Azure AD, Google Workspace) for centralized user management.
  • Enable audit logging. Configure the API server audit policy to log authentication events, resource modifications, and sensitive operations. Ship logs to your SIEM for monitoring and alerting.
  • Restrict API server network exposure. The API server should not be accessible from the public internet. Use a VPN, bastion host, or private endpoint for administrative access.
  • Enable admission controllers. Admission controllers intercept requests to the API server and can enforce policies before resources are created. Essential controllers include PodSecurity, NodeRestriction, and ResourceQuota.

Implement Strong RBAC

Role-Based Access Control (RBAC) is Kubernetes' authorization mechanism. The default configuration is often far too permissive.

RBAC best practices:

  • Follow the principle of least privilege - grant only the permissions each user or service account actually needs
  • Never use the cluster-admin ClusterRole for routine operations
  • Create namespace-scoped Roles rather than cluster-wide ClusterRoles whenever possible
  • Audit RBAC configurations regularly - use tools like rbac-lookup or kubectl-who-can to understand effective permissions
  • Avoid granting * (wildcard) verbs or resources in roles
  • Restrict create and patch permissions on Pods, Deployments, and other workload resources to deployment pipelines, not individual users
  • Bind service accounts to specific namespaces and limit their permissions
# Example: A restricted Role for a development team
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  namespace: development
  name: developer-role
rules:
- apiGroups: [""]
  resources: ["pods", "pods/log", "services", "configmaps"]
  verbs: ["get", "list", "watch"]
- apiGroups: ["apps"]
  resources: ["deployments"]
  verbs: ["get", "list", "watch"]

Pod Security: Constraining Workloads

Pods are the execution units in Kubernetes, and misconfigured pods are one of the most common paths to cluster compromise.

Use Pod Security Standards

Kubernetes Pod Security Standards define three profiles that restrict pod configurations:

  • Privileged - No restrictions (use only for system-level workloads like CNI plugins)
  • Baseline - Prevents known privilege escalations (blocks hostNetwork, hostPID, privileged containers)
  • Restricted - Heavily restricted, following security best practices (requires non-root, drops all capabilities, uses read-only root filesystem)

Apply these at the namespace level using Pod Security Admission:

apiVersion: v1
kind: Namespace
metadata:
  name: production
  labels:
    pod-security.kubernetes.io/enforce: restricted
    pod-security.kubernetes.io/audit: restricted
    pod-security.kubernetes.io/warn: restricted

Essential Pod Security Configurations

For every production workload, configure these security context settings:

securityContext:
  runAsNonRoot: true
  runAsUser: 1000
  runAsGroup: 1000
  readOnlyRootFilesystem: true
  allowPrivilegeEscalation: false
  capabilities:
    drop:
      - ALL
  seccompProfile:
    type: RuntimeDefault

What each setting prevents:

  • runAsNonRoot - Prevents containers from running as root, which limits the impact of container escapes
  • readOnlyRootFilesystem - Prevents attackers from writing malicious binaries to the container filesystem
  • allowPrivilegeEscalation: false - Blocks processes from gaining more privileges than their parent
  • drop ALL capabilities - Removes Linux capabilities that could enable privilege escalation
  • seccompProfile: RuntimeDefault - Restricts the system calls the container can make

Network Policies: Microsegmentation

By default, every pod in a Kubernetes cluster can communicate with every other pod. This means a compromised pod in one namespace can reach databases, internal APIs, and control plane services in other namespaces. Network policies implement microsegmentation to restrict this lateral movement.

Default Deny Policy

Start with a default deny policy in every namespace, then selectively allow required traffic:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny-all
  namespace: production
spec:
  podSelector: {}
  policyTypes:
  - Ingress
  - Egress

Allow Only Required Traffic

After applying default deny, create specific policies for legitimate communication:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-frontend-to-backend
  namespace: production
spec:
  podSelector:
    matchLabels:
      app: backend
  policyTypes:
  - Ingress
  ingress:
  - from:
    - podSelector:
        matchLabels:
          app: frontend
    ports:
    - protocol: TCP
      port: 8080

Network policy design principles:

  • Define policies per microservice based on actual communication patterns
  • Restrict egress to prevent compromised pods from reaching external command-and-control servers
  • Allow DNS egress (port 53 to kube-dns) so service discovery continues to function
  • Use namespace selectors to restrict cross-namespace traffic to explicitly approved paths
  • Test policies in audit mode before enforcing to avoid breaking legitimate traffic

Note that network policies require a CNI plugin that supports them. Calico, Cilium, and Antrea all support network policies. The default kubenet CNI does not.

Image Security: Trust What You Run

Container images are the software supply chain entry point for your Kubernetes workloads.

Image Scanning and Admission Control

  • Scan all images for known vulnerabilities before they are deployed using Trivy, Grype, or Snyk Container
  • Integrate scanning into your CI/CD pipeline and block images with critical or high vulnerabilities
  • Use an admission controller (OPA Gatekeeper, Kyverno, or a commercial solution) to prevent deployment of unscanned or non-compliant images
  • Only allow images from trusted registries - block pulls from public Docker Hub in production

Image Hardening

  • Use minimal base images (distroless, Alpine, or scratch) to reduce the attack surface
  • Never include package managers, shells, or debugging tools in production images
  • Pin base image versions to specific digests, not mutable tags
  • Sign images using cosign/Sigstore and verify signatures at admission time
  • Run images as non-root users by defining a USER directive in your Dockerfile
  • Scan for secrets accidentally included in image layers

Secrets Management

Kubernetes Secrets are base64-encoded, not encrypted. Anyone with read access to Secrets in a namespace can decode them trivially.

Secrets management best practices:

  • Enable encryption at rest for etcd, which stores all Kubernetes resources including Secrets
  • Use an external secrets manager (HashiCorp Vault, AWS Secrets Manager, Azure Key Vault, GCP Secret Manager) and sync secrets into Kubernetes using the External Secrets Operator or Secrets Store CSI Driver
  • Rotate secrets regularly and automate the rotation process
  • Limit RBAC access to Secret resources - most users and service accounts should not be able to read Secrets directly
  • Avoid mounting secrets as environment variables when possible - use volume mounts instead, which are less likely to leak through process listings or crash dumps
  • Never commit secrets to source control, even encrypted ones (use sealed-secrets or external secrets operators instead)

Runtime Security and Monitoring

Prevention is essential, but you also need to detect threats that bypass preventive controls.

Runtime Threat Detection

Deploy a runtime security tool that monitors container behavior and alerts on anomalous activity:

  • Falco (open source) - Detects unexpected system calls, file access, network connections, and process execution using kernel-level monitoring
  • Tetragon (open source, from Cilium) - eBPF-based runtime enforcement and observability
  • Commercial options - Sysdig Secure, Aqua Security, Prisma Cloud Compute

Critical runtime events to alert on:

  • Shell execution inside a container (/bin/sh, /bin/bash)
  • Unexpected outbound network connections from application containers
  • File writes to sensitive paths (/etc/shadow, /etc/passwd)
  • Privilege escalation attempts
  • Kubernetes API access from within pods (potential service account token abuse)
  • Container drift - new binaries or scripts appearing in a running container

Monitoring and Observability

  • Centralize Kubernetes audit logs and ship them to your SIEM
  • Monitor the Kubernetes API for unusual patterns (mass secret reads, RBAC changes, pod exec events)
  • Implement pod-level network flow logging to detect unexpected communication patterns
  • Set up alerts for security-relevant Kubernetes events (failed authentication, denied requests, policy violations)

Need help building this?

Our team specializes in turning these ideas into production systems. Let's talk.