Uncover hidden risks

Watch how the Wiz platform can expose unseen risks in your cloud environment without drowning your team in alerts.

Kubernetes Security Context: Best practices

In Kubernetes, a security context defines privilege and access control settings for a Pod or Container. It allows you to specify security configurations such as user and group IDs, filesystem permissions, and capabilities.

6 minutes read

Kubernetes security contexts are vital for establishing privilege and access controls within pods and containers. These settings enable developers and administrators to enforce security policies and minimize the risks associated with containerized applications. 

By design, Kubernetes offers a high degree of flexibility and scalability. However, this also introduces significant security risks if not properly managed: Using container images, shared host operating systems, and the dynamic provisioning of resources can expose applications to various attack vectors, including privilege escalation attacks and unauthorized access. Security contexts are Kubernetes' answer to these challenges, providing a framework for defining container security contexts and pod security policies that govern how applications run and interact with the underlying infrastructure. 

Security context settings allow you to control the capabilities of a container process, restrict a container's access to the root filesystem, and prevent privilege escalation attacks. To specify these settings, you use various fields in the pod and container specifications, such as securityContext and runAsUser. The data in these fields interact with the container runtimes to apply the specified security mechanisms.

This blog post explores the benefits of implementing security contexts and the types of security contexts available. We’ll also take an in-depth look at best practices for securing your Kubernetes deployments. Stay tuned as we navigate the ins and outs of Kubernetes security, empowering you to fortify your cloud-native applications against emerging threats.

Benefits of implementing security contexts

By fine-tuning container and pod security settings, organizations can achieve a robust defense mechanism against common vulnerabilities and exploits. Here are the key benefits of Kubernetes security contexts:

Enhanced security posture

As we’ve seen, security contexts enable administrators and developers to enforce strict security policies on containers and pods. This includes running processes as a non-root user, controlling access to the root filesystem, and limiting the capabilities of container processes. These measures significantly mitigate the risk of unauthorized access and privilege escalation attacks, ensuring that even if attackers compromise a container, their ability to cause harm is severely restricted.

For example, by setting the readOnlyRootFilesystem to true, a container is forced to operate with a root filesystem that cannot be modified. This prevents malicious software from being installed or existing programs from being tampered with, greatly enhancing the container's defense against attacks.

Reduced attack surface within Kubernetes clusters

By default, containers may have more privileges than they need, which malicious actors can exploit. Security contexts apply the principle of least privilege, ensuring containers and pods operate only with the permissions they require. This approach reduces the attack surface by limiting the number of potential entry points available to attackers.

Improved compliance and audit readiness

Many industries are governed by strict regulatory standards that dictate how data must be protected. Implementing security contexts helps organizations comply with these regulations by providing mechanisms to control access, enforce security policies, and log relevant security events. In other words, security contexts do more than help you pass audits: They also maintain your reputation and customers’ trust.

Types of security contexts

Kubernetes offers two levels at which security contexts can be applied. Let’s take a closer look:

1. Pod security contexts

Pod security contexts apply to all containers within a pod. They are defined in the pod specification and can set policies that affect the entire pod, such as SELinux labels, fsGroup, and supplemental groups:

  • SELinux options isolate pod processes from each other and the host.

  • fsGroup options specify the group ID associated with volume mounts in the pod, controlling access to shared storage.

  • runAsUser and runAsGroup options define the user and group IDs to run the containers in the pod, ensuring they don't run with root privileges.

2. Container security contexts

While pod security contexts provide broad strokes for security, container security contexts allow for more granular control: These settings are detailed in the specification for each container, allowing them to supersede certain security settings at the pod level for that particular container:

  • Capability management enables adding or dropping specific Linux capabilities for a container and fine-tuning its access to system calls.

  • ReadOnlyRootFilesystem makes the root filesystem of a container read-only, preventing modifications and limiting the impact of a breach.

  • The AllowPrivilegeEscalation setting determines if a process can acquire more privileges than those of its parent process, making it a critical setting for preventing privilege escalation attacks.

The relationship between Kubernetes security contexts, RBAC, and pod security admission

Keeping Kubernetes clusters secure involves various components that work together to protect against unauthorized access and potential vulnerabilities. Integrating security contexts with RBAC and pod security admission creates a comprehensive security framework for Kubernetes clusters. Here's how these components work together:

  • Security contexts define the security settings at the pod and container level, such as running as a non-root user and disabling privilege escalation.

  • RBAC controls who can perform operations within the cluster (including creating, modifying, or deleting pods and other resources) based on their roles.

  • Pod Security admission ensures that pods comply with the cluster's security policies before they are admitted, providing an automated enforcement mechanism.

Best practices for Kubernetes security contexts

Next, let’s look at actionable best practices and their impact on your cluster's security:

1. Define security contexts at both the pod and container level

Security contexts allow you to define privilege and access control settings for containers and pods. Applying these settings at both levels ensures that your security policies are tailored to the specific needs of each application component.

