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 2019-03-06 "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.
157 flag sets the "securebits" flags
159 .BR capabilities (7))
160 to their default values (all flags disabled) in the child (for
166 Note that because the caller no longer has capabilities
167 in its original user namespace after a call to
169 it is not possible for a process to reset its "securebits" flags while
170 retaining its user namespace membership by using a pair of
172 calls to move to another user namespace and then return to
173 its original user namespace.
175 The rules for determining whether or not a process has a capability
176 in a particular user namespace are as follows:
178 A process has a capability inside a user namespace
179 if it is a member of that namespace and
180 it has the capability in its effective capability set.
181 A process can gain capabilities in its effective capability
183 For example, it may execute a set-user-ID program or an
184 executable with associated file capabilities.
186 a process may gain capabilities via the effect of
191 as already described.
192 .\" In the 3.8 sources, see security/commoncap.c::cap_capable():
194 If a process has a capability in a user namespace,
195 then it has that capability in all child (and further removed descendant)
198 .\" * The owner of the user namespace in the parent of the
199 .\" * user namespace has all caps.
200 When a user namespace is created, the kernel records the effective
201 user ID of the creating process as being the "owner" of the namespace.
202 .\" (and likewise associates the effective group ID of the creating process
203 .\" with the namespace).
204 A process that resides
205 in the parent of the user namespace
206 .\" See kernel commit 520d9eabce18edfef76a60b7b839d54facafe1f9 for a fix
208 and whose effective user ID matches the owner of the namespace
209 has all capabilities in the namespace.
210 .\" This includes the case where the process executes a set-user-ID
211 .\" program that confers the effective UID of the creator of the namespace.
212 By virtue of the previous rule,
213 this means that the process has all capabilities in all
214 further removed descendant user namespaces as well.
218 operation can be used to discover the user ID of the owner of the namespace;
222 .\" ============================================================
224 .SS Effect of capabilities within a user namespace
225 Having a capability inside a user namespace
226 permits a process to perform operations (that require privilege)
227 only on resources governed by that namespace.
228 In other words, having a capability in a user namespace permits a process
229 to perform privileged operations on resources that are governed by (nonuser)
230 namespaces owned by (associated with) the user namespace
231 (see the next subsection).
233 On the other hand, there are many privileged operations that affect
234 resources that are not associated with any namespace type,
235 for example, changing the system time (governed by
237 loading a kernel module (governed by
238 .BR CAP_SYS_MODULE ),
239 and creating a device (governed by
241 Only a process with privileges in the
243 user namespace can perform such operations.
247 within the user namespace that owns a process's mount namespace
248 allows that process to create bind mounts
249 and mount the following types of filesystems:
250 .\" fs_flags = FS_USERNS_MOUNT in kernel sources
274 .\" commit b2197755b2633e164a439682fb05a9b5ea48f706
281 within the user namespace that owns a process's cgroup namespace
282 allows (since Linux 4.6)
283 that process to the mount the cgroup version 2 filesystem and
284 cgroup version 1 named hierarchies
285 (i.e., cgroup filesystems mounted with the
291 within the user namespace that owns a process's PID namespace
292 allows (since Linux 3.8)
293 that process to mount
297 Note however, that mounting block-based filesystems can be done
298 only by a process that holds
300 in the initial user namespace.
302 .\" ============================================================
304 .SS Interaction of user namespaces and other types of namespaces
305 Starting in Linux 3.8, unprivileged processes can create user namespaces,
306 and the other types of namespaces can be created with just the
308 capability in the caller's user namespace.
310 When a nonuser namespace is created,
311 it is owned by the user namespace in which the creating process
312 was a member at the time of the creation of the namespace.
313 Actions on the nonuser namespace
314 require capabilities in the corresponding user namespace.
318 is specified along with other
324 call, the user namespace is guaranteed to be created first,
329 privileges over the remaining namespaces created by the call.
330 Thus, it is possible for an unprivileged caller to specify this combination
333 When a new namespace (other than a user namespace) is created via
337 the kernel records the user namespace of the creating process as the owner of
339 (This association can't be changed.)
340 When a process in the new namespace subsequently performs
341 privileged operations that operate on global
342 resources isolated by the namespace,
343 the permission checks are performed according to the process's capabilities
344 in the user namespace that the kernel associated with the new namespace.
345 For example, suppose that a process attempts to change the hostname
346 .RB ( sethostname (2)),
347 a resource governed by the UTS namespace.
349 the kernel will determine which user namespace owns
350 the process's UTS namespace, and check whether the process has the
352 .RB ( CAP_SYS_ADMIN )
353 in that user namespace.
358 operation can be used to discover the user namespace
359 that owns a nonuser namespace; see
362 .\" ============================================================
364 .SS User and group ID mappings: uid_map and gid_map
365 When a user namespace is created,
366 it starts out without a mapping of user IDs (group IDs)
367 to the parent user namespace.
369 .IR /proc/[pid]/uid_map
371 .IR /proc/[pid]/gid_map
372 files (available since Linux 3.5)
373 .\" commit 22d917d80e842829d0ca0a561967d728eb1d6303
374 expose the mappings for user and group IDs
375 inside the user namespace for the process
377 These files can be read to view the mappings in a user namespace and
378 written to (once) to define the mappings.
380 The description in the following paragraphs explains the details for
384 but each instance of "user ID" is replaced by "group ID".
388 file exposes the mapping of user IDs from the user namespace
391 to the user namespace of the process that opened
393 (but see a qualification to this point below).
394 In other words, processes that are in different user namespaces
395 will potentially see different values when reading from a particular
397 file, depending on the user ID mappings for the user namespaces
398 of the reading processes.
402 file specifies a 1-to-1 mapping of a range of contiguous
403 user IDs between two user namespaces.
404 (When a user namespace is first created, this file is empty.)
405 The specification in each line takes the form of
406 three numbers delimited by white space.
407 The first two numbers specify the starting user ID in
408 each of the two user namespaces.
409 The third number specifies the length of the mapped range.
410 In detail, the fields are interpreted as follows:
412 The start of the range of user IDs in
413 the user namespace of the process
416 The start of the range of user
417 IDs to which the user IDs specified by field one map.
418 How field two is interpreted depends on whether the process that opened
422 are in the same user namespace, as follows:
425 If the two processes are in different user namespaces:
426 field two is the start of a range of
427 user IDs in the user namespace of the process that opened
430 If the two processes are in the same user namespace:
431 field two is the start of the range of
432 user IDs in the parent user namespace of the process
434 This case enables the opener of
436 (the common case here is opening
437 .IR /proc/self/uid_map )
438 to see the mapping of user IDs into the user namespace of the process
439 that created this user namespace.
442 The length of the range of user IDs that is mapped between the two
445 System calls that return user IDs (group IDs)\(emfor example,
448 and the credential fields in the structure returned by
449 .BR stat (2)\(emreturn
450 the user ID (group ID) mapped into the caller's user namespace.
452 When a process accesses a file, its user and group IDs
453 are mapped into the initial user namespace for the purpose of permission
454 checking and assigning IDs when creating a file.
455 When a process retrieves file user and group IDs via
457 the IDs are mapped in the opposite direction,
458 to produce values relative to the process user and group ID mappings.
460 The initial user namespace has no parent namespace,
461 but, for consistency, the kernel provides dummy user and group
462 ID mapping files for this namespace.
467 is the same) from a shell in the initial namespace shows:
471 $ \fBcat /proc/$$/uid_map\fP
476 This mapping tells us
477 that the range starting at user ID 0 in this namespace
478 maps to a range starting at 0 in the (nonexistent) parent namespace,
479 and the length of the range is the largest 32-bit unsigned integer.
480 This leaves 4294967295 (the 32-bit signed \-1 value) unmapped.
483 is used in several interfaces (e.g.,
485 as a way to specify "no user ID".
488 unmapped and unusable guarantees that there will be no
489 confusion when using these interfaces.
491 .\" ============================================================
493 .SS Defining user and group ID mappings: writing to uid_map and gid_map
495 After the creation of a new user namespace, the
499 of the processes in the namespace may be written to
501 to define the mapping of user IDs in the new user namespace.
502 An attempt to write more than once to a
504 file in a user namespace fails with the error
506 Similar rules apply for
513 must conform to the following rules:
515 The three fields must be valid numbers,
516 and the last field must be greater than 0.
518 Lines are terminated by newline characters.
520 There is a limit on the number of lines in the file.
521 In Linux 4.14 and earlier, this limit was (arbitrarily)
522 .\" 5*12-byte records could fit in a 64B cache line
525 .\" commit 6397fac4915ab3002dc15aae751455da1a852f25
526 the limit is 340 lines.
527 In addition, the number of bytes written to
528 the file must be less than the system page size,
529 and the write must be performed at the start of the file (i.e.,
533 can't be used to write to nonzero offsets in the file).
535 The range of user IDs (group IDs)
536 specified in each line cannot overlap with the ranges
538 In the initial implementation (Linux 3.8), this requirement was
539 satisfied by a simplistic implementation that imposed the further
541 the values in both field 1 and field 2 of successive lines must be
542 in ascending numerical order,
543 which prevented some otherwise valid maps from being created.
545 .\" commit 0bd14b4fd72afd5df41e9fd59f356740f22fceba
546 fix this limitation, allowing any valid set of nonoverlapping maps.
548 At least one line must be written to the file.
550 Writes that violate the above rules fail with the error
553 In order for a process to write to the
554 .I /proc/[pid]/uid_map
555 .RI ( /proc/[pid]/gid_map )
556 file, all of the following requirements must be met:
558 The writing process must have the
561 capability in the user namespace of the process
564 The writing process must either be in the user namespace of the process
566 or be in the parent user namespace of the process
569 The mapped user IDs (group IDs) must in turn have a mapping
570 in the parent user namespace.
572 One of the following two cases applies:
576 the writing process has the
584 No further restrictions apply:
585 the process can make mappings to arbitrary user IDs (group IDs)
586 in the parent user namespace.
590 otherwise all of the following restrictions apply:
596 must consist of a single line that maps
597 the writing process's effective user ID
598 (group ID) in the parent user namespace to a user ID (group ID)
599 in the user namespace.
601 The writing process must have the same effective user ID as the process
602 that created the user namespace.
608 system call must first be denied by writing
611 .I /proc/[pid]/setgroups
612 file (see below) before writing to
617 Writes that violate the above rules fail with the error
620 .\" ============================================================
622 .SS Interaction with system calls that change process UIDs or GIDs
623 In a user namespace where the
625 file has not been written, the system calls that change user IDs will fail.
628 file has not been written, the system calls that change group IDs will fail.
633 files have been written, only the mapped values may be used in
634 system calls that change user and group IDs.
636 For user IDs, the relevant system calls include
642 For group IDs, the relevant system calls include
653 .I /proc/[pid]/setgroups
654 file before writing to
655 .I /proc/[pid]/gid_map
656 .\" Things changed in Linux 3.19
657 .\" commit 9cc46516ddf497ea16e8d7cb986ae03a0f6b92f8
658 .\" commit 66d2f338ee4c449396b6f99f5e75cd18eb6df272
659 .\" http://lwn.net/Articles/626665/
660 will permanently disable
662 in a user namespace and allow writing to
663 .I /proc/[pid]/gid_map
666 capability in the parent user namespace.
668 .\" ============================================================
670 .SS The /proc/[pid]/setgroups file
672 .\" commit 9cc46516ddf497ea16e8d7cb986ae03a0f6b92f8
673 .\" commit 66d2f338ee4c449396b6f99f5e75cd18eb6df272
674 .\" http://lwn.net/Articles/626665/
675 .\" http://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2014-8989
678 .I /proc/[pid]/setgroups
679 file displays the string
681 if processes in the user namespace that contains the process
683 are permitted to employ the
685 system call; it displays
689 is not permitted in that user namespace.
690 Note that regardless of the value in the
691 .I /proc/[pid]/setgroups
692 file (and regardless of the process's capabilities), calls to
694 are also not permitted if
695 .IR /proc/[pid]/gid_map
696 has not yet been set.
698 A privileged process (one with the
700 capability in the namespace) may write either of the strings
706 writing a group ID mapping
707 for this user namespace to the file
708 .IR /proc/[pid]/gid_map .
711 prevents any process in the user namespace from employing
714 The essence of the restrictions described in the preceding
715 paragraph is that it is permitted to write to
716 .I /proc/[pid]/setgroups
717 only so long as calling
719 is disallowed because
720 .I /proc/[pid]gid_map
722 This ensures that a process cannot transition from a state where
724 is allowed to a state where
727 a process can transition only from
733 The default value of this file in the initial user namespace is
737 .IR /proc/[pid]/gid_map
739 (which has the effect of enabling
741 in the user namespace),
742 it is no longer possible to disallow
747 .IR /proc/[pid]/setgroups
748 (the write fails with the error
751 A child user namespace inherits the
752 .IR /proc/[pid]/setgroups
753 setting from its parent.
761 system call can't subsequently be reenabled (by writing
763 to the file) in this user namespace.
764 (Attempts to do so fail with the error
766 This restriction also propagates down to all child user namespaces of
770 .I /proc/[pid]/setgroups
771 file was added in Linux 3.19,
772 but was backported to many earlier stable kernel series,
773 because it addresses a security issue.
774 The issue concerned files with permissions such as "rwx\-\-\-rwx".
775 Such files give fewer permissions to "group" than they do to "other".
776 This means that dropping groups using
778 might allow a process file access that it did not formerly have.
779 Before the existence of user namespaces this was not a concern,
780 since only a privileged process (one with the
782 capability) could call
784 However, with the introduction of user namespaces,
785 it became possible for an unprivileged process to create
786 a new namespace in which the user had all privileges.
787 This then allowed formerly unprivileged
788 users to drop groups and thus gain file access
789 that they did not previously have.
791 .I /proc/[pid]/setgroups
792 file was added to address this security issue,
793 by denying any pathway for an unprivileged process to drop groups with
796 .\" /proc/PID/setgroups
797 .\" [allow == setgroups() is allowed, "deny" == setgroups() is disallowed]
798 .\" * Can write if have CAP_SYS_ADMIN in NS
799 .\" * Must write BEFORE writing to /proc/PID/gid_map
802 .\" * Must already have written to gid_map
803 .\" * /proc/PID/setgroups must be "allow"
805 .\" /proc/PID/gid_map -- writing
806 .\" * Must already have written "deny" to /proc/PID/setgroups
808 .\" ============================================================
810 .SS Unmapped user and group IDs
812 There are various places where an unmapped user ID (group ID)
813 may be exposed to user space.
814 For example, the first process in a new user namespace may call
816 before a user ID mapping has been defined for the namespace.
817 In most such cases, an unmapped user ID is converted
818 .\" from_kuid_munged(), from_kgid_munged()
819 to the overflow user ID (group ID);
820 the default value for the overflow user ID (group ID) is 65534.
821 See the descriptions of
822 .IR /proc/sys/kernel/overflowuid
824 .IR /proc/sys/kernel/overflowgid
828 The cases where unmapped IDs are mapped in this fashion include
829 system calls that return user IDs
833 credentials passed over a UNIX domain socket,
835 credentials returned by
838 and the System V IPC "ctl"
841 credentials exposed by
842 .IR /proc/[pid]/status
844 .IR /proc/sysvipc/* ,
845 credentials returned via the
849 received with a signal (see
851 credentials written to the process accounting file (see
853 and credentials returned with POSIX message queue notifications (see
856 There is one notable case where unmapped user and group IDs are
858 .\" from_kuid(), from_kgid()
859 .\" Also F_GETOWNER_UIDS is an exception
860 converted to the corresponding overflow ID value.
865 file in which there is no mapping for the second field,
866 that field is displayed as 4294967295 (\-1 as an unsigned integer).
868 .\" ============================================================
872 In order to determine permissions when an unprivileged process accesses a file
873 (or other resource such as a System V IPC object),
874 the process credentials (UID, GID) and the file credentials
875 are in effect mapped back to what they would be in
876 the initial user namespace and then compared to determine
877 the permissions that the process has on the file.
879 .\" ============================================================
881 .SS Operation of file-related capabilities
883 Certain capabilities allow a process to bypass various
884 kernel-enforced restrictions when performing operations on
885 files owned by other users or groups.
886 These capabilities are:
888 .BR CAP_DAC_OVERRIDE ,
889 .BR CAP_DAC_READ_SEARCH ,
894 Within a user namespace,
895 these capabilities allow a process to bypass the rules
896 if the process has the relevant capability over the file,
899 the process has the relevant effective capability in its user namespace; and
901 the file's user ID and group ID both have valid mappings
902 in the user namespace.
906 capability is treated somewhat exceptionally:
907 most of the checks that it governs can be bypassed so long as
908 just the file's user ID has a mapping in the user namespace
909 .\" These are the checks performed by the kernel function
910 .\" inode_owner_or_capable(). There is one exception to the exception:
911 .\" overriding the directory sticky permission bit requires that
912 .\" the file has a valid mapping for both its UID and GID.
913 (i.e., the file's group ID does not need to have a valid mapping).
915 .\" ============================================================
917 .SS Set-user-ID and set-group-ID programs
919 When a process inside a user namespace executes
920 a set-user-ID (set-group-ID) program,
921 the process's effective user (group) ID inside the namespace is changed
922 to whatever value is mapped for the user (group) ID of the file.
923 However, if either the user
925 the group ID of the file has no mapping inside the namespace,
926 the set-user-ID (set-group-ID) bit is silently ignored:
927 the new program is executed,
928 but the process's effective user (group) ID is left unchanged.
929 (This mirrors the semantics of executing a set-user-ID or set-group-ID
930 program that resides on a filesystem that was mounted with the
932 flag, as described in
935 .\" ============================================================
939 When a process's user and group IDs are passed over a UNIX domain socket
940 to a process in a different user namespace (see the description of
944 they are translated into the corresponding values as per the
945 receiving process's user and group ID mappings.
948 Namespaces are a Linux-specific feature.
951 Over the years, there have been a lot of features that have been added
952 to the Linux kernel that have been made available only to privileged users
953 because of their potential to confuse set-user-ID-root applications.
954 In general, it becomes safe to allow the root user in a user namespace to
955 use those features because it is impossible, while in a user namespace,
956 to gain more privilege than the root user of a user namespace has.
958 .\" ============================================================
961 Use of user namespaces requires a kernel that is configured with the
964 User namespaces require support in a range of subsystems across
966 When an unsupported subsystem is configured into the kernel,
967 it is not possible to configure user namespaces support.
969 As at Linux 3.8, most relevant subsystems supported user namespaces,
970 but a number of filesystems did not have the infrastructure needed
971 to map user and group IDs between user namespaces.
972 Linux 3.9 added the required infrastructure support for many of
973 the remaining unsupported filesystems
974 (Plan 9 (9P), Andrew File System (AFS), Ceph, CIFS, CODA, NFS, and OCFS2).
975 Linux 3.12 added support for the last of the unsupported major filesystems,
976 .\" commit d6970d4b726cea6d7a9bc4120814f95c09571fc3
980 The program below is designed to allow experimenting with
981 user namespaces, as well as other types of namespaces.
982 It creates namespaces as specified by command-line options and then executes
983 a command inside those namespaces.
986 function inside the program provide a full explanation of the program.
987 The following shell session demonstrates its use.
989 First, we look at the run-time environment:
993 $ \fBuname \-rs\fP # Need Linux 3.8 or later
995 $ \fBid \-u\fP # Running as unprivileged user
1002 Now start a new shell in new user
1008 namespaces, with user ID
1012 1000 mapped to 0 inside the user namespace:
1016 $ \fB./userns_child_exec \-p \-m \-U \-M '0 1000 1' \-G '0 1000 1' bash\fP
1020 The shell has PID 1, because it is the first process in the new
1032 filesystem and listing all of the processes visible
1033 in the new PID namespace shows that the shell can't see
1034 any processes outside the PID namespace:
1038 bash$ \fBmount \-t proc proc /proc\fP
1040 PID TTY STAT TIME COMMAND
1042 22 pts/3 R+ 0:00 ps ax
1046 Inside the user namespace, the shell has user and group ID 0,
1047 and a full set of permitted and effective capabilities:
1051 bash$ \fBcat /proc/$$/status | egrep '^[UG]id'\fP
1054 bash$ \fBcat /proc/$$/status | egrep '^Cap(Prm|Inh|Eff)'\fP
1055 CapInh: 0000000000000000
1056 CapPrm: 0000001fffffffff
1057 CapEff: 0000001fffffffff
1063 /* userns_child_exec.c
1065 Licensed under GNU General Public License v2 or later
1067 Create a child process that executes a shell command in new
1068 namespace(s); allow UID and GID mappings to be specified when
1069 creating a user namespace.
1075 #include <sys/wait.h>
1083 /* A simple error\-handling function: print an error message based
1084 on the value in \(aqerrno\(aq and terminate the calling process */
1086 #define errExit(msg) do { perror(msg); exit(EXIT_FAILURE); \e
1090 char **argv; /* Command to be executed by child, with args */
1091 int pipe_fd[2]; /* Pipe used to synchronize parent and child */
1099 fprintf(stderr, "Usage: %s [options] cmd [arg...]\en\en", pname);
1100 fprintf(stderr, "Create a child process that executes a shell "
1101 "command in a new user namespace,\en"
1102 "and possibly also other new namespace(s).\en\en");
1103 fprintf(stderr, "Options can be:\en\en");
1104 #define fpe(str) fprintf(stderr, " %s", str);
1105 fpe("\-i New IPC namespace\en");
1106 fpe("\-m New mount namespace\en");
1107 fpe("\-n New network namespace\en");
1108 fpe("\-p New PID namespace\en");
1109 fpe("\-u New UTS namespace\en");
1110 fpe("\-U New user namespace\en");
1111 fpe("\-M uid_map Specify UID map for user namespace\en");
1112 fpe("\-G gid_map Specify GID map for user namespace\en");
1113 fpe("\-z Map user\(aqs UID and GID to 0 in user namespace\en");
1114 fpe(" (equivalent to: \-M \(aq0 <uid> 1\(aq \-G \(aq0 <gid> 1\(aq)\en");
1115 fpe("\-v Display verbose messages\en");
1117 fpe("If \-z, \-M, or \-G is specified, \-U is required.\en");
1118 fpe("It is not permitted to specify both \-z and either \-M or \-G.\en");
1120 fpe("Map strings for \-M and \-G consist of records of the form:\en");
1122 fpe(" ID\-inside\-ns ID\-outside\-ns len\en");
1124 fpe("A map string can contain multiple records, separated"
1126 fpe("the commas are replaced by newlines before writing"
1127 " to map files.\en");
1132 /* Update the mapping file \(aqmap_file\(aq, with the value provided in
1133 \(aqmapping\(aq, a string that defines a UID or GID mapping. A UID or
1134 GID mapping consists of one or more newline\-delimited records
1137 ID_inside\-ns ID\-outside\-ns length
1139 Requiring the user to supply a string that contains newlines is
1140 of course inconvenient for command\-line use. Thus, we permit the
1141 use of commas to delimit records in this string, and replace them
1142 with newlines before writing the string to the file. */
1145 update_map(char *mapping, char *map_file)
1148 size_t map_len; /* Length of \(aqmapping\(aq */
1150 /* Replace commas in mapping string with newlines */
1152 map_len = strlen(mapping);
1153 for (j = 0; j < map_len; j++)
1154 if (mapping[j] == \(aq,\(aq)
1155 mapping[j] = \(aq\en\(aq;
1157 fd = open(map_file, O_RDWR);
1159 fprintf(stderr, "ERROR: open %s: %s\en", map_file,
1164 if (write(fd, mapping, map_len) != map_len) {
1165 fprintf(stderr, "ERROR: write %s: %s\en", map_file,
1173 /* Linux 3.19 made a change in the handling of setgroups(2) and the
1174 \(aqgid_map\(aq file to address a security issue. The issue allowed
1175 *unprivileged* users to employ user namespaces in order to drop
1176 The upshot of the 3.19 changes is that in order to update the
1177 \(aqgid_maps\(aq file, use of the setgroups() system call in this
1178 user namespace must first be disabled by writing "deny" to one of
1179 the /proc/PID/setgroups files for this namespace. That is the
1180 purpose of the following function. */
1183 proc_setgroups_write(pid_t child_pid, char *str)
1185 char setgroups_path[PATH_MAX];
1188 snprintf(setgroups_path, PATH_MAX, "/proc/%ld/setgroups",
1191 fd = open(setgroups_path, O_RDWR);
1194 /* We may be on a system that doesn\(aqt support
1195 /proc/PID/setgroups. In that case, the file won\(aqt exist,
1196 and the system won\(aqt impose the restrictions that Linux 3.19
1197 added. That\(aqs fine: we don\(aqt need to do anything in order
1198 to permit \(aqgid_map\(aq to be updated.
1200 However, if the error from open() was something other than
1201 the ENOENT error that is expected for that case, let the
1204 if (errno != ENOENT)
1205 fprintf(stderr, "ERROR: open %s: %s\en", setgroups_path,
1210 if (write(fd, str, strlen(str)) == \-1)
1211 fprintf(stderr, "ERROR: write %s: %s\en", setgroups_path,
1217 static int /* Start function for cloned child */
1218 childFunc(void *arg)
1220 struct child_args *args = (struct child_args *) arg;
1223 /* Wait until the parent has updated the UID and GID mappings.
1224 See the comment in main(). We wait for end of file on a
1225 pipe that will be closed by the parent process once it has
1226 updated the mappings. */
1228 close(args\->pipe_fd[1]); /* Close our descriptor for the write
1229 end of the pipe so that we see EOF
1230 when parent closes its descriptor */
1231 if (read(args\->pipe_fd[0], &ch, 1) != 0) {
1233 "Failure in child: read from pipe returned != 0\en");
1237 close(args\->pipe_fd[0]);
1239 /* Execute a shell command */
1241 printf("About to exec %s\en", args\->argv[0]);
1242 execvp(args\->argv[0], args\->argv);
1246 #define STACK_SIZE (1024 * 1024)
1248 static char child_stack[STACK_SIZE]; /* Space for child\(aqs stack */
1251 main(int argc, char *argv[])
1253 int flags, opt, map_zero;
1255 struct child_args args;
1256 char *uid_map, *gid_map;
1257 const int MAP_BUF_SIZE = 100;
1258 char map_buf[MAP_BUF_SIZE];
1259 char map_path[PATH_MAX];
1261 /* Parse command\-line options. The initial \(aq+\(aq character in
1262 the final getopt() argument prevents GNU\-style permutation
1263 of command\-line options. That\(aqs useful, since sometimes
1264 the \(aqcommand\(aq to be executed by this program itself
1265 has command\-line options. We don\(aqt want getopt() to treat
1266 those as options to this program. */
1273 while ((opt = getopt(argc, argv, "+imnpuUM:G:zv")) != \-1) {
1275 case \(aqi\(aq: flags |= CLONE_NEWIPC; break;
1276 case \(aqm\(aq: flags |= CLONE_NEWNS; break;
1277 case \(aqn\(aq: flags |= CLONE_NEWNET; break;
1278 case \(aqp\(aq: flags |= CLONE_NEWPID; break;
1279 case \(aqu\(aq: flags |= CLONE_NEWUTS; break;
1280 case \(aqv\(aq: verbose = 1; break;
1281 case \(aqz\(aq: map_zero = 1; break;
1282 case \(aqM\(aq: uid_map = optarg; break;
1283 case \(aqG\(aq: gid_map = optarg; break;
1284 case \(aqU\(aq: flags |= CLONE_NEWUSER; break;
1285 default: usage(argv[0]);
1289 /* \-M or \-G without \-U is nonsensical */
1291 if (((uid_map != NULL || gid_map != NULL || map_zero) &&
1292 !(flags & CLONE_NEWUSER)) ||
1293 (map_zero && (uid_map != NULL || gid_map != NULL)))
1296 args.argv = &argv[optind];
1298 /* We use a pipe to synchronize the parent and child, in order to
1299 ensure that the parent sets the UID and GID maps before the child
1300 calls execve(). This ensures that the child maintains its
1301 capabilities during the execve() in the common case where we
1302 want to map the child\(aqs effective user ID to 0 in the new user
1303 namespace. Without this synchronization, the child would lose
1304 its capabilities if it performed an execve() with nonzero
1305 user IDs (see the capabilities(7) man page for details of the
1306 transformation of a process\(aqs capabilities during execve()). */
1308 if (pipe(args.pipe_fd) == \-1)
1311 /* Create the child in new namespace(s) */
1313 child_pid = clone(childFunc, child_stack + STACK_SIZE,
1314 flags | SIGCHLD, &args);
1315 if (child_pid == \-1)
1318 /* Parent falls through to here */
1321 printf("%s: PID of child created by clone() is %ld\en",
1322 argv[0], (long) child_pid);
1324 /* Update the UID and GID maps in the child */
1326 if (uid_map != NULL || map_zero) {
1327 snprintf(map_path, PATH_MAX, "/proc/%ld/uid_map",
1330 snprintf(map_buf, MAP_BUF_SIZE, "0 %ld 1", (long) getuid());
1333 update_map(uid_map, map_path);
1336 if (gid_map != NULL || map_zero) {
1337 proc_setgroups_write(child_pid, "deny");
1339 snprintf(map_path, PATH_MAX, "/proc/%ld/gid_map",
1342 snprintf(map_buf, MAP_BUF_SIZE, "0 %ld 1", (long) getgid());
1345 update_map(gid_map, map_path);
1348 /* Close the write end of the pipe, to signal to the child that we
1349 have updated the UID and GID maps */
1351 close(args.pipe_fd[1]);
1353 if (waitpid(child_pid, NULL, 0) == \-1) /* Wait for child */
1357 printf("%s: terminating\en", argv[0]);
1363 .BR newgidmap (1), \" From the shadow package
1364 .BR newuidmap (1), \" From the shadow package
1370 .BR subgid (5), \" From the shadow package
1371 .BR subuid (5), \" From the shadow package
1372 .BR capabilities (7),
1373 .BR cgroup_namespaces (7)
1374 .BR credentials (7),
1376 .BR pid_namespaces (7)
1378 The kernel source file
1379 .IR Documentation/namespaces/resource-control.txt .