0% found this document useful (0 votes)
41 views10 pages

Kubernetes Security Contexts Best Practices Cheatsheet

This cheat sheet outlines best practices for securing Kubernetes environments, emphasizing the importance of configuring security contexts for pods and containers to minimize vulnerabilities. It provides advanced techniques such as running containers as non-root, enforcing Pod Security Admission, and implementing runtime security measures like container forensics and continuous upgrades. The document also highlights the role of comprehensive platforms like Wiz in enhancing Kubernetes security through automated policy enforcement and advanced threat detection.

Uploaded by

akshayonthecloud
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views10 pages

Kubernetes Security Contexts Best Practices Cheatsheet

This cheat sheet outlines best practices for securing Kubernetes environments, emphasizing the importance of configuring security contexts for pods and containers to minimize vulnerabilities. It provides advanced techniques such as running containers as non-root, enforcing Pod Security Admission, and implementing runtime security measures like container forensics and continuous upgrades. The document also highlights the role of comprehensive platforms like Wiz in enhancing Kubernetes security through automated policy enforcement and advanced threat detection.

Uploaded by

akshayonthecloud
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Cheat Sheet

Kubernetes Security
Contexts Best Practices
Kubernetes has transformed the management and deployment of
containerized applications: Its powerful orchestration capabilities
enable developers and operations teams to efficiently scale,
deploy, and manage applications in a dynamic environment.
However, great power requires great responsibility. Securing
Kubernetes environments is essential to protect sensitive data,
maintain compliance, and prevent unauthorized access.

Security in Kubernetes is multifaceted, covering everything from network policies to runtime security and
monitoring. Given that pods and containers are distributed across the cluster, a single misconfiguration
can expose an entire cluster to potential threats. That’s why adopting best practices for configuring
Kubernetes security contexts for pods and containers is a crucial part of maintaining a robust and secure
environment.

This cheat sheet provides a detailed guide to Kubernetes security context best practices, focusing on
advanced techniques and configurations. By following the best practices outlined in this document, you
can ensure that your Kubernetes clusters are both secure and resilient despite the continuously evolving
landscape of cyber threats.

Understanding Kubernetes security contexts


In Kubernetes, a security context defines the security settings for a container or pod. These settings
dictate how processes run within the container, the permissions they have, and the security features
they use. The security context is crucial for defining constraints and ensuring pods and containers
operate with the minimum required privileges, which significantly reduces your attack surface. A security
context can include a variety of settings, such as:

runAsUser Defines the user ID under which the container process should run

runAsGroup Specifies the primary group ID to run the container process

runAsNonRoot Ensures the container operates without root privileges

readOnlyRootFilesystem Ensures the root filesystem is mounted as read-only

seLinuxOptions Sets SELinux options for the container

capabilities Specifies additional Linux capabilities to add or remove

© Wiz Inc. All Rights Reserved. 1


Properly configuring security contexts is essential for maintaining a secure Kubernetes environment.

Misconfigurations can introduce serious security risks—such as privilege escalation and unauthorized

access—that can ultimately lead to potential breaches. On the other hand, correctly configured security

contexts help you to:

Enforce the least-privilege principle: Ensuring containers have only the necessary permissions

prevents unnecessary access. Running containers with the least privilege necessary also reduces the

risk of threat actors getting elevated privileges

Optimize containment: Proper settings help contain breaches to individual containers or pods,

preventing lateral movement within the cluster

Maintain compliance: Correct configurations aid in meeting compliance requirements and industry

standards.

Advanced best practices for Kubernetes

security contexts

Securing a Kubernetes environment involves more than just basic configurations; it requires

implementing advanced security measures to protect against sophisticated threats. This section covers

the expert-level best practices for configuring Kubernetes security contexts, providing detailed

strategies and technical examples to fortify your clusters.

1 Container and pod security

1. Run containers as non-root

Running containers as root can lead to serious security vulnerabilities. If an attacker compromises a

