user_namespaces(7)
๐ธ user_namespaces(7) โ Miscellaneous Information Manual ๐ธ
ok so bestie, listen. this is the user_namespaces(7) page, and it's a big one, so we're doing it in parts. part 1 starts now, no cap. ๐
โจ NAME โจ
user_namespaces โ overview of Linux user namespaces ๐
๐ฆ DESCRIPTION ๐ฆ
ok so if you want the whole big-picture tour of namespaces in general, go read namespaces(7) first. that one's the vibe-setter. this page is about user namespaces specifically, and bestie, they are the moment.
User namespaces isolate security-related identifiers and attributes. and when we say "security-related identifiers and attributes", we mean specifically:
- user IDs and group IDs (peep
credentials(7)) - the root directory
- keys (peep
keyrings(7)) - capabilities (peep
capabilities(7))
the way a process's user and group IDs can be different inside and outside a user namespace?? iconic. literally you can have a totally normal, unprivileged user ID outside a user namespace while having a user ID of 0 inside the namespace. translation: the process has full privileges for operations inside the user namespace, but is unprivileged for operations outside the namespace. main character inside, regular civilian outside. ๐ซถ
๐ Nested namespaces, namespace membership ๐
User namespaces can be nested. so every user namespace โ except the initial ("root") namespace โ has a parent user namespace, and can have zero or more child user namespaces. cute lil family tree fr fr. ๐ณ
the parent user namespace is the user namespace of the process that creates the user namespace, via a call to unshare(2) or clone(2) with the CLONE_NEWUSER flag.
the kernel imposes a limit (since Linux 3.11) of 32 nested levels of user namespaces. calls tounshare(2)orclone(2)that would cause this limit to be exceeded fail with the errorEUSERS. so no, you can't just keep nesting forever, bestie. it's giving elevator limit. ๐
Each process is a member of exactly one user namespace. no polyamory here, one namespace only:
- a process created via
fork(2)orclone(2)without theCLONE_NEWUSERflag is a member of the same user namespace as its parent. - a single-threaded process can join another user namespace with
setns(2)if it has theCAP_SYS_ADMINin that namespace; upon doing so, it gains a full set of capabilities in that namespace. โจ
A call to clone(2) or unshare(2) with the CLONE_NEWUSER flag makes the new child process (for clone(2)) or the caller (for unshare(2)) a member of the new user namespace created by the call.
The NS_GET_PARENT ioctl(2) operation can be used to discover the parental relationship between user namespaces; peep ioctl_nsfs(2). ๐ง
ok now a lil warning that is lowkey a gotcha:
A task that changes one of its effective IDs will have its dumpability reset to the value in /proc/sys/fs/suid_dumpable. This may affect the ownership of proc files of child processes and may thus cause the parent to lack the permissions to write to mapping files of child processes running in a new user namespace. In such cases, making the parent process dumpable, using PR_SET_DUMPABLE in a call to prctl(2), before creating a child process in a new user namespace may rectify this problem. See prctl(2) and proc(5) for details on how ownership is affected.
so like, if your parent can't write the mapping files and you're sitting there like "why ๐ญ" โ that might be it. check your dumpability. slay accordingly.
๐ Capabilities ๐
The child process created by clone(2) with the CLONE_NEWUSER flag starts out with a complete set of capabilities in the new user namespace. queen behavior. ๐
Likewise, a process that creates a new user namespace using unshare(2) or joins an existing user namespace using setns(2) gains a full set of capabilities in that namespace. but flip side: that process has no capabilities in the parent (for clone(2)) or previous (for unshare(2) and setns(2)) user namespace โ even if the new namespace is created or joined by the root user (i.e., a process with user ID 0 in the root namespace). like, even root doesn't get a pass here. the audacity, honestly.
Note that a call to execve(2) will cause a process's capabilities to be recalculated in the usual way (see capabilities(7)). Consequently, unless the process has a user ID of 0 within the namespace, or the executable file has a nonempty inheritable capabilities mask, the process will lose all capabilities. See the discussion of user and group ID mappings, below.
A call to clone(2) or unshare(2) using the CLONE_NEWUSER flag, or a call to setns(2) that moves the caller into another user namespace, sets the "securebits" flags (see capabilities(7)) to their default values (all flags disabled) in the child (for clone(2)) or caller (for unshare(2) or setns(2)).
and here's the sad part: because the caller no longer has capabilities in its original user namespace after a call tosetns(2), it is not possible for a process to reset its "securebits" flags while retaining its user namespace membership by using a pair ofsetns(2)calls to move to another user namespace and then return to its original user namespace. yeah. that trick does not work. sorry bestie. ๐
The rules for determining whether or not a process has a capability in a particular user namespace are as follows:
- A process has a capability inside a user namespace if it is a member of that namespace and it has the capability in its effective capability set. A process can gain capabilities in its effective capability set in various ways. For example, it may execute a set-user-ID program or an executable with associated file capabilities. In addition, a process may gain capabilities via the effect of
clone(2),unshare(2), orsetns(2), as already described. - If a process has a capability in a user namespace, then it has that capability in all child (and further removed descendant) namespaces as well. inherited slay. ๐
- When a user namespace is created, the kernel records the effective user ID of the creating process as being the "owner" of the namespace. A process that resides in the parent of the user namespace and whose effective user ID matches the owner of the namespace has all capabilities in the namespace. By virtue of the previous rule, this means that the process has all capabilities in all further removed descendant user namespaces as well. The
NS_GET_OWNER_UIDioctl(2)operation can be used to discover the user ID of the owner of the namespace; peepioctl_nsfs(2). โจ
๐ Effect of capabilities within a user namespace ๐
Having a capability inside a user namespace permits a process to perform operations (that require privilege) only on resources governed by that namespace. In other words, having a capability in a user namespace permits a process to perform privileged operations on resources that are governed by (nonuser) namespaces owned by (associated with) the user namespace โ see the next subsection. so cute, so scoped: your power stays in your lane. ๐ธ
On the other hand, there are many privileged operations that affect resources that are not associated with any namespace type. for example:
- changing the system (i.e., calendar) time โ governed by
CAP_SYS_TIME - loading a kernel module โ governed by
CAP_SYS_MODULE - creating a device โ governed by
CAP_MKNOD
Only a process with privileges in the initial user namespace can perform such operations. no exceptions. periodt. ๐ฅ
Holding CAP_SYS_ADMIN within the user namespace that owns a process's mount namespace allows that process to create bind mounts and mount the following types of filesystems:
/proc(since Linux 3.8)/sys(since Linux 3.8)devpts(since Linux 3.9)tmpfs(5)(since Linux 3.9)ramfs(since Linux 3.9)mqueue(since Linux 3.9)bpf(since Linux 4.4)overlayfs(since Linux 5.11)
Holding CAP_SYS_ADMIN within the user namespace that owns a process's cgroup namespace allows (since Linux 4.6) that process to mount the cgroup version 2 filesystem and cgroup version 1 named hierarchies (i.e., cgroup filesystems mounted with the "none,name=" option).
Holding CAP_SYS_ADMIN within the user namespace that owns a process's PID namespace allows (since Linux 3.8) that process to mount /proc filesystems.
However โ and pls don't skip this one โ mounting block-based filesystems can be done only by a process that holds CAP_SYS_ADMIN in the initial user namespace. that one's not up for debate. ๐
๐ Interaction of user namespaces and other types of namespaces ๐
Since Linux 3.8, unprivileged processes can create user namespaces, and the other types of namespaces can be created with just the CAP_SYS_ADMIN capability in the caller's user namespace. yes, unprivileged besties, you got this. ๐ซถ
When a nonuser namespace is created, it is owned by the user namespace in which the creating process was a member at the time of the creation of the namespace. Privileged operations on resources governed by the nonuser namespace require that the process has the necessary capabilities in the user namespace that owns the nonuser namespace.
If CLONE_NEWUSER is specified along with other CLONE_NEW* flags in a single clone(2) or unshare(2) call, the user namespace is guaranteed to be created first, giving the child (clone(2)) or caller (unshare(2)) privileges over the remaining namespaces created by the call. Thus, it is possible for an unprivileged caller to specify this combination of flags. order of operations, but make it a glow-up. โจ
When a new namespace (other than a user namespace) is created via clone(2) or unshare(2), the kernel records the user namespace of the creating process as the owner of the new namespace. (This association can't be changed.) When a process in the new namespace subsequently performs privileged operations that operate on global resources isolated by the namespace, the permission checks are performed according to the process's capabilities in the user namespace that the kernel associated with the new namespace.
for example: suppose that a process attempts to change the hostname (sethostname(2)), a resource governed by the UTS namespace. In this case, the kernel will determine which user namespace owns the process's UTS namespace, and check whether the process has the required capability (CAP_SYS_ADMIN) in that user namespace. so it's giving "who's your owner? ok and do you have the perms there?" ๐
The NS_GET_USERNS ioctl(2) operation can be used to discover the user namespace that owns a nonuser namespace; peep ioctl_nsfs(2).
๐ User and group ID mappings: uid_map and gid_map ๐
When a user namespace is created, it starts out without a mapping of user IDs (group IDs) to the parent user namespace. brand new, no connections. ๐ญ
The /proc/pid/uid_map and /proc/pid/gid_map files (available since Linux 3.5) expose the mappings for user and group IDs inside the user namespace for the process pid. These files can be read to view the mappings in a user namespace and written to (once) to define the mappings. once. one write. that's your one shot, don't waste it. ๐ฅ
The description in the following paragraphs explains the details for uid_map; gid_map is exactly the same, but each instance of "user ID" is replaced by "group ID". (like a find-and-replace, but make it gender โจ)
The uid_map file exposes the mapping of user IDs from the user namespace of the process pid to the user namespace of the process that opened uid_map (but see a qualification to this point below). In other words, processes that are in different user namespaces will potentially see different values when reading from a particular uid_map file, depending on the user ID mappings for the user namespaces of the reading processes. same file, different truths. it's giving perspective. ๐ฆ
(to be continued, bestie โ part 2 is coming and it's a whole thing ๐)
Each line in the uid_map file sets up a 1-to-1 mapping of a range of contiguous user IDs between two user namespaces. (fun fact bestie: when a user namespace is first created, this file is empty โ a whole blank slate โจ) Every line is literally just three numbers, separated by white space. The first two numbers are the starting user ID in each of the two user namespaces, and the third number is how big the mapped range is. Let's break the fields down properly:
- The start of the range of user IDs in the user namespace of the process pid.
- The start of the range of user IDs to which the user IDs specified by field one map. How field two gets interpreted depends on whether the process that opened
uid_mapand the process pid are in the same user namespace, like so:- (a) If the two processes are in different user namespaces: field two is the start of a range of user IDs in the user namespace of the process that opened
uid_map. - (b) If the two processes are in the same user namespace: field two is the start of the range of user IDs in the parent user namespace of the process pid. This case is the one that lets the opener of
uid_map(and the common case here is opening/proc/self/uid_map) see the mapping of user IDs into the user namespace of the process that created this user namespace.
- (a) If the two processes are in different user namespaces: field two is the start of a range of user IDs in the user namespace of the process that opened
- The size of the range of user IDs that is mapped between the two user namespaces.
System calls that return user IDs (group IDs) โ think getuid(2), getgid(2), and the credential fields in the structure returned by stat(2) โ return the user ID (group ID) mapped into the caller's user namespace. ๐
When a process accesses a file, its user and group IDs get mapped into the initial user namespace, for the purposes of permission checking and assigning IDs when a file is created. When a process retrieves file user and group IDs via stat(2), the IDs get mapped in the opposite direction, so the values come out relative to the process's user and group ID mappings.
The initial user namespace has no parent namespace, but for consistency's sake the kernel still provides dummy user and group ID mapping files for it. Peeking at the uid_map file (gid_map is the same) from a shell in the initial namespace shows you this:
$ cat /proc/$$/uid_map;
0 0 4294967295
So this mapping is telling us that the range starting at user ID 0 in this namespace maps to a range starting at 0 in the (nonexistent) parent namespace, and the size of that range is the largest 32-bit unsigned integer. That leaves 4294967295 (the 32-bit signed -1 value) unmapped, and bestie that is on purpose: (uid_t) -1 is used in several interfaces (e.g., setreuid(2)) as a way to say "no user ID". Leaving (uid_t) -1 unmapped and unusable guarantees there's no confusion when these interfaces get used. periodt. ๐
โจ Defining user and group ID mappings: writing to uid_map and gid_map โจ
Once a new user namespace exists, the uid_map file of one of the processes in that namespace may be written to once to define the mapping of user IDs in the new user namespace. Try to write more than once to a uid_map file in a user namespace and it fails with the error EPERM. Same rules apply for gid_map files.
Anything written to uid_map (gid_map) has to pass these validity rules:
- The three fields must be valid numbers, and the last field must be greater than 0. (no zeros, no nonsense ๐ )
- Lines are terminated by newline characters.
- There's a cap on how many lines the file can hold. Up to Linux 4.14, this limit was (arbitrarily) set at 5 lines. Since Linux 4.16, the limit is 340 lines. On top of that, the number of bytes written to the file must be less than the system page size, and the write has to happen at the start of the file (so no,
lseek(2)andpwrite(2)can't be used to write to nonzero offsets in the file ๐). - The range of user IDs (group IDs) specified in each line cannot overlap with the ranges in any other lines. Back in the initial implementation (Linux 3.8), this requirement was satisfied by a simplistic implementation that added another requirement โ that the values in both field 1 and field 2 of successive lines be in ascending numerical order โ which blocked some otherwise valid maps from ever being created. Since Linux 3.9, that limitation is gone, so any valid set of nonoverlapping maps is fair game. slay.
- At least one line must be written to the file.
Writes that break the rules above fail with the error EINVAL.
And for a process to write to /proc/pid/uid_map (/proc/pid/gid_map), all of these permission requirements have to be met:
- The writing process must have the
CAP_SETUID(CAP_SETGID) capability in the user namespace of the process pid. - The writing process must either be in the user namespace of the process pid or be in the parent user namespace of the process pid.
- The mapped user IDs (group IDs) must in turn have a mapping in the parent user namespace.
- If updating
/proc/pid/uid_mapto create a mapping that maps UID 0 in the parent namespace, then one of these has to be true:- (a) if the writing process is in the parent user namespace, then it must have the
CAP_SETFCAPcapability in that user namespace; or - (b) if the writing process is in the child user namespace, then the process that created the user namespace must have had the
CAP_SETFCAPcapability when the namespace was created.
- (a) if the writing process is in the parent user namespace, then it must have the
This rule has been in place since Linux 5.12. It eliminates an earlier security bug ๐ whereby a UID 0 process that lacks the CAP_SETFCAP capability โ which is needed to create a binary with namespaced file capabilities (as described in capabilities(7)) โ could nevertheless create such a binary, by these steps:
- Create a new user namespace with the identity mapping (i.e., UID 0 in the new user namespace maps to UID 0 in the parent namespace), so that UID 0 in both namespaces is equivalent to the same root user ID.
- Since the child process has the
CAP_SETFCAPcapability, it could create a binary with namespaced file capabilities that would then be effective in the parent user namespace (because the root user IDs are the same in the two namespaces).
- One of the following two cases applies:
- (a) Either the writing process has the
CAP_SETUID(CAP_SETGID) capability in the parent user namespace.- No further restrictions apply: the process can make mappings to arbitrary user IDs (group IDs) in the parent user namespace. ๐
- (b) Or otherwise all of the following restrictions apply:
- The data written to
uid_map(gid_map) must consist of a single line that maps the writing process's effective user ID (group ID) in the parent user namespace to a user ID (group ID) in the user namespace. - The writing process must have the same effective user ID as the process that created the user namespace.
- In the case of
gid_map, use of thesetgroups(2)system call must first be denied by writing"deny"to the/proc/pid/setgroupsfile (see below) before writing togid_map.
- The data written to
- (a) Either the writing process has the
Writes that violate the rules above fail with the error EPERM.
๐ฆ Project ID mappings: projid_map ๐ฆ
Just like user and group ID mappings, you can also create project ID mappings for a user namespace. (Project IDs are used for disk quotas; see setquota(8) and quotactl(2).) ๐
Project ID mappings are defined by writing to the /proc/pid/projid_map file (present since Linux 3.7).
The validity rules for writing to /proc/pid/projid_map are the same as for writing to the uid_map file; violate them and write(2) fails with the error EINVAL.
The permission rules for writing to /proc/pid/projid_map go like this:
- The writing process must either be in the user namespace of the process pid or be in the parent user namespace of the process pid.
- The mapped project IDs must in turn have a mapping in the parent user namespace.
Break these rules and write(2) fails with the error EPERM.
๐ Interaction with system calls that change process UIDs or GIDs ๐
In a user namespace where the uid_map file hasn't been written, the system calls that change user IDs will fail. Same energy for group IDs: if the gid_map file hasn't been written, the system calls that change group IDs will fail. Once uid_map and gid_map have been written, only the mapped values may be used in system calls that change user and group IDs.
For user IDs, the relevant system calls include setuid(2), setfsuid(2), setreuid(2), and setresuid(2). For group IDs, the relevant ones include setgid(2), setfsgid(2), setregid(2), setresgid(2), and setgroups(2).
Writing "deny" to the /proc/pid/setgroups file before writing to /proc/pid/gid_map will permanently disable setgroups(2) in a user namespace, and it also allows writing to /proc/pid/gid_map without having the CAP_SETGID capability in the parent user namespace. ngl that's the tradeoff. ๐ซถ
๐ธ The /proc/pid/setgroups file ๐ธ
The /proc/pid/setgroups file displays the string "allow" if processes in the user namespace that contains the process pid are permitted to employ the setgroups(2) system call; it displays "deny" if setgroups(2) is not permitted in that user namespace. Heads up though: regardless of the value in the /proc/pid/setgroups file (and regardless of the process's capabilities), calls to setgroups(2) are also not permitted if /proc/pid/gid_map has not yet been set.
A privileged process (one with the CAP_SYS_ADMIN capability in the namespace) may write either of the strings "allow" or "deny" to this file before writing a group ID mapping for this user namespace to the file /proc/pid/gid_map. Writing the string "deny" prevents any process in the user namespace from employing setgroups(2).
The essence of the restrictions described in the paragraph above is: it's permitted to write to /proc/pid/setgroups only so long as calling setgroups(2) is disallowed because /proc/pid/gid_map has not been set. This ensures a process cannot transition from a state where setgroups(2) is allowed to a state where setgroups(2) is denied; a process can only transition from setgroups(2) being disallowed to setgroups(2) being allowed. one-way door, bestie. ๐ชโจ
The default value of this file in the initial user namespace is "allow".
Once /proc/pid/gid_map has been written to (which, lowkey, is the thing that enables setgroups(2) in the user namespace), you literally cannot disallow setgroups(2) anymore by writing "deny" to /proc/pid/setgroups โ that write just fails with the error EPERM. no takebacksies bestie ๐ญ
A child user namespace inherits the /proc/pid/setgroups setting from its parent. family trauma, it's giving hereditary ๐
And if the setgroups file has the value "deny", then the setgroups(2) system call can't be reenabled afterwards (like, by writing "allow" to the file) in this user namespace. Attempts to do that fail with EPERM. And this restriction also propagates down to all child user namespaces of this user namespace. it's giving generational, fr fr ๐ซถ
/proc/pid/setgroups was added in Linux 3.19, but got backported to many earlier stable kernel series, because it fixes a whole security issue โจ. Here's the tea: the issue was about files with permissions like "rwx---rwx". Those files give fewer permissions to "group" than they do to "other". So dropping groups with setgroups(2) might let a process access a file it didn't have access to before โ not me gaining file access through a loophole ๐. Before user namespaces existed this wasn't a concern, because only a privileged process (one holding the CAP_SETGID capability) could call setgroups(2). But once user namespaces showed up, an unprivileged process could create a new namespace in which the user had all the privileges. Which then let formerly unprivileged users drop groups and snag file access they never had before. /proc/pid/setgroups was added to address exactly that, by denying any pathway for an unprivileged process to drop groups with setgroups(2). iconic defensive move, ate ๐ฅ
โจ Unmapped user and group IDs โจ
There are various places where an unmapped user ID (group ID) may be exposed to user space. For example, the first process in a new user namespace may call getuid(2) before a user ID mapping has even been defined for the namespace. In most such cases, an unmapped user ID is converted to the overflow user ID (group ID) โ and the default value for the overflow user ID (group ID) is 65534. Peep the descriptions of /proc/sys/kernel/overflowuid and /proc/sys/kernel/overflowgid in proc(5) for the deets.
The cases where unmapped IDs get mapped this way include:
- system calls that return user IDs (
getuid(2),getgid(2), and similar) - credentials passed over a UNIX domain socket
- credentials returned by
stat(2),waitid(2), and the System V IPC"ctl"IPC_STAToperations - credentials exposed by
/proc/pid/statusand the files in/proc/sysvipc/* - credentials returned via the
si_uidfield in thesiginfo_treceived with a signal (seesigaction(2)) - credentials written to the process accounting file (see
acct(5)) - credentials returned with POSIX message queue notifications (see
mq_notify(3))
There is one notable case where unmapped user and group IDs are not converted to the corresponding overflow ID value ๐. When you're viewing a uid_map or gid_map file where there's no mapping for the second field, that field shows up as 4294967295 (-1 as an unsigned integer).
๐ธ Accessing files ๐ธ
To figure out permissions when an unprivileged process accesses a file, the process credentials (UID, GID) and the file credentials are โ in effect โ mapped back to what they would be in the initial user namespace, and then compared to determine which permissions the process has on that file. Same deal for other objects that use the credentials-plus-permissions-mask accessibility model, like System V IPC objects. mapping back to the group chat to check who's allowed in ๐
๐ฆ Operation of file-related capabilities ๐ฆ
Certain capabilities let a process bypass various kernel-enforced restrictions when it's doing operations on files owned by other users or groups. Those capabilities are: CAP_CHOWN, CAP_DAC_OVERRIDE, CAP_DAC_READ_SEARCH, CAP_FOWNER, and CAP_FSETID.
Within a user namespace, these capabilities let a process bypass the rules if the process has the relevant capability over the file, meaning that:
- the process has the relevant effective capability in its user namespace; and
- the file's user ID and group ID both have valid mappings in the user namespace.
CAP_FOWNER is treated a lil exceptionally ๐: it lets a process bypass the corresponding rules so long as at least the file's user ID has a mapping in the user namespace โ meaning the file's group ID does not need to have a valid mapping. main character capability energy, honestly.
๐ Set-user-ID and set-group-ID programs ๐
When a process inside a user namespace executes a set-user-ID (set-group-ID) program, the process's effective user (group) ID inside the namespace is changed to whatever value is mapped for the user (group) ID of the file. However, if either the user or the group ID of the file has no mapping inside the namespace, the set-user-ID (set-group-ID) bit is silently ignored โ the new program still gets executed, but the process's effective user (group) ID is left unchanged. (This mirrors the semantics of executing a set-user-ID or set-group-ID program living on a filesystem that was mounted with the MS_NOSUID flag, as described in mount(2).) quietly ignored, it's giving ghosted ๐
๐ Miscellaneous ๐
When a process's user and group IDs are passed over a UNIX domain socket to a process in a different user namespace (see the description of SCM_CREDENTIALS in unix(7)), they get translated into the corresponding values according to the receiving process's user and group ID mappings. translating for the group chat, so thoughtful ๐ซถ
๐ STANDARDS ๐
Linux.
๐ NOTES ๐
Over the years, so many features got added to the Linux kernel that were only made available to privileged users, because of their potential to confuse set-user-ID-root applications. But bestie, in general it becomes safe to let the root user inside a user namespace use those features, because while you're in a user namespace it is impossible to gain more privilege than the root user of a user namespace already has. the ceiling is the ceiling โจ
๐ Global root ๐
The term "global root" is sometimes used as shorthand for user ID 0 in the initial user namespace.
๐ Availability ๐
Using user namespaces requires a kernel that's configured with the CONFIG_USER_NS option. User namespaces require support in a whole range of subsystems across the kernel โ and when an unsupported subsystem is configured into the kernel, it is not possible to configure user namespaces support. it's giving all-or-nothing ๐ญ
As at Linux 3.8, most relevant subsystems supported user namespaces, but a number of filesystems did not have the infrastructure needed to map user and group IDs between user namespaces. Linux 3.9 added the required infrastructure support for many of the remaining unsupported filesystems (Plan 9 (9P), Andrew File System (AFS), Ceph, CIFS, CODA, NFS, and OCFS2). Linux 3.12 added support for the last of the unsupported major filesystems, XFS. they really said "we'll get there" and got there ๐ซถ
๐ฅ EXAMPLES ๐ฅ
The program below is designed to let you experiment with user namespaces, as well as other types of namespaces. It creates namespaces as specified by command-line options and then executes a command inside those namespaces. The comments and the usage() function inside the program give you a full explanation of the program. And the shell session below demonstrates it in action โจ
First, we look at the run-time environment:
$ uname -rs; # Need Linux 3.8 or later
Linux 3.8.0
$ id -u; # Running as unprivileged user
1000
$ id -g;
1000
Now start a new shell in new user (-U), mount (-m), and PID (-p) namespaces, with user ID (-M) and group ID (-G) 1000 mapped to 0 inside the user namespace:
$ ./userns_child_exec -p -m -U -M '0 1000 1' -G '0 1000 1' bash;
The shell has PID 1, because it is the first process in the new PID namespace:
bash$ echo $$;
1
Mounting a new /proc filesystem and listing all the processes visible in the new PID namespace shows that the shell can't see any processes outside the PID namespace:
bash$ mount -t proc proc /proc;
bash$ ps ax;
PID TTY STAT TIME COMMAND
1 pts/3 S 0:00 bash
22 pts/3 R+ 0:00 ps ax
Inside the user namespace, the shell has user and group ID 0, plus a full set of permitted and effective capabilities:
bash$ cat /proc/$$/status | egrep '^[UG]id';
Uid: 0 0 0 0
Gid: 0 0 0 0
bash$ cat /proc/$$/status | egrep '^Cap(Prm|Inh|Eff)';
CapInh: 0000000000000000
CapPrm: 0000001fffffffff
CapEff: 0000001fffffffff
๐ง Program source ๐ง
/* userns_child_exec.c
Licensed under GNU General Public License v2 or later
Create a child process that executes a shell command in new
namespace(s); allow UID and GID mappings to be specified when
creating a user namespace.
*/
#define _GNU_SOURCE
#include <err.h>
#include <sched.h>
#include <unistd.h>
#include <stdint.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <signal.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <limits.h>
#include <errno.h>
struct child_args {
char **argv; /* Command to be executed by child, with args */
int pipe_fd[2]; /* Pipe used to synchronize parent and child */
};
static int verbose;
static void
usage(char *pname)
{
fprintf(stderr, "Usage: %s [options] cmd [arg...]\n\n", pname);
fprintf(stderr, "Create a child process that executes a shell "
"command in a new user namespace,\n"
"and possibly also other new namespace(s).\n\n");
fprintf(stderr, "Options can be:\n\n");
#define fpe(str) fprintf(stderr, " %s", str);
fpe("-i New IPC namespace\n");
fpe("-m New mount namespace\n");
fpe("-n New network namespace\n");
fpe("-p New PID namespace\n");
fpe("-u New UTS namespace\n");
fpe("-U New user namespace\n");
fpe("-M uid_map Specify UID map for user namespace\n");
fpe("-G gid_map Specify GID map for user namespace\n");
fpe("-z Map user's UID and GID to 0 in user namespace\n");
fpe(" (equivalent to: -M '0 <uid> 1' -G '0 <gid> 1')\n");
fpe("-v Display verbose messages\n");
fpe("\n");
fpe("If -z, -M, or -G is specified, -U is required.\n");
fpe("It is not permitted to specify both -z and either -M or -G.\n");
fpe("\n");
fpe("Map strings for -M and -G consist of records of the form:\n");
fpe("\n");
fpe(" ID-inside-ns ID-outside-ns size\n");
fpe("\n");
fpe("A map string can contain multiple records, separated"
" by commas;\n");
fpe("the commas are replaced by newlines before writing"
" to map files.\n");
exit(EXIT_FAILURE);
}
/* Update the mapping file 'map_file', with the value provided in
'mapping', a string that defines a UID or GID mapping. A UID or
GID mapping consists of one or more newline-delimited records
of the form:
ID_inside-ns ID-outside-ns size
Requiring the user to supply a string that contains newlines is
of course inconvenient for command-line use. Thus, we permit the
use of commas to delimit records in this string, and replace them
with newlines before writing the string to the file. */
static void
update_map(char *mapping, char *map_file)
{
int fd;
size_t map_len; /* Length of 'mapping' */
/* Replace commas in mapping string with newlines. */
map_len = strlen(mapping);
for (size_t j = 0; j < map_len; j++)
if (mapping[j] == ',')
mapping[j] = '\n';
fd = open(map_file, O_RDWR);
if (fd == -1) {
fprintf(stderr, "ERROR: open %s: %s\n", map_file,
strerror(errno));
exit(EXIT_FAILURE);
}
if (write(fd, mapping, map_len) != map_len) {
fprintf(stderr, "ERROR: write %s: %s\n", map_file,
strerror(errno));
exit(EXIT_FAILURE);
}
close(fd);
}
/* Linux 3.19 made a change in the handling of setgroups(2) and
the 'gid_map' file to address a security issue. The issue
allowed *unprivileged* users to employ user namespaces in
order to drop groups. The upshot of the 3.19 changes is that
in order to update the 'gid_maps' file, use of the setgroups()
system call in this user namespace must first be disabled by
writing "deny" to one of the /proc/PID/setgroups files for
this namespace. That is the purpose of the following function. */
static void
proc_setgroups_write(pid_t child_pid, char *str)
{
char setgroups_path[PATH_MAX];
int fd;
snprintf(setgroups_path, PATH_MAX, "/proc/%jd/setgroups",
(intmax_t) child_pid);
fd = open(setgroups_path, O_RDWR);
if (fd == -1) {
/* We may be on a system that doesn't support
/proc/PID/setgroups. In that case, the file won't exist,
and the system won't impose the restrictions that Linux 3.19
added. That's fine: we don't need to do anything in order
to permit 'gid_map' to be updated.
However, if the error from open() was something other than
the ENOENT error that is expected for that case, let the
user know. */
if (errno != ENOENT)
fprintf(stderr, "ERROR: open %s: %s\n", setgroups_path,
strerror(errno));
return;
}
if (write(fd, str, strlen(str)) == -1)
fprintf(stderr, "ERROR: write %s: %s\n", setgroups_path,
strerror(errno));
close(fd);
}
static int /* Start function for cloned child */
childFunc(void *arg)
{
struct child_args *args = arg;
char ch;
/* Wait until the parent has updated the UID and GID mappings.
See the comment in main(). We wait for end of file on a
pipe that will be closed by the parent process once it has
updated the mappings. */
close(args->pipe_fd[1]); /* Close our descriptor for the write
end of the pipe so that we see EOF
when parent closes its descriptor. */
if (read(args->pipe_fd[0], &ch, 1) != 0) {
fprintf(stderr,
"Failure in child: read from pipe returned != 0\n");
exit(EXIT_FAILURE);
}
close(args->pipe_fd[0]);
/* Execute a shell command. */
printf("About to exec %s\n", args->argv[0]);
execvp(args->argv[0], args->argv);
err(EXIT_FAILURE, "execvp");
}
#define STACK_SIZE (1024 * 1024)
static char child_stack[STACK_SIZE]; /* Space for child's stack */
int
main(int argc, char *argv[])
{
int flags, opt, map_zero;
pid_t child_pid;
struct child_args args;
char *uid_map, *gid_map;
const int MAP_BUF_SIZE = 100;
char map_buf[MAP_BUF_SIZE];
char map_path[PATH_MAX];
/* Parse command-line options. The initial '+' character in
the final getopt() argument prevents GNU-style permutation
of command-line options. That's useful, since sometimes
the 'command' to be executed by this program itself
has command-line options. We don't want getopt() to treat
those as options to this program. */
flags = 0;
verbose = 0;
gid_map = NULL;
uid_map = NULL;
map_zero = 0;
while ((opt = getopt(argc, argv, "+imnpuUM:G:zv")) != -1) {
switch (opt) {
case 'i': flags |= CLONE_NEWIPC; break;
case 'm': flags |= CLONE_NEWNS; break;
case 'n': flags |= CLONE_NEWNET; break;
case 'p': flags |= CLONE_NEWPID; break;
case 'u': flags |= CLONE_NEWUTS; break;
case 'v': verbose = 1; break;
case 'z': map_zero = 1; break;
case 'M': uid_map = optarg; break;
case 'G': gid_map = optarg; break;
case 'U': flags |= CLONE_NEWUSER; break;
default: usage(argv[0]);
}
}
/* -M or -G without -U is nonsensical */
if (((uid_map != NULL || gid_map != NULL || map_zero) &&
!(flags & CLONE_NEWUSER)) ||
(map_zero && (uid_map != NULL || gid_map != NULL)))
usage(argv[0]);
args.argv = &argv[optind];
/* We use a pipe to synchronize the parent and child, in order to
ensure that the parent sets the UID and GID maps before the child
calls execve(). This ensures that the child maintains its
capabilities during the execve() in the common case where we
want to map the child's effective user ID to 0 in the new user
namespace. Without this synchronization, the child would lose
its capabilities if it performed an execve() with nonzero
user IDs (see the capabilities(7) man page for details of the
transformation of a process's capabilities during execve()). */
if (pipe(args.pipe_fd) == -1)
err(EXIT_FAILURE, "pipe");
/* Create the child in new namespace(s). */
child_pid = clone(childFunc, child_stack + STACK_SIZE,
flags | SIGCHLD, &args);
if (child_pid == -1)
err(EXIT_FAILURE, "clone");
/* Parent falls through to here. */
if (verbose)
printf("%s: PID of child created by clone() is %jd\n",
argv[0], (intmax_t) child_pid);
/* Update the UID and GID maps in the child. */
if (uid_map != NULL || map_zero) {
snprintf(map_path, PATH_MAX, "/proc/%jd/uid_map",
(intmax_t) child_pid);
if (map_zero) {
snprintf(map_buf, MAP_BUF_SIZE, "0 %jd 1",
(intmax_t) getuid());
uid_map = map_buf;
}
update_map(uid_map, map_path);
}
if (gid_map != NULL || map_zero) {
proc_setgroups_write(child_pid, "deny");
snprintf(map_path, PATH_MAX, "/proc/%jd/gid_map",
(intmax_t) child_pid);
if (map_zero) {
snprintf(map_buf, MAP_BUF_SIZE, "0 %ld 1",
(intmax_t) getgid());
gid_map = map_buf;
}
update_map(gid_map, map_path);
}
/* Close the write end of the pipe, to signal to the child that we
have updated the UID and GID maps. */
close(args.pipe_fd[1]);
if (waitpid(child_pid, NULL, 0) == -1) /* Wait for child */
err(EXIT_FAILURE, "waitpid");
if (verbose)
printf("%s: terminating\n", argv[0]);
exit(EXIT_SUCCESS);
}
okay bestie that's the whole program ๐ and yes it's a lot of code, but you literally just watched a user namespace get born, mapped, and exec'd into existence. main character energy fr fr. copy it, compile it, run it, be obsessed ๐ซถ
๐ SEE ALSO ๐
run, don't walk, to these besties โ they're all part of the same lore ๐
newgidmap(1)newuidmap(1)clone(2)ptrace(2)setns(2)unshare(2)proc(5)subgid(5)subuid(5)capabilities(7)cgroup_namespaces(7)credentials(7)namespaces(7)pid_namespaces(7)
and if you want to go deep deep, the kernel source file is right there waiting for you ๐ง:
Documentation/admin-guide/namespaces/resource-control.rst
aaand that's a wrap on the whole page, no cap ๐ thank you for coming to my TED talk about user namespaces. this lil masterpiece lives in Linux man-pages 6.20, dated 2026-02-08 โ go forth and map your UIDs responsibly, ily, bye ๐๐ฆโจ
๐ฆ where this page comes from
- arch rolling: man-pages 6.20-1 ยท BSD-2-Clause AND BSD-3-Clause AND BSD-4.3TAHOE AND BSD-4-Clause-UC AND GPL-1.0-or-later AND GPL-2.0-only AND GPL-2.0-or-later AND GPL-3.0-or-later AND LGPL-3.0-linking-exception AND LGPL-3.0-or-later AND LicenseRef-Public-Domain AND LicenseRef-UltraPermissive AND Linux-man-pages-1-para AND Linux-man-pages-copyleft AND Linux-man-pages-copyleft-2-para AND Linux-man-pages-copyleft-var AND MIT AND Spencer-94
- nixpkgs unstable: man-pages 6.20
- ๐ the page's license: Linux-man-pages-copyleft
- Copyright 2013-2014, Michael Kerrisk <mtk.manpages@gmail.com>
- Copyright 2012-2014, Eric W. Biederman <ebiederm@xmission.com>
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms