1 .\" Copyright (c) 2013 by Michael Kerrisk <mtk.manpages@gmail.com>
2 .\" and Copyright (c) 2012 by Eric W. Biederman <ebiederm@xmission.com>
4 .\" Permission is granted to make and distribute verbatim copies of this
5 .\" manual provided the copyright notice and this permission notice are
6 .\" preserved on all copies.
8 .\" Permission is granted to copy and distribute modified versions of this
9 .\" manual under the conditions for verbatim copying, provided that the
10 .\" entire resulting derived work is distributed under the terms of a
11 .\" permission notice identical to this one.
13 .\" Since the Linux kernel and libraries are constantly changing, this
14 .\" manual page may be incorrect or out-of-date. The author(s) assume no
15 .\" responsibility for errors or omissions, or for damages resulting from
16 .\" the use of the information contained herein. The author(s) may not
17 .\" have taken the same level of care in the production of this manual,
18 .\" which is licensed free of charge, as they might when working
21 .\" Formatted or processed versions of this manual, if unaccompanied by
22 .\" the source, must acknowledge the copyright and authors of this work.
25 .TH USER_NAMESPACES 7 2013-01-14 "Linux" "Linux Programmer's Manual"
27 user_namespaces \- overview of Linux user_namespaces
29 For an overview of namespaces, see
32 User namespaces isolate security-related identifiers, in particular,
33 user IDs and group IDs (see
37 .\" FIXME: This page says very little about the interaction
38 .\" of user namespaces and keys. Add something on this topic.
40 .BR capabilities (7)).
41 A process's user and group IDs can be different
42 inside and outside a user namespace.
44 a process can have a normal unprivileged user ID outside a user namespace
45 while at the same time having a user ID of 0 inside the namespace;
47 the process has full privileges for operations inside the user namespace,
48 but is unprivileged for operations outside the namespace.
50 .\" ============================================================
52 .SS Nested namespaces, namespace membership
53 User namespaces can be nested;
54 that is, each user namespace\(emexcept the initial ("root")
55 namespace\(emhas a parent user namespace,
56 and can have zero or more child user namespaces.
57 The parent user namespace is the user namespace
58 of the process that creates the user namespace via a call to
66 The kernel imposes (since version 3.11) a limit of 32 nested levels of
67 .\" commit 8742f229b635bf1c1c84a3dfe5e47c814c20b5c8
69 .\" FIXME Explain the rationale for this limit. (What is the rationale?)
74 that would cause this limit to be exceeded fail with the error
77 Each process is a member of exactly one user namespace.
84 flag is a member of the same user namespace as its parent.
85 A process can join another user namespace with
90 upon doing so, it gains a full set of capabilities in that namespace.
98 flag makes the new child process (for
102 a member of the new user namespace created by the call.
104 .\" ============================================================
107 The child process created by
111 flag starts out with a complete set
112 of capabilities in the new user namespace.
113 Likewise, a process that creates a new user namespace using
115 or joins an existing user namespace using
117 gains a full set of capabilities in that namespace.
119 that process has no capabilities in the parent (in the case of
121 or previous (in the case of
126 even if the new namespace is created or joined by the root user
127 (i.e., a process with user ID 0 in the root namespace).
131 will cause a process to lose any capabilities that it has,
132 unless it has a user ID of 0 within the namespace.
135 a user ID mapping for ID 0 must be defined,
136 and the caller may also need to use
138 or similar to set its user ID to 0.
147 flag sets the "securebits" flags
149 .BR capabilities (7))
150 to their default values (all flags disabled) in the child (for
156 Note that because the caller no longer has capabilities
157 in its original user namespace after a call to
159 it is not possible for a process to reset its "securebits" flags while
160 retaining its user namespace membership by using a pair of
162 calls to move to another user namespace and then return to
163 its original user namespace.
165 Having a capability inside a user namespace
166 permits a process to perform operations (that require privilege)
167 only on resources governed by that 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 Interaction of user namespaces and other types of namespaces
212 Starting in Linux 3.8, unprivileged processes can create user namespaces,
213 and mount, PID, IPC, network, and UTS namespaces can be created with just the
215 capability in the caller's user namespace.
219 is specified along with other
225 call, the user namespace is guaranteed to be created first,
230 privileges over the remaining namespaces created by the call.
231 Thus, it is possible for an unprivileged caller to specify this combination
234 When a new IPC, mount, network, PID, or UTS namespace is created via
238 the kernel records the user namespace of the creating process against
240 (This association can't be changed.)
241 When a process in the new namespace subsequently performs
242 privileged operations that operate on global
243 resources isolated by the namespace,
244 the permission checks are performed according to the process's capabilities
245 in the user namespace that the kernel associated with the new namespace.
247 .\" ============================================================
249 .SS User and group ID mappings: uid_map and gid_map
250 When a user namespace is created,
251 it starts out without a mapping of user IDs (group IDs)
252 to the parent user namespace.
254 .IR /proc/[pid]/uid_map
256 .IR /proc/[pid]/gid_map
257 files (available since Linux 3.5)
258 .\" commit 22d917d80e842829d0ca0a561967d728eb1d6303
259 expose the mappings for user and group IDs
260 inside the user namespace for the process
262 These files can be read to view the mappings in a user namespace and
263 written to (once) to define the mappings.
265 The description in the following paragraphs explains the details for
269 but each instance of "user ID" is replaced by "group ID".
273 file exposes the mapping of user IDs from the user namespace
276 to the user namespace of the process that opened
278 (but see a qualification to this point below).
279 In other words, processes that are in different user namespaces
280 will potentially see different values when reading from a particular
282 file, depending on the user ID mappings for the user namespaces
283 of the reading processes.
287 file specifies a 1-to-1 mapping of a range of contiguous
288 user IDs between two user namespaces.
289 (When a user namespace is first created, this file is empty.)
290 The specification in each line takes the form of
291 three numbers delimited by white space.
292 The first two numbers specify the starting user ID in
293 each of the two user namespaces.
294 The third number specifies the length of the mapped range.
295 In detail, the fields are interpreted as follows:
297 The start of the range of user IDs in
298 the user namespace of the process
301 The start of the range of user
302 IDs to which the user IDs specified by field one map.
303 How field two is interpreted depends on whether the process that opened
307 are in the same user namespace, as follows:
310 If the two processes are in different user namespaces:
311 field two is the start of a range of
312 user IDs in the user namespace of the process that opened
315 If the two processes are in the same user namespace:
316 field two is the start of the range of
317 user IDs in the parent user namespace of the process
319 This case enables the opener of
321 (the common case here is opening
322 .IR /proc/self/uid_map )
323 to see the mapping of user IDs into the user namespace of the process
324 that created this user namespace.
327 The length of the range of user IDs that is mapped between the two
330 System calls that return user IDs (group IDs)\(emfor example,
333 and the credential fields in the structure returned by
334 .BR stat (2)\(emreturn
335 the user ID (group ID) mapped into the caller's user namespace.
337 When a process accesses a file, its user and group IDs
338 are mapped into the initial user namespace for the purpose of permission
339 checking and assigning IDs when creating a file.
340 When a process retrieves file user and group IDs via
342 the IDs are mapped in the opposite direction,
343 to produce values relative to the process user and group ID mappings.
345 The initial user namespace has no parent namespace,
346 but, for consistency, the kernel provides dummy user and group
347 ID mapping files for this namespace.
352 is the same) from a shell in the initial namespace shows:
356 $ \fBcat /proc/$$/uid_map\fP
361 This mapping tells us
362 that the range starting at user ID 0 in this namespace
363 maps to a range starting at 0 in the (nonexistent) parent namespace,
364 and the length of the range is the largest 32-bit unsigned integer.
366 .\" ============================================================
368 .SS Defining user and group ID mappings: writing to uid_map and gid_map
370 After the creation of a new user namespace, the
374 of the processes in the namespace may be written to
376 to define the mapping of user IDs in the new user namespace.
377 An attempt to write more than once to a
379 file in a user namespace fails with the error
381 Similar rules apply for
388 must conform to the following rules:
390 The three fields must be valid numbers,
391 and the last field must be greater than 0.
393 Lines are terminated by newline characters.
395 There is an (arbitrary) limit on the number of lines in the file.
396 As at Linux 3.8, the limit is five lines.
397 In addition, the number of bytes written to
398 the file must be less than the system page size,
399 .\" FIXME(Eric): the restriction "less than" rather than "less than or equal"
400 .\" seems strangely arbitrary. Furthermore, the comment does not agree
401 .\" with the code in kernel/user_namespace.c. Which is correct.
402 and the write must be performed at the start of the file (i.e.,
406 can't be used to write to nonzero offsets in the file).
408 The range of user IDs (group IDs)
409 specified in each line cannot overlap with the ranges
411 In the initial implementation (Linux 3.8), this requirement was
412 satisfied by a simplistic implementation that imposed the further
414 the values in both field 1 and field 2 of successive lines must be
415 in ascending numerical order,
416 which prevented some otherwise valid maps from being created.
418 .\" commit 0bd14b4fd72afd5df41e9fd59f356740f22fceba
419 fix this limitation, allowing any valid set of nonoverlapping maps.
421 At least one line must be written to the file.
423 Writes that violate the above rules fail with the error
426 In order for a process to write to the
427 .I /proc/[pid]/uid_map
428 .RI ( /proc/[pid]/gid_map )
429 file, all of the following requirements must be met:
431 The writing process must have the
434 capability in the user namespace of the process
437 The writing process must be in either the user namespace of the process
439 or inside the parent user namespace of the process
442 The mapped user IDs (group IDs) must in turn have a mapping
443 in the parent user namespace.
445 One of the following is true:
451 consists of a single line that maps the writing process's filesystem user ID
452 (group ID) in the parent user namespace to a user ID (group ID)
453 in the user namespace.
454 The usual case here is that this single line provides a mapping for user ID
455 of the process that created the namespace.
460 capability in the parent user namespace.
461 Thus, a privileged process can make mappings to arbitrary user IDs (group IDs)
462 in the parent user namespace.
465 Writes that violate the above rules fail with the error
468 .\" ============================================================
470 .SS Unmapped user and group IDs
472 There are various places where an unmapped user ID (group ID)
473 may be exposed to user space.
474 For example, the first process in a new user namespace may call
476 before a user ID mapping has been defined for the namespace.
477 In most such cases, an unmapped user ID is converted
478 .\" from_kuid_munged(), from_kgid_munged()
479 to the overflow user ID (group ID);
480 the default value for the overflow user ID (group ID) is 65534.
481 See the descriptions of
482 .IR /proc/sys/kernel/overflowuid
484 .IR /proc/sys/kernel/overflowgid
488 The cases where unmapped IDs are mapped in this fashion include
489 system calls that return user IDs
493 credentials passed over a UNIX domain socket,
495 credentials returned by
498 and the System V IPC "ctl"
501 credentials exposed by
504 .IR /proc/sysvipc/* ,
505 credentials returned via the
509 received with a signal (see
511 credentials written to the process accounting file (see
513 and credentials returned with POSIX message queue notifications (see
516 There is one notable case where unmapped user and group IDs are
518 .\" from_kuid(), from_kgid()
519 .\" Also F_GETOWNER_UIDS is an exception
520 converted to the corresponding overflow ID value.
525 file in which there is no mapping for the second field,
526 that field is displayed as 4294967295 (\-1 as an unsigned integer);
528 .\" ============================================================
530 .SS Set-user-ID and set-group-ID programs
532 When a process inside a user namespace executes
533 a set-user-ID (set-group-ID) program,
534 the process's effective user (group) ID inside the namespace is changed
535 to whatever value is mapped for the user (group) ID of the file.
536 However, if either the user
538 the group ID of the file has no mapping inside the namespace,
539 the set-user-ID (set-group-ID) bit is silently ignored:
540 the new program is executed,
541 but the process's effective user (group) ID is left unchanged.
542 (This mirrors the semantics of executing a set-user-ID or set-group-ID
543 program that resides on a filesystem that was mounted with the
545 flag, as described in
548 .\" ============================================================
552 When a process's user and group IDs are passed over a UNIX domain socket
553 to a process in a different user namespace (see the description of
557 they are translated into the corresponding values as per the
558 receiving process's user and group ID mappings.
561 Namespaces are a Linux-specific feature.
564 Over the years, there have been a lot of features that have been added
565 to the Linux kernel that have been made available only to privileged users
566 because of their potential to confuse set-user-ID-root applications.
567 In general, it becomes safe to allow the root user in a user namespace to
568 use those features because it is impossible, while in a user namespace,
569 to gain more privilege than the root user of a user namespace has.
571 .\" ============================================================
574 Use of user namespaces requires a kernel that is configured with the
577 User namespaces require support in a range of subsystems across
579 When an unsupported subsystem is configured into the kernel,
580 it is not possible to configure user namespaces support.
582 As at Linux 3.8, most relevant subsystems supported user namespaces,
583 but a number of filesystems did not have the infrastructure needed
584 to map user and group IDs between user namespaces.
585 Linux 3.9 added the required infrastructure support for many of
586 the remaining unsupported filesystems
587 (Plan 9 (9P), Andrew File System (AFS), Ceph, CIFS, CODA, NFS, and OCFS2).
588 Linux 3.11 added support the last of the unsupported major filesystems,
589 .\" commit d6970d4b726cea6d7a9bc4120814f95c09571fc3
593 The program below is designed to allow experimenting with
594 user namespaces, as well as other types of namespaces.
595 It creates namespaces as specified by command-line options and then executes
596 a command inside those namespaces.
599 function inside the program provide a full explanation of the program.
600 The following shell session demonstrates its use.
602 First, we look at the run-time environment:
606 $ \fBuname -rs\fP # Need Linux 3.8 or later
608 $ \fBid -u\fP # Running as unprivileged user
615 Now start a new shell in new user
621 namespaces, with user ID
625 1000 mapped to 0 inside the user namespace:
629 $ \fB./userns_child_exec -p -m -U -M '0 1000 1' -G '0 1000 1' bash\fP
633 The shell has PID 1, because it is the first process in the new
643 Inside the user namespace, the shell has user and group ID 0,
644 and a full set of permitted and effective capabilities:
648 bash$ \fBcat /proc/$$/status | egrep '^[UG]id'\fP
651 bash$ \fBcat /proc/$$/status | egrep '^Cap(Prm|Inh|Eff)'\fP
652 CapInh: 0000000000000000
653 CapPrm: 0000001fffffffff
654 CapEff: 0000001fffffffff
660 filesystem and listing all of the processes visible
661 in the new PID namespace shows that the shell can't see
662 any processes outside the PID namespace:
666 bash$ \fBmount -t proc proc /proc\fP
668 PID TTY STAT TIME COMMAND
670 22 pts/3 R+ 0:00 ps ax
676 /* userns_child_exec.c
678 Licensed under GNU General Public License v2 or later
680 Create a child process that executes a shell command in new
681 namespace(s); allow UID and GID mappings to be specified when
682 creating a user namespace.
688 #include <sys/wait.h>
696 /* A simple error\-handling function: print an error message based
697 on the value in \(aqerrno\(aq and terminate the calling process */
699 #define errExit(msg) do { perror(msg); exit(EXIT_FAILURE); \\
703 char **argv; /* Command to be executed by child, with args */
704 int pipe_fd[2]; /* Pipe used to synchronize parent and child */
712 fprintf(stderr, "Usage: %s [options] cmd [arg...]\\n\\n", pname);
713 fprintf(stderr, "Create a child process that executes a shell "
714 "command in a new user namespace,\\n"
715 "and possibly also other new namespace(s).\\n\\n");
716 fprintf(stderr, "Options can be:\\n\\n");
717 #define fpe(str) fprintf(stderr, " %s", str);
718 fpe("\-i New IPC namespace\\n");
719 fpe("\-m New mount namespace\\n");
720 fpe("\-n New network namespace\\n");
721 fpe("\-p New PID namespace\\n");
722 fpe("\-u New UTS namespace\\n");
723 fpe("\-U New user namespace\\n");
724 fpe("\-M uid_map Specify UID map for user namespace\\n");
725 fpe("\-G gid_map Specify GID map for user namespace\\n");
726 fpe("\-z Map user\(aqs UID and GID to 0 in user namespace\\n");
727 fpe(" (equivalent to: \-M \(aq0 <uid> 1\(aq \-G \(aq0 <gid> 1\(aq)\\n");
728 fpe("\-v Display verbose messages\\n");
730 fpe("If \-z, \-M, or \-G is specified, \-U is required.\\n");
731 fpe("It is not permitted to specify both \-z and either \-M or \-G.\\n");
733 fpe("Map strings for \-M and \-G consist of records of the form:\\n");
735 fpe(" ID\-inside\-ns ID\-outside\-ns len\\n");
737 fpe("A map string can contain multiple records, separated"
739 fpe("the commas are replaced by newlines before writing"
740 " to map files.\\n");
745 /* Update the mapping file \(aqmap_file\(aq, with the value provided in
746 \(aqmapping\(aq, a string that defines a UID or GID mapping. A UID or
747 GID mapping consists of one or more newline\-delimited records
750 ID_inside\-ns ID\-outside\-ns length
752 Requiring the user to supply a string that contains newlines is
753 of course inconvenient for command\-line use. Thus, we permit the
754 use of commas to delimit records in this string, and replace them
755 with newlines before writing the string to the file. */
758 update_map(char *mapping, char *map_file)
761 size_t map_len; /* Length of \(aqmapping\(aq */
763 /* Replace commas in mapping string with newlines */
765 map_len = strlen(mapping);
766 for (j = 0; j < map_len; j++)
767 if (mapping[j] == \(aq,\(aq)
768 mapping[j] = \(aq\\n\(aq;
770 fd = open(map_file, O_RDWR);
772 fprintf(stderr, "ERROR: open %s: %s\\n", map_file,
777 if (write(fd, mapping, map_len) != map_len) {
778 fprintf(stderr, "ERROR: write %s: %s\\n", map_file,
786 static int /* Start function for cloned child */
789 struct child_args *args = (struct child_args *) arg;
792 /* Wait until the parent has updated the UID and GID mappings.
793 See the comment in main(). We wait for end of file on a
794 pipe that will be closed by the parent process once it has
795 updated the mappings. */
797 close(args\->pipe_fd[1]); /* Close our descriptor for the write
798 end of the pipe so that we see EOF
799 when parent closes its descriptor */
800 if (read(args\->pipe_fd[0], &ch, 1) != 0) {
802 "Failure in child: read from pipe returned != 0\\n");
806 /* Execute a shell command */
808 printf("About to exec %s\\n", args\->argv[0]);
809 execvp(args\->argv[0], args\->argv);
813 #define STACK_SIZE (1024 * 1024)
815 static char child_stack[STACK_SIZE]; /* Space for child\(aqs stack */
818 main(int argc, char *argv[])
820 int flags, opt, map_zero;
822 struct child_args args;
823 char *uid_map, *gid_map;
824 const int MAP_BUF_SIZE = 100;
825 char map_buf[MAP_BUF_SIZE];
826 char map_path[PATH_MAX];
828 /* Parse command\-line options. The initial \(aq+\(aq character in
829 the final getopt() argument prevents GNU\-style permutation
830 of command\-line options. That\(aqs useful, since sometimes
831 the \(aqcommand\(aq to be executed by this program itself
832 has command\-line options. We don\(aqt want getopt() to treat
833 those as options to this program. */
840 while ((opt = getopt(argc, argv, "+imnpuUM:G:zv")) != \-1) {
842 case \(aqi\(aq: flags |= CLONE_NEWIPC; break;
843 case \(aqm\(aq: flags |= CLONE_NEWNS; break;
844 case \(aqn\(aq: flags |= CLONE_NEWNET; break;
845 case \(aqp\(aq: flags |= CLONE_NEWPID; break;
846 case \(aqu\(aq: flags |= CLONE_NEWUTS; break;
847 case \(aqv\(aq: verbose = 1; break;
848 case \(aqz\(aq: map_zero = 1; break;
849 case \(aqM\(aq: uid_map = optarg; break;
850 case \(aqG\(aq: gid_map = optarg; break;
851 case \(aqU\(aq: flags |= CLONE_NEWUSER; break;
852 default: usage(argv[0]);
856 /* \-M or \-G without \-U is nonsensical */
858 if (((uid_map != NULL || gid_map != NULL || map_zero) &&
859 !(flags & CLONE_NEWUSER)) ||
860 (map_zero && (uid_map != NULL || gid_map != NULL)))
863 args.argv = &argv[optind];
865 /* We use a pipe to synchronize the parent and child, in order to
866 ensure that the parent sets the UID and GID maps before the child
867 calls execve(). This ensures that the child maintains its
868 capabilities during the execve() in the common case where we
869 want to map the child\(aqs effective user ID to 0 in the new user
870 namespace. Without this synchronization, the child would lose
871 its capabilities if it performed an execve() with nonzero
872 user IDs (see the capabilities(7) man page for details of the
873 transformation of a process\(aqs capabilities during execve()). */
875 if (pipe(args.pipe_fd) == \-1)
878 /* Create the child in new namespace(s) */
880 child_pid = clone(childFunc, child_stack + STACK_SIZE,
881 flags | SIGCHLD, &args);
882 if (child_pid == \-1)
885 /* Parent falls through to here */
888 printf("%s: PID of child created by clone() is %ld\\n",
889 argv[0], (long) child_pid);
891 /* Update the UID and GID maps in the child */
893 if (uid_map != NULL || map_zero) {
894 snprintf(map_path, PATH_MAX, "/proc/%ld/uid_map",
897 snprintf(map_buf, MAP_BUF_SIZE, "0 %ld 1", (long) getuid());
900 update_map(uid_map, map_path);
902 if (gid_map != NULL || map_zero) {
903 snprintf(map_path, PATH_MAX, "/proc/%ld/gid_map",
906 snprintf(map_buf, MAP_BUF_SIZE, "0 %ld 1", (long) getgid());
909 update_map(gid_map, map_path);
912 /* Close the write end of the pipe, to signal to the child that we
913 have updated the UID and GID maps */
915 close(args.pipe_fd[1]);
917 if (waitpid(child_pid, NULL, 0) == \-1) /* Wait for child */
921 printf("%s: terminating\\n", argv[0]);
927 .BR newgidmap (1), \" From the shadow package
928 .BR newuidmap (1), \" From the shadow package
933 .BR subgid (5), \" From the shadow package
934 .BR subuid (5), \" From the shadow package
936 .BR capabilities (7),
938 .BR pid_namespaces (7)
940 The kernel source file
941 .IR Documentation/namespaces/resource-control.txt .