How does /proc interact with PID namespaces?

I do not understand how namespaces interact with /proc. I assumed that /proc returns values based on the process that queries them.

For example, let’s determine the PID of the current process inside the global PID namespace:

$ bwrap --bind / / readlink /proc/self
6182

This makes sense to me. However, when I isolate readlink in its own PID namespace:

$ bwrap --bind / / --unshare-pid readlink /proc/self
6177

I get the same result! To get the PID inside the namespace, I need to add --proc /proc:

$ bwrap --bind / / --unshare-pid --proc /proc readlink /proc/self
2

But shouldn’t /proc always take the context of the reading process into account? Why is the extra procfs required and how is it related to the readlink process?

If I do not create a new PID namespace, the extra procfs makes no difference:

$ bwrap --bind / / --proc /proc readlink /proc/self
6179
Asked By: Georg Schölly

||

This is one of the gotchas of namespaces. With

bwrap --bind / / --unshare-pid readlink /proc/self

you’ve created a new PID namespace, and a new mount namespace (because bwrap does that by default), but you’re explicitly bind-mounting the external / into that mount namespace. The result is that, inside the new mount namespace, /proc is the same as outside — try

bwrap --bind / / --unshare-pid ps -ef

The key feature here is described in man pid_namespaces:

A /proc filesystem shows (in the /proc/[pid] directories) only
processes visible in the PID namespace of the process that
performed the mount
, even if the /proc filesystem is viewed from
processes in other namespaces.

(emphasis mine). You can see /proc memorising the appropriate PID namespace here.

So readlink sees /proc through the eyes of the PID namespace that performed the mount, not through its own PID namespace.

Adding --proc=/proc mounts /proc anew, inside the forked bwrap in the new PID namespace, so its contents reflect the new PID namespace.

Answered By: Stephen Kitt
Categories: Answers Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.