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 (date) "Linux man-pages (unreleased)"
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\[em]except the initial ("root")
39 namespace\[em]has 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 Linux 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 A task that changes one of its effective IDs
96 will have its dumpability reset to the value in
97 .IR /proc/sys/fs/suid_dumpable .
98 This may affect the ownership of proc files of child processes
99 and may thus cause the parent to lack the permissions
100 to write to mapping files of child processes running in a new user namespace.
101 In such cases making the parent process dumpable, using
105 before creating a child process in a new user namespace
106 may rectify this problem.
111 for details on how ownership is affected.
113 .\" ============================================================
116 The child process created by
120 flag starts out with a complete set
121 of capabilities in the new user namespace.
122 Likewise, a process that creates a new user namespace using
124 or joins an existing user namespace using
126 gains a full set of capabilities in that namespace.
128 that process has no capabilities in the parent (in the case of
130 or previous (in the case of
135 even if the new namespace is created or joined by the root user
136 (i.e., a process with user ID 0 in the root namespace).
140 will cause a process's capabilities to be recalculated in the usual way (see
141 .BR capabilities (7)).
143 unless the process has a user ID of 0 within the namespace,
144 or the executable file has a nonempty inheritable capabilities mask,
145 the process will lose all capabilities.
146 See the discussion of user and group ID mappings, below.
157 that moves the caller into another user namespace
158 sets the "securebits" flags
160 .BR capabilities (7))
161 to their default values (all flags disabled) in the child (for
167 Note that because the caller no longer has capabilities
168 in its original user namespace after a call to
170 it is not possible for a process to reset its "securebits" flags while
171 retaining its user namespace membership by using a pair of
173 calls to move to another user namespace and then return to
174 its original user namespace.
176 The rules for determining whether or not a process has a capability
177 in a particular user namespace are as follows:
179 A process has a capability inside a user namespace
180 if it is a member of that namespace and
181 it has the capability in its effective capability set.
182 A process can gain capabilities in its effective capability
184 For example, it may execute a set-user-ID program or an
185 executable with associated file capabilities.
187 a process may gain capabilities via the effect of
192 as already described.
193 .\" In the 3.8 sources, see security/commoncap.c::cap_capable():
195 If a process has a capability in a user namespace,
196 then it has that capability in all child (and further removed descendant)
199 .\" * The owner of the user namespace in the parent of the
200 .\" * user namespace has all caps.
201 When a user namespace is created, the kernel records the effective
202 user ID of the creating process as being the "owner" of the namespace.
203 .\" (and likewise associates the effective group ID of the creating process
204 .\" with the namespace).
205 A process that resides
206 in the parent of the user namespace
207 .\" See kernel commit 520d9eabce18edfef76a60b7b839d54facafe1f9 for a fix
209 and whose effective user ID matches the owner of the namespace
210 has all capabilities in the namespace.
211 .\" This includes the case where the process executes a set-user-ID
212 .\" program that confers the effective UID of the creator of the namespace.
213 By virtue of the previous rule,
214 this means that the process has all capabilities in all
215 further removed descendant user namespaces as well.
219 operation can be used to discover the user ID of the owner of the namespace;
223 .\" ============================================================
225 .SS Effect of capabilities within a user namespace
226 Having a capability inside a user namespace
227 permits a process to perform operations (that require privilege)
228 only on resources governed by that namespace.
229 In other words, having a capability in a user namespace permits a process
230 to perform privileged operations on resources that are governed by (nonuser)
231 namespaces owned by (associated with) the user namespace
232 (see the next subsection).
234 On the other hand, there are many privileged operations that affect
235 resources that are not associated with any namespace type,
236 for example, changing the system (i.e., calendar) time (governed by
238 loading a kernel module (governed by
239 .BR CAP_SYS_MODULE ),
240 and creating a device (governed by
242 Only a process with privileges in the
244 user namespace can perform such operations.
248 within the user namespace that owns a process's mount namespace
249 allows that process to create bind mounts
250 and mount the following types of filesystems:
251 .\" fs_flags = FS_USERNS_MOUNT in kernel sources
275 .\" commit b2197755b2633e164a439682fb05a9b5ea48f706
279 .\" commit 92dbc9dedccb9759c7f9f2f0ae6242396376988f
280 .\" commit 4cb2c00c43b3fe88b32f29df4f76da1b92c33224
287 within the user namespace that owns a process's cgroup namespace
288 allows (since Linux 4.6)
289 that process to the mount the cgroup version 2 filesystem and
290 cgroup version 1 named hierarchies
291 (i.e., cgroup filesystems mounted with the
297 within the user namespace that owns a process's PID namespace
298 allows (since Linux 3.8)
299 that process to mount
303 Note, however, that mounting block-based filesystems can be done
304 only by a process that holds
306 in the initial user namespace.
308 .\" ============================================================
310 .SS Interaction of user namespaces and other types of namespaces
311 Starting in Linux 3.8, unprivileged processes can create user namespaces,
312 and the other types of namespaces can be created with just the
314 capability in the caller's user namespace.
316 When a nonuser namespace is created,
317 it is owned by the user namespace in which the creating process
318 was a member at the time of the creation of the namespace.
319 Privileged operations on resources governed by the nonuser namespace
320 require that the process has the necessary capabilities
321 in the user namespace that owns the nonuser namespace.
325 is specified along with other
331 call, the user namespace is guaranteed to be created first,
336 privileges over the remaining namespaces created by the call.
337 Thus, it is possible for an unprivileged caller to specify this combination
340 When a new namespace (other than a user namespace) is created via
344 the kernel records the user namespace of the creating process as the owner of
346 (This association can't be changed.)
347 When a process in the new namespace subsequently performs
348 privileged operations that operate on global
349 resources isolated by the namespace,
350 the permission checks are performed according to the process's capabilities
351 in the user namespace that the kernel associated with the new namespace.
352 For example, suppose that a process attempts to change the hostname
353 .RB ( sethostname (2)),
354 a resource governed by the UTS namespace.
356 the kernel will determine which user namespace owns
357 the process's UTS namespace, and check whether the process has the
359 .RB ( CAP_SYS_ADMIN )
360 in that user namespace.
365 operation can be used to discover the user namespace
366 that owns a nonuser namespace; see
369 .\" ============================================================
371 .SS User and group ID mappings: uid_map and gid_map
372 When a user namespace is created,
373 it starts out without a mapping of user IDs (group IDs)
374 to the parent user namespace.
376 .IR /proc/ pid /uid_map
378 .IR /proc/ pid /gid_map
379 files (available since Linux 3.5)
380 .\" commit 22d917d80e842829d0ca0a561967d728eb1d6303
381 expose the mappings for user and group IDs
382 inside the user namespace for the process
384 These files can be read to view the mappings in a user namespace and
385 written to (once) to define the mappings.
387 The description in the following paragraphs explains the details for
391 but each instance of "user ID" is replaced by "group ID".
395 file exposes the mapping of user IDs from the user namespace
398 to the user namespace of the process that opened
400 (but see a qualification to this point below).
401 In other words, processes that are in different user namespaces
402 will potentially see different values when reading from a particular
404 file, depending on the user ID mappings for the user namespaces
405 of the reading processes.
409 file specifies a 1-to-1 mapping of a range of contiguous
410 user IDs between two user namespaces.
411 (When a user namespace is first created, this file is empty.)
412 The specification in each line takes the form of
413 three numbers delimited by white space.
414 The first two numbers specify the starting user ID in
415 each of the two user namespaces.
416 The third number specifies the length of the mapped range.
417 In detail, the fields are interpreted as follows:
419 The start of the range of user IDs in
420 the user namespace of the process
423 The start of the range of user
424 IDs to which the user IDs specified by field one map.
425 How field two is interpreted depends on whether the process that opened
429 are in the same user namespace, as follows:
432 If the two processes are in different user namespaces:
433 field two is the start of a range of
434 user IDs in the user namespace of the process that opened
437 If the two processes are in the same user namespace:
438 field two is the start of the range of
439 user IDs in the parent user namespace of the process
441 This case enables the opener of
443 (the common case here is opening
444 .IR /proc/self/uid_map )
445 to see the mapping of user IDs into the user namespace of the process
446 that created this user namespace.
449 The length of the range of user IDs that is mapped between the two
452 System calls that return user IDs (group IDs)\[em]for example,
455 and the credential fields in the structure returned by
456 .BR stat (2)\[em]return
457 the user ID (group ID) mapped into the caller's user namespace.
459 When a process accesses a file, its user and group IDs
460 are mapped into the initial user namespace for the purpose of permission
461 checking and assigning IDs when creating a file.
462 When a process retrieves file user and group IDs via
464 the IDs are mapped in the opposite direction,
465 to produce values relative to the process user and group ID mappings.
467 The initial user namespace has no parent namespace,
468 but, for consistency, the kernel provides dummy user and group
469 ID mapping files for this namespace.
474 is the same) from a shell in the initial namespace shows:
478 $ \fBcat /proc/$$/uid_map\fP
483 This mapping tells us
484 that the range starting at user ID 0 in this namespace
485 maps to a range starting at 0 in the (nonexistent) parent namespace,
486 and the length of the range is the largest 32-bit unsigned integer.
487 This leaves 4294967295 (the 32-bit signed \-1 value) unmapped.
490 is used in several interfaces (e.g.,
492 as a way to specify "no user ID".
495 unmapped and unusable guarantees that there will be no
496 confusion when using these interfaces.
498 .\" ============================================================
500 .SS Defining user and group ID mappings: writing to uid_map and gid_map
501 After the creation of a new user namespace, the
505 of the processes in the namespace may be written to
507 to define the mapping of user IDs in the new user namespace.
508 An attempt to write more than once to a
510 file in a user namespace fails with the error
512 Similar rules apply for
519 must conform to the following validity rules:
521 The three fields must be valid numbers,
522 and the last field must be greater than 0.
524 Lines are terminated by newline characters.
526 There is a limit on the number of lines in the file.
527 In Linux 4.14 and earlier, this limit was (arbitrarily)
528 .\" 5*12-byte records could fit in a 64B cache line
531 .\" commit 6397fac4915ab3002dc15aae751455da1a852f25
532 the limit is 340 lines.
533 In addition, the number of bytes written to
534 the file must be less than the system page size,
535 and the write must be performed at the start of the file (i.e.,
539 can't be used to write to nonzero offsets in the file).
541 The range of user IDs (group IDs)
542 specified in each line cannot overlap with the ranges
544 In the initial implementation (Linux 3.8), this requirement was
545 satisfied by a simplistic implementation that imposed the further
547 the values in both field 1 and field 2 of successive lines must be
548 in ascending numerical order,
549 which prevented some otherwise valid maps from being created.
551 .\" commit 0bd14b4fd72afd5df41e9fd59f356740f22fceba
552 fix this limitation, allowing any valid set of nonoverlapping maps.
554 At least one line must be written to the file.
556 Writes that violate the above rules fail with the error
559 In order for a process to write to the
560 .IR /proc/ pid /uid_map
561 .RI ( /proc/ pid /gid_map )
562 file, all of the following permission requirements must be met:
564 The writing process must have the
567 capability in the user namespace of the process
570 The writing process must either be in the user namespace of the process
572 or be in the parent user namespace of the process
575 The mapped user IDs (group IDs) must in turn have a mapping
576 in the parent user namespace.
579 .IR /proc/ pid /uid_map
580 to create a mapping that maps UID 0 in the parent namespace,
581 then one of the following must be true:
584 if writing process is in the parent user namespace,
585 then it must have the
587 capability in that user namespace; or
589 if the writing process is in the child user namespace,
590 then the process that created the user namespace must have had the
592 capability when the namespace was created.
595 This rule has been in place since
596 .\" commit db2e718a47984b9d71ed890eb2ea36ecf150de18
598 It eliminates an earlier security bug whereby
599 a UID 0 process that lacks the
602 which is needed to create a binary with namespaced file capabilities
604 .BR capabilities (7)),
605 could nevertheless create such a binary,
606 by the following steps:
609 Create a new user namespace with the identity mapping
610 (i.e., UID 0 in the new user namespace maps to UID 0 in the parent namespace),
611 so that UID 0 in both namespaces is equivalent to the same root user ID.
613 Since the child process has the
615 capability, it could create a binary with namespaced file capabilities
616 that would then be effective in the parent user namespace
617 (because the root user IDs are the same in the two namespaces).
620 One of the following two cases applies:
624 the writing process has the
632 No further restrictions apply:
633 the process can make mappings to arbitrary user IDs (group IDs)
634 in the parent user namespace.
638 otherwise all of the following restrictions apply:
644 must consist of a single line that maps
645 the writing process's effective user ID
646 (group ID) in the parent user namespace to a user ID (group ID)
647 in the user namespace.
649 The writing process must have the same effective user ID as the process
650 that created the user namespace.
656 system call must first be denied by writing
659 .IR /proc/ pid /setgroups
660 file (see below) before writing to
665 Writes that violate the above rules fail with the error
668 .\" ============================================================
670 .SS Project ID mappings: projid_map
671 Similarly to user and group ID mappings,
672 it is possible to create project ID mappings for a user namespace.
673 (Project IDs are used for disk quotas; see
678 Project ID mappings are defined by writing to the
679 .IR /proc/ pid /projid_map
681 .\" commit f76d207a66c3a53defea67e7d36c3eb1b7d6d61d
684 The validity rules for writing to the
685 .IR /proc/ pid /projid_map
686 file are as for writing to the
688 file; violation of these rules causes
690 to fail with the error
693 The permission rules for writing to the
694 .IR /proc/ pid /projid_map
697 The writing process must either be in the user namespace of the process
699 or be in the parent user namespace of the process
702 The mapped project IDs must in turn have a mapping
703 in the parent user namespace.
705 Violation of these rules causes
707 to fail with the error
710 .\" ============================================================
712 .SS Interaction with system calls that change process UIDs or GIDs
713 In a user namespace where the
715 file has not been written, the system calls that change user IDs will fail.
718 file has not been written, the system calls that change group IDs will fail.
723 files have been written, only the mapped values may be used in
724 system calls that change user and group IDs.
726 For user IDs, the relevant system calls include
732 For group IDs, the relevant system calls include
743 .IR /proc/ pid /setgroups
744 file before writing to
745 .IR /proc/ pid /gid_map
746 .\" Things changed in Linux 3.19
747 .\" commit 9cc46516ddf497ea16e8d7cb986ae03a0f6b92f8
748 .\" commit 66d2f338ee4c449396b6f99f5e75cd18eb6df272
749 .\" http://lwn.net/Articles/626665/
750 will permanently disable
752 in a user namespace and allow writing to
753 .IR /proc/ pid /gid_map
756 capability in the parent user namespace.
758 .\" ============================================================
760 .SS The \fI/proc/\fPpid\fI/setgroups\fP file
762 .\" commit 9cc46516ddf497ea16e8d7cb986ae03a0f6b92f8
763 .\" commit 66d2f338ee4c449396b6f99f5e75cd18eb6df272
764 .\" http://lwn.net/Articles/626665/
765 .\" http://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2014-8989
768 .IR /proc/ pid /setgroups
769 file displays the string
770 .RI \[dq] allow \[dq]
771 if processes in the user namespace that contains the process
773 are permitted to employ the
775 system call; it displays
779 is not permitted in that user namespace.
780 Note that regardless of the value in the
781 .IR /proc/ pid /setgroups
782 file (and regardless of the process's capabilities), calls to
784 are also not permitted if
785 .IR /proc/ pid /gid_map
786 has not yet been set.
788 A privileged process (one with the
790 capability in the namespace) may write either of the strings
791 .RI \[dq] allow \[dq]
796 writing a group ID mapping
797 for this user namespace to the file
798 .IR /proc/ pid /gid_map .
801 prevents any process in the user namespace from employing
804 The essence of the restrictions described in the preceding
805 paragraph is that it is permitted to write to
806 .IR /proc/ pid /setgroups
807 only so long as calling
809 is disallowed because
810 .IR /proc/ pid /gid_map
812 This ensures that a process cannot transition from a state where
814 is allowed to a state where
817 a process can transition only from
823 The default value of this file in the initial user namespace is
824 .RI \[dq] allow \[dq].
827 .IR /proc/ pid /gid_map
829 (which has the effect of enabling
831 in the user namespace),
832 it is no longer possible to disallow
837 .IR /proc/ pid /setgroups
838 (the write fails with the error
841 A child user namespace inherits the
842 .IR /proc/ pid /setgroups
843 setting from its parent.
848 .RI \[dq] deny \[dq],
851 system call can't subsequently be reenabled (by writing
852 .RI \[dq] allow \[dq]
853 to the file) in this user namespace.
854 (Attempts to do so fail with the error
856 This restriction also propagates down to all child user namespaces of
860 .IR /proc/ pid /setgroups
861 file was added in Linux 3.19,
862 but was backported to many earlier stable kernel series,
863 because it addresses a security issue.
864 The issue concerned files with permissions such as "rwx\-\-\-rwx".
865 Such files give fewer permissions to "group" than they do to "other".
866 This means that dropping groups using
868 might allow a process file access that it did not formerly have.
869 Before the existence of user namespaces this was not a concern,
870 since only a privileged process (one with the
872 capability) could call
874 However, with the introduction of user namespaces,
875 it became possible for an unprivileged process to create
876 a new namespace in which the user had all privileges.
877 This then allowed formerly unprivileged
878 users to drop groups and thus gain file access
879 that they did not previously have.
881 .IR /proc/ pid /setgroups
882 file was added to address this security issue,
883 by denying any pathway for an unprivileged process to drop groups with
886 .\" /proc/PID/setgroups
887 .\" [allow == setgroups() is allowed, "deny" == setgroups() is disallowed]
888 .\" * Can write if have CAP_SYS_ADMIN in NS
889 .\" * Must write BEFORE writing to /proc/PID/gid_map
892 .\" * Must already have written to gid_map
893 .\" * /proc/PID/setgroups must be "allow"
895 .\" /proc/PID/gid_map -- writing
896 .\" * Must already have written "deny" to /proc/PID/setgroups
898 .\" ============================================================
900 .SS Unmapped user and group IDs
901 There are various places where an unmapped user ID (group ID)
902 may be exposed to user space.
903 For example, the first process in a new user namespace may call
905 before a user ID mapping has been defined for the namespace.
906 In most such cases, an unmapped user ID is converted
907 .\" from_kuid_munged(), from_kgid_munged()
908 to the overflow user ID (group ID);
909 the default value for the overflow user ID (group ID) is 65534.
910 See the descriptions of
911 .I /proc/sys/kernel/overflowuid
913 .I /proc/sys/kernel/overflowgid
917 The cases where unmapped IDs are mapped in this fashion include
918 system calls that return user IDs
922 credentials passed over a UNIX domain socket,
924 credentials returned by
927 and the System V IPC "ctl"
930 credentials exposed by
931 .IR /proc/ pid /status
933 .IR /proc/sysvipc/* ,
934 credentials returned via the
938 received with a signal (see
940 credentials written to the process accounting file (see
942 and credentials returned with POSIX message queue notifications (see
945 There is one notable case where unmapped user and group IDs are
947 .\" from_kuid(), from_kgid()
948 .\" Also F_GETOWNER_UIDS is an exception
949 converted to the corresponding overflow ID value.
954 file in which there is no mapping for the second field,
955 that field is displayed as 4294967295 (\-1 as an unsigned integer).
957 .\" ============================================================
960 In order to determine permissions when an unprivileged process accesses a file,
961 the process credentials (UID, GID) and the file credentials
962 are in effect mapped back to what they would be in
963 the initial user namespace and then compared to determine
964 the permissions that the process has on the file.
965 The same is also true of other objects that employ the credentials plus
966 permissions mask accessibility model, such as System V IPC objects.
968 .\" ============================================================
970 .SS Operation of file-related capabilities
971 Certain capabilities allow a process to bypass various
972 kernel-enforced restrictions when performing operations on
973 files owned by other users or groups.
974 These capabilities are:
976 .BR CAP_DAC_OVERRIDE ,
977 .BR CAP_DAC_READ_SEARCH ,
982 Within a user namespace,
983 these capabilities allow a process to bypass the rules
984 if the process has the relevant capability over the file,
987 the process has the relevant effective capability in its user namespace; and
989 the file's user ID and group ID both have valid mappings
990 in the user namespace.
994 capability is treated somewhat exceptionally:
995 .\" These are the checks performed by the kernel function
996 .\" inode_owner_or_capable(). There is one exception to the exception:
997 .\" overriding the directory sticky permission bit requires that
998 .\" the file has a valid mapping for both its UID and GID.
999 it allows a process to bypass the corresponding rules so long as
1000 at least the file's user ID has a mapping in the user namespace
1001 (i.e., the file's group ID does not need to have a valid mapping).
1003 .\" ============================================================
1005 .SS Set-user-ID and set-group-ID programs
1006 When a process inside a user namespace executes
1007 a set-user-ID (set-group-ID) program,
1008 the process's effective user (group) ID inside the namespace is changed
1009 to whatever value is mapped for the user (group) ID of the file.
1010 However, if either the user
1012 the group ID of the file has no mapping inside the namespace,
1013 the set-user-ID (set-group-ID) bit is silently ignored:
1014 the new program is executed,
1015 but the process's effective user (group) ID is left unchanged.
1016 (This mirrors the semantics of executing a set-user-ID or set-group-ID
1017 program that resides on a filesystem that was mounted with the
1019 flag, as described in
1022 .\" ============================================================
1025 When a process's user and group IDs are passed over a UNIX domain socket
1026 to a process in a different user namespace (see the description of
1030 they are translated into the corresponding values as per the
1031 receiving process's user and group ID mappings.
1037 Over the years, there have been a lot of features that have been added
1038 to the Linux kernel that have been made available only to privileged users
1039 because of their potential to confuse set-user-ID-root applications.
1040 In general, it becomes safe to allow the root user in a user namespace to
1041 use those features because it is impossible, while in a user namespace,
1042 to gain more privilege than the root user of a user namespace has.
1044 .\" ============================================================
1047 The term "global root" is sometimes used as a shorthand for
1048 user ID 0 in the initial user namespace.
1050 .\" ============================================================
1053 Use of user namespaces requires a kernel that is configured with the
1056 User namespaces require support in a range of subsystems across
1058 When an unsupported subsystem is configured into the kernel,
1059 it is not possible to configure user namespaces support.
1061 As at Linux 3.8, most relevant subsystems supported user namespaces,
1062 but a number of filesystems did not have the infrastructure needed
1063 to map user and group IDs between user namespaces.
1064 Linux 3.9 added the required infrastructure support for many of
1065 the remaining unsupported filesystems
1066 (Plan 9 (9P), Andrew File System (AFS), Ceph, CIFS, CODA, NFS, and OCFS2).
1067 Linux 3.12 added support for the last of the unsupported major filesystems,
1068 .\" commit d6970d4b726cea6d7a9bc4120814f95c09571fc3
1072 The program below is designed to allow experimenting with
1073 user namespaces, as well as other types of namespaces.
1074 It creates namespaces as specified by command-line options and then executes
1075 a command inside those namespaces.
1078 function inside the program provide a full explanation of the program.
1079 The following shell session demonstrates its use.
1081 First, we look at the run-time environment:
1085 $ \fBuname \-rs\fP # Need Linux 3.8 or later
1087 $ \fBid \-u\fP # Running as unprivileged user
1094 Now start a new shell in new user
1100 namespaces, with user ID
1104 1000 mapped to 0 inside the user namespace:
1108 $ \fB./userns_child_exec \-p \-m \-U \-M \[aq]0 1000 1\[aq] \-G \[aq]0 1000 1\[aq] bash\fP
1112 The shell has PID 1, because it is the first process in the new
1124 filesystem and listing all of the processes visible
1125 in the new PID namespace shows that the shell can't see
1126 any processes outside the PID namespace:
1130 bash$ \fBmount \-t proc proc /proc\fP
1132 PID TTY STAT TIME COMMAND
1134 22 pts/3 R+ 0:00 ps ax
1138 Inside the user namespace, the shell has user and group ID 0,
1139 and a full set of permitted and effective capabilities:
1143 bash$ \fBcat /proc/$$/status | egrep \[aq]\[ha][UG]id\[aq]\fP
1146 bash$ \fBcat /proc/$$/status | egrep \[aq]\[ha]Cap(Prm|Inh|Eff)\[aq]\fP
1147 CapInh: 0000000000000000
1148 CapPrm: 0000001fffffffff
1149 CapEff: 0000001fffffffff
1155 /* userns_child_exec.c
1157 Licensed under GNU General Public License v2 or later
1159 Create a child process that executes a shell command in new
1160 namespace(s); allow UID and GID mappings to be specified when
1161 creating a user namespace.
1169 #include <sys/wait.h>
1178 char **argv; /* Command to be executed by child, with args */
1179 int pipe_fd[2]; /* Pipe used to synchronize parent and child */
1187 fprintf(stderr, "Usage: %s [options] cmd [arg...]\en\en", pname);
1188 fprintf(stderr, "Create a child process that executes a shell "
1189 "command in a new user namespace,\en"
1190 "and possibly also other new namespace(s).\en\en");
1191 fprintf(stderr, "Options can be:\en\en");
1192 #define fpe(str) fprintf(stderr, " %s", str);
1193 fpe("\-i New IPC namespace\en");
1194 fpe("\-m New mount namespace\en");
1195 fpe("\-n New network namespace\en");
1196 fpe("\-p New PID namespace\en");
1197 fpe("\-u New UTS namespace\en");
1198 fpe("\-U New user namespace\en");
1199 fpe("\-M uid_map Specify UID map for user namespace\en");
1200 fpe("\-G gid_map Specify GID map for user namespace\en");
1201 fpe("\-z Map user\[aq]s UID and GID to 0 in user namespace\en");
1202 fpe(" (equivalent to: \-M \[aq]0 <uid> 1\[aq] \-G \[aq]0 <gid> 1\[aq])\en");
1203 fpe("\-v Display verbose messages\en");
1205 fpe("If \-z, \-M, or \-G is specified, \-U is required.\en");
1206 fpe("It is not permitted to specify both \-z and either \-M or \-G.\en");
1208 fpe("Map strings for \-M and \-G consist of records of the form:\en");
1210 fpe(" ID\-inside\-ns ID\-outside\-ns len\en");
1212 fpe("A map string can contain multiple records, separated"
1214 fpe("the commas are replaced by newlines before writing"
1215 " to map files.\en");
1220 /* Update the mapping file \[aq]map_file\[aq], with the value provided in
1221 \[aq]mapping\[aq], a string that defines a UID or GID mapping. A UID or
1222 GID mapping consists of one or more newline\-delimited records
1225 ID_inside\-ns ID\-outside\-ns length
1227 Requiring the user to supply a string that contains newlines is
1228 of course inconvenient for command\-line use. Thus, we permit the
1229 use of commas to delimit records in this string, and replace them
1230 with newlines before writing the string to the file. */
1233 update_map(char *mapping, char *map_file)
1236 size_t map_len; /* Length of \[aq]mapping\[aq] */
1238 /* Replace commas in mapping string with newlines. */
1240 map_len = strlen(mapping);
1241 for (size_t j = 0; j < map_len; j++)
1242 if (mapping[j] == \[aq],\[aq])
1243 mapping[j] = \[aq]\en\[aq];
1245 fd = open(map_file, O_RDWR);
1247 fprintf(stderr, "ERROR: open %s: %s\en", map_file,
1252 if (write(fd, mapping, map_len) != map_len) {
1253 fprintf(stderr, "ERROR: write %s: %s\en", map_file,
1261 /* Linux 3.19 made a change in the handling of setgroups(2) and
1262 the \[aq]gid_map\[aq] file to address a security issue. The issue
1263 allowed *unprivileged* users to employ user namespaces in
1264 order to drop groups. The upshot of the 3.19 changes is that
1265 in order to update the \[aq]gid_maps\[aq] file, use of the setgroups()
1266 system call in this user namespace must first be disabled by
1267 writing "deny" to one of the /proc/PID/setgroups files for
1268 this namespace. That is the purpose of the following function. */
1271 proc_setgroups_write(pid_t child_pid, char *str)
1273 char setgroups_path[PATH_MAX];
1276 snprintf(setgroups_path, PATH_MAX, "/proc/%jd/setgroups",
1277 (intmax_t) child_pid);
1279 fd = open(setgroups_path, O_RDWR);
1282 /* We may be on a system that doesn\[aq]t support
1283 /proc/PID/setgroups. In that case, the file won\[aq]t exist,
1284 and the system won\[aq]t impose the restrictions that Linux 3.19
1285 added. That\[aq]s fine: we don\[aq]t need to do anything in order
1286 to permit \[aq]gid_map\[aq] to be updated.
1288 However, if the error from open() was something other than
1289 the ENOENT error that is expected for that case, let the
1292 if (errno != ENOENT)
1293 fprintf(stderr, "ERROR: open %s: %s\en", setgroups_path,
1298 if (write(fd, str, strlen(str)) == \-1)
1299 fprintf(stderr, "ERROR: write %s: %s\en", setgroups_path,
1305 static int /* Start function for cloned child */
1306 childFunc(void *arg)
1308 struct child_args *args = arg;
1311 /* Wait until the parent has updated the UID and GID mappings.
1312 See the comment in main(). We wait for end of file on a
1313 pipe that will be closed by the parent process once it has
1314 updated the mappings. */
1316 close(args\->pipe_fd[1]); /* Close our descriptor for the write
1317 end of the pipe so that we see EOF
1318 when parent closes its descriptor. */
1319 if (read(args\->pipe_fd[0], &ch, 1) != 0) {
1321 "Failure in child: read from pipe returned != 0\en");
1325 close(args\->pipe_fd[0]);
1327 /* Execute a shell command. */
1329 printf("About to exec %s\en", args\->argv[0]);
1330 execvp(args\->argv[0], args\->argv);
1331 err(EXIT_FAILURE, "execvp");
1334 #define STACK_SIZE (1024 * 1024)
1336 static char child_stack[STACK_SIZE]; /* Space for child\[aq]s stack */
1339 main(int argc, char *argv[])
1341 int flags, opt, map_zero;
1343 struct child_args args;
1344 char *uid_map, *gid_map;
1345 const int MAP_BUF_SIZE = 100;
1346 char map_buf[MAP_BUF_SIZE];
1347 char map_path[PATH_MAX];
1349 /* Parse command\-line options. The initial \[aq]+\[aq] character in
1350 the final getopt() argument prevents GNU\-style permutation
1351 of command\-line options. That\[aq]s useful, since sometimes
1352 the \[aq]command\[aq] to be executed by this program itself
1353 has command\-line options. We don\[aq]t want getopt() to treat
1354 those as options to this program. */
1361 while ((opt = getopt(argc, argv, "+imnpuUM:G:zv")) != \-1) {
1363 case \[aq]i\[aq]: flags |= CLONE_NEWIPC; break;
1364 case \[aq]m\[aq]: flags |= CLONE_NEWNS; break;
1365 case \[aq]n\[aq]: flags |= CLONE_NEWNET; break;
1366 case \[aq]p\[aq]: flags |= CLONE_NEWPID; break;
1367 case \[aq]u\[aq]: flags |= CLONE_NEWUTS; break;
1368 case \[aq]v\[aq]: verbose = 1; break;
1369 case \[aq]z\[aq]: map_zero = 1; break;
1370 case \[aq]M\[aq]: uid_map = optarg; break;
1371 case \[aq]G\[aq]: gid_map = optarg; break;
1372 case \[aq]U\[aq]: flags |= CLONE_NEWUSER; break;
1373 default: usage(argv[0]);
1377 /* \-M or \-G without \-U is nonsensical */
1379 if (((uid_map != NULL || gid_map != NULL || map_zero) &&
1380 !(flags & CLONE_NEWUSER)) ||
1381 (map_zero && (uid_map != NULL || gid_map != NULL)))
1384 args.argv = &argv[optind];
1386 /* We use a pipe to synchronize the parent and child, in order to
1387 ensure that the parent sets the UID and GID maps before the child
1388 calls execve(). This ensures that the child maintains its
1389 capabilities during the execve() in the common case where we
1390 want to map the child\[aq]s effective user ID to 0 in the new user
1391 namespace. Without this synchronization, the child would lose
1392 its capabilities if it performed an execve() with nonzero
1393 user IDs (see the capabilities(7) man page for details of the
1394 transformation of a process\[aq]s capabilities during execve()). */
1396 if (pipe(args.pipe_fd) == \-1)
1397 err(EXIT_FAILURE, "pipe");
1399 /* Create the child in new namespace(s). */
1401 child_pid = clone(childFunc, child_stack + STACK_SIZE,
1402 flags | SIGCHLD, &args);
1403 if (child_pid == \-1)
1404 err(EXIT_FAILURE, "clone");
1406 /* Parent falls through to here. */
1409 printf("%s: PID of child created by clone() is %jd\en",
1410 argv[0], (intmax_t) child_pid);
1412 /* Update the UID and GID maps in the child. */
1414 if (uid_map != NULL || map_zero) {
1415 snprintf(map_path, PATH_MAX, "/proc/%jd/uid_map",
1416 (intmax_t) child_pid);
1418 snprintf(map_buf, MAP_BUF_SIZE, "0 %jd 1",
1419 (intmax_t) getuid());
1422 update_map(uid_map, map_path);
1425 if (gid_map != NULL || map_zero) {
1426 proc_setgroups_write(child_pid, "deny");
1428 snprintf(map_path, PATH_MAX, "/proc/%jd/gid_map",
1429 (intmax_t) child_pid);
1431 snprintf(map_buf, MAP_BUF_SIZE, "0 %ld 1",
1432 (intmax_t) getgid());
1435 update_map(gid_map, map_path);
1438 /* Close the write end of the pipe, to signal to the child that we
1439 have updated the UID and GID maps. */
1441 close(args.pipe_fd[1]);
1443 if (waitpid(child_pid, NULL, 0) == \-1) /* Wait for child */
1444 err(EXIT_FAILURE, "waitpid");
1447 printf("%s: terminating\en", argv[0]);
1453 .BR newgidmap (1), \" From the shadow package
1454 .BR newuidmap (1), \" From the shadow package
1460 .BR subgid (5), \" From the shadow package
1461 .BR subuid (5), \" From the shadow package
1462 .BR capabilities (7),
1463 .BR cgroup_namespaces (7),
1464 .BR credentials (7),
1466 .BR pid_namespaces (7)
1468 The kernel source file
1469 .IR Documentation/admin\-guide/namespaces/resource\-control.rst .