Dockerfile Security: Avoid Default, Root, or Dynamic User

This page describes a highlighted problem produced by the Docker and Kubernetes Security scanner plugin.

You could find more details on the internal page: Cloud (IaC) Security plugin

If this project has been helpful to you, please consider giving it a ⭐ on GitHub to help others discover it.

What’s the problem?

Docker images that do not set a static non-root user expose containers to risks. Using default, root, or dynamic user assignment in a Dockerfile lets attackers gain root access.

Description

Running containers with an undefined user or with the root user increases the attack surface. Dynamic assignment can override the intended user and make the container vulnerable.

One important notice: this check only considers the final user specified in the Dockerfile. It is acceptable to run build operations as root if you later switch to a dedicated non-root user.

Note that some base images may use a non-root user by default. Always verify the default user by checking the image documentation or using commands like docker inspect.

Examples

  • Implicit User: Not specifying a user makes Docker run the container with its default user. This default may be root a non-root user. Attackers can override this setting.
  • Explicit Root User: Writing USER root forces the container to run as root. This practice increases risk.
  • Dynamic User Assignment: Using environment variables or runtime parameters to assign a user lets attackers change the user to root. This dynamic method lacks consistency and security.

Solution

Always create and use a dedicated static non-root user in your Dockerfile. Avoid dynamic user assignment that can be overridden.

Problematic Code

# Example 1: Implicitly using the default user (can be overridden)
FROM ubuntu:20.04
RUN whoami
# Example 2: Explicitly setting the user to root
FROM ubuntu:20.04
USER root
RUN whoami
# Example 3: Dynamic user assignment via an environment variable (risky if overridden)
ARG APP_USER
FROM ubuntu:20.04
USER $APP_USER
RUN whoami

Verified Code

FROM ubuntu:20.04
# Create a dedicated non-root user and group
RUN groupadd --system app && useradd --system --create-home --gid app app
# Switch to the non-root user
USER app
RUN whoami