Kubernetes Pod Security Standards
Understanding and implementing Pod Security Standards in Kubernetes
Introduction to Pod Security Standards
Pod Security Standards (PSS) in Kubernetes provide a standardized approach to securing pod deployments. These standards define different levels of security restrictions that can be applied to pods, helping organizations implement consistent security policies across their Kubernetes clusters.
Pod Security Standards were introduced in Kubernetes v1.22 to replace the deprecated PodSecurityPolicy (PSP) admission controller, offering a more flexible and maintainable approach to pod security. Unlike PSP, which was an all-or-nothing admission controller that required cluster-wide privileges to manage, PSS can be implemented gradually and at different levels within a cluster, making adoption significantly easier.
The creation of Pod Security Standards addressed several challenges that organizations faced with PodSecurityPolicies:
- Complexity: PodSecurityPolicies were difficult to author correctly and understand
- Privilege Requirements: Managing PSPs required cluster-admin privileges
- Validation Challenges: Testing PSPs was cumbersome before applying them
- All-or-Nothing Implementation: PSPs couldn't be rolled out incrementally
- Maintenance Burden: PSPs required ongoing updates as Kubernetes evolved
These standards are particularly important because pods are the fundamental building blocks in Kubernetes, and securing them properly is essential for maintaining overall cluster security. By implementing Pod Security Standards, organizations can significantly reduce the attack surface and mitigate the risk of container escapes and privilege escalation attacks.
The Pod Security Standards specification is now an integral part of the Kubernetes project, maintained by the Security Special Interest Group (SIG-Security). This ensures that the standards evolve alongside Kubernetes itself, maintaining compatibility with new features while addressing emerging security concerns in containerized environments.
The Three Security Profiles
Pod Security Standards define three distinct security profiles, each with different levels of restriction:
Privileged Profile
- Unrestricted policy with minimal security controls
- Allows privileged operations that could compromise the node
- Provides the same level of access as the node's root user
- Suitable for system-level workloads that require extensive permissions
- Examples: cluster add-ons, node monitoring agents, CNI plugins
- Used when functionality takes precedence over security restrictions
- Represents the highest risk level if compromised
- Permits all privileged escalation paths, including:
- Running as privileged containers
- Accessing host namespaces (network, PID, IPC)
- Using host ports and networking
- Mounting host paths and sensitive volumes
- Running as root with unrestricted capabilities
- Specific use cases include:
- Container networking plugins requiring host network access
- Storage drivers requiring direct device access
- Node problem detectors requiring deep system visibility
- Monitoring agents requiring comprehensive system metrics
- Security tooling that enforces policies at the node level
Baseline Profile
- Minimally restrictive policy that prevents known privilege escalations
- Allows default (minimally specified) Pod configuration
- Permits most workloads to run without modification
- Blocks known privilege escalation vectors
- Restricts dangerous capabilities and host access
- Suitable for default security for non-sensitive applications
- Represents a middle ground between functionality and security
- Prevents the following high-risk practices:
- Running privileged containers
- Sharing host namespaces directly
- Mounting host directories as writable volumes
- Running as root with dangerous capabilities
- Using hostPort to bind to host network interfaces
- Allows common container behaviors:
- Running as any user ID, including root
- Adding and dropping specific capabilities
- Using the default seccomp profile
- Using any SELinux context configured by the platform
- Using any AppArmor profile configured by the platform
- Mounting persistent volumes, configMaps, and secrets
- Most suitable for:
- Legacy applications that haven't been designed for security
- Applications from third parties without security modifications
- Internal applications with moderate security requirements
- Development and testing environments
Restricted Profile
- Highly restrictive policy enforcing security best practices
- Follows hardening guidelines for pods
- Significantly limits the attack surface of containerized applications
- Suitable for applications handling sensitive data or running in multi-tenant environments
- Implements principle of least privilege
- May require modifications to existing workloads to be compliant
- Represents the most secure configuration for critical workloads
- Enforces strong security controls including:
- Mandatory non-root user execution
- Prevention of privilege escalation completely
- Removal of ALL Linux capabilities by default
- Strict use of SecComp profiles (RuntimeDefault or Localhost)
- Restriction of volume types to secure options only
- Prohibition of hostPath volumes entirely
- Restriction of file system groups and supplemental groups
- Required read-only root filesystems
- Explicit declaration of security contexts
- Applications must be specifically designed for:
- Running with least privilege
- Operating without root access
- Using minimal container images
- Functioning with immutable filesystems
- Declaring all required permissions explicitly
- Best suited for:
- High-security workloads with sensitive data
- Multi-tenant environments with strong isolation needs
- Financial, healthcare, and government applications
- Applications subject to compliance requirements
- Production environments with critical infrastructure
Key Control Mechanisms
Pod Security Standards enforce various control mechanisms to ensure appropriate security levels:
The example above demonstrates a pod configured according to the Restricted profile, implementing multiple security controls to minimize the pod's attack surface.
Control Categories in Detail
- Host Namespaces
- Controls whether pods can share host namespaces
- Impacts
hostNetwork,hostPID, andhostIPCsettings - Baseline/Restricted: Sharing host namespaces is not allowed
- Prevents pods from accessing host-level resources and processes
- Security implications:
hostNetwork: truegives pod access to host's network interfaceshostPID: trueallows pod to see and signal all processes on the nodehostIPC: trueenables pod to use host's inter-process communication
- Potential attack vectors if allowed:
- Network sniffing of all traffic on the node
- Process injection or termination on the host
- Memory inspection of host processes
- Lateral movement between containers and host
- Example policy check:
- Privileged Containers
- Controls whether containers can run with privileged flag
- Privileged containers essentially have host-level access
- Baseline/Restricted: Privileged containers are not allowed
- Security implications of privileged containers:
- Disables all security mechanisms enforced by the container runtime
- Grants access to all devices on the host
- Allows mounting of sensitive host paths
- Enables modification of kernel parameters
- Permits loading of kernel modules
- Bypasses AppArmor, SELinux, and seccomp profiles
- Equivalent to giving root access to the host system
- Most dangerous security setting in Kubernetes
- Legitimate uses limited to system components like:
- Storage drivers requiring direct device access
- Network plugins needing to configure host networking
- Security monitoring tools that need deep system access
- Example policy check:
- Capabilities
- Controls Linux capabilities granted to containers
- Baseline: Some dangerous capabilities are forbidden
- Restricted: All capabilities are dropped by default, must be explicitly added
- Linux capabilities provide fine-grained control over privileged operations
- Baseline profile prohibits these dangerous capabilities:
NET_ADMIN: Configure network interfaces, routing tables, etc.SYS_ADMIN: Perform various system administration operationsSYS_PTRACE: Trace arbitrary processes using ptraceSYS_MODULE: Load and unload kernel modulesDAC_READ_SEARCH: Bypass file read permission checksLINUX_IMMUTABLE: Make files immutableNET_RAW: Use RAW and PACKET socketsSYS_CHROOT: Use chroot()
- Restricted profile requires dropping ALL capabilities first:
- Only explicitly adds back necessary capabilities
- Common safe capabilities to add back include:
NET_BIND_SERVICE: Bind to ports below 1024CHOWN: Make arbitrary changes to file UIDs and GIDsDAC_OVERRIDE: Bypass file read, write, and execute permission checksSETUID/SETGID: Make arbitrary manipulations of process UIDs/GIDsFOWNER: Bypass permission checks on operations that normally require the filesystem UID of the process to match the UID of the file
- Example policy check (Restricted):
- Volume Types
- Restricts the types of volumes that can be mounted
- Controls access to sensitive host paths
- Baseline/Restricted: Dangerous volume types are forbidden
- Example of forbidden volumes: hostPath, NFS for baseline and gcePersistentDisk for restricted
- Privilege Escalation
- Controls whether processes can gain more privileges than their parent
- Baseline: No requirement
- Restricted: Must explicitly disable privilege escalation
- Technical details:
- Controls the no_new_privs flag on Linux
- Prevents setuid binaries from changing privileges
- Blocks subprocess elevation beyond parent process
- Critical security control for containing process permissions
- Common privilege escalation paths in containers:
- Using setuid binaries inside the container
- Exploiting vulnerable binaries with setuid bit
- Utilizing capabilities to gain higher privileges
- Leveraging container runtime vulnerabilities
- Security impact:
- Even non-root containers can escalate to root if not restricted
- Creates potential escape paths from container to host
- Allows lateral movement within cluster with higher privileges
- Example policy check (Restricted):
- Running as Non-root
- Controls whether containers can run as the root user
- Baseline: No requirement
- Restricted: Must run as non-root user
- Security significance:
- Running as root (UID 0) grants extensive permissions inside container
- Root access increases potential impact of container breakouts
- Container root != Host root, but still poses higher risk
- Breaking out as root provides immediate path to privilege escalation
- Implementation options:
- Container image defines non-root user (USER directive in Dockerfile)
- Pod or container specifies runAsUser with non-zero UID
- Pod or container sets runAsNonRoot: true
- Common non-root user patterns:
- Using high UIDs (e.g., 1000-65535) to avoid system UIDs
- Creating dedicated service accounts in container images
- Implementing read-only filesystem with specific write paths
- Using distroless or minimal images with non-root users
- Example policy check (Restricted):
- More explicit example:
- Seccomp Profile
- Controls system call restrictions
- Baseline: No requirement
- Restricted: Must use RuntimeDefault or Localhost seccomp profile
- Technical background:
- Seccomp (secure computing mode) filters system calls from containers
- System calls are the interface between user applications and kernel
- Restricting system calls significantly reduces attack surface
- Prevents exploitation of kernel vulnerabilities
- Available profile types:
Unconfined: No restrictions (dangerous, not allowed in Restricted)RuntimeDefault: Container runtime's built-in default profileLocalhost: Custom profile loaded from node filesystem
- Security benefits:
- Blocks dangerous system calls not needed by application
- Prevents container breakout exploits using kernel vulnerabilities
- Reduces kernel attack surface by ~75% with default profiles
- Adds defense-in-depth when combined with other controls
- Implementation considerations:
- RuntimeDefault is sufficient for most applications
- Custom profiles require deeper application understanding
- Requires kernel support for seccomp (standard in modern distributions)
- May require application testing to ensure compatibility
- Example policy check (Restricted):
- Custom profile example:
Implementing Pod Security Standards
Kubernetes offers multiple ways to implement Pod Security Standards:
Pod Security Admission Controller
- Built-in admission controller in Kubernetes 1.23+
- Configurable at namespace level
- Supports three modes: enforce, audit, and warn
- Labels determine which standards apply to each namespace
- Three enforcement modes with different behaviors:
enforce: Rejects non-compliant pods at admission timeaudit: Allows non-compliant pods but logs violations as audit eventswarn: Allows non-compliant pods but returns warnings to the user
- Can apply different profiles to each mode:
- Enforce baseline while auditing against restricted
- Gradually increase enforcement as applications adapt
- Maintain visibility into compliance status during migration
- Optional version control through additional labels:
pod-security.kubernetes.io/enforce-version: v1.25- Ensures stability during Kubernetes upgrades
- Controls which version of the PSS specification applies
- Example namespace labels:
- Graduated implementation example:
Webhook-based Solutions
- Use dynamic admission controllers for fine-grained control
- Examples include OPA Gatekeeper and Kyverno
- Allows for custom policies beyond standard PSS
- Supports advanced validation logic
- Key advantages over built-in admission controller:
- More complex conditional logic and exceptions
- Custom validation rules specific to organization needs
- Integration with external policy systems
- Ability to mutate pods to make them compliant
- Centralized policy management across clusters
- Integration with audit and compliance systems
- Support for non-pod resources (Deployments, StatefulSets)
- Kyverno features:
- Kubernetes-native policy management
- No new language to learn (uses YAML)
- Supports validation, mutation, and generation
- Can enforce PSS profiles plus additional controls
- Provides exceptions mechanism for special cases
- Example Kyverno policy:
- Advanced Kyverno policy with exceptions:
Policy-as-Code Tools
- Define security policies as code
- Integrates with GitOps workflows
- Examples include Conftest and Checkov
- Validates manifests before deployment
- Shift-left security approach:
- Catches security issues before deployment
- Integrates into CI/CD pipelines
- Provides feedback during development
- Enforces policies at code review time
- Prevents non-compliant resources from being applied
- Reduces operational security burden
- Open Policy Agent (OPA) Conftest:
- Uses Rego policy language
- Validates Kubernetes YAML against policies
- Can be run locally or in CI/CD pipelines
- Provides detailed policy violation information
- Supports multiple policy libraries
- Infrastructure as Code scanning:
- Checkov analyzes Kubernetes manifests for misconfigurations
- Detects security issues across multiple resources
- Provides auto-remediation suggestions
- Can enforce PSS controls pre-deployment
- Example Conftest policy:
Security Contexts
- Apply security settings directly to pods and containers
- Implement controls without admission controllers
- Requires discipline from application teams
- Example pod with security contexts:
Migrating from PodSecurityPolicy
If you're transitioning from the deprecated PodSecurityPolicy to Pod Security Standards, follow these steps:
- Analyze current PodSecurityPolicies
- Identify security requirements in existing PSPs
- Determine appropriate PSS profiles for each workload
- Example analysis script:
- Create namespace strategy
- Decide which PSS profile applies to each namespace
- Consider gradual implementation with warn mode first
- Example namespace mapping:
- Test with warn mode
- Apply audit/warn modes before enforcing
- Collect and analyze violations
- Make necessary workload modifications
- Example labels for testing:
- Implement enforce mode gradually
- Start with low-risk namespaces
- Monitor for unexpected issues
- Adjust security profiles as needed
- Example gradual rollout plan:
Best Practices
- Apply defense in depth
- Don't rely solely on Pod Security Standards
- Combine with network policies, RBAC, and image scanning
- Implement runtime security monitoring
- Example comprehensive layered approach:
- Start with audit mode
- Use audit mode to identify non-compliant workloads
- Monitor logs for violations before enforcing
- Create inventory of all policy violations
- Categorize violations by severity and complexity
- Develop remediation plan for each violation type
- Work with application teams to address issues
- Set deadlines for compliance based on risk
- Implement warning mode before enforcement
- Document exceptions with justification and timeline
- Example audit command:
- Example audit analysis script:
- Create exemptions carefully
- Some system workloads require privileged access
- Document and review all exemptions
- Use separate namespaces for privileged workloads
- Example namespace for exemptions:
- Conduct regular compliance audits
- Periodically review PSS implementation
- Verify that namespaces have appropriate profiles
- Check for unauthorized changes to security settings
- Example audit script:
- Use namespace inheritance for consistency
- Apply labels to parent namespaces
- Use hierarchical namespace controllers when available
- Ensure consistent application of standards
- Example using HNC (Hierarchical Namespace Controller):
PSS in CI/CD Pipelines
Integrating Pod Security Standards into CI/CD pipelines ensures that non-compliant workloads are caught before they reach the cluster:
- Pre-deployment validation
- Validate Kubernetes manifests against PSS during CI
- Fail the pipeline for non-compliant resources
- Example using kubeaudit in CI:
- Policy-as-code in pipelines
- Implement OPA/Conftest checks in CI
- Validate against specific PSS profiles
- Example Conftest in GitLab CI:
Monitoring and Auditing PSS
Continuous monitoring of Pod Security Standards ensures ongoing compliance:
- Audit logging
- Enable audit logging for Pod Security Admission
- Analyze logs for policy violations
- Set up alerts for repeated violations
- Example audit policy:
- Compliance dashboards
- Create dashboards showing PSS compliance
- Track violations by namespace and profile
- Monitor trends in security posture
- Example monitoring tools: Prometheus, Grafana, Falco
- Regular security reviews
- Periodically review PSS implementation
- Adjust profiles based on new threats
- Update policies to address emerging vulnerabilities
- Example review schedule:
Pod Security Standards provide a robust framework for securing Kubernetes workloads according to their specific security requirements. By understanding and properly implementing PSS, organizations can significantly enhance their Kubernetes security posture while maintaining operational flexibility.
