By default, containers execute everything as the root
user. Granted that containers are running in an isolated environment, but still, a publicly facing daemon is running as root on a system, and a security breach may give an attacker access to this particular container, and maybe root shell access, giving access at least to the container's Docker overlay network. Would we like to see this issue combined with a 0-day local kernel security breach that would give the attacker access to the Docker host? Probably not. Then, maybe we should keep some of the good old practices and start by executing our daemon as a user other than root.
To step through this recipe, you will need the following:
Let's take a simple HTTP server that answers on the port 8000
of the container. Executed through a container, it would look like this, as seen earlier in this book:
FROM debian:jessie-slim COPY src/hello/hello /usr/bin/hello RUN chmod +x /usr/bin/hello EXPOSE 8000 ENTRYPOINT ["/usr/bin/hello"]
This will work, but things aren't looking that great security-wise; our daemon is, in fact, running as the root
user, even though it's running on an unprivileged port:
$ ps aux USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND root 1 0.6 0.2 36316 4180 ? Ssl+ 23:30 0:00 /usr/bin/hello
This is suboptimal from a security point of view. Containers are real systems, so they too can have users. Combined with the USER
instruction in the Dockerfile, we'll be able to execute commands as an unprivileged user! Here's how an optimized Dockerfile looks, adding a normal user and group for the hello
user, and then executing the /usr/bin/hello
HTTP server as this new unprivileged user:
FROM debian:jessie-slim COPY src/hello/hello /usr/bin/hello RUN chmod +x /usr/bin/hello RUN groupadd -r hello && useradd -r -g hello hello USER hello EXPOSE 8000 ENTRYPOINT ["/usr/bin/hello"]
Once built and running, the daemon still runs correctly, but as an unprivileged user:
$ ps aux USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND hello 1 0.0 0.2 36316 4768 ? Ssl+ 23:33 0:00 /usr/bin/hello
We're now building tougher containers!
3.137.223.190