[Kubernetes] SecurityContext

Kubernetes organizes and launches container processes. You can configure which user or group will launch the process in a docker level or in a Kubernetes level.


Docker User

By default, the root (id = 0) is the user to run a container process.

There are several ways to set a different user to run the docker image process.

  • USER instruction in a docker file as a default user
  • Override a user at the run-time
docker run ... -u=""
docker run ... --user=""

You can set the username or UID and optionally the groupname or GID for the specified command.

--user=[ user | user:group | uid | uid:gid | user:gid | uid:group ]

Docker Runtime Privilege

By default, Docker containers are unprivileged.

  • A container cannot access any devices.
  • For example, you can not run a Docker daemon inside a container.

You can run a container as privileged using the –privileged option. A container can access all devices on the host.

docker run --privileged

If you want to allow only one or more devices accessible within a container, you can use the –device option.

docker run --device=/dev/sda:/dev/xvdc

Docker Linux Capabilities

In addition to –privileged, you can micro-control capabilities using –cap-add and –cap-drop options.

Please check the Docker documentation (https://docs.docker.com/engine/reference/run/) to see the list of available capabilities you can configure.

# docker run --cap-add
# docker run --cap-drop

docker run --rm -it --cap-add SYS_ADMIN --device /dev/fuse sshfs

docker run --cap-add=ALL --cap-drop=MKNOD

SecurityContext

The “SecurityContext” is the part of pod spec that defines privilege and access control settings for a pod.

  • The SecurityContext configurations can be applied at either the pod or container level.
    • The container setting will override the pod setting.
  • It can define special operating system level permissions such as who can run the pod.
    • runAsUser: user ID (UID)
    • runAsGroup: group ID (GID)
    • fsGroup
spec:
  securityContext:
     runAsUser: 2000
     fsGroup: 4000
  containers:
  - name: my-container
    image: busybox
    securityContext:
      runAsUser: 3000
       allowPrivilegeEscalation: false

You can grant certain privileges to a process without granting all the privileges of the root user.

  • Include the capabilities field in the SecurityContext section of the Container manifest.
  • Capabilities are only supported at the container level, not at the pod level.
spec:
  containers:
  - name: my-container
  image: busybox
  securityContext:
    capabilities:
      add: ["NET_ADMIN", "SYS_TIME"]

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s