Pod level

Define a security context for the entire pod to set policies that apply to all containers within the pod:

apiVersion: v1
kind: Pod
  name: example-pod
    runAsUser: 1000
    fsGroup: 2000
  - name: example-container
    image: example/image

Container level

Override pod-level settings for specific containers to address unique security requirements:

  - name: example-container
    image: example/image
      allowPrivilegeEscalation: false
      readOnlyRootFilesystem: true

2. Leverage the readOnlyRootFilesystem setting for immutable containers

Setting a container's root filesystem to read-only mode can significantly enhance security by preventing unauthorized changes to the filesystem. This setting helps protect against many attacks, including those that attempt to write malicious files to the container's filesystem. You can configure the readOnlyRootFilesystem attribute in the container's securityContext field:

  readOnlyRootFilesystem: true

3. Enforce the use of non-root containers

Using non-root users to run containers reduces the risk of privilege escalation attacks. If an attacker compromises a container running as a non-root user, their ability to cause harm is significantly limited compared to a container running as root.

You can specify a non-root user ID for the container process by using the runAsUser field:

  runAsUser: 1000

4. Disable privilege escalation

As we’ve seen, disabling privilege escalation prevents a process from gaining more privileges than its parent process, which is crucial for limiting the impact of a compromised container. This setting helps mitigate the risk of an attacker exploiting a vulnerability to gain elevated privileges within the container or the host system.

In the container's security context, you can set the allowPrivilegeEscalation field to false:

  allowPrivilegeEscalation: false

5. Manage Linux capabilities with drop and add

Linux capabilities divide the root user's privileges into segmented privileges that are more manageable. Removing unnecessary capabilities and adding only the ones required for your container can significantly enhance security. 

To follow the principle of least privilege, drop all capabilities and add only those necessary for the container to operate:

    - ALL

Implementing these best practices can significantly enhance the security of your Kubernetes deployments. Each measure contributes to a defense-in-depth strategy, keeping your containers and pods resilient against common threats and vulnerabilities.

Wiz: A full-stack Kubernetes security platform

Kubernetes clusters present unique challenges and opportunities for security enhancement. To make the most out of Kubernetes, it’s a good idea to leverage a comprehensive solution that offers seamless integration with Kubernetes and provides prevention, detection, and response capabilities. Enter Wiz. Our all-in-one platform enables security, development, and DevOps teams to collaborate effectively, so that security facilitates cloud development instead of becoming a barrier to agility.

Key features of the Wiz platform

  • Security for the complete SDLC: Wiz secures containers and Kubernetes environments throughout the software development life cycle (SDLC). This includes scanning infrastructure as code (IaC) like Dockerfiles and Kubernetes YAMLs for misconfigurations and security risks. Our Wiz Admission Controller ensures only trusted images that meet security policies are deployed, blocking untrusted or non-compliant resources from entering your environment​.

  • Real-time threat detection and response: With the real-time visibility of Kubernetes cluster activities provided by our Kubernetes Audit Log Collector, Wiz detects suspicious behaviors by correlating audit logs with container and host-level activities, enabling swift response to potential security incidents​.

  • Unified cloud security: Wiz acts as a single command center for all your cloud security needs, offering insights and controls across multiple cloud providers and Kubernetes clusters.

  • Agentless vulnerability scanning: Scan your cloud environment, including containers and Kubernetes clusters, without deploying agents. Our agentless approach simplifies security operations and reduces overhead​.

  • Comprehensive coverage: Wiz covers all aspects of cloud security, from cloud security posture management (CSPM) and cloud infrastructure entitlement management (CIEM) to container security and IaC scanning, ensuring no part of your Kubernetes environment is left unprotected.

  • Actionable insights: Leverage Wiz to prioritize findings based on risk, providing clear, actionable insights that enable teams to focus on the most critical issues first.

To see how Wiz can transform your Kubernetes security strategy, schedule a demo today.

Empower your developers, from code to production

Learn why the fastest growing companies trust Wiz to secure Kubernetes from build-time to runtime.

Get a demo

Continue reading

Azure Security Risks & Mitigation Steps

Wiz Experts Team

This article offers an extensive examination of Azure environments’ most pressing security risks along with suggested approaches for effectively mitigating these challenges.

Remote Code Execution Attacks Explained

Wiz Experts Team

Remote code execution refers to a security vulnerability through which malicious actors can remotely run code on your systems or servers.

Understanding Cloud Security Risks

Wiz Experts Team

A cloud security risk is any threat that might impact the confidentiality, integrity, and availability (CIA) of data and applications hosted in the cloud.

Cloud Sprawl Explained

Wiz Experts Team

Cloud sprawl is a phenomenon that involves the unmanaged growth of cloud-based resources and services.

CSPM vs DSPM: Why You Need Both

Wiz Experts Team

Discover the similarities between CSPM and DSPM, what factors set them apart, and which one is the best choice for your organization’s needs.