container running as root , they potentially gain root access to the host node, leading to a complete

cluster compromise. Running containers as non-root users minimizes the potential damage a threat actor

can cause, even if they succeed in exploiting a vulnerability inside the container.

To configure a container to run as a non-root user, specify the runAsUser and runAsGroup fields in the

security context of the pod or container specification. Additionally, use the runAsNonRoot field to

ensure the container does not run as root. The following code snippet implements these best practices:

© Wiz Inc. All Rights Reserved. 2


apiVersion: v1

kind: Pod

metadata:

name: secure-pod

spec:

securityContext:

runAsUser: 1000

runAsGroup: 3000

runAsNonRoot: true

containers:

- name: secure-container

image: my-secure-image:latest

securityContext:

allowPrivilegeEscalation: false

capabilities:

drop:

- ALL

runAsUser: 1000

runAsGroup: 3000

readOnlyRootFilesystem: true

seccompProfile:

type: RuntimeDefault

Let’s take a closer look


runAsUser: 1000 and runAsGroup: 3000 specify the user and group IDs
runAsNonRoot: true ensures the container will not run as root
allowPrivilegeEscalation: false prevents the container from gaining additional privileges
capabilities.drop: ALL removes all additional Linux capabilities
readOnlyRootFilesystem: true ensures the root filesystem is read-only
seccompProfile: type: RuntimeDefault applies the default seccomp profile.

© Wiz Inc. All Rights Reserved. 3


2. Enforce security contexts with Pod Security Admission
Pod Security Admission is a native Kubernetes feature that enforces security protocols for pods by
checking their configurations against set security profiles. This validation ensures that only pods meeting
specified security criteria can be deployed, enhancing overall cluster security. It replaces the deprecated
PodSecurityPolicy and provides a straightforward way to implement security contexts across your
cluster.

By applying specific labels to namespaces, you can control the security policies for all pods within those
namespaces. The Pod Security Admission Controller supports three policies
Privileged: No restrictions; this policy allows all pod configuration
Baseline: Aimed at ease of adoption; it prevents known privilege escalations while minimizing
restriction
Restricted: Enforces the most restrictive policy, targeting current pod hardening best practices

Label your namespaces with the desired policy level to enforce security contexts using Pod Security
Admission. For example, to enforce the restricted policy on a namespace:

$ kubectl label namespace secure-namespace

pod-security.kubernetes.io/enforce=restricted

