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 .\" %%%LICENSE_START(VERBATIM)
5 .\" Permission is granted to make and distribute verbatim copies of this
6 .\" manual provided the copyright notice and this permission notice are
7 .\" preserved on all copies.
9 .\" Permission is granted to copy and distribute modified versions of this
10 .\" manual under the conditions for verbatim copying, provided that the
11 .\" entire resulting derived work is distributed under the terms of a
12 .\" permission notice identical to this one.
14 .\" Since the Linux kernel and libraries are constantly changing, this
15 .\" manual page may be incorrect or out-of-date. The author(s) assume no
16 .\" responsibility for errors or omissions, or for damages resulting from
17 .\" the use of the information contained herein. The author(s) may not
18 .\" have taken the same level of care in the production of this manual,
19 .\" which is licensed free of charge, as they might when working
22 .\" Formatted or processed versions of this manual, if unaccompanied by
23 .\" the source, must acknowledge the copyright and authors of this work.
27 .TH USER_NAMESPACES 7 2021-03-22 "Linux" "Linux Programmer's Manual"
29 user_namespaces \- overview of Linux user namespaces
31 For an overview of namespaces, see
34 User namespaces isolate security-related identifiers and attributes,
36 user IDs and group IDs (see
41 .\" FIXME: This page says very little about the interaction
42 .\" of user namespaces and keys. Add something on this topic.
44 .BR capabilities (7)).
45 A process's user and group IDs can be different
46 inside and outside a user namespace.
48 a process can have a normal unprivileged user ID outside a user namespace
49 while at the same time having a user ID of 0 inside the namespace;
51 the process has full privileges for operations inside the user namespace,
52 but is unprivileged for operations outside the namespace.
54 .\" ============================================================
56 .SS Nested namespaces, namespace membership
57 User namespaces can be nested;
58 that is, each user namespace\(emexcept the initial ("root")
59 namespace\(emhas a parent user namespace,
60 and can have zero or more child user namespaces.
61 The parent user namespace is the user namespace
62 of the process that creates the user namespace via a call to
70 The kernel imposes (since version 3.11) a limit of 32 nested levels of
71 .\" commit 8742f229b635bf1c1c84a3dfe5e47c814c20b5c8
73 .\" FIXME Explain the rationale for this limit. (What is the rationale?)
78 that would cause this limit to be exceeded fail with the error
81 Each process is a member of exactly one user namespace.
88 flag is a member of the same user namespace as its parent.
89 A single-threaded process can join another user namespace with
94 upon doing so, it gains a full set of capabilities in that namespace.
102 flag makes the new child process (for
106 a member of the new user namespace created by the call.
111 operation can be used to discover the parental relationship
112 between user namespaces; see
115 .\" ============================================================
118 The child process created by
122 flag starts out with a complete set
123 of capabilities in the new user namespace.
124 Likewise, a process that creates a new user namespace using
126 or joins an existing user namespace using
128 gains a full set of capabilities in that namespace.
130 that process has no capabilities in the parent (in the case of
132 or previous (in the case of
137 even if the new namespace is created or joined by the root user
138 (i.e., a process with user ID 0 in the root namespace).
142 will cause a process's capabilities to be recalculated in the usual way (see
143 .BR capabilities (7)).
145 unless the process has a user ID of 0 within the namespace,
146 or the executable file has a nonempty inheritable capabilities mask,
147 the process will lose all capabilities.
148 See the discussion of user and group ID mappings, below.
159 that moves the caller into another user namespace
160 sets the "securebits" flags
162 .BR capabilities (7))
163 to their default values (all flags disabled) in the child (for
169 Note that because the caller no longer has capabilities
170 in its original user namespace after a call to
172 it is not possible for a process to reset its "securebits" flags while
173 retaining its user namespace membership by using a pair of
175 calls to move to another user namespace and then return to
176 its original user namespace.
178 The rules for determining whether or not a process has a capability
179 in a particular user namespace are as follows:
181 A process has a capability inside a user namespace
182 if it is a member of that namespace and
183 it has the capability in its effective capability set.
184 A process can gain capabilities in its effective capability
186 For example, it may execute a set-user-ID program or an
187 executable with associated file capabilities.
189 a process may gain capabilities via the effect of
194 as already described.
195 .\" In the 3.8 sources, see security/commoncap.c::cap_capable():
197 If a process has a capability in a user namespace,
198 then it has that capability in all child (and further removed descendant)
201 .\" * The owner of the user namespace in the parent of the
202 .\" * user namespace has all caps.
203 When a user namespace is created, the kernel records the effective
204 user ID of the creating process as being the "owner" of the namespace.
205 .\" (and likewise associates the effective group ID of the creating process
206 .\" with the namespace).
207 A process that resides
208 in the parent of the user namespace
209 .\" See kernel commit 520d9eabce18edfef76a60b7b839d54facafe1f9 for a fix
211 and whose effective user ID matches the owner of the namespace
212 has all capabilities in the namespace.
213 .\" This includes the case where the process executes a set-user-ID
214 .\" program that confers the effective UID of the creator of the namespace.
215 By virtue of the previous rule,
216 this means that the process has all capabilities in all
217 further removed descendant user namespaces as well.
221 operation can be used to discover the user ID of the owner of the namespace;
225 .\" ============================================================
227 .SS Effect of capabilities within a user namespace
228 Having a capability inside a user namespace
229 permits a process to perform operations (that require privilege)
230 only on resources governed by that namespace.
231 In other words, having a capability in a user namespace permits a process
232 to perform privileged operations on resources that are governed by (nonuser)
233 namespaces owned by (associated with) the user namespace
234 (see the next subsection).
236 On the other hand, there are many privileged operations that affect
237 resources that are not associated with any namespace type,
238 for example, changing the system (i.e., calendar) time (governed by
240 loading a kernel module (governed by
241 .BR CAP_SYS_MODULE ),
242 and creating a device (governed by
244 Only a process with privileges in the
246 user namespace can perform such operations.
250 within the user namespace that owns a process's mount namespace
251 allows that process to create bind mounts
252 and mount the following types of filesystems:
253 .\" fs_flags = FS_USERNS_MOUNT in kernel sources
277 .\" commit b2197755b2633e164a439682fb05a9b5ea48f706
281 .\" commit 92dbc9dedccb9759c7f9f2f0ae6242396376988f
282 .\" commit 4cb2c00c43b3fe88b32f29df4f76da1b92c33224
289 within the user namespace that owns a process's cgroup namespace
290 allows (since Linux 4.6)
291 that process to the mount the cgroup version 2 filesystem and
292 cgroup version 1 named hierarchies
293 (i.e., cgroup filesystems mounted with the
299 within the user namespace that owns a process's PID namespace
300 allows (since Linux 3.8)
301 that process to mount
305 Note, however, that mounting block-based filesystems can be done
306 only by a process that holds
308 in the initial user namespace.
310 .\" ============================================================
312 .SS Interaction of user namespaces and other types of namespaces
313 Starting in Linux 3.8, unprivileged processes can create user namespaces,
314 and the other types of namespaces can be created with just the
316 capability in the caller's user namespace.
318 When a nonuser namespace is created,
319 it is owned by the user namespace in which the creating process
320 was a member at the time of the creation of the namespace.
321 Privileged operations on resources governed by the nonuser namespace
322 require that the process has the necessary capabilities
323 in the user namespace that owns the nonuser namespace.
327 is specified along with other
333 call, the user namespace is guaranteed to be created first,
338 privileges over the remaining namespaces created by the call.
339 Thus, it is possible for an unprivileged caller to specify this combination
342 When a new namespace (other than a user namespace) is created via
346 the kernel records the user namespace of the creating process as the owner of
348 (This association can't be changed.)
349 When a process in the new namespace subsequently performs
350 privileged operations that operate on global
351 resources isolated by the namespace,
352 the permission checks are performed according to the process's capabilities
353 in the user namespace that the kernel associated with the new namespace.
354 For example, suppose that a process attempts to change the hostname
355 .RB ( sethostname (2)),
356 a resource governed by the UTS namespace.
358 the kernel will determine which user namespace owns
359 the process's UTS namespace, and check whether the process has the
361 .RB ( CAP_SYS_ADMIN )
362 in that user namespace.
367 operation can be used to discover the user namespace
368 that owns a nonuser namespace; see
371 .\" ============================================================
373 .SS User and group ID mappings: uid_map and gid_map
374 When a user namespace is created,
375 it starts out without a mapping of user IDs (group IDs)
376 to the parent user namespace.
378 .IR /proc/[pid]/uid_map
380 .IR /proc/[pid]/gid_map
381 files (available since Linux 3.5)
382 .\" commit 22d917d80e842829d0ca0a561967d728eb1d6303
383 expose the mappings for user and group IDs
384 inside the user namespace for the process
386 These files can be read to view the mappings in a user namespace and
387 written to (once) to define the mappings.
389 The description in the following paragraphs explains the details for
393 but each instance of "user ID" is replaced by "group ID".
397 file exposes the mapping of user IDs from the user namespace
400 to the user namespace of the process that opened
402 (but see a qualification to this point below).
403 In other words, processes that are in different user namespaces
404 will potentially see different values when reading from a particular
406 file, depending on the user ID mappings for the user namespaces
407 of the reading processes.
411 file specifies a 1-to-1 mapping of a range of contiguous
412 user IDs between two user namespaces.
413 (When a user namespace is first created, this file is empty.)
414 The specification in each line takes the form of
415 three numbers delimited by white space.
416 The first two numbers specify the starting user ID in
417 each of the two user namespaces.
418 The third number specifies the length of the mapped range.
419 In detail, the fields are interpreted as follows:
421 The start of the range of user IDs in
422 the user namespace of the process
425 The start of the range of user
426 IDs to which the user IDs specified by field one map.
427 How field two is interpreted depends on whether the process that opened
431 are in the same user namespace, as follows:
434 If the two processes are in different user namespaces:
435 field two is the start of a range of
436 user IDs in the user namespace of the process that opened
439 If the two processes are in the same user namespace:
440 field two is the start of the range of
441 user IDs in the parent user namespace of the process
443 This case enables the opener of
445 (the common case here is opening
446 .IR /proc/self/uid_map )
447 to see the mapping of user IDs into the user namespace of the process
448 that created this user namespace.
451 The length of the range of user IDs that is mapped between the two
454 System calls that return user IDs (group IDs)\(emfor example,
457 and the credential fields in the structure returned by
458 .BR stat (2)\(emreturn
459 the user ID (group ID) mapped into the caller's user namespace.
461 When a process accesses a file, its user and group IDs
462 are mapped into the initial user namespace for the purpose of permission
463 checking and assigning IDs when creating a file.
464 When a process retrieves file user and group IDs via
466 the IDs are mapped in the opposite direction,
467 to produce values relative to the process user and group ID mappings.
469 The initial user namespace has no parent namespace,
470 but, for consistency, the kernel provides dummy user and group
471 ID mapping files for this namespace.
476 is the same) from a shell in the initial namespace shows:
480 $ \fBcat /proc/$$/uid_map\fP
485 This mapping tells us
486 that the range starting at user ID 0 in this namespace
487 maps to a range starting at 0 in the (nonexistent) parent namespace,
488 and the length of the range is the largest 32-bit unsigned integer.
489 This leaves 4294967295 (the 32-bit signed \-1 value) unmapped.
492 is used in several interfaces (e.g.,
494 as a way to specify "no user ID".
497 unmapped and unusable guarantees that there will be no
498 confusion when using these interfaces.
500 .\" ============================================================
502 .SS Defining user and group ID mappings: writing to uid_map and gid_map
503 After the creation of a new user namespace, the
507 of the processes in the namespace may be written to
509 to define the mapping of user IDs in the new user namespace.
510 An attempt to write more than once to a
512 file in a user namespace fails with the error
514 Similar rules apply for
521 must conform to the following validity rules:
523 The three fields must be valid numbers,
524 and the last field must be greater than 0.
526 Lines are terminated by newline characters.
528 There is a limit on the number of lines in the file.
529 In Linux 4.14 and earlier, this limit was (arbitrarily)
530 .\" 5*12-byte records could fit in a 64B cache line
533 .\" commit 6397fac4915ab3002dc15aae751455da1a852f25
534 the limit is 340 lines.
535 In addition, the number of bytes written to
536 the file must be less than the system page size,
537 and the write must be performed at the start of the file (i.e.,
541 can't be used to write to nonzero offsets in the file).
543 The range of user IDs (group IDs)
544 specified in each line cannot overlap with the ranges
546 In the initial implementation (Linux 3.8), this requirement was
547 satisfied by a simplistic implementation that imposed the further
549 the values in both field 1 and field 2 of successive lines must be
550 in ascending numerical order,
551 which prevented some otherwise valid maps from being created.
553 .\" commit 0bd14b4fd72afd5df41e9fd59f356740f22fceba
554 fix this limitation, allowing any valid set of nonoverlapping maps.
556 At least one line must be written to the file.
558 Writes that violate the above rules fail with the error
561 In order for a process to write to the
562 .I /proc/[pid]/uid_map
563 .RI ( /proc/[pid]/gid_map )
564 file, all of the following permission requirements must be met:
566 The writing process must have the
569 capability in the user namespace of the process
572 The writing process must either be in the user namespace of the process
574 or be in the parent user namespace of the process
577 The mapped user IDs (group IDs) must in turn have a mapping
578 in the parent user namespace.
581 .IR /proc/[pid]/uid_map
582 to create a mapping that maps UID 0 in the parent namespace,
583 then one of the following must be true:
586 if writing process is in the parent user namespace,
587 then it must have the
589 capability in that user namespace; or
591 if the writing process is in the child user namespace,
592 then the process that created the user namespace must have had the
594 capability when the namespace was created.
597 This rule has been in place since
598 .\" commit db2e718a47984b9d71ed890eb2ea36ecf150de18
600 It eliminates an earlier security bug whereby
601 a UID 0 process that lacks the
604 which is needed to create a binary with namespaced file capabilities
606 .BR capabilities (7)),
607 could nevertheless create such a binary,
608 by the following steps:
611 Create a new user namespace with the identity mapping
612 (i.e., UID 0 in the new user namespace maps to UID 0 in the parent namespace),
613 so that UID 0 in both namespaces is equivalent to the same root user ID.
615 Since the child process has the
617 capability, it could create a binary with namespaced file capabilities
618 that would then be effective in the parent user namespace
619 (because the root user IDs are the same in the two namespaces).
622 One of the following two cases applies:
626 the writing process has the
634 No further restrictions apply:
635 the process can make mappings to arbitrary user IDs (group IDs)
636 in the parent user namespace.
640 otherwise all of the following restrictions apply:
646 must consist of a single line that maps
647 the writing process's effective user ID
648 (group ID) in the parent user namespace to a user ID (group ID)
649 in the user namespace.
651 The writing process must have the same effective user ID as the process
652 that created the user namespace.
658 system call must first be denied by writing
661 .I /proc/[pid]/setgroups
662 file (see below) before writing to
667 Writes that violate the above rules fail with the error
670 .\" ============================================================
672 .SS Project ID mappings: projid_map
673 Similarly to user and group ID mappings,
674 it is possible to create project ID mappings for a user namespace.
675 (Project IDs are used for disk quotas; see
680 Project ID mappings are defined by writing to the
681 .I /proc/[pid]/projid_map
683 .\" commit f76d207a66c3a53defea67e7d36c3eb1b7d6d61d
686 The validity rules for writing to the
687 .I /proc/[pid]/projid_map
688 file are as for writing to the
690 file; violation of these rules causes
692 to fail with the error
695 The permission rules for writing to the
696 .I /proc/[pid]/projid_map
699 The writing process must either be in the user namespace of the process
701 or be in the parent user namespace of the process
704 The mapped project IDs must in turn have a mapping
705 in the parent user namespace.
707 Violation of these rules causes
709 to fail with the error
712 .\" ============================================================
714 .SS Interaction with system calls that change process UIDs or GIDs
715 In a user namespace where the
717 file has not been written, the system calls that change user IDs will fail.
720 file has not been written, the system calls that change group IDs will fail.
725 files have been written, only the mapped values may be used in
726 system calls that change user and group IDs.
728 For user IDs, the relevant system calls include
734 For group IDs, the relevant system calls include
745 .I /proc/[pid]/setgroups
746 file before writing to
747 .I /proc/[pid]/gid_map
748 .\" Things changed in Linux 3.19
749 .\" commit 9cc46516ddf497ea16e8d7cb986ae03a0f6b92f8
750 .\" commit 66d2f338ee4c449396b6f99f5e75cd18eb6df272
751 .\" http://lwn.net/Articles/626665/
752 will permanently disable
754 in a user namespace and allow writing to
755 .I /proc/[pid]/gid_map
758 capability in the parent user namespace.
760 .\" ============================================================
762 .SS The /proc/[pid]/setgroups file
764 .\" commit 9cc46516ddf497ea16e8d7cb986ae03a0f6b92f8
765 .\" commit 66d2f338ee4c449396b6f99f5e75cd18eb6df272
766 .\" http://lwn.net/Articles/626665/
767 .\" http://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2014-8989
770 .I /proc/[pid]/setgroups
771 file displays the string
773 if processes in the user namespace that contains the process
775 are permitted to employ the
777 system call; it displays
781 is not permitted in that user namespace.
782 Note that regardless of the value in the
783 .I /proc/[pid]/setgroups
784 file (and regardless of the process's capabilities), calls to
786 are also not permitted if
787 .IR /proc/[pid]/gid_map
788 has not yet been set.
790 A privileged process (one with the
792 capability in the namespace) may write either of the strings
798 writing a group ID mapping
799 for this user namespace to the file
800 .IR /proc/[pid]/gid_map .
803 prevents any process in the user namespace from employing
806 The essence of the restrictions described in the preceding
807 paragraph is that it is permitted to write to
808 .I /proc/[pid]/setgroups
809 only so long as calling
811 is disallowed because
812 .I /proc/[pid]/gid_map
814 This ensures that a process cannot transition from a state where
816 is allowed to a state where
819 a process can transition only from
825 The default value of this file in the initial user namespace is
829 .IR /proc/[pid]/gid_map
831 (which has the effect of enabling
833 in the user namespace),
834 it is no longer possible to disallow
839 .IR /proc/[pid]/setgroups
840 (the write fails with the error
843 A child user namespace inherits the
844 .IR /proc/[pid]/setgroups
845 setting from its parent.
853 system call can't subsequently be reenabled (by writing
855 to the file) in this user namespace.
856 (Attempts to do so fail with the error
858 This restriction also propagates down to all child user namespaces of
862 .I /proc/[pid]/setgroups
863 file was added in Linux 3.19,
864 but was backported to many earlier stable kernel series,
865 because it addresses a security issue.
866 The issue concerned files with permissions such as "rwx\-\-\-rwx".
867 Such files give fewer permissions to "group" than they do to "other".
868 This means that dropping groups using
870 might allow a process file access that it did not formerly have.
871 Before the existence of user namespaces this was not a concern,
872 since only a privileged process (one with the
874 capability) could call
876 However, with the introduction of user namespaces,
877 it became possible for an unprivileged process to create
878 a new namespace in which the user had all privileges.
879 This then allowed formerly unprivileged
880 users to drop groups and thus gain file access
881 that they did not previously have.
883 .I /proc/[pid]/setgroups
884 file was added to address this security issue,
885 by denying any pathway for an unprivileged process to drop groups with
888 .\" /proc/PID/setgroups
889 .\" [allow == setgroups() is allowed, "deny" == setgroups() is disallowed]
890 .\" * Can write if have CAP_SYS_ADMIN in NS
891 .\" * Must write BEFORE writing to /proc/PID/gid_map
894 .\" * Must already have written to gid_map
895 .\" * /proc/PID/setgroups must be "allow"
897 .\" /proc/PID/gid_map -- writing
898 .\" * Must already have written "deny" to /proc/PID/setgroups
900 .\" ============================================================
902 .SS Unmapped user and group IDs
903 There are various places where an unmapped user ID (group ID)
904 may be exposed to user space.
905 For example, the first process in a new user namespace may call
907 before a user ID mapping has been defined for the namespace.
908 In most such cases, an unmapped user ID is converted
909 .\" from_kuid_munged(), from_kgid_munged()
910 to the overflow user ID (group ID);
911 the default value for the overflow user ID (group ID) is 65534.
912 See the descriptions of
913 .IR /proc/sys/kernel/overflowuid
915 .IR /proc/sys/kernel/overflowgid
919 The cases where unmapped IDs are mapped in this fashion include
920 system calls that return user IDs
924 credentials passed over a UNIX domain socket,
926 credentials returned by
929 and the System V IPC "ctl"
932 credentials exposed by
933 .IR /proc/[pid]/status
935 .IR /proc/sysvipc/* ,
936 credentials returned via the
940 received with a signal (see
942 credentials written to the process accounting file (see
944 and credentials returned with POSIX message queue notifications (see
947 There is one notable case where unmapped user and group IDs are
949 .\" from_kuid(), from_kgid()
950 .\" Also F_GETOWNER_UIDS is an exception
951 converted to the corresponding overflow ID value.
956 file in which there is no mapping for the second field,
957 that field is displayed as 4294967295 (\-1 as an unsigned integer).
959 .\" ============================================================
962 In order to determine permissions when an unprivileged process accesses a file,
963 the process credentials (UID, GID) and the file credentials
964 are in effect mapped back to what they would be in
965 the initial user namespace and then compared to determine
966 the permissions that the process has on the file.
967 The same is also of other objects that employ the credentials plus
968 permissions mask accessibility model, such as System V IPC objects
970 .\" ============================================================
972 .SS Operation of file-related capabilities
973 Certain capabilities allow a process to bypass various
974 kernel-enforced restrictions when performing operations on
975 files owned by other users or groups.
976 These capabilities are:
978 .BR CAP_DAC_OVERRIDE ,
979 .BR CAP_DAC_READ_SEARCH ,
984 Within a user namespace,
985 these capabilities allow a process to bypass the rules
986 if the process has the relevant capability over the file,
989 the process has the relevant effective capability in its user namespace; and
991 the file's user ID and group ID both have valid mappings
992 in the user namespace.
996 capability is treated somewhat exceptionally:
997 .\" These are the checks performed by the kernel function
998 .\" inode_owner_or_capable(). There is one exception to the exception:
999 .\" overriding the directory sticky permission bit requires that
1000 .\" the file has a valid mapping for both its UID and GID.
1001 it allows a process to bypass the corresponding rules so long as
1002 at least the file's user ID has a mapping in the user namespace
1003 (i.e., the file's group ID does not need to have a valid mapping).
1005 .\" ============================================================
1007 .SS Set-user-ID and set-group-ID programs
1008 When a process inside a user namespace executes
1009 a set-user-ID (set-group-ID) program,
1010 the process's effective user (group) ID inside the namespace is changed
1011 to whatever value is mapped for the user (group) ID of the file.
1012 However, if either the user
1014 the group ID of the file has no mapping inside the namespace,
1015 the set-user-ID (set-group-ID) bit is silently ignored:
1016 the new program is executed,
1017 but the process's effective user (group) ID is left unchanged.
1018 (This mirrors the semantics of executing a set-user-ID or set-group-ID
1019 program that resides on a filesystem that was mounted with the
1021 flag, as described in
1024 .\" ============================================================
1027 When a process's user and group IDs are passed over a UNIX domain socket
1028 to a process in a different user namespace (see the description of
1032 they are translated into the corresponding values as per the
1033 receiving process's user and group ID mappings.
1036 Namespaces are a Linux-specific feature.
1039 Over the years, there have been a lot of features that have been added
1040 to the Linux kernel that have been made available only to privileged users
1041 because of their potential to confuse set-user-ID-root applications.
1042 In general, it becomes safe to allow the root user in a user namespace to
1043 use those features because it is impossible, while in a user namespace,
1044 to gain more privilege than the root user of a user namespace has.
1046 .\" ============================================================
1049 Use of user namespaces requires a kernel that is configured with the
1052 User namespaces require support in a range of subsystems across
1054 When an unsupported subsystem is configured into the kernel,
1055 it is not possible to configure user namespaces support.
1057 As at Linux 3.8, most relevant subsystems supported user namespaces,
1058 but a number of filesystems did not have the infrastructure needed
1059 to map user and group IDs between user namespaces.
1060 Linux 3.9 added the required infrastructure support for many of
1061 the remaining unsupported filesystems
1062 (Plan 9 (9P), Andrew File System (AFS), Ceph, CIFS, CODA, NFS, and OCFS2).
1063 Linux 3.12 added support for the last of the unsupported major filesystems,
1064 .\" commit d6970d4b726cea6d7a9bc4120814f95c09571fc3
1068 The program below is designed to allow experimenting with
1069 user namespaces, as well as other types of namespaces.
1070 It creates namespaces as specified by command-line options and then executes
1071 a command inside those namespaces.
1074 function inside the program provide a full explanation of the program.
1075 The following shell session demonstrates its use.
1077 First, we look at the run-time environment:
1081 $ \fBuname \-rs\fP # Need Linux 3.8 or later
1083 $ \fBid \-u\fP # Running as unprivileged user
1090 Now start a new shell in new user
1096 namespaces, with user ID
1100 1000 mapped to 0 inside the user namespace:
1104 $ \fB./userns_child_exec \-p \-m \-U \-M \(aq0 1000 1\(aq \-G \(aq0 1000 1\(aq bash\fP
1108 The shell has PID 1, because it is the first process in the new
1120 filesystem and listing all of the processes visible
1121 in the new PID namespace shows that the shell can't see
1122 any processes outside the PID namespace:
1126 bash$ \fBmount \-t proc proc /proc\fP
1128 PID TTY STAT TIME COMMAND
1130 22 pts/3 R+ 0:00 ps ax
1134 Inside the user namespace, the shell has user and group ID 0,
1135 and a full set of permitted and effective capabilities:
1139 bash$ \fBcat /proc/$$/status | egrep \(aq\(ha[UG]id\(aq\fP
1142 bash$ \fBcat /proc/$$/status | egrep \(aq\(haCap(Prm|Inh|Eff)\(aq\fP
1143 CapInh: 0000000000000000
1144 CapPrm: 0000001fffffffff
1145 CapEff: 0000001fffffffff
1151 /* userns_child_exec.c
1153 Licensed under GNU General Public License v2 or later
1155 Create a child process that executes a shell command in new
1156 namespace(s); allow UID and GID mappings to be specified when
1157 creating a user namespace.
1164 #include <sys/wait.h>
1172 /* A simple error\-handling function: print an error message based
1173 on the value in \(aqerrno\(aq and terminate the calling process. */
1175 #define errExit(msg) do { perror(msg); exit(EXIT_FAILURE); \e
1179 char **argv; /* Command to be executed by child, with args */
1180 int pipe_fd[2]; /* Pipe used to synchronize parent and child */
1188 fprintf(stderr, "Usage: %s [options] cmd [arg...]\en\en", pname);
1189 fprintf(stderr, "Create a child process that executes a shell "
1190 "command in a new user namespace,\en"
1191 "and possibly also other new namespace(s).\en\en");
1192 fprintf(stderr, "Options can be:\en\en");
1193 #define fpe(str) fprintf(stderr, " %s", str);
1194 fpe("\-i New IPC namespace\en");
1195 fpe("\-m New mount namespace\en");
1196 fpe("\-n New network namespace\en");
1197 fpe("\-p New PID namespace\en");
1198 fpe("\-u New UTS namespace\en");
1199 fpe("\-U New user namespace\en");
1200 fpe("\-M uid_map Specify UID map for user namespace\en");
1201 fpe("\-G gid_map Specify GID map for user namespace\en");
1202 fpe("\-z Map user\(aqs UID and GID to 0 in user namespace\en");
1203 fpe(" (equivalent to: \-M \(aq0 <uid> 1\(aq \-G \(aq0 <gid> 1\(aq)\en");
1204 fpe("\-v Display verbose messages\en");
1206 fpe("If \-z, \-M, or \-G is specified, \-U is required.\en");
1207 fpe("It is not permitted to specify both \-z and either \-M or \-G.\en");
1209 fpe("Map strings for \-M and \-G consist of records of the form:\en");
1211 fpe(" ID\-inside\-ns ID\-outside\-ns len\en");
1213 fpe("A map string can contain multiple records, separated"
1215 fpe("the commas are replaced by newlines before writing"
1216 " to map files.\en");
1221 /* Update the mapping file \(aqmap_file\(aq, with the value provided in
1222 \(aqmapping\(aq, a string that defines a UID or GID mapping. A UID or
1223 GID mapping consists of one or more newline\-delimited records
1226 ID_inside\-ns ID\-outside\-ns length
1228 Requiring the user to supply a string that contains newlines is
1229 of course inconvenient for command\-line use. Thus, we permit the
1230 use of commas to delimit records in this string, and replace them
1231 with newlines before writing the string to the file. */
1234 update_map(char *mapping, char *map_file)
1237 size_t map_len; /* Length of \(aqmapping\(aq */
1239 /* Replace commas in mapping string with newlines. */
1241 map_len = strlen(mapping);
1242 for (int j = 0; j < map_len; j++)
1243 if (mapping[j] == \(aq,\(aq)
1244 mapping[j] = \(aq\en\(aq;
1246 fd = open(map_file, O_RDWR);
1248 fprintf(stderr, "ERROR: open %s: %s\en", map_file,
1253 if (write(fd, mapping, map_len) != map_len) {
1254 fprintf(stderr, "ERROR: write %s: %s\en", map_file,
1262 /* Linux 3.19 made a change in the handling of setgroups(2) and the
1263 \(aqgid_map\(aq file to address a security issue. The issue allowed
1264 *unprivileged* users to employ user namespaces in order to drop
1265 The upshot of the 3.19 changes is that in order to update the
1266 \(aqgid_maps\(aq file, use of the setgroups() system call in this
1267 user namespace must first be disabled by writing "deny" to one of
1268 the /proc/PID/setgroups files for this namespace. That is the
1269 purpose of the following function. */
1272 proc_setgroups_write(pid_t child_pid, char *str)
1274 char setgroups_path[PATH_MAX];
1277 snprintf(setgroups_path, PATH_MAX, "/proc/%jd/setgroups",
1278 (intmax_t) child_pid);
1280 fd = open(setgroups_path, O_RDWR);
1283 /* We may be on a system that doesn\(aqt support
1284 /proc/PID/setgroups. In that case, the file won\(aqt exist,
1285 and the system won\(aqt impose the restrictions that Linux 3.19
1286 added. That\(aqs fine: we don\(aqt need to do anything in order
1287 to permit \(aqgid_map\(aq to be updated.
1289 However, if the error from open() was something other than
1290 the ENOENT error that is expected for that case, let the
1293 if (errno != ENOENT)
1294 fprintf(stderr, "ERROR: open %s: %s\en", setgroups_path,
1299 if (write(fd, str, strlen(str)) == \-1)
1300 fprintf(stderr, "ERROR: write %s: %s\en", setgroups_path,
1306 static int /* Start function for cloned child */
1307 childFunc(void *arg)
1309 struct child_args *args = arg;
1312 /* Wait until the parent has updated the UID and GID mappings.
1313 See the comment in main(). We wait for end of file on a
1314 pipe that will be closed by the parent process once it has
1315 updated the mappings. */
1317 close(args\->pipe_fd[1]); /* Close our descriptor for the write
1318 end of the pipe so that we see EOF
1319 when parent closes its descriptor. */
1320 if (read(args\->pipe_fd[0], &ch, 1) != 0) {
1322 "Failure in child: read from pipe returned != 0\en");
1326 close(args\->pipe_fd[0]);
1328 /* Execute a shell command. */
1330 printf("About to exec %s\en", args\->argv[0]);
1331 execvp(args\->argv[0], args\->argv);
1335 #define STACK_SIZE (1024 * 1024)
1337 static char child_stack[STACK_SIZE]; /* Space for child\(aqs stack */
1340 main(int argc, char *argv[])
1342 int flags, opt, map_zero;
1344 struct child_args args;
1345 char *uid_map, *gid_map;
1346 const int MAP_BUF_SIZE = 100;
1347 char map_buf[MAP_BUF_SIZE];
1348 char map_path[PATH_MAX];
1350 /* Parse command\-line options. The initial \(aq+\(aq character in
1351 the final getopt() argument prevents GNU\-style permutation
1352 of command\-line options. That\(aqs useful, since sometimes
1353 the \(aqcommand\(aq to be executed by this program itself
1354 has command\-line options. We don\(aqt want getopt() to treat
1355 those as options to this program. */
1362 while ((opt = getopt(argc, argv, "+imnpuUM:G:zv")) != \-1) {
1364 case \(aqi\(aq: flags |= CLONE_NEWIPC; break;
1365 case \(aqm\(aq: flags |= CLONE_NEWNS; break;
1366 case \(aqn\(aq: flags |= CLONE_NEWNET; break;
1367 case \(aqp\(aq: flags |= CLONE_NEWPID; break;
1368 case \(aqu\(aq: flags |= CLONE_NEWUTS; break;
1369 case \(aqv\(aq: verbose = 1; break;
1370 case \(aqz\(aq: map_zero = 1; break;
1371 case \(aqM\(aq: uid_map = optarg; break;
1372 case \(aqG\(aq: gid_map = optarg; break;
1373 case \(aqU\(aq: flags |= CLONE_NEWUSER; break;
1374 default: usage(argv[0]);
1378 /* \-M or \-G without \-U is nonsensical */
1380 if (((uid_map != NULL || gid_map != NULL || map_zero) &&
1381 !(flags & CLONE_NEWUSER)) ||
1382 (map_zero && (uid_map != NULL || gid_map != NULL)))
1385 args.argv = &argv[optind];
1387 /* We use a pipe to synchronize the parent and child, in order to
1388 ensure that the parent sets the UID and GID maps before the child
1389 calls execve(). This ensures that the child maintains its
1390 capabilities during the execve() in the common case where we
1391 want to map the child\(aqs effective user ID to 0 in the new user
1392 namespace. Without this synchronization, the child would lose
1393 its capabilities if it performed an execve() with nonzero
1394 user IDs (see the capabilities(7) man page for details of the
1395 transformation of a process\(aqs capabilities during execve()). */
1397 if (pipe(args.pipe_fd) == \-1)
1400 /* Create the child in new namespace(s). */
1402 child_pid = clone(childFunc, child_stack + STACK_SIZE,
1403 flags | SIGCHLD, &args);
1404 if (child_pid == \-1)
1407 /* Parent falls through to here. */
1410 printf("%s: PID of child created by clone() is %jd\en",
1411 argv[0], (intmax_t) child_pid);
1413 /* Update the UID and GID maps in the child. */
1415 if (uid_map != NULL || map_zero) {
1416 snprintf(map_path, PATH_MAX, "/proc/%jd/uid_map",
1417 (intmax_t) child_pid);
1419 snprintf(map_buf, MAP_BUF_SIZE, "0 %jd 1",
1420 (intmax_t) getuid());
1423 update_map(uid_map, map_path);
1426 if (gid_map != NULL || map_zero) {
1427 proc_setgroups_write(child_pid, "deny");
1429 snprintf(map_path, PATH_MAX, "/proc/%jd/gid_map",
1430 (intmax_t) child_pid);
1432 snprintf(map_buf, MAP_BUF_SIZE, "0 %ld 1",
1433 (intmax_t) getgid());
1436 update_map(gid_map, map_path);
1439 /* Close the write end of the pipe, to signal to the child that we
1440 have updated the UID and GID maps. */
1442 close(args.pipe_fd[1]);
1444 if (waitpid(child_pid, NULL, 0) == \-1) /* Wait for child */
1448 printf("%s: terminating\en", argv[0]);
1454 .BR newgidmap (1), \" From the shadow package
1455 .BR newuidmap (1), \" From the shadow package
1461 .BR subgid (5), \" From the shadow package
1462 .BR subuid (5), \" From the shadow package
1463 .BR capabilities (7),
1464 .BR cgroup_namespaces (7),
1465 .BR credentials (7),
1467 .BR pid_namespaces (7)
1469 The kernel source file
1470 .IR Documentation/admin\-guide/namespaces/resource\-control.rst .