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 2016-07-17 "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.
108 .\" ============================================================
111 The child process created by
115 flag starts out with a complete set
116 of capabilities in the new user namespace.
117 Likewise, a process that creates a new user namespace using
119 or joins an existing user namespace using
121 gains a full set of capabilities in that namespace.
123 that process has no capabilities in the parent (in the case of
125 or previous (in the case of
130 even if the new namespace is created or joined by the root user
131 (i.e., a process with user ID 0 in the root namespace).
135 will cause a process's capabilities to be recalculated in the usual way (see
136 .BR capabilities (7)).
138 unless the process has a user ID of 0 within the namespace,
139 or the executable file has a nonempty inheritable capabilities mask,
140 the process will lose all capabilities.
141 See the discussion of user and group ID mappings, below.
150 flag sets the "securebits" flags
152 .BR capabilities (7))
153 to their default values (all flags disabled) in the child (for
159 Note that because the caller no longer has capabilities
160 in its original user namespace after a call to
162 it is not possible for a process to reset its "securebits" flags while
163 retaining its user namespace membership by using a pair of
165 calls to move to another user namespace and then return to
166 its original user namespace.
168 The rules for determining whether or not a process has a capability
169 in a particular user namespace are as follows:
171 A process has a capability inside a user namespace
172 if it is a member of that namespace and
173 it has the capability in its effective capability set.
174 A process can gain capabilities in its effective capability
176 For example, it may execute a set-user-ID program or an
177 executable with associated file capabilities.
179 a process may gain capabilities via the effect of
184 as already described.
185 .\" In the 3.8 sources, see security/commoncap.c::cap_capable():
187 If a process has a capability in a user namespace,
188 then it has that capability in all child (and further removed descendant)
191 .\" * The owner of the user namespace in the parent of the
192 .\" * user namespace has all caps.
193 When a user namespace is created, the kernel records the effective
194 user ID of the creating process as being the "owner" of the namespace.
195 .\" (and likewise associates the effective group ID of the creating process
196 .\" with the namespace).
197 A process that resides
198 in the parent of the user namespace
199 .\" See kernel commit 520d9eabce18edfef76a60b7b839d54facafe1f9 for a fix
201 and whose effective user ID matches the owner of the namespace
202 has all capabilities in the namespace.
203 .\" This includes the case where the process executes a set-user-ID
204 .\" program that confers the effective UID of the creator of the namespace.
205 By virtue of the previous rule,
206 this means that the process has all capabilities in all
207 further removed descendant user namespaces as well.
209 .\" ============================================================
211 .SS Effect of capabilities within a user namespace
212 Having a capability inside a user namespace
213 permits a process to perform operations (that require privilege)
214 only on resources governed by that namespace.
215 In other words, having a capability in a user namespace permits a process
216 to perform privileged operations on resources that are governed by (nonuser)
217 namespaces associated with the user namespace (see the next subsection).
219 On the other hand, there are many privileged operations that affect
220 resources that are not associated with any namespace type,
221 for example, changing the system time (governed by
223 loading a kernel module (governed by
224 .BR CAP_SYS_MODULE ),
225 and creating a device (governed by
227 Only a process with privileges in the
229 user namespace can perform such operations.
233 within the user namespace associated with a process's mount namespace
234 allows that process to create bind mounts
235 and mount the following types of filesystems:
236 .\" fs_flags = FS_USERNS_MOUNT in kernel sources
260 .\" commit b2197755b2633e164a439682fb05a9b5ea48f706
267 within the user namespace associated with a process's cgroup namespace
268 allows (since Linux 4.6)
269 that process to the mount cgroup version 2 filesystem and
270 cgroup version 1 named hierarchies
271 (i.e., cgroup filesystems mounted with the
277 within the user namespace associated with a process's PID namespace
278 allows (since Linux 3.8)
279 that process to mount
283 Note however, that mounting block-based filesystems can be done
284 only by a process that holds
286 in the initial user namespace.
288 .\" ============================================================
290 .SS Interaction of user namespaces and other types of namespaces
291 Starting in Linux 3.8, unprivileged processes can create user namespaces,
292 and other the other types of namespaces can be created with just the
294 capability in the caller's user namespace.
296 When a non-user-namespace is created,
297 it is owned by the user namespace in which the creating process
298 was a member at the time of the creation of the namespace.
299 Actions on the non-user-namespace
300 require capabilities in the corresponding user namespace.
304 is specified along with other
310 call, the user namespace is guaranteed to be created first,
315 privileges over the remaining namespaces created by the call.
316 Thus, it is possible for an unprivileged caller to specify this combination
319 When a new namespace (other than a user namespace) is created via
323 the kernel records the user namespace of the creating process against
325 (This association can't be changed.)
326 When a process in the new namespace subsequently performs
327 privileged operations that operate on global
328 resources isolated by the namespace,
329 the permission checks are performed according to the process's capabilities
330 in the user namespace that the kernel associated with the new namespace.
331 For example, suppose that a process attempts to change the hostname
332 .RB ( sethostname (2)),
333 a resource governed by the UTS namespace.
335 the kernel will determine which user namespace is associated with
336 the process's UTS namespace, and check whether the process has the
338 .RB ( CAP_SYS_ADMIN )
339 in that user namespace.
341 .\" ============================================================
343 .SS Restrictions on mount namespaces
344 Note the following points with respect to mount namespaces:
346 A mount namespace has an owner user namespace.
347 A mount namespace whose owner user namespace is different from
348 the owner user namespace of its parent mount namespace is
349 considered a less privileged mount namespace.
351 When creating a less privileged mount namespace,
352 shared mounts are reduced to slave mounts.
353 This ensures that mappings performed in less
354 privileged mount namespaces will not propagate to more privileged
358 .\" What does "come as a single unit from more privileged mount" mean?
359 Mounts that come as a single unit from more privileged mount are
360 locked together and may not be separated in a less privileged mount
365 operation brings across all of the mounts from the original
366 mount namespace as a single unit,
367 and recursive mounts that propagate between
368 mount namespaces propagate as a single unit.)
376 and the "atime" flags
380 settings become locked
381 .\" commit 9566d6742852c527bf5af38af5cbb878dad75705
382 .\" Author: Eric W. Biederman <ebiederm@xmission.com>
383 .\" Date: Mon Jul 28 17:26:07 2014 -0700
385 .\" mnt: Correct permission checks in do_remount
387 when propagated from a more privileged to
388 a less privileged mount namespace,
389 and may not be changed in the less privileged mount namespace.
391 .\" (As of 3.18-rc1 (in Al Viro's 2014-08-30 vfs.git#for-next tree))
392 A file or directory that is a mount point in one namespace that is not
393 a mount point in another namespace, may be renamed, unlinked, or removed
395 in the mount namespace in which it is not a mount point
396 (subject to the usual permission checks).
398 Previously, attempting to unlink, rename, or remove a file or directory
399 that was a mount point in another mount namespace would result in the error
401 That behavior had technical problems of enforcement (e.g., for NFS)
402 and permitted denial-of-service attacks against more privileged users.
403 (i.e., preventing individual files from being updated
404 by bind mounting on top of them).
406 .\" ============================================================
408 .SS User and group ID mappings: uid_map and gid_map
409 When a user namespace is created,
410 it starts out without a mapping of user IDs (group IDs)
411 to the parent user namespace.
413 .IR /proc/[pid]/uid_map
415 .IR /proc/[pid]/gid_map
416 files (available since Linux 3.5)
417 .\" commit 22d917d80e842829d0ca0a561967d728eb1d6303
418 expose the mappings for user and group IDs
419 inside the user namespace for the process
421 These files can be read to view the mappings in a user namespace and
422 written to (once) to define the mappings.
424 The description in the following paragraphs explains the details for
428 but each instance of "user ID" is replaced by "group ID".
432 file exposes the mapping of user IDs from the user namespace
435 to the user namespace of the process that opened
437 (but see a qualification to this point below).
438 In other words, processes that are in different user namespaces
439 will potentially see different values when reading from a particular
441 file, depending on the user ID mappings for the user namespaces
442 of the reading processes.
446 file specifies a 1-to-1 mapping of a range of contiguous
447 user IDs between two user namespaces.
448 (When a user namespace is first created, this file is empty.)
449 The specification in each line takes the form of
450 three numbers delimited by white space.
451 The first two numbers specify the starting user ID in
452 each of the two user namespaces.
453 The third number specifies the length of the mapped range.
454 In detail, the fields are interpreted as follows:
456 The start of the range of user IDs in
457 the user namespace of the process
460 The start of the range of user
461 IDs to which the user IDs specified by field one map.
462 How field two is interpreted depends on whether the process that opened
466 are in the same user namespace, as follows:
469 If the two processes are in different user namespaces:
470 field two is the start of a range of
471 user IDs in the user namespace of the process that opened
474 If the two processes are in the same user namespace:
475 field two is the start of the range of
476 user IDs in the parent user namespace of the process
478 This case enables the opener of
480 (the common case here is opening
481 .IR /proc/self/uid_map )
482 to see the mapping of user IDs into the user namespace of the process
483 that created this user namespace.
486 The length of the range of user IDs that is mapped between the two
489 System calls that return user IDs (group IDs)\(emfor example,
492 and the credential fields in the structure returned by
493 .BR stat (2)\(emreturn
494 the user ID (group ID) mapped into the caller's user namespace.
496 When a process accesses a file, its user and group IDs
497 are mapped into the initial user namespace for the purpose of permission
498 checking and assigning IDs when creating a file.
499 When a process retrieves file user and group IDs via
501 the IDs are mapped in the opposite direction,
502 to produce values relative to the process user and group ID mappings.
504 The initial user namespace has no parent namespace,
505 but, for consistency, the kernel provides dummy user and group
506 ID mapping files for this namespace.
511 is the same) from a shell in the initial namespace shows:
515 $ \fBcat /proc/$$/uid_map\fP
520 This mapping tells us
521 that the range starting at user ID 0 in this namespace
522 maps to a range starting at 0 in the (nonexistent) parent namespace,
523 and the length of the range is the largest 32-bit unsigned integer.
524 This leaves 4294967295 (the 32-bit signed \-1 value) unmapped.
527 is used in several interfaces (e.g.,
529 as a way to specify "no user ID".
532 unmapped and unusable guarantees that there will be no
533 confusion when using these interfaces.
535 .\" ============================================================
537 .SS Defining user and group ID mappings: writing to uid_map and gid_map
539 After the creation of a new user namespace, the
543 of the processes in the namespace may be written to
545 to define the mapping of user IDs in the new user namespace.
546 An attempt to write more than once to a
548 file in a user namespace fails with the error
550 Similar rules apply for
557 must conform to the following rules:
559 The three fields must be valid numbers,
560 and the last field must be greater than 0.
562 Lines are terminated by newline characters.
564 There is an (arbitrary) limit on the number of lines in the file.
565 As at Linux 3.18, the limit is five lines.
566 In addition, the number of bytes written to
567 the file must be less than the system page size,
568 .\" FIXME(Eric): the restriction "less than" rather than "less than or equal"
569 .\" seems strangely arbitrary. Furthermore, the comment does not agree
570 .\" with the code in kernel/user_namespace.c. Which is correct?
571 and the write must be performed at the start of the file (i.e.,
575 can't be used to write to nonzero offsets in the file).
577 The range of user IDs (group IDs)
578 specified in each line cannot overlap with the ranges
580 In the initial implementation (Linux 3.8), this requirement was
581 satisfied by a simplistic implementation that imposed the further
583 the values in both field 1 and field 2 of successive lines must be
584 in ascending numerical order,
585 which prevented some otherwise valid maps from being created.
587 .\" commit 0bd14b4fd72afd5df41e9fd59f356740f22fceba
588 fix this limitation, allowing any valid set of nonoverlapping maps.
590 At least one line must be written to the file.
592 Writes that violate the above rules fail with the error
595 In order for a process to write to the
596 .I /proc/[pid]/uid_map
597 .RI ( /proc/[pid]/gid_map )
598 file, all of the following requirements must be met:
600 The writing process must have the
603 capability in the user namespace of the process
606 The writing process must either be in the user namespace of the process
608 or be in the parent user namespace of the process
611 The mapped user IDs (group IDs) must in turn have a mapping
612 in the parent user namespace.
614 One of the following two cases applies:
618 the writing process has the
626 No further restrictions apply:
627 the process can make mappings to arbitrary user IDs (group IDs)
628 in the parent user namespace.
632 otherwise all of the following restrictions apply:
638 must consist of a single line that maps
639 the writing process's effective user ID
640 (group ID) in the parent user namespace to a user ID (group ID)
641 in the user namespace.
643 The writing process must have the same effective user ID as the process
644 that created the user namespace.
650 system call must first be denied by writing
653 .I /proc/[pid]/setgroups
654 file (see below) before writing to
659 Writes that violate the above rules fail with the error
662 .\" ============================================================
664 .SS Interaction with system calls that change process UIDs or GIDs
665 In a user namespace where the
667 file has not been written, the system calls that change user IDs will fail.
670 file has not been written, the system calls that change group IDs will fail.
675 files have been written, only the mapped values may be used in
676 system calls that change user and group IDs.
678 For user IDs, the relevant system calls include
684 For group IDs, the relevant system calls include
695 .I /proc/[pid]/setgroups
696 file before writing to
697 .I /proc/[pid]/gid_map
698 .\" Things changed in Linux 3.19
699 .\" commit 9cc46516ddf497ea16e8d7cb986ae03a0f6b92f8
700 .\" commit 66d2f338ee4c449396b6f99f5e75cd18eb6df272
701 .\" http://lwn.net/Articles/626665/
702 will permanently disable
704 in a user namespace and allow writing to
705 .I /proc/[pid]/gid_map
708 capability in the parent user namespace.
710 .\" ============================================================
712 .SS The /proc/[pid]/setgroups file
714 .\" commit 9cc46516ddf497ea16e8d7cb986ae03a0f6b92f8
715 .\" commit 66d2f338ee4c449396b6f99f5e75cd18eb6df272
716 .\" http://lwn.net/Articles/626665/
717 .\" http://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2014-8989
720 .I /proc/[pid]/setgroups
721 file displays the string
723 if processes in the user namespace that contains the process
725 are permitted to employ the
727 system call; it displays
731 is not permitted in that user namespace.
732 Note that regardless of the value in the
733 .I /proc/[pid]/setgroups
734 file (and regardless of the process's capabilities), calls to
736 are also not permitted if
737 .IR /proc/[pid]/gid_map
738 has not yet been set.
740 A privileged process (one with the
742 capability in the namespace) may write either of the strings
748 writing a group ID mapping
749 for this user namespace to the file
750 .IR /proc/[pid]/gid_map .
753 prevents any process in the user namespace from employing
756 The essence of the restrictions described in the preceding
757 paragraph is that it is permitted to write to
758 .I /proc/[pid]/setgroups
759 only so long as calling
761 is disallowed because
762 .I /proc/[pid]gid_map
764 This ensures that a process cannot transition from a state where
766 is allowed to a state where
769 a process can transition only from
775 The default value of this file in the initial user namespace is
779 .IR /proc/[pid]/gid_map
781 (which has the effect of enabling
783 in the user namespace),
784 it is no longer possible to disallow
789 .IR /proc/[pid]/setgroups
790 (the write fails with the error
793 A child user namespace inherits the
794 .IR /proc/[pid]/setgroups
795 setting from its parent.
803 system call can't subsequently be reenabled (by writing
805 to the file) in this user namespace.
806 (Attempts to do so will fail with the error
808 This restriction also propagates down to all child user namespaces of
812 .I /proc/[pid]/setgroups
813 file was added in Linux 3.19,
814 but was backported to many earlier stable kernel series,
815 because it addresses a security issue.
816 The issue concerned files with permissions such as "rwx\-\-\-rwx".
817 Such files give fewer permissions to "group" than they do to "other".
818 This means that dropping groups using
820 might allow a process file access that it did not formerly have.
821 Before the existence of user namespaces this was not a concern,
822 since only a privileged process (one with the
824 capability) could call
826 However, with the introduction of user namespaces,
827 it became possible for an unprivileged process to create
828 a new namespace in which the user had all privileges.
829 This then allowed formerly unprivileged
830 users to drop groups and thus gain file access
831 that they did not previously have.
833 .I /proc/[pid]/setgroups
834 file was added to address this security issue,
835 by denying any pathway for an unprivileged process to drop groups with
838 .\" /proc/PID/setgroups
839 .\" [allow == setgroups() is allowed, "deny" == setgroups() is disallowed]
840 .\" * Can write if have CAP_SYS_ADMIN in NS
841 .\" * Must write BEFORE writing to /proc/PID/gid_map
844 .\" * Must already have written to gid_maps
845 .\" * /proc/PID/setgroups must be "allow"
847 .\" /proc/PID/gid_map -- writing
848 .\" * Must already have written "deny" to /proc/PID/setgroups
850 .\" ============================================================
852 .SS Unmapped user and group IDs
854 There are various places where an unmapped user ID (group ID)
855 may be exposed to user space.
856 For example, the first process in a new user namespace may call
858 before a user ID mapping has been defined for the namespace.
859 In most such cases, an unmapped user ID is converted
860 .\" from_kuid_munged(), from_kgid_munged()
861 to the overflow user ID (group ID);
862 the default value for the overflow user ID (group ID) is 65534.
863 See the descriptions of
864 .IR /proc/sys/kernel/overflowuid
866 .IR /proc/sys/kernel/overflowgid
870 The cases where unmapped IDs are mapped in this fashion include
871 system calls that return user IDs
875 credentials passed over a UNIX domain socket,
877 credentials returned by
880 and the System V IPC "ctl"
883 credentials exposed by
884 .IR /proc/[pid]/status
886 .IR /proc/sysvipc/* ,
887 credentials returned via the
891 received with a signal (see
893 credentials written to the process accounting file (see
895 and credentials returned with POSIX message queue notifications (see
898 There is one notable case where unmapped user and group IDs are
900 .\" from_kuid(), from_kgid()
901 .\" Also F_GETOWNER_UIDS is an exception
902 converted to the corresponding overflow ID value.
907 file in which there is no mapping for the second field,
908 that field is displayed as 4294967295 (\-1 as an unsigned integer);
910 .\" ============================================================
912 .SS Set-user-ID and set-group-ID programs
914 When a process inside a user namespace executes
915 a set-user-ID (set-group-ID) program,
916 the process's effective user (group) ID inside the namespace is changed
917 to whatever value is mapped for the user (group) ID of the file.
918 However, if either the user
920 the group ID of the file has no mapping inside the namespace,
921 the set-user-ID (set-group-ID) bit is silently ignored:
922 the new program is executed,
923 but the process's effective user (group) ID is left unchanged.
924 (This mirrors the semantics of executing a set-user-ID or set-group-ID
925 program that resides on a filesystem that was mounted with the
927 flag, as described in
930 .\" ============================================================
934 When a process's user and group IDs are passed over a UNIX domain socket
935 to a process in a different user namespace (see the description of
939 they are translated into the corresponding values as per the
940 receiving process's user and group ID mappings.
943 Namespaces are a Linux-specific feature.
946 Over the years, there have been a lot of features that have been added
947 to the Linux kernel that have been made available only to privileged users
948 because of their potential to confuse set-user-ID-root applications.
949 In general, it becomes safe to allow the root user in a user namespace to
950 use those features because it is impossible, while in a user namespace,
951 to gain more privilege than the root user of a user namespace has.
953 .\" ============================================================
956 Use of user namespaces requires a kernel that is configured with the
959 User namespaces require support in a range of subsystems across
961 When an unsupported subsystem is configured into the kernel,
962 it is not possible to configure user namespaces support.
964 As at Linux 3.8, most relevant subsystems supported user namespaces,
965 but a number of filesystems did not have the infrastructure needed
966 to map user and group IDs between user namespaces.
967 Linux 3.9 added the required infrastructure support for many of
968 the remaining unsupported filesystems
969 (Plan 9 (9P), Andrew File System (AFS), Ceph, CIFS, CODA, NFS, and OCFS2).
970 Linux 3.12 added support the last of the unsupported major filesystems,
971 .\" commit d6970d4b726cea6d7a9bc4120814f95c09571fc3
975 The program below is designed to allow experimenting with
976 user namespaces, as well as other types of namespaces.
977 It creates namespaces as specified by command-line options and then executes
978 a command inside those namespaces.
981 function inside the program provide a full explanation of the program.
982 The following shell session demonstrates its use.
984 First, we look at the run-time environment:
988 $ \fBuname -rs\fP # Need Linux 3.8 or later
990 $ \fBid -u\fP # Running as unprivileged user
997 Now start a new shell in new user
1003 namespaces, with user ID
1007 1000 mapped to 0 inside the user namespace:
1011 $ \fB./userns_child_exec -p -m -U -M '0 1000 1' -G '0 1000 1' bash\fP
1015 The shell has PID 1, because it is the first process in the new
1025 Inside the user namespace, the shell has user and group ID 0,
1026 and a full set of permitted and effective capabilities:
1030 bash$ \fBcat /proc/$$/status | egrep '^[UG]id'\fP
1033 bash$ \fBcat /proc/$$/status | egrep '^Cap(Prm|Inh|Eff)'\fP
1034 CapInh: 0000000000000000
1035 CapPrm: 0000001fffffffff
1036 CapEff: 0000001fffffffff
1042 filesystem and listing all of the processes visible
1043 in the new PID namespace shows that the shell can't see
1044 any processes outside the PID namespace:
1048 bash$ \fBmount -t proc proc /proc\fP
1050 PID TTY STAT TIME COMMAND
1052 22 pts/3 R+ 0:00 ps ax
1058 /* userns_child_exec.c
1060 Licensed under GNU General Public License v2 or later
1062 Create a child process that executes a shell command in new
1063 namespace(s); allow UID and GID mappings to be specified when
1064 creating a user namespace.
1070 #include <sys/wait.h>
1078 /* A simple error\-handling function: print an error message based
1079 on the value in \(aqerrno\(aq and terminate the calling process */
1081 #define errExit(msg) do { perror(msg); exit(EXIT_FAILURE); \\
1085 char **argv; /* Command to be executed by child, with args */
1086 int pipe_fd[2]; /* Pipe used to synchronize parent and child */
1094 fprintf(stderr, "Usage: %s [options] cmd [arg...]\\n\\n", pname);
1095 fprintf(stderr, "Create a child process that executes a shell "
1096 "command in a new user namespace,\\n"
1097 "and possibly also other new namespace(s).\\n\\n");
1098 fprintf(stderr, "Options can be:\\n\\n");
1099 #define fpe(str) fprintf(stderr, " %s", str);
1100 fpe("\-i New IPC namespace\\n");
1101 fpe("\-m New mount namespace\\n");
1102 fpe("\-n New network namespace\\n");
1103 fpe("\-p New PID namespace\\n");
1104 fpe("\-u New UTS namespace\\n");
1105 fpe("\-U New user namespace\\n");
1106 fpe("\-M uid_map Specify UID map for user namespace\\n");
1107 fpe("\-G gid_map Specify GID map for user namespace\\n");
1108 fpe("\-z Map user\(aqs UID and GID to 0 in user namespace\\n");
1109 fpe(" (equivalent to: \-M \(aq0 <uid> 1\(aq \-G \(aq0 <gid> 1\(aq)\\n");
1110 fpe("\-v Display verbose messages\\n");
1112 fpe("If \-z, \-M, or \-G is specified, \-U is required.\\n");
1113 fpe("It is not permitted to specify both \-z and either \-M or \-G.\\n");
1115 fpe("Map strings for \-M and \-G consist of records of the form:\\n");
1117 fpe(" ID\-inside\-ns ID\-outside\-ns len\\n");
1119 fpe("A map string can contain multiple records, separated"
1121 fpe("the commas are replaced by newlines before writing"
1122 " to map files.\\n");
1127 /* Update the mapping file \(aqmap_file\(aq, with the value provided in
1128 \(aqmapping\(aq, a string that defines a UID or GID mapping. A UID or
1129 GID mapping consists of one or more newline\-delimited records
1132 ID_inside\-ns ID\-outside\-ns length
1134 Requiring the user to supply a string that contains newlines is
1135 of course inconvenient for command\-line use. Thus, we permit the
1136 use of commas to delimit records in this string, and replace them
1137 with newlines before writing the string to the file. */
1140 update_map(char *mapping, char *map_file)
1143 size_t map_len; /* Length of \(aqmapping\(aq */
1145 /* Replace commas in mapping string with newlines */
1147 map_len = strlen(mapping);
1148 for (j = 0; j < map_len; j++)
1149 if (mapping[j] == \(aq,\(aq)
1150 mapping[j] = \(aq\\n\(aq;
1152 fd = open(map_file, O_RDWR);
1154 fprintf(stderr, "ERROR: open %s: %s\\n", map_file,
1159 if (write(fd, mapping, map_len) != map_len) {
1160 fprintf(stderr, "ERROR: write %s: %s\\n", map_file,
1168 /* Linux 3.19 made a change in the handling of setgroups(2) and the
1169 \(aqgid_map\(aq file to address a security issue. The issue allowed
1170 *unprivileged* users to employ user namespaces in order to drop
1171 The upshot of the 3.19 changes is that in order to update the
1172 \(aqgid_maps\(aq file, use of the setgroups() system call in this
1173 user namespace must first be disabled by writing "deny" to one of
1174 the /proc/PID/setgroups files for this namespace. That is the
1175 purpose of the following function. */
1178 proc_setgroups_write(pid_t child_pid, char *str)
1180 char setgroups_path[PATH_MAX];
1183 snprintf(setgroups_path, PATH_MAX, "/proc/%ld/setgroups",
1186 fd = open(setgroups_path, O_RDWR);
1189 /* We may be on a system that doesn\(aqt support
1190 /proc/PID/setgroups. In that case, the file won\(aqt exist,
1191 and the system won\(aqt impose the restrictions that Linux 3.19
1192 added. That\(aqs fine: we don\(aqt need to do anything in order
1193 to permit \(aqgid_map\(aq to be updated.
1195 However, if the error from open() was something other than
1196 the ENOENT error that is expected for that case, let the
1199 if (errno != ENOENT)
1200 fprintf(stderr, "ERROR: open %s: %s\\n", setgroups_path,
1205 if (write(fd, str, strlen(str)) == \-1)
1206 fprintf(stderr, "ERROR: write %s: %s\\n", setgroups_path,
1212 static int /* Start function for cloned child */
1213 childFunc(void *arg)
1215 struct child_args *args = (struct child_args *) arg;
1218 /* Wait until the parent has updated the UID and GID mappings.
1219 See the comment in main(). We wait for end of file on a
1220 pipe that will be closed by the parent process once it has
1221 updated the mappings. */
1223 close(args\->pipe_fd[1]); /* Close our descriptor for the write
1224 end of the pipe so that we see EOF
1225 when parent closes its descriptor */
1226 if (read(args\->pipe_fd[0], &ch, 1) != 0) {
1228 "Failure in child: read from pipe returned != 0\\n");
1232 /* Execute a shell command */
1234 printf("About to exec %s\\n", args\->argv[0]);
1235 execvp(args\->argv[0], args\->argv);
1239 #define STACK_SIZE (1024 * 1024)
1241 static char child_stack[STACK_SIZE]; /* Space for child\(aqs stack */
1244 main(int argc, char *argv[])
1246 int flags, opt, map_zero;
1248 struct child_args args;
1249 char *uid_map, *gid_map;
1250 const int MAP_BUF_SIZE = 100;
1251 char map_buf[MAP_BUF_SIZE];
1252 char map_path[PATH_MAX];
1254 /* Parse command\-line options. The initial \(aq+\(aq character in
1255 the final getopt() argument prevents GNU\-style permutation
1256 of command\-line options. That\(aqs useful, since sometimes
1257 the \(aqcommand\(aq to be executed by this program itself
1258 has command\-line options. We don\(aqt want getopt() to treat
1259 those as options to this program. */
1266 while ((opt = getopt(argc, argv, "+imnpuUM:G:zv")) != \-1) {
1268 case \(aqi\(aq: flags |= CLONE_NEWIPC; break;
1269 case \(aqm\(aq: flags |= CLONE_NEWNS; break;
1270 case \(aqn\(aq: flags |= CLONE_NEWNET; break;
1271 case \(aqp\(aq: flags |= CLONE_NEWPID; break;
1272 case \(aqu\(aq: flags |= CLONE_NEWUTS; break;
1273 case \(aqv\(aq: verbose = 1; break;
1274 case \(aqz\(aq: map_zero = 1; break;
1275 case \(aqM\(aq: uid_map = optarg; break;
1276 case \(aqG\(aq: gid_map = optarg; break;
1277 case \(aqU\(aq: flags |= CLONE_NEWUSER; break;
1278 default: usage(argv[0]);
1282 /* \-M or \-G without \-U is nonsensical */
1284 if (((uid_map != NULL || gid_map != NULL || map_zero) &&
1285 !(flags & CLONE_NEWUSER)) ||
1286 (map_zero && (uid_map != NULL || gid_map != NULL)))
1289 args.argv = &argv[optind];
1291 /* We use a pipe to synchronize the parent and child, in order to
1292 ensure that the parent sets the UID and GID maps before the child
1293 calls execve(). This ensures that the child maintains its
1294 capabilities during the execve() in the common case where we
1295 want to map the child\(aqs effective user ID to 0 in the new user
1296 namespace. Without this synchronization, the child would lose
1297 its capabilities if it performed an execve() with nonzero
1298 user IDs (see the capabilities(7) man page for details of the
1299 transformation of a process\(aqs capabilities during execve()). */
1301 if (pipe(args.pipe_fd) == \-1)
1304 /* Create the child in new namespace(s) */
1306 child_pid = clone(childFunc, child_stack + STACK_SIZE,
1307 flags | SIGCHLD, &args);
1308 if (child_pid == \-1)
1311 /* Parent falls through to here */
1314 printf("%s: PID of child created by clone() is %ld\\n",
1315 argv[0], (long) child_pid);
1317 /* Update the UID and GID maps in the child */
1319 if (uid_map != NULL || map_zero) {
1320 snprintf(map_path, PATH_MAX, "/proc/%ld/uid_map",
1323 snprintf(map_buf, MAP_BUF_SIZE, "0 %ld 1", (long) getuid());
1326 update_map(uid_map, map_path);
1329 if (gid_map != NULL || map_zero) {
1330 proc_setgroups_write(child_pid, "deny");
1332 snprintf(map_path, PATH_MAX, "/proc/%ld/gid_map",
1335 snprintf(map_buf, MAP_BUF_SIZE, "0 %ld 1", (long) getgid());
1338 update_map(gid_map, map_path);
1341 /* Close the write end of the pipe, to signal to the child that we
1342 have updated the UID and GID maps */
1344 close(args.pipe_fd[1]);
1346 if (waitpid(child_pid, NULL, 0) == \-1) /* Wait for child */
1350 printf("%s: terminating\\n", argv[0]);
1356 .BR newgidmap (1), \" From the shadow package
1357 .BR newuidmap (1), \" From the shadow package
1363 .BR subgid (5), \" From the shadow package
1364 .BR subuid (5), \" From the shadow package
1365 .BR capabilities (7),
1366 .BR cgroup_namespaces (7)
1367 .BR credentials (7),
1369 .BR pid_namespaces (7)
1371 The kernel source file
1372 .IR Documentation/namespaces/resource-control.txt .