Skip to content

k8s-securitycontext-defined

Apply security context to your pods and containers

A securityContext defines privilege and access control settings for a Pod or Container and are a recommended best practice in order to protect your systems from a number of real world vulnerabilities and possible privilege escalations. By applying a securityContext, you restrict the overall privileges that a Container may have and further protect your runtime environment.

These settings may be configued at a number of different levels:

  • A securityContext may be defined on a Pod and will apply all of the Pod's Containers.
  • A securityContext may be defined on a Container and will override settings defined on the Pod.
  • A securityContext may be enforced via a PodSecurityPolicy.

In the case where your organization enforces a policy via a PodSecurityPolicy, it is recommended that you disable this rule in your Boostsecurity Policy in order to reduce false positives.

Configuration

Although number of parameters exist for the securityContext, we will mainly focus on the following as they are most common.

  • allowPrivilegeEscalation: Controls whether a process can gain more privileges than its parent process. This should be false.
  • privileged: Processes in privileged containers are essentially equivalent to root on the host. This should be false.
  • readOnlyRootFilesystem: Whether this container has a read-only root filesystem. When possible, this shoule be true.
  • runAsGroup: The GID to run the entrypoint of the container process. This should be >= 1000.
  • runAsNonRoot: Indicates that the container must run as a non-root user. This should be true.
  • runAsUser: The UID to run the entrypoint of the container process. This should be >= 1000.

Examples

Insecure Example

# pods.yaml
apiVersion: v1
kind: Pod
metadata:
  name: default
spec:
  containers:
    - name: app
      image: registry/image:tag
    securityContext: null
  securityContext: null
---
apiVersion: v1
kind: Pod
metadata:
  name: privileged
spec:
  containers:
    - name: app
      image: registry/image:tag
      securityContext:
        privileged: true
  securityContext:
    runAsUser: 0

Secure Example

# pods.yaml
apiVersion: v1
kind: Pod
metadata:
  name: default
spec:
  containers:
    - name: app
      image: registry/image:tag
  securityContext:
    allowPrivilegeEscalation: false
    readOnlyRootFilesystem: true
    runAsGroup: 1000
    runAsNonRoot: true
    runAsUser: 1000

More information