1 .\" Copyright (c) 2013, 2014 by Michael Kerrisk <mtk.manpages@gmail.com>
2 .\" and Copyright (c) 2012, 2014 by Eric W. Biederman <ebiederm@xmission.com>
4 .\" SPDX-License-Identifier: Linux-man-pages-copyleft
7 .TH USER_NAMESPACES 7 2021-08-27 "Linux" "Linux Programmer's Manual"
9 user_namespaces \- overview of Linux user namespaces
11 For an overview of namespaces, see
14 User namespaces isolate security-related identifiers and attributes,
16 user IDs and group IDs (see
21 .\" FIXME: This page says very little about the interaction
22 .\" of user namespaces and keys. Add something on this topic.
24 .BR capabilities (7)).
25 A process's user and group IDs can be different
26 inside and outside a user namespace.
28 a process can have a normal unprivileged user ID outside a user namespace
29 while at the same time having a user ID of 0 inside the namespace;
31 the process has full privileges for operations inside the user namespace,
32 but is unprivileged for operations outside the namespace.
34 .\" ============================================================
36 .SS Nested namespaces, namespace membership
37 User namespaces can be nested;
38 that is, each user namespace\(emexcept the initial ("root")
39 namespace\(emhas a parent user namespace,
40 and can have zero or more child user namespaces.
41 The parent user namespace is the user namespace
42 of the process that creates the user namespace via a call to
50 The kernel imposes (since version 3.11) a limit of 32 nested levels of
51 .\" commit 8742f229b635bf1c1c84a3dfe5e47c814c20b5c8
53 .\" FIXME Explain the rationale for this limit. (What is the rationale?)
58 that would cause this limit to be exceeded fail with the error
61 Each process is a member of exactly one user namespace.
68 flag is a member of the same user namespace as its parent.
69 A single-threaded process can join another user namespace with
74 upon doing so, it gains a full set of capabilities in that namespace.
82 flag makes the new child process (for
86 a member of the new user namespace created by the call.
91 operation can be used to discover the parental relationship
92 between user namespaces; see
95 .\" ============================================================
98 The child process created by
102 flag starts out with a complete set
103 of capabilities in the new user namespace.
104 Likewise, a process that creates a new user namespace using
106 or joins an existing user namespace using
108 gains a full set of capabilities in that namespace.
110 that process has no capabilities in the parent (in the case of
112 or previous (in the case of
117 even if the new namespace is created or joined by the root user
118 (i.e., a process with user ID 0 in the root namespace).
122 will cause a process's capabilities to be recalculated in the usual way (see
123 .BR capabilities (7)).
125 unless the process has a user ID of 0 within the namespace,
126 or the executable file has a nonempty inheritable capabilities mask,
127 the process will lose all capabilities.
128 See the discussion of user and group ID mappings, below.
139 that moves the caller into another user namespace
140 sets the "securebits" flags
142 .BR capabilities (7))
143 to their default values (all flags disabled) in the child (for
149 Note that because the caller no longer has capabilities
150 in its original user namespace after a call to
152 it is not possible for a process to reset its "securebits" flags while
153 retaining its user namespace membership by using a pair of
155 calls to move to another user namespace and then return to
156 its original user namespace.
158 The rules for determining whether or not a process has a capability
159 in a particular user namespace are as follows:
161 A process has a capability inside a user namespace
162 if it is a member of that namespace and
163 it has the capability in its effective capability set.
164 A process can gain capabilities in its effective capability
166 For example, it may execute a set-user-ID program or an
167 executable with associated file capabilities.
169 a process may gain capabilities via the effect of
174 as already described.
175 .\" In the 3.8 sources, see security/commoncap.c::cap_capable():
177 If a process has a capability in a user namespace,
178 then it has that capability in all child (and further removed descendant)
181 .\" * The owner of the user namespace in the parent of the
182 .\" * user namespace has all caps.
183 When a user namespace is created, the kernel records the effective
184 user ID of the creating process as being the "owner" of the namespace.
185 .\" (and likewise associates the effective group ID of the creating process
186 .\" with the namespace).
187 A process that resides
188 in the parent of the user namespace
189 .\" See kernel commit 520d9eabce18edfef76a60b7b839d54facafe1f9 for a fix
191 and whose effective user ID matches the owner of the namespace
192 has all capabilities in the namespace.
193 .\" This includes the case where the process executes a set-user-ID
194 .\" program that confers the effective UID of the creator of the namespace.
195 By virtue of the previous rule,
196 this means that the process has all capabilities in all
197 further removed descendant user namespaces as well.
201 operation can be used to discover the user ID of the owner of the namespace;
205 .\" ============================================================
207 .SS Effect of capabilities within a user namespace
208 Having a capability inside a user namespace
209 permits a process to perform operations (that require privilege)
210 only on resources governed by that namespace.
211 In other words, having a capability in a user namespace permits a process
212 to perform privileged operations on resources that are governed by (nonuser)
213 namespaces owned by (associated with) the user namespace
214 (see the next subsection).
216 On the other hand, there are many privileged operations that affect
217 resources that are not associated with any namespace type,
218 for example, changing the system (i.e., calendar) time (governed by
220 loading a kernel module (governed by
221 .BR CAP_SYS_MODULE ),
222 and creating a device (governed by
224 Only a process with privileges in the
226 user namespace can perform such operations.
230 within the user namespace that owns a process's mount namespace
231 allows that process to create bind mounts
232 and mount the following types of filesystems:
233 .\" fs_flags = FS_USERNS_MOUNT in kernel sources
257 .\" commit b2197755b2633e164a439682fb05a9b5ea48f706
261 .\" commit 92dbc9dedccb9759c7f9f2f0ae6242396376988f
262 .\" commit 4cb2c00c43b3fe88b32f29df4f76da1b92c33224
269 within the user namespace that owns a process's cgroup namespace
270 allows (since Linux 4.6)
271 that process to the mount the cgroup version 2 filesystem and
272 cgroup version 1 named hierarchies
273 (i.e., cgroup filesystems mounted with the
279 within the user namespace that owns a process's PID namespace
280 allows (since Linux 3.8)
281 that process to mount
285 Note, however, that mounting block-based filesystems can be done
286 only by a process that holds
288 in the initial user namespace.
290 .\" ============================================================
292 .SS Interaction of user namespaces and other types of namespaces
293 Starting in Linux 3.8, unprivileged processes can create user namespaces,
294 and the other types of namespaces can be created with just the
296 capability in the caller's user namespace.
298 When a nonuser namespace is created,
299 it is owned by the user namespace in which the creating process
300 was a member at the time of the creation of the namespace.
301 Privileged operations on resources governed by the nonuser namespace
302 require that the process has the necessary capabilities
303 in the user namespace that owns the nonuser namespace.
307 is specified along with other
313 call, the user namespace is guaranteed to be created first,
318 privileges over the remaining namespaces created by the call.
319 Thus, it is possible for an unprivileged caller to specify this combination
322 When a new namespace (other than a user namespace) is created via
326 the kernel records the user namespace of the creating process as the owner of
328 (This association can't be changed.)
329 When a process in the new namespace subsequently performs
330 privileged operations that operate on global
331 resources isolated by the namespace,
332 the permission checks are performed according to the process's capabilities
333 in the user namespace that the kernel associated with the new namespace.
334 For example, suppose that a process attempts to change the hostname
335 .RB ( sethostname (2)),
336 a resource governed by the UTS namespace.
338 the kernel will determine which user namespace owns
339 the process's UTS namespace, and check whether the process has the
341 .RB ( CAP_SYS_ADMIN )
342 in that user namespace.
347 operation can be used to discover the user namespace
348 that owns a nonuser namespace; see
351 .\" ============================================================
353 .SS User and group ID mappings: uid_map and gid_map
354 When a user namespace is created,
355 it starts out without a mapping of user IDs (group IDs)
356 to the parent user namespace.
358 .IR /proc/[pid]/uid_map
360 .IR /proc/[pid]/gid_map
361 files (available since Linux 3.5)
362 .\" commit 22d917d80e842829d0ca0a561967d728eb1d6303
363 expose the mappings for user and group IDs
364 inside the user namespace for the process
366 These files can be read to view the mappings in a user namespace and
367 written to (once) to define the mappings.
369 The description in the following paragraphs explains the details for
373 but each instance of "user ID" is replaced by "group ID".
377 file exposes the mapping of user IDs from the user namespace
380 to the user namespace of the process that opened
382 (but see a qualification to this point below).
383 In other words, processes that are in different user namespaces
384 will potentially see different values when reading from a particular
386 file, depending on the user ID mappings for the user namespaces
387 of the reading processes.
391 file specifies a 1-to-1 mapping of a range of contiguous
392 user IDs between two user namespaces.
393 (When a user namespace is first created, this file is empty.)
394 The specification in each line takes the form of
395 three numbers delimited by white space.
396 The first two numbers specify the starting user ID in
397 each of the two user namespaces.
398 The third number specifies the length of the mapped range.
399 In detail, the fields are interpreted as follows:
401 The start of the range of user IDs in
402 the user namespace of the process
405 The start of the range of user
406 IDs to which the user IDs specified by field one map.
407 How field two is interpreted depends on whether the process that opened
411 are in the same user namespace, as follows:
414 If the two processes are in different user namespaces:
415 field two is the start of a range of
416 user IDs in the user namespace of the process that opened
419 If the two processes are in the same user namespace:
420 field two is the start of the range of
421 user IDs in the parent user namespace of the process
423 This case enables the opener of
425 (the common case here is opening
426 .IR /proc/self/uid_map )
427 to see the mapping of user IDs into the user namespace of the process
428 that created this user namespace.
431 The length of the range of user IDs that is mapped between the two
434 System calls that return user IDs (group IDs)\(emfor example,
437 and the credential fields in the structure returned by
438 .BR stat (2)\(emreturn
439 the user ID (group ID) mapped into the caller's user namespace.
441 When a process accesses a file, its user and group IDs
442 are mapped into the initial user namespace for the purpose of permission
443 checking and assigning IDs when creating a file.
444 When a process retrieves file user and group IDs via
446 the IDs are mapped in the opposite direction,
447 to produce values relative to the process user and group ID mappings.
449 The initial user namespace has no parent namespace,
450 but, for consistency, the kernel provides dummy user and group
451 ID mapping files for this namespace.
456 is the same) from a shell in the initial namespace shows:
460 $ \fBcat /proc/$$/uid_map\fP
465 This mapping tells us
466 that the range starting at user ID 0 in this namespace
467 maps to a range starting at 0 in the (nonexistent) parent namespace,
468 and the length of the range is the largest 32-bit unsigned integer.
469 This leaves 4294967295 (the 32-bit signed \-1 value) unmapped.
472 is used in several interfaces (e.g.,
474 as a way to specify "no user ID".
477 unmapped and unusable guarantees that there will be no
478 confusion when using these interfaces.
480 .\" ============================================================
482 .SS Defining user and group ID mappings: writing to uid_map and gid_map
483 After the creation of a new user namespace, the
487 of the processes in the namespace may be written to
489 to define the mapping of user IDs in the new user namespace.
490 An attempt to write more than once to a
492 file in a user namespace fails with the error
494 Similar rules apply for
501 must conform to the following validity rules:
503 The three fields must be valid numbers,
504 and the last field must be greater than 0.
506 Lines are terminated by newline characters.
508 There is a limit on the number of lines in the file.
509 In Linux 4.14 and earlier, this limit was (arbitrarily)
510 .\" 5*12-byte records could fit in a 64B cache line
513 .\" commit 6397fac4915ab3002dc15aae751455da1a852f25
514 the limit is 340 lines.
515 In addition, the number of bytes written to
516 the file must be less than the system page size,
517 and the write must be performed at the start of the file (i.e.,
521 can't be used to write to nonzero offsets in the file).
523 The range of user IDs (group IDs)
524 specified in each line cannot overlap with the ranges
526 In the initial implementation (Linux 3.8), this requirement was
527 satisfied by a simplistic implementation that imposed the further
529 the values in both field 1 and field 2 of successive lines must be
530 in ascending numerical order,
531 which prevented some otherwise valid maps from being created.
533 .\" commit 0bd14b4fd72afd5df41e9fd59f356740f22fceba
534 fix this limitation, allowing any valid set of nonoverlapping maps.
536 At least one line must be written to the file.
538 Writes that violate the above rules fail with the error
541 In order for a process to write to the
542 .I /proc/[pid]/uid_map
543 .RI ( /proc/[pid]/gid_map )
544 file, all of the following permission requirements must be met:
546 The writing process must have the
549 capability in the user namespace of the process
552 The writing process must either be in the user namespace of the process
554 or be in the parent user namespace of the process
557 The mapped user IDs (group IDs) must in turn have a mapping
558 in the parent user namespace.
561 .IR /proc/[pid]/uid_map
562 to create a mapping that maps UID 0 in the parent namespace,
563 then one of the following must be true:
566 if writing process is in the parent user namespace,
567 then it must have the
569 capability in that user namespace; or
571 if the writing process is in the child user namespace,
572 then the process that created the user namespace must have had the
574 capability when the namespace was created.
577 This rule has been in place since
578 .\" commit db2e718a47984b9d71ed890eb2ea36ecf150de18
580 It eliminates an earlier security bug whereby
581 a UID 0 process that lacks the
584 which is needed to create a binary with namespaced file capabilities
586 .BR capabilities (7)),
587 could nevertheless create such a binary,
588 by the following steps:
591 Create a new user namespace with the identity mapping
592 (i.e., UID 0 in the new user namespace maps to UID 0 in the parent namespace),
593 so that UID 0 in both namespaces is equivalent to the same root user ID.
595 Since the child process has the
597 capability, it could create a binary with namespaced file capabilities
598 that would then be effective in the parent user namespace
599 (because the root user IDs are the same in the two namespaces).
602 One of the following two cases applies:
606 the writing process has the
614 No further restrictions apply:
615 the process can make mappings to arbitrary user IDs (group IDs)
616 in the parent user namespace.
620 otherwise all of the following restrictions apply:
626 must consist of a single line that maps
627 the writing process's effective user ID
628 (group ID) in the parent user namespace to a user ID (group ID)
629 in the user namespace.
631 The writing process must have the same effective user ID as the process
632 that created the user namespace.
638 system call must first be denied by writing
641 .I /proc/[pid]/setgroups
642 file (see below) before writing to
647 Writes that violate the above rules fail with the error
650 .\" ============================================================
652 .SS Project ID mappings: projid_map
653 Similarly to user and group ID mappings,
654 it is possible to create project ID mappings for a user namespace.
655 (Project IDs are used for disk quotas; see
660 Project ID mappings are defined by writing to the
661 .I /proc/[pid]/projid_map
663 .\" commit f76d207a66c3a53defea67e7d36c3eb1b7d6d61d
666 The validity rules for writing to the
667 .I /proc/[pid]/projid_map
668 file are as for writing to the
670 file; violation of these rules causes
672 to fail with the error
675 The permission rules for writing to the
676 .I /proc/[pid]/projid_map
679 The writing process must either be in the user namespace of the process
681 or be in the parent user namespace of the process
684 The mapped project IDs must in turn have a mapping
685 in the parent user namespace.
687 Violation of these rules causes
689 to fail with the error
692 .\" ============================================================
694 .SS Interaction with system calls that change process UIDs or GIDs
695 In a user namespace where the
697 file has not been written, the system calls that change user IDs will fail.
700 file has not been written, the system calls that change group IDs will fail.
705 files have been written, only the mapped values may be used in
706 system calls that change user and group IDs.
708 For user IDs, the relevant system calls include
714 For group IDs, the relevant system calls include
725 .I /proc/[pid]/setgroups
726 file before writing to
727 .I /proc/[pid]/gid_map
728 .\" Things changed in Linux 3.19
729 .\" commit 9cc46516ddf497ea16e8d7cb986ae03a0f6b92f8
730 .\" commit 66d2f338ee4c449396b6f99f5e75cd18eb6df272
731 .\" http://lwn.net/Articles/626665/
732 will permanently disable
734 in a user namespace and allow writing to
735 .I /proc/[pid]/gid_map
738 capability in the parent user namespace.
740 .\" ============================================================
742 .SS The /proc/[pid]/setgroups file
744 .\" commit 9cc46516ddf497ea16e8d7cb986ae03a0f6b92f8
745 .\" commit 66d2f338ee4c449396b6f99f5e75cd18eb6df272
746 .\" http://lwn.net/Articles/626665/
747 .\" http://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2014-8989
750 .I /proc/[pid]/setgroups
751 file displays the string
753 if processes in the user namespace that contains the process
755 are permitted to employ the
757 system call; it displays
761 is not permitted in that user namespace.
762 Note that regardless of the value in the
763 .I /proc/[pid]/setgroups
764 file (and regardless of the process's capabilities), calls to
766 are also not permitted if
767 .IR /proc/[pid]/gid_map
768 has not yet been set.
770 A privileged process (one with the
772 capability in the namespace) may write either of the strings
778 writing a group ID mapping
779 for this user namespace to the file
780 .IR /proc/[pid]/gid_map .
783 prevents any process in the user namespace from employing
786 The essence of the restrictions described in the preceding
787 paragraph is that it is permitted to write to
788 .I /proc/[pid]/setgroups
789 only so long as calling
791 is disallowed because
792 .I /proc/[pid]/gid_map
794 This ensures that a process cannot transition from a state where
796 is allowed to a state where
799 a process can transition only from
805 The default value of this file in the initial user namespace is
809 .IR /proc/[pid]/gid_map
811 (which has the effect of enabling
813 in the user namespace),
814 it is no longer possible to disallow
819 .IR /proc/[pid]/setgroups
820 (the write fails with the error
823 A child user namespace inherits the
824 .IR /proc/[pid]/setgroups
825 setting from its parent.
833 system call can't subsequently be reenabled (by writing
835 to the file) in this user namespace.
836 (Attempts to do so fail with the error
838 This restriction also propagates down to all child user namespaces of
842 .I /proc/[pid]/setgroups
843 file was added in Linux 3.19,
844 but was backported to many earlier stable kernel series,
845 because it addresses a security issue.
846 The issue concerned files with permissions such as "rwx\-\-\-rwx".
847 Such files give fewer permissions to "group" than they do to "other".
848 This means that dropping groups using
850 might allow a process file access that it did not formerly have.
851 Before the existence of user namespaces this was not a concern,
852 since only a privileged process (one with the
854 capability) could call
856 However, with the introduction of user namespaces,
857 it became possible for an unprivileged process to create
858 a new namespace in which the user had all privileges.
859 This then allowed formerly unprivileged
860 users to drop groups and thus gain file access
861 that they did not previously have.
863 .I /proc/[pid]/setgroups
864 file was added to address this security issue,
865 by denying any pathway for an unprivileged process to drop groups with
868 .\" /proc/PID/setgroups
869 .\" [allow == setgroups() is allowed, "deny" == setgroups() is disallowed]
870 .\" * Can write if have CAP_SYS_ADMIN in NS
871 .\" * Must write BEFORE writing to /proc/PID/gid_map
874 .\" * Must already have written to gid_map
875 .\" * /proc/PID/setgroups must be "allow"
877 .\" /proc/PID/gid_map -- writing
878 .\" * Must already have written "deny" to /proc/PID/setgroups
880 .\" ============================================================
882 .SS Unmapped user and group IDs
883 There are various places where an unmapped user ID (group ID)
884 may be exposed to user space.
885 For example, the first process in a new user namespace may call
887 before a user ID mapping has been defined for the namespace.
888 In most such cases, an unmapped user ID is converted
889 .\" from_kuid_munged(), from_kgid_munged()
890 to the overflow user ID (group ID);
891 the default value for the overflow user ID (group ID) is 65534.
892 See the descriptions of
893 .IR /proc/sys/kernel/overflowuid
895 .IR /proc/sys/kernel/overflowgid
899 The cases where unmapped IDs are mapped in this fashion include
900 system calls that return user IDs
904 credentials passed over a UNIX domain socket,
906 credentials returned by
909 and the System V IPC "ctl"
912 credentials exposed by
913 .IR /proc/[pid]/status
915 .IR /proc/sysvipc/* ,
916 credentials returned via the
920 received with a signal (see
922 credentials written to the process accounting file (see
924 and credentials returned with POSIX message queue notifications (see
927 There is one notable case where unmapped user and group IDs are
929 .\" from_kuid(), from_kgid()
930 .\" Also F_GETOWNER_UIDS is an exception
931 converted to the corresponding overflow ID value.
936 file in which there is no mapping for the second field,
937 that field is displayed as 4294967295 (\-1 as an unsigned integer).
939 .\" ============================================================
942 In order to determine permissions when an unprivileged process accesses a file,
943 the process credentials (UID, GID) and the file credentials
944 are in effect mapped back to what they would be in
945 the initial user namespace and then compared to determine
946 the permissions that the process has on the file.
947 The same is also of other objects that employ the credentials plus
948 permissions mask accessibility model, such as System V IPC objects
950 .\" ============================================================
952 .SS Operation of file-related capabilities
953 Certain capabilities allow a process to bypass various
954 kernel-enforced restrictions when performing operations on
955 files owned by other users or groups.
956 These capabilities are:
958 .BR CAP_DAC_OVERRIDE ,
959 .BR CAP_DAC_READ_SEARCH ,
964 Within a user namespace,
965 these capabilities allow a process to bypass the rules
966 if the process has the relevant capability over the file,
969 the process has the relevant effective capability in its user namespace; and
971 the file's user ID and group ID both have valid mappings
972 in the user namespace.
976 capability is treated somewhat exceptionally:
977 .\" These are the checks performed by the kernel function
978 .\" inode_owner_or_capable(). There is one exception to the exception:
979 .\" overriding the directory sticky permission bit requires that
980 .\" the file has a valid mapping for both its UID and GID.
981 it allows a process to bypass the corresponding rules so long as
982 at least the file's user ID has a mapping in the user namespace
983 (i.e., the file's group ID does not need to have a valid mapping).
985 .\" ============================================================
987 .SS Set-user-ID and set-group-ID programs
988 When a process inside a user namespace executes
989 a set-user-ID (set-group-ID) program,
990 the process's effective user (group) ID inside the namespace is changed
991 to whatever value is mapped for the user (group) ID of the file.
992 However, if either the user
994 the group ID of the file has no mapping inside the namespace,
995 the set-user-ID (set-group-ID) bit is silently ignored:
996 the new program is executed,
997 but the process's effective user (group) ID is left unchanged.
998 (This mirrors the semantics of executing a set-user-ID or set-group-ID
999 program that resides on a filesystem that was mounted with the
1001 flag, as described in
1004 .\" ============================================================
1007 When a process's user and group IDs are passed over a UNIX domain socket
1008 to a process in a different user namespace (see the description of
1012 they are translated into the corresponding values as per the
1013 receiving process's user and group ID mappings.
1016 Namespaces are a Linux-specific feature.
1019 Over the years, there have been a lot of features that have been added
1020 to the Linux kernel that have been made available only to privileged users
1021 because of their potential to confuse set-user-ID-root applications.
1022 In general, it becomes safe to allow the root user in a user namespace to
1023 use those features because it is impossible, while in a user namespace,
1024 to gain more privilege than the root user of a user namespace has.
1026 .\" ============================================================
1029 The term "global root" is sometimes used as a shorthand for
1030 user ID 0 in the initial user namespace.
1032 .\" ============================================================
1035 Use of user namespaces requires a kernel that is configured with the
1038 User namespaces require support in a range of subsystems across
1040 When an unsupported subsystem is configured into the kernel,
1041 it is not possible to configure user namespaces support.
1043 As at Linux 3.8, most relevant subsystems supported user namespaces,
1044 but a number of filesystems did not have the infrastructure needed
1045 to map user and group IDs between user namespaces.
1046 Linux 3.9 added the required infrastructure support for many of
1047 the remaining unsupported filesystems
1048 (Plan 9 (9P), Andrew File System (AFS), Ceph, CIFS, CODA, NFS, and OCFS2).
1049 Linux 3.12 added support for the last of the unsupported major filesystems,
1050 .\" commit d6970d4b726cea6d7a9bc4120814f95c09571fc3
1054 The program below is designed to allow experimenting with
1055 user namespaces, as well as other types of namespaces.
1056 It creates namespaces as specified by command-line options and then executes
1057 a command inside those namespaces.
1060 function inside the program provide a full explanation of the program.
1061 The following shell session demonstrates its use.
1063 First, we look at the run-time environment:
1067 $ \fBuname \-rs\fP # Need Linux 3.8 or later
1069 $ \fBid \-u\fP # Running as unprivileged user
1076 Now start a new shell in new user
1082 namespaces, with user ID
1086 1000 mapped to 0 inside the user namespace:
1090 $ \fB./userns_child_exec \-p \-m \-U \-M \(aq0 1000 1\(aq \-G \(aq0 1000 1\(aq bash\fP
1094 The shell has PID 1, because it is the first process in the new
1106 filesystem and listing all of the processes visible
1107 in the new PID namespace shows that the shell can't see
1108 any processes outside the PID namespace:
1112 bash$ \fBmount \-t proc proc /proc\fP
1114 PID TTY STAT TIME COMMAND
1116 22 pts/3 R+ 0:00 ps ax
1120 Inside the user namespace, the shell has user and group ID 0,
1121 and a full set of permitted and effective capabilities:
1125 bash$ \fBcat /proc/$$/status | egrep \(aq\(ha[UG]id\(aq\fP
1128 bash$ \fBcat /proc/$$/status | egrep \(aq\(haCap(Prm|Inh|Eff)\(aq\fP
1129 CapInh: 0000000000000000
1130 CapPrm: 0000001fffffffff
1131 CapEff: 0000001fffffffff
1137 /* userns_child_exec.c
1139 Licensed under GNU General Public License v2 or later
1141 Create a child process that executes a shell command in new
1142 namespace(s); allow UID and GID mappings to be specified when
1143 creating a user namespace.
1150 #include <sys/wait.h>
1158 /* A simple error\-handling function: print an error message based
1159 on the value in \(aqerrno\(aq and terminate the calling process. */
1161 #define errExit(msg) do { perror(msg); exit(EXIT_FAILURE); \e
1165 char **argv; /* Command to be executed by child, with args */
1166 int pipe_fd[2]; /* Pipe used to synchronize parent and child */
1174 fprintf(stderr, "Usage: %s [options] cmd [arg...]\en\en", pname);
1175 fprintf(stderr, "Create a child process that executes a shell "
1176 "command in a new user namespace,\en"
1177 "and possibly also other new namespace(s).\en\en");
1178 fprintf(stderr, "Options can be:\en\en");
1179 #define fpe(str) fprintf(stderr, " %s", str);
1180 fpe("\-i New IPC namespace\en");
1181 fpe("\-m New mount namespace\en");
1182 fpe("\-n New network namespace\en");
1183 fpe("\-p New PID namespace\en");
1184 fpe("\-u New UTS namespace\en");
1185 fpe("\-U New user namespace\en");
1186 fpe("\-M uid_map Specify UID map for user namespace\en");
1187 fpe("\-G gid_map Specify GID map for user namespace\en");
1188 fpe("\-z Map user\(aqs UID and GID to 0 in user namespace\en");
1189 fpe(" (equivalent to: \-M \(aq0 <uid> 1\(aq \-G \(aq0 <gid> 1\(aq)\en");
1190 fpe("\-v Display verbose messages\en");
1192 fpe("If \-z, \-M, or \-G is specified, \-U is required.\en");
1193 fpe("It is not permitted to specify both \-z and either \-M or \-G.\en");
1195 fpe("Map strings for \-M and \-G consist of records of the form:\en");
1197 fpe(" ID\-inside\-ns ID\-outside\-ns len\en");
1199 fpe("A map string can contain multiple records, separated"
1201 fpe("the commas are replaced by newlines before writing"
1202 " to map files.\en");
1207 /* Update the mapping file \(aqmap_file\(aq, with the value provided in
1208 \(aqmapping\(aq, a string that defines a UID or GID mapping. A UID or
1209 GID mapping consists of one or more newline\-delimited records
1212 ID_inside\-ns ID\-outside\-ns length
1214 Requiring the user to supply a string that contains newlines is
1215 of course inconvenient for command\-line use. Thus, we permit the
1216 use of commas to delimit records in this string, and replace them
1217 with newlines before writing the string to the file. */
1220 update_map(char *mapping, char *map_file)
1223 size_t map_len; /* Length of \(aqmapping\(aq */
1225 /* Replace commas in mapping string with newlines. */
1227 map_len = strlen(mapping);
1228 for (int j = 0; j < map_len; j++)
1229 if (mapping[j] == \(aq,\(aq)
1230 mapping[j] = \(aq\en\(aq;
1232 fd = open(map_file, O_RDWR);
1234 fprintf(stderr, "ERROR: open %s: %s\en", map_file,
1239 if (write(fd, mapping, map_len) != map_len) {
1240 fprintf(stderr, "ERROR: write %s: %s\en", map_file,
1248 /* Linux 3.19 made a change in the handling of setgroups(2) and the
1249 \(aqgid_map\(aq file to address a security issue. The issue allowed
1250 *unprivileged* users to employ user namespaces in order to drop
1251 The upshot of the 3.19 changes is that in order to update the
1252 \(aqgid_maps\(aq file, use of the setgroups() system call in this
1253 user namespace must first be disabled by writing "deny" to one of
1254 the /proc/PID/setgroups files for this namespace. That is the
1255 purpose of the following function. */
1258 proc_setgroups_write(pid_t child_pid, char *str)
1260 char setgroups_path[PATH_MAX];
1263 snprintf(setgroups_path, PATH_MAX, "/proc/%jd/setgroups",
1264 (intmax_t) child_pid);
1266 fd = open(setgroups_path, O_RDWR);
1269 /* We may be on a system that doesn\(aqt support
1270 /proc/PID/setgroups. In that case, the file won\(aqt exist,
1271 and the system won\(aqt impose the restrictions that Linux 3.19
1272 added. That\(aqs fine: we don\(aqt need to do anything in order
1273 to permit \(aqgid_map\(aq to be updated.
1275 However, if the error from open() was something other than
1276 the ENOENT error that is expected for that case, let the
1279 if (errno != ENOENT)
1280 fprintf(stderr, "ERROR: open %s: %s\en", setgroups_path,
1285 if (write(fd, str, strlen(str)) == \-1)
1286 fprintf(stderr, "ERROR: write %s: %s\en", setgroups_path,
1292 static int /* Start function for cloned child */
1293 childFunc(void *arg)
1295 struct child_args *args = arg;
1298 /* Wait until the parent has updated the UID and GID mappings.
1299 See the comment in main(). We wait for end of file on a
1300 pipe that will be closed by the parent process once it has
1301 updated the mappings. */
1303 close(args\->pipe_fd[1]); /* Close our descriptor for the write
1304 end of the pipe so that we see EOF
1305 when parent closes its descriptor. */
1306 if (read(args\->pipe_fd[0], &ch, 1) != 0) {
1308 "Failure in child: read from pipe returned != 0\en");
1312 close(args\->pipe_fd[0]);
1314 /* Execute a shell command. */
1316 printf("About to exec %s\en", args\->argv[0]);
1317 execvp(args\->argv[0], args\->argv);
1321 #define STACK_SIZE (1024 * 1024)
1323 static char child_stack[STACK_SIZE]; /* Space for child\(aqs stack */
1326 main(int argc, char *argv[])
1328 int flags, opt, map_zero;
1330 struct child_args args;
1331 char *uid_map, *gid_map;
1332 const int MAP_BUF_SIZE = 100;
1333 char map_buf[MAP_BUF_SIZE];
1334 char map_path[PATH_MAX];
1336 /* Parse command\-line options. The initial \(aq+\(aq character in
1337 the final getopt() argument prevents GNU\-style permutation
1338 of command\-line options. That\(aqs useful, since sometimes
1339 the \(aqcommand\(aq to be executed by this program itself
1340 has command\-line options. We don\(aqt want getopt() to treat
1341 those as options to this program. */
1348 while ((opt = getopt(argc, argv, "+imnpuUM:G:zv")) != \-1) {
1350 case \(aqi\(aq: flags |= CLONE_NEWIPC; break;
1351 case \(aqm\(aq: flags |= CLONE_NEWNS; break;
1352 case \(aqn\(aq: flags |= CLONE_NEWNET; break;
1353 case \(aqp\(aq: flags |= CLONE_NEWPID; break;
1354 case \(aqu\(aq: flags |= CLONE_NEWUTS; break;
1355 case \(aqv\(aq: verbose = 1; break;
1356 case \(aqz\(aq: map_zero = 1; break;
1357 case \(aqM\(aq: uid_map = optarg; break;
1358 case \(aqG\(aq: gid_map = optarg; break;
1359 case \(aqU\(aq: flags |= CLONE_NEWUSER; break;
1360 default: usage(argv[0]);
1364 /* \-M or \-G without \-U is nonsensical */
1366 if (((uid_map != NULL || gid_map != NULL || map_zero) &&
1367 !(flags & CLONE_NEWUSER)) ||
1368 (map_zero && (uid_map != NULL || gid_map != NULL)))
1371 args.argv = &argv[optind];
1373 /* We use a pipe to synchronize the parent and child, in order to
1374 ensure that the parent sets the UID and GID maps before the child
1375 calls execve(). This ensures that the child maintains its
1376 capabilities during the execve() in the common case where we
1377 want to map the child\(aqs effective user ID to 0 in the new user
1378 namespace. Without this synchronization, the child would lose
1379 its capabilities if it performed an execve() with nonzero
1380 user IDs (see the capabilities(7) man page for details of the
1381 transformation of a process\(aqs capabilities during execve()). */
1383 if (pipe(args.pipe_fd) == \-1)
1386 /* Create the child in new namespace(s). */
1388 child_pid = clone(childFunc, child_stack + STACK_SIZE,
1389 flags | SIGCHLD, &args);
1390 if (child_pid == \-1)
1393 /* Parent falls through to here. */
1396 printf("%s: PID of child created by clone() is %jd\en",
1397 argv[0], (intmax_t) child_pid);
1399 /* Update the UID and GID maps in the child. */
1401 if (uid_map != NULL || map_zero) {
1402 snprintf(map_path, PATH_MAX, "/proc/%jd/uid_map",
1403 (intmax_t) child_pid);
1405 snprintf(map_buf, MAP_BUF_SIZE, "0 %jd 1",
1406 (intmax_t) getuid());
1409 update_map(uid_map, map_path);
1412 if (gid_map != NULL || map_zero) {
1413 proc_setgroups_write(child_pid, "deny");
1415 snprintf(map_path, PATH_MAX, "/proc/%jd/gid_map",
1416 (intmax_t) child_pid);
1418 snprintf(map_buf, MAP_BUF_SIZE, "0 %ld 1",
1419 (intmax_t) getgid());
1422 update_map(gid_map, map_path);
1425 /* Close the write end of the pipe, to signal to the child that we
1426 have updated the UID and GID maps. */
1428 close(args.pipe_fd[1]);
1430 if (waitpid(child_pid, NULL, 0) == \-1) /* Wait for child */
1434 printf("%s: terminating\en", argv[0]);
1440 .BR newgidmap (1), \" From the shadow package
1441 .BR newuidmap (1), \" From the shadow package
1447 .BR subgid (5), \" From the shadow package
1448 .BR subuid (5), \" From the shadow package
1449 .BR capabilities (7),
1450 .BR cgroup_namespaces (7),
1451 .BR credentials (7),
1453 .BR pid_namespaces (7)
1455 The kernel source file
1456 .IR Documentation/admin\-guide/namespaces/resource\-control.rst .