This label ensures that any pod created in secure-namespace must comply with the restricted security
policies, which include
Disallowing privileged containers (privileged: false
Preventing privilege escalation (allowPrivilegeEscalation: false
Requiring that containers run as a non-root user (runAsNonRoot: true
Enforcing read-only root filesystems (readOnlyRootFilesystem: true
Restricting host namespace sharing (hostPID, hostIPC, hostNetwork set to false)

If a pod violates these policies, the Pod Security Admission Controller will deny its creation, ensuring that
only pods adhering to the specified security contexts are deployed.

Benefits of using Pod Security Admission include


Simplified policy enforcement: Easily apply security policies across namespaces without managing
individual pod specifications
Consistent security posture: Ensure all pods within a namespace comply with the same security
standards
Ease of use: Labels provide a straightforward way to manage security policies without the complexity
of prior solutions like PodSecurityPolicy.

© Wiz Inc. All Rights Reserved. 4


3. Control Linux capabilities
Linux capabilities partition the privileges of the root user into distinct units, allowing processes to have
only the necessary privileges without granting full root access. You reduce the potential impact if a
container is compromised by dropping unnecessary capabilities. It's a best practice to drop all
capabilities and then add only necessary ones. Here's how to do it:

securityContext:

capabilities:

drop:

- ALL

add:

- NET_BIND_SERVICE

All capabilities are dropped in this example, and only NET_BIND_SERVICE is added to allow binding to
ports below 1024.

4. Enforce SELinux policies or AppArmor policies


Security-Enhanced Linux (SELinux) is a Linux kernel security module that applies strict access control
policies, restricting how applications and processes can interact with system resources. These policies
define how processes interact with files, devices, and other processes. In Kubernetes, enforcing SELinux
policies ensures containers operate within defined security boundaries, limiting their ability to affect
other processes or the host system. Creating SELinux policies can be complex, but tools like Udica
simplify this process. Alternatively, you can achieve similar security with AppArmor, another Linux
security module that enforces per-container access control policies.

To implement SELinux policies, you must set the SELinux options in the security context of your
Kubernetes pods or containers. In the following pod definition, seLinuxOptions sets the SELinux user,
role, type, and level for the pod. This configuration makes sure that the container operates under
strict SELinux policies:

© Wiz Inc. All Rights Reserved. 5


apiVersion: v1

kind: Pod

metadata:

name: selinux-pod

spec:

securityContext:

seLinuxOptions:

user: "system_u"

role: "system_r"

type: "spc_t"

level: "s0:c123,c456"

containers:

- name: selinux-container

image: my-secure-image:latest

securityContext:

allowPrivilegeEscalation: false

runAsUser: 1000

capabilities:

drop:

- ALL

5. Use fsGroup to set supplemental group IDs


The fsGroup field in the security context allows you to specify a supplemental group ID for all file system
operations. This is particularly useful for sharing data between containers and ensuring that the file
permissions are set correctly.

securityContext:

fsGroup: 2000

By setting fsGroup, you ensure that any files created by the container are accessible by the group ID
specified.

2 Enhancing runtime security


1. Implement runtime container forensics
Runtime container forensics involves monitoring and analyzing container activity to detect and respond
to potential security incidents. This includes logging, anomaly detection, and tracing container activities
to understand and mitigate threats.

© Wiz Inc. All Rights Reserved. 6


Falco is an open-source runtime security tool that detects anomalous behavior in containers,
Kubernetes, and cloud environments. It continuously monitors system calls against a powerful set of
security rules, providing real-time detection and alerting for security threats. It integrates with other
components like Kubernetes audit logs and CloudTrail for comprehensive threat detection. Then, it sends
alerts to various outputs like Slack, Elasticsearch, and other custom channels for timely incident
response:

Falco extended architecture


gRPC
FILTER

ALERTING
EXPRESSION
FILE

STDOUT

SYSDIG
SHELL
FALCO RULES
LIBRARIES
WEB

SERVER HTTP
AUDIT LOGS &

METADATA

MODULE/

eBPF PROBE

Figure 1: Falco overview (Source: Falco)

2. Implement continuous upgrades and patch management


Regular updates and patching are critical for maintaining the security of your Kubernetes cluster. Security
vulnerabilities are frequently discovered, and patches are released to mitigate them. Keeping your cluster
and its components up-to-date protects you against known vulnerabilities.

Kured (KUbernetes REboot Daemon) is an open-source daemon that automatically reboots nodes in a
Kubernetes cluster when required, such as after a kernel security update.

As illustrated in the diagram, the node reboot process in Kured begins with a node detecting a pending
reboot due to a kernel update. Kured cordons the node, ensuring no new pods are scheduled, and drains
existing pods to other nodes. After the node is drained, Kured triggers the reboot. Once the node is back
online, it rejoins the cluster, and normal operations resume, maintaining the cluster's security and stability.

© Wiz Inc. All Rights Reserved. 7


AKS cluster

AKS node Kured

Ubuntu Linux VM Pods check for DaemonSet


existence of file
on each node
/var/run/

Cron apt
reboot-required Pod

Communicates with API Server to


reschedule pods, cordon and drain node
before rebooting

Kubernetes
Kubernetes

Scheduler API Server

Figure 2: Kured running in an AKS cluster (Source: Microsoft)

2. Implement continuous upgrades and patch management

Regular updates and patching are critical for maintaining the security of your Kubernetes cluster. Security
vulnerabilities are frequently discovered, and patches are released to mitigate them. Keeping your cluster
and its components up-to-date protects you against known vulnerabilities.

Kured (KUbernetes REboot Daemon) is an open-source daemon that automatically reboots nodes in a
Kubernetes cluster when required, such as after a kernel security update.

As illustrated in the diagram, the node reboot process in Kured begins with a node detecting a pending
reboot due to a kernel update. Kured cordons the node, ensuring no new pods are scheduled, and drains
existing pods to other nodes. After the node is drained, Kured triggers the reboot. Once the node is back
online, it rejoins the cluster, and normal operations resume, maintaining the cluster's security and stability.

2 Monitoring and auditing

1. Monitor and analyze logs


Effective log management and analysis are crucial for detecting and responding to security incidents.
Tools like Splunk; Prometheus; and the Elasticsearch, Fluentd, and Kibana (EFK) stack provide robust log
management solutions.

The EFK stack consists of a lightweight log forwarder that collects logs from Kubernetes pods and
forwards them to Fluentd. Fluentd then processes and enriches the logs before sending them to
Elasticsearch, where they are stored and indexed. Finally, Kibana provides a powerful interface for
visualizing and querying the logs, enabling real-time monitoring and analysis of log data.

© Wiz Inc. All Rights Reserved. 8


K8S Master K8S Worker #1 K8S Worker #2

Service “my-nginx”

Namespace
Namespace

“default” “default”

Pod
Pod

“my-nginx” “my-nginx”

Log output Log output

Namespace
Namespace
Namespace

“kube-system” “kube-system” “kube-system”

Daemon Daemon Daemon


Set Set Set
“Fluentd” “Fluentd” “Fluentd”

Figure 3: Logging with the EFK stack (Source: Fluent Bit)

2. Implement advanced threat detection

Advanced threat detection involves using machine learning (ML) to identify unusual patterns in container
and cluster activities. This automated approach facilitates the early detection of threats.

As previously mentioned, Falco continuously monitors system calls and kernel events against security
rules to detect suspicious behavior in real time. The following code snippet demonstrates how you can
write customized Falco rules to define what constitutes suspicious behavior. In this example, the rule
detects any attempts to write to files within the /etc directory, which is a common target for malicious
activities:

- rule: Write below etc

desc: Detect any write below /etc directory

condition: evt.type = "open" and fd.name startswith "/etc" and evt.dir = "<"

output: "File below /etc opened for writing (user=%user.name


command=%proc.cmdline file=%fd.name)"

priority: WARNING

© Wiz Inc. All Rights Reserved. 9


Wiz: A comprehensive Kubernetes security
platform
While the tools and best practices above significantly enhance Kubernetes security, they are often only
partially optimal. Each tool addresses specific aspects of security, but achieving comprehensive
protection requires seamless integration and continuous monitoring across all layers of your stack. This is
where a unified platform like Wiz comes in.

Wiz provides comprehensive solutions that enhance Kubernetes security through advanced threat
detection, continuous monitoring, and automated policy enforcement. Wiz offers deep visibility into the
security posture of Kubernetes clusters, helping organizations identify and remediate vulnerabilities. 

When it comes to security context configurations, look to Wiz for

Automated policy enforcement: Wiz automatically enforces security policies, ensuring compliance
and reducing misconfigurations

Advanced threat detection: Wiz uses sensors to obtain runtime context and correlates events from
the control plane, pods, nodes, and cloud environments to identify and respond to security incidents

Continuous monitoring: Wiz continuously monitors Kubernetes clusters, providing real-time visibility
into security events

Vulnerability management: Wiz identifies and prioritizes vulnerabilities, providing actionable insights
for remediation.

Wiz delivers a holistic security solution, bridging the gaps and ensuring robust, end-to-end protection for
your Kubernetes environments.

Request a demo today to see how Wiz can Get a Demo


help you achieve all your comprehensive
security goals!

© Wiz Inc. All Rights Reserved. 10

You might also like