capabilities.7, user_namespaces.7: Describe CAP_SETFCAP
[man-pages.git] / man7 / user_namespaces.7
blob3378b6057ed8c0685d14dc7abe5a212843a2fa5c
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>
3 .\"
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.
8 .\"
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.
13 .\"
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
20 .\" professionally.
21 .\"
22 .\" Formatted or processed versions of this manual, if unaccompanied by
23 .\" the source, must acknowledge the copyright and authors of this work.
24 .\" %%%LICENSE_END
25 .\"
26 .\"
27 .TH USER_NAMESPACES 7 2021-03-22 "Linux" "Linux Programmer's Manual"
28 .SH NAME
29 user_namespaces \- overview of Linux user namespaces
30 .SH DESCRIPTION
31 For an overview of namespaces, see
32 .BR namespaces (7).
33 .PP
34 User namespaces isolate security-related identifiers and attributes,
35 in particular,
36 user IDs and group IDs (see
37 .BR credentials (7)),
38 the root directory,
39 keys (see
40 .BR keyrings (7)),
41 .\" FIXME: This page says very little about the interaction
42 .\" of user namespaces and keys. Add something on this topic.
43 and capabilities (see
44 .BR capabilities (7)).
45 A process's user and group IDs can be different
46 inside and outside a user namespace.
47 In particular,
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;
50 in other words,
51 the process has full privileges for operations inside the user namespace,
52 but is unprivileged for operations outside the namespace.
53 .\"
54 .\" ============================================================
55 .\"
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
63 .BR unshare (2)
65 .BR clone (2)
66 with the
67 .BR CLONE_NEWUSER
68 flag.
69 .PP
70 The kernel imposes (since version 3.11) a limit of 32 nested levels of
71 .\" commit 8742f229b635bf1c1c84a3dfe5e47c814c20b5c8
72 user namespaces.
73 .\" FIXME Explain the rationale for this limit. (What is the rationale?)
74 Calls to
75 .BR unshare (2)
77 .BR clone (2)
78 that would cause this limit to be exceeded fail with the error
79 .BR EUSERS .
80 .PP
81 Each process is a member of exactly one user namespace.
82 A process created via
83 .BR fork (2)
85 .BR clone (2)
86 without the
87 .BR CLONE_NEWUSER
88 flag is a member of the same user namespace as its parent.
89 A single-threaded process can join another user namespace with
90 .BR setns (2)
91 if it has the
92 .BR CAP_SYS_ADMIN
93 in that namespace;
94 upon doing so, it gains a full set of capabilities in that namespace.
95 .PP
96 A call to
97 .BR clone (2)
99 .BR unshare (2)
100 with the
101 .BR CLONE_NEWUSER
102 flag makes the new child process (for
103 .BR clone (2))
104 or the caller (for
105 .BR unshare (2))
106 a member of the new user namespace created by the call.
109 .BR NS_GET_PARENT
110 .BR ioctl (2)
111 operation can be used to discover the parental relationship
112 between user namespaces; see
113 .BR ioctl_ns (2).
115 .\" ============================================================
117 .SS Capabilities
118 The child process created by
119 .BR clone (2)
120 with the
121 .BR CLONE_NEWUSER
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
125 .BR unshare (2)
126 or joins an existing user namespace using
127 .BR setns (2)
128 gains a full set of capabilities in that namespace.
129 On the other hand,
130 that process has no capabilities in the parent (in the case of
131 .BR clone (2))
132 or previous (in the case of
133 .BR unshare (2)
135 .BR setns (2))
136 user namespace,
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).
140 Note that a call to
141 .BR execve (2)
142 will cause a process's capabilities to be recalculated in the usual way (see
143 .BR capabilities (7)).
144 Consequently,
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.
150 A call to
151 .BR clone (2)
153 .BR unshare (2)
154 using the
155 .BR CLONE_NEWUSER
156 flag
157 or a call to
158 .BR setns (2)
159 that moves the caller into another user namespace
160 sets the "securebits" flags
161 (see
162 .BR capabilities (7))
163 to their default values (all flags disabled) in the child (for
164 .BR clone (2))
165 or caller (for
166 .BR unshare (2)
168 .BR setns (2)).
169 Note that because the caller no longer has capabilities
170 in its original user namespace after a call to
171 .BR setns (2),
172 it is not possible for a process to reset its "securebits" flags while
173 retaining its user namespace membership by using a pair of
174 .BR setns (2)
175 calls to move to another user namespace and then return to
176 its original user namespace.
178 The rules for determining whether or not a process has a capability
179 in a particular user namespace are as follows:
180 .IP 1. 3
181 A process has a capability inside a user namespace
182 if it is a member of that namespace and
183 it has the capability in its effective capability set.
184 A process can gain capabilities in its effective capability
185 set in various ways.
186 For example, it may execute a set-user-ID program or an
187 executable with associated file capabilities.
188 In addition,
189 a process may gain capabilities via the effect of
190 .BR clone (2),
191 .BR unshare (2),
193 .BR setns (2),
194 as already described.
195 .\" In the 3.8 sources, see security/commoncap.c::cap_capable():
196 .IP 2.
197 If a process has a capability in a user namespace,
198 then it has that capability in all child (and further removed descendant)
199 namespaces as well.
200 .IP 3.
201 .\" * The owner of the user namespace in the parent of the
202 .\" * user namespace has all caps.
203 When a user namespace is created, the kernel records the effective
204 user ID of the creating process as being the "owner" of the namespace.
205 .\" (and likewise associates the effective group ID of the creating process
206 .\" with the namespace).
207 A process that resides
208 in the parent of the user namespace
209 .\" See kernel commit 520d9eabce18edfef76a60b7b839d54facafe1f9 for a fix
210 .\" on this point
211 and whose effective user ID matches the owner of the namespace
212 has all capabilities in the namespace.
213 .\"     This includes the case where the process executes a set-user-ID
214 .\"     program that confers the effective UID of the creator of the namespace.
215 By virtue of the previous rule,
216 this means that the process has all capabilities in all
217 further removed descendant user namespaces as well.
219 .B NS_GET_OWNER_UID
220 .BR ioctl (2)
221 operation can be used to discover the user ID of the owner of the namespace;
223 .BR ioctl_ns (2).
225 .\" ============================================================
227 .SS Effect of capabilities within a user namespace
228 Having a capability inside a user namespace
229 permits a process to perform operations (that require privilege)
230 only on resources governed by that namespace.
231 In other words, having a capability in a user namespace permits a process
232 to perform privileged operations on resources that are governed by (nonuser)
233 namespaces owned by (associated with) the user namespace
234 (see the next subsection).
236 On the other hand, there are many privileged operations that affect
237 resources that are not associated with any namespace type,
238 for example, changing the system (i.e., calendar) time (governed by
239 .BR CAP_SYS_TIME ),
240 loading a kernel module (governed by
241 .BR CAP_SYS_MODULE ),
242 and creating a device (governed by
243 .BR CAP_MKNOD ).
244 Only a process with privileges in the
245 .I initial
246 user namespace can perform such operations.
248 Holding
249 .B CAP_SYS_ADMIN
250 within the user namespace that owns a process's mount namespace
251 allows that process to create bind mounts
252 and mount the following types of filesystems:
253 .\" fs_flags = FS_USERNS_MOUNT in kernel sources
255 .RS 4
256 .PD 0
257 .IP * 2
258 .IR /proc
259 (since Linux 3.8)
260 .IP *
261 .IR /sys
262 (since Linux 3.8)
263 .IP *
264 .IR devpts
265 (since Linux 3.9)
266 .IP *
267 .BR tmpfs (5)
268 (since Linux 3.9)
269 .IP *
270 .IR ramfs
271 (since Linux 3.9)
272 .IP *
273 .IR mqueue
274 (since Linux 3.9)
275 .IP *
276 .IR bpf
277 .\" commit b2197755b2633e164a439682fb05a9b5ea48f706
278 (since Linux 4.4)
279 .IP *
280 .IR overlayfs
281 .\" commit 92dbc9dedccb9759c7f9f2f0ae6242396376988f
282 .\" commit 4cb2c00c43b3fe88b32f29df4f76da1b92c33224
283 (since Linux 5.11)
287 Holding
288 .B CAP_SYS_ADMIN
289 within the user namespace that owns a process's cgroup namespace
290 allows (since Linux 4.6)
291 that process to the mount the cgroup version 2 filesystem and
292 cgroup version 1 named hierarchies
293 (i.e., cgroup filesystems mounted with the
294 .IR """none,name="""
295 option).
297 Holding
298 .B CAP_SYS_ADMIN
299 within the user namespace that owns a process's PID namespace
300 allows (since Linux 3.8)
301 that process to mount
302 .I /proc
303 filesystems.
305 Note however, that mounting block-based filesystems can be done
306 only by a process that holds
307 .BR CAP_SYS_ADMIN
308 in the initial user namespace.
310 .\" ============================================================
312 .SS Interaction of user namespaces and other types of namespaces
313 Starting in Linux 3.8, unprivileged processes can create user namespaces,
314 and the other types of namespaces can be created with just the
315 .B CAP_SYS_ADMIN
316 capability in the caller's user namespace.
318 When a nonuser namespace is created,
319 it is owned by the user namespace in which the creating process
320 was a member at the time of the creation of the namespace.
321 Privileged operations on resources governed by the nonuser namespace
322 require that the process has the necessary capabilities
323 in the user namespace that owns the nonuser namespace.
326 .BR CLONE_NEWUSER
327 is specified along with other
328 .B CLONE_NEW*
329 flags in a single
330 .BR clone (2)
332 .BR unshare (2)
333 call, the user namespace is guaranteed to be created first,
334 giving the child
335 .RB ( clone (2))
336 or caller
337 .RB ( unshare (2))
338 privileges over the remaining namespaces created by the call.
339 Thus, it is possible for an unprivileged caller to specify this combination
340 of flags.
342 When a new namespace (other than a user namespace) is created via
343 .BR clone (2)
345 .BR unshare (2),
346 the kernel records the user namespace of the creating process as the owner of
347 the new namespace.
348 (This association can't be changed.)
349 When a process in the new namespace subsequently performs
350 privileged operations that operate on global
351 resources isolated by the namespace,
352 the permission checks are performed according to the process's capabilities
353 in the user namespace that the kernel associated with the new namespace.
354 For example, suppose that a process attempts to change the hostname
355 .RB ( sethostname (2)),
356 a resource governed by the UTS namespace.
357 In this case,
358 the kernel will determine which user namespace owns
359 the process's UTS namespace, and check whether the process has the
360 required capability
361 .RB ( CAP_SYS_ADMIN )
362 in that user namespace.
365 .BR NS_GET_USERNS
366 .BR ioctl (2)
367 operation can be used to discover the user namespace
368 that owns a nonuser namespace; see
369 .BR ioctl_ns (2).
371 .\" ============================================================
373 .SS User and group ID mappings: uid_map and gid_map
374 When a user namespace is created,
375 it starts out without a mapping of user IDs (group IDs)
376 to the parent user namespace.
378 .IR /proc/[pid]/uid_map
380 .IR /proc/[pid]/gid_map
381 files (available since Linux 3.5)
382 .\" commit 22d917d80e842829d0ca0a561967d728eb1d6303
383 expose the mappings for user and group IDs
384 inside the user namespace for the process
385 .IR pid .
386 These files can be read to view the mappings in a user namespace and
387 written to (once) to define the mappings.
389 The description in the following paragraphs explains the details for
390 .IR uid_map ;
391 .IR gid_map
392 is exactly the same,
393 but each instance of "user ID" is replaced by "group ID".
396 .I uid_map
397 file exposes the mapping of user IDs from the user namespace
398 of the process
399 .IR pid
400 to the user namespace of the process that opened
401 .IR uid_map
402 (but see a qualification to this point below).
403 In other words, processes that are in different user namespaces
404 will potentially see different values when reading from a particular
405 .I uid_map
406 file, depending on the user ID mappings for the user namespaces
407 of the reading processes.
409 Each line in the
410 .I uid_map
411 file specifies a 1-to-1 mapping of a range of contiguous
412 user IDs between two user namespaces.
413 (When a user namespace is first created, this file is empty.)
414 The specification in each line takes the form of
415 three numbers delimited by white space.
416 The first two numbers specify the starting user ID in
417 each of the two user namespaces.
418 The third number specifies the length of the mapped range.
419 In detail, the fields are interpreted as follows:
420 .IP (1) 4
421 The start of the range of user IDs in
422 the user namespace of the process
423 .IR pid .
424 .IP (2)
425 The start of the range of user
426 IDs to which the user IDs specified by field one map.
427 How field two is interpreted depends on whether the process that opened
428 .I uid_map
429 and the process
430 .IR pid
431 are in the same user namespace, as follows:
433 .IP a) 3
434 If the two processes are in different user namespaces:
435 field two is the start of a range of
436 user IDs in the user namespace of the process that opened
437 .IR uid_map .
438 .IP b)
439 If the two processes are in the same user namespace:
440 field two is the start of the range of
441 user IDs in the parent user namespace of the process
442 .IR pid .
443 This case enables the opener of
444 .I uid_map
445 (the common case here is opening
446 .IR /proc/self/uid_map )
447 to see the mapping of user IDs into the user namespace of the process
448 that created this user namespace.
450 .IP (3)
451 The length of the range of user IDs that is mapped between the two
452 user namespaces.
454 System calls that return user IDs (group IDs)\(emfor example,
455 .BR getuid (2),
456 .BR getgid (2),
457 and the credential fields in the structure returned by
458 .BR stat (2)\(emreturn
459 the user ID (group ID) mapped into the caller's user namespace.
461 When a process accesses a file, its user and group IDs
462 are mapped into the initial user namespace for the purpose of permission
463 checking and assigning IDs when creating a file.
464 When a process retrieves file user and group IDs via
465 .BR stat (2),
466 the IDs are mapped in the opposite direction,
467 to produce values relative to the process user and group ID mappings.
469 The initial user namespace has no parent namespace,
470 but, for consistency, the kernel provides dummy user and group
471 ID mapping files for this namespace.
472 Looking at the
473 .I uid_map
474 file
475 .RI ( gid_map
476 is the same) from a shell in the initial namespace shows:
478 .in +4n
480 $ \fBcat /proc/$$/uid_map\fP
481          0          0 4294967295
485 This mapping tells us
486 that the range starting at user ID 0 in this namespace
487 maps to a range starting at 0 in the (nonexistent) parent namespace,
488 and the length of the range is the largest 32-bit unsigned integer.
489 This leaves 4294967295 (the 32-bit signed \-1 value) unmapped.
490 This is deliberate:
491 .IR "(uid_t)\ \-1"
492 is used in several interfaces (e.g.,
493 .BR setreuid (2))
494 as a way to specify "no user ID".
495 Leaving
496 .IR "(uid_t)\ \-1"
497 unmapped and unusable guarantees that there will be no
498 confusion when using these interfaces.
500 .\" ============================================================
502 .SS Defining user and group ID mappings: writing to uid_map and gid_map
503 After the creation of a new user namespace, the
504 .I uid_map
505 file of
506 .I one
507 of the processes in the namespace may be written to
508 .I once
509 to define the mapping of user IDs in the new user namespace.
510 An attempt to write more than once to a
511 .I uid_map
512 file in a user namespace fails with the error
513 .BR EPERM .
514 Similar rules apply for
515 .I gid_map
516 files.
518 The lines written to
519 .IR uid_map
520 .RI ( gid_map )
521 must conform to the following rules:
522 .IP * 3
523 The three fields must be valid numbers,
524 and the last field must be greater than 0.
525 .IP *
526 Lines are terminated by newline characters.
527 .IP *
528 There is a limit on the number of lines in the file.
529 In Linux 4.14 and earlier, this limit was (arbitrarily)
530 .\" 5*12-byte records could fit in a 64B cache line
531 set at 5 lines.
532 Since Linux 4.15,
533 .\" commit 6397fac4915ab3002dc15aae751455da1a852f25
534 the limit is 340 lines.
535 In addition, the number of bytes written to
536 the file must be less than the system page size,
537 and the write must be performed at the start of the file (i.e.,
538 .BR lseek (2)
540 .BR pwrite (2)
541 can't be used to write to nonzero offsets in the file).
542 .IP *
543 The range of user IDs (group IDs)
544 specified in each line cannot overlap with the ranges
545 in any other lines.
546 In the initial implementation (Linux 3.8), this requirement was
547 satisfied by a simplistic implementation that imposed the further
548 requirement that
549 the values in both field 1 and field 2 of successive lines must be
550 in ascending numerical order,
551 which prevented some otherwise valid maps from being created.
552 Linux 3.9 and later
553 .\" commit 0bd14b4fd72afd5df41e9fd59f356740f22fceba
554 fix this limitation, allowing any valid set of nonoverlapping maps.
555 .IP *
556 At least one line must be written to the file.
558 Writes that violate the above rules fail with the error
559 .BR EINVAL .
561 In order for a process to write to the
562 .I /proc/[pid]/uid_map
563 .RI ( /proc/[pid]/gid_map )
564 file, all of the following requirements must be met:
565 .IP 1. 3
566 The writing process must have the
567 .BR CAP_SETUID
568 .RB ( CAP_SETGID )
569 capability in the user namespace of the process
570 .IR pid .
571 .IP 2.
572 The writing process must either be in the user namespace of the process
573 .I pid
574 or be in the parent user namespace of the process
575 .IR pid .
576 .IP 3.
577 The mapped user IDs (group IDs) must in turn have a mapping
578 in the parent user namespace.
579 .IP 4.
580 .\" commit db2e718a47984b9d71ed890eb2ea36ecf150de18
581 If a writing process is root (i.e. UID 0) trying to map host user ID 0,
582 it must have
583 .B CAP_SETFCAP
584 capability (since Linux 5.12).
585 .IP 5.
586 One of the following two cases applies:
588 .IP * 3
589 .IR Either
590 the writing process has the
591 .BR CAP_SETUID
592 .RB ( CAP_SETGID )
593 capability in the
594 .I parent
595 user namespace.
597 .IP + 3
598 No further restrictions apply:
599 the process can make mappings to arbitrary user IDs (group IDs)
600 in the parent user namespace.
602 .IP * 3
603 .IR Or
604 otherwise all of the following restrictions apply:
606 .IP + 3
607 The data written to
608 .I uid_map
609 .RI ( gid_map )
610 must consist of a single line that maps
611 the writing process's effective user ID
612 (group ID) in the parent user namespace to a user ID (group ID)
613 in the user namespace.
614 .IP +
615 The writing process must have the same effective user ID as the process
616 that created the user namespace.
617 .IP +
618 In the case of
619 .IR gid_map ,
620 use of the
621 .BR setgroups (2)
622 system call must first be denied by writing
623 .RI \(dq deny \(dq
624 to the
625 .I /proc/[pid]/setgroups
626 file (see below) before writing to
627 .IR gid_map .
631 Writes that violate the above rules fail with the error
632 .BR EPERM .
634 .\" ============================================================
636 .SS Interaction with system calls that change process UIDs or GIDs
637 In a user namespace where the
638 .I uid_map
639 file has not been written, the system calls that change user IDs will fail.
640 Similarly, if the
641 .I gid_map
642 file has not been written, the system calls that change group IDs will fail.
643 After the
644 .I uid_map
646 .I gid_map
647 files have been written, only the mapped values may be used in
648 system calls that change user and group IDs.
650 For user IDs, the relevant system calls include
651 .BR setuid (2),
652 .BR setfsuid (2),
653 .BR setreuid (2),
655 .BR setresuid (2).
656 For group IDs, the relevant system calls include
657 .BR setgid (2),
658 .BR setfsgid (2),
659 .BR setregid (2),
660 .BR setresgid (2),
662 .BR setgroups (2).
664 Writing
665 .RI \(dq deny \(dq
666 to the
667 .I /proc/[pid]/setgroups
668 file before writing to
669 .I /proc/[pid]/gid_map
670 .\" Things changed in Linux 3.19
671 .\" commit 9cc46516ddf497ea16e8d7cb986ae03a0f6b92f8
672 .\" commit 66d2f338ee4c449396b6f99f5e75cd18eb6df272
673 .\" http://lwn.net/Articles/626665/
674 will permanently disable
675 .BR setgroups (2)
676 in a user namespace and allow writing to
677 .I /proc/[pid]/gid_map
678 without having the
679 .BR CAP_SETGID
680 capability in the parent user namespace.
682 .\" ============================================================
684 .SS The /proc/[pid]/setgroups file
686 .\" commit 9cc46516ddf497ea16e8d7cb986ae03a0f6b92f8
687 .\" commit 66d2f338ee4c449396b6f99f5e75cd18eb6df272
688 .\" http://lwn.net/Articles/626665/
689 .\" http://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2014-8989
692 .I /proc/[pid]/setgroups
693 file displays the string
694 .RI \(dq allow \(dq
695 if processes in the user namespace that contains the process
696 .I pid
697 are permitted to employ the
698 .BR setgroups (2)
699 system call; it displays
700 .RI \(dq deny \(dq
702 .BR setgroups (2)
703 is not permitted in that user namespace.
704 Note that regardless of the value in the
705 .I /proc/[pid]/setgroups
706 file (and regardless of the process's capabilities), calls to
707 .BR setgroups (2)
708 are also not permitted if
709 .IR /proc/[pid]/gid_map
710 has not yet been set.
712 A privileged process (one with the
713 .BR CAP_SYS_ADMIN
714 capability in the namespace) may write either of the strings
715 .RI \(dq allow \(dq
717 .RI \(dq deny \(dq
718 to this file
719 .I before
720 writing a group ID mapping
721 for this user namespace to the file
722 .IR /proc/[pid]/gid_map .
723 Writing the string
724 .RI \(dq deny \(dq
725 prevents any process in the user namespace from employing
726 .BR setgroups (2).
728 The essence of the restrictions described in the preceding
729 paragraph is that it is permitted to write to
730 .I /proc/[pid]/setgroups
731 only so long as calling
732 .BR setgroups (2)
733 is disallowed because
734 .I /proc/[pid]/gid_map
735 has not been set.
736 This ensures that a process cannot transition from a state where
737 .BR setgroups (2)
738 is allowed to a state where
739 .BR setgroups (2)
740 is denied;
741 a process can transition only from
742 .BR setgroups (2)
743 being disallowed to
744 .BR setgroups (2)
745 being allowed.
747 The default value of this file in the initial user namespace is
748 .RI \(dq allow \(dq.
750 Once
751 .IR /proc/[pid]/gid_map
752 has been written to
753 (which has the effect of enabling
754 .BR setgroups (2)
755 in the user namespace),
756 it is no longer possible to disallow
757 .BR setgroups (2)
758 by writing
759 .RI \(dq deny \(dq
761 .IR /proc/[pid]/setgroups
762 (the write fails with the error
763 .BR EPERM ).
765 A child user namespace inherits the
766 .IR /proc/[pid]/setgroups
767 setting from its parent.
769 If the
770 .I setgroups
771 file has the value
772 .RI \(dq deny \(dq,
773 then the
774 .BR setgroups (2)
775 system call can't subsequently be reenabled (by writing
776 .RI \(dq allow \(dq
777 to the file) in this user namespace.
778 (Attempts to do so fail with the error
779 .BR EPERM .)
780 This restriction also propagates down to all child user namespaces of
781 this user namespace.
784 .I /proc/[pid]/setgroups
785 file was added in Linux 3.19,
786 but was backported to many earlier stable kernel series,
787 because it addresses a security issue.
788 The issue concerned files with permissions such as "rwx\-\-\-rwx".
789 Such files give fewer permissions to "group" than they do to "other".
790 This means that dropping groups using
791 .BR setgroups (2)
792 might allow a process file access that it did not formerly have.
793 Before the existence of user namespaces this was not a concern,
794 since only a privileged process (one with the
795 .BR CAP_SETGID
796 capability) could call
797 .BR setgroups (2).
798 However, with the introduction of user namespaces,
799 it became possible for an unprivileged process to create
800 a new namespace in which the user had all privileges.
801 This then allowed formerly unprivileged
802 users to drop groups and thus gain file access
803 that they did not previously have.
805 .I /proc/[pid]/setgroups
806 file was added to address this security issue,
807 by denying any pathway for an unprivileged process to drop groups with
808 .BR setgroups (2).
810 .\" /proc/PID/setgroups
811 .\"     [allow == setgroups() is allowed, "deny" == setgroups() is disallowed]
812 .\"     * Can write if have CAP_SYS_ADMIN in NS
813 .\"     * Must write BEFORE writing to /proc/PID/gid_map
815 .\" setgroups()
816 .\"     * Must already have written to gid_map
817 .\"     * /proc/PID/setgroups must be "allow"
819 .\" /proc/PID/gid_map -- writing
820 .\"     * Must already have written "deny" to /proc/PID/setgroups
822 .\" ============================================================
824 .SS Unmapped user and group IDs
825 There are various places where an unmapped user ID (group ID)
826 may be exposed to user space.
827 For example, the first process in a new user namespace may call
828 .BR getuid (2)
829 before a user ID mapping has been defined for the namespace.
830 In most such cases, an unmapped user ID is converted
831 .\" from_kuid_munged(), from_kgid_munged()
832 to the overflow user ID (group ID);
833 the default value for the overflow user ID (group ID) is 65534.
834 See the descriptions of
835 .IR /proc/sys/kernel/overflowuid
837 .IR /proc/sys/kernel/overflowgid
839 .BR proc (5).
841 The cases where unmapped IDs are mapped in this fashion include
842 system calls that return user IDs
843 .RB ( getuid (2),
844 .BR getgid (2),
845 and similar),
846 credentials passed over a UNIX domain socket,
847 .\" also SO_PEERCRED
848 credentials returned by
849 .BR stat (2),
850 .BR waitid (2),
851 and the System V IPC "ctl"
852 .B IPC_STAT
853 operations,
854 credentials exposed by
855 .IR /proc/[pid]/status
856 and the files in
857 .IR /proc/sysvipc/* ,
858 credentials returned via the
859 .I si_uid
860 field in the
861 .I siginfo_t
862 received with a signal (see
863 .BR sigaction (2)),
864 credentials written to the process accounting file (see
865 .BR acct (5)),
866 and credentials returned with POSIX message queue notifications (see
867 .BR mq_notify (3)).
869 There is one notable case where unmapped user and group IDs are
870 .I not
871 .\" from_kuid(), from_kgid()
872 .\" Also F_GETOWNER_UIDS is an exception
873 converted to the corresponding overflow ID value.
874 When viewing a
875 .I uid_map
877 .I gid_map
878 file in which there is no mapping for the second field,
879 that field is displayed as 4294967295 (\-1 as an unsigned integer).
881 .\" ============================================================
883 .SS Accessing files
884 In order to determine permissions when an unprivileged process accesses a file,
885 the process credentials (UID, GID) and the file credentials
886 are in effect mapped back to what they would be in
887 the initial user namespace and then compared to determine
888 the permissions that the process has on the file.
889 The same is also of other objects that employ the credentials plus
890 permissions mask accessibility model, such as System V IPC objects
892 .\" ============================================================
894 .SS Operation of file-related capabilities
895 Certain capabilities allow a process to bypass various
896 kernel-enforced restrictions when performing operations on
897 files owned by other users or groups.
898 These capabilities are:
899 .BR CAP_CHOWN ,
900 .BR CAP_DAC_OVERRIDE ,
901 .BR CAP_DAC_READ_SEARCH ,
902 .BR CAP_FOWNER ,
904 .BR CAP_FSETID .
906 Within a user namespace,
907 these capabilities allow a process to bypass the rules
908 if the process has the relevant capability over the file,
909 meaning that:
910 .IP * 3
911 the process has the relevant effective capability in its user namespace; and
912 .IP *
913 the file's user ID and group ID both have valid mappings
914 in the user namespace.
917 .BR CAP_FOWNER
918 capability is treated somewhat exceptionally:
919 .\" These are the checks performed by the kernel function
920 .\" inode_owner_or_capable(). There is one exception to the exception:
921 .\" overriding the directory sticky permission bit requires that
922 .\" the file has a valid mapping for both its UID and GID.
923 it allows a process to bypass the corresponding rules so long as
924 at least the file's user ID has a mapping in the user namespace
925 (i.e., the file's group ID does not need to have a valid mapping).
927 .\" ============================================================
929 .SS Set-user-ID and set-group-ID programs
930 When a process inside a user namespace executes
931 a set-user-ID (set-group-ID) program,
932 the process's effective user (group) ID inside the namespace is changed
933 to whatever value is mapped for the user (group) ID of the file.
934 However, if either the user
935 .I or
936 the group ID of the file has no mapping inside the namespace,
937 the set-user-ID (set-group-ID) bit is silently ignored:
938 the new program is executed,
939 but the process's effective user (group) ID is left unchanged.
940 (This mirrors the semantics of executing a set-user-ID or set-group-ID
941 program that resides on a filesystem that was mounted with the
942 .BR MS_NOSUID
943 flag, as described in
944 .BR mount (2).)
946 .\" ============================================================
948 .SS Miscellaneous
949 When a process's user and group IDs are passed over a UNIX domain socket
950 to a process in a different user namespace (see the description of
951 .B SCM_CREDENTIALS
953 .BR unix (7)),
954 they are translated into the corresponding values as per the
955 receiving process's user and group ID mappings.
957 .SH CONFORMING TO
958 Namespaces are a Linux-specific feature.
960 .SH NOTES
961 Over the years, there have been a lot of features that have been added
962 to the Linux kernel that have been made available only to privileged users
963 because of their potential to confuse set-user-ID-root applications.
964 In general, it becomes safe to allow the root user in a user namespace to
965 use those features because it is impossible, while in a user namespace,
966 to gain more privilege than the root user of a user namespace has.
968 .\" ============================================================
970 .SS Availability
971 Use of user namespaces requires a kernel that is configured with the
972 .B CONFIG_USER_NS
973 option.
974 User namespaces require support in a range of subsystems across
975 the kernel.
976 When an unsupported subsystem is configured into the kernel,
977 it is not possible to configure user namespaces support.
979 As at Linux 3.8, most relevant subsystems supported user namespaces,
980 but a number of filesystems did not have the infrastructure needed
981 to map user and group IDs between user namespaces.
982 Linux 3.9 added the required infrastructure support for many of
983 the remaining unsupported filesystems
984 (Plan 9 (9P), Andrew File System (AFS), Ceph, CIFS, CODA, NFS, and OCFS2).
985 Linux 3.12 added support for the last of the unsupported major filesystems,
986 .\" commit d6970d4b726cea6d7a9bc4120814f95c09571fc3
987 XFS.
989 .SH EXAMPLES
990 The program below is designed to allow experimenting with
991 user namespaces, as well as other types of namespaces.
992 It creates namespaces as specified by command-line options and then executes
993 a command inside those namespaces.
994 The comments and
995 .I usage()
996 function inside the program provide a full explanation of the program.
997 The following shell session demonstrates its use.
999 First, we look at the run-time environment:
1001 .in +4n
1003 $ \fBuname \-rs\fP     # Need Linux 3.8 or later
1004 Linux 3.8.0
1005 $ \fBid \-u\fP         # Running as unprivileged user
1006 1000
1007 $ \fBid \-g\fP
1008 1000
1012 Now start a new shell in new user
1013 .RI ( \-U ),
1014 mount
1015 .RI ( \-m ),
1016 and PID
1017 .RI ( \-p )
1018 namespaces, with user ID
1019 .RI ( \-M )
1020 and group ID
1021 .RI ( \-G )
1022 1000 mapped to 0 inside the user namespace:
1024 .in +4n
1026 $ \fB./userns_child_exec \-p \-m \-U \-M \(aq0 1000 1\(aq \-G \(aq0 1000 1\(aq bash\fP
1030 The shell has PID 1, because it is the first process in the new
1031 PID namespace:
1033 .in +4n
1035 bash$ \fBecho $$\fP
1040 Mounting a new
1041 .I /proc
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:
1046 .in +4n
1048 bash$ \fBmount \-t proc proc /proc\fP
1049 bash$ \fBps ax\fP
1050   PID TTY      STAT   TIME COMMAND
1051     1 pts/3    S      0:00 bash
1052    22 pts/3    R+     0:00 ps ax
1056 Inside the user namespace, the shell has user and group ID 0,
1057 and a full set of permitted and effective capabilities:
1059 .in +4n
1061 bash$ \fBcat /proc/$$/status | egrep \(aq\(ha[UG]id\(aq\fP
1062 Uid:    0       0       0       0
1063 Gid:    0       0       0       0
1064 bash$ \fBcat /proc/$$/status | egrep \(aq\(haCap(Prm|Inh|Eff)\(aq\fP
1065 CapInh: 0000000000000000
1066 CapPrm: 0000001fffffffff
1067 CapEff: 0000001fffffffff
1070 .SS Program source
1073 /* userns_child_exec.c
1075    Licensed under GNU General Public License v2 or later
1077    Create a child process that executes a shell command in new
1078    namespace(s); allow UID and GID mappings to be specified when
1079    creating a user namespace.
1081 #define _GNU_SOURCE
1082 #include <sched.h>
1083 #include <unistd.h>
1084 #include <stdint.h>
1085 #include <stdlib.h>
1086 #include <sys/wait.h>
1087 #include <signal.h>
1088 #include <fcntl.h>
1089 #include <stdio.h>
1090 #include <string.h>
1091 #include <limits.h>
1092 #include <errno.h>
1094 /* A simple error\-handling function: print an error message based
1095    on the value in \(aqerrno\(aq and terminate the calling process. */
1097 #define errExit(msg)    do { perror(msg); exit(EXIT_FAILURE); \e
1098                         } while (0)
1100 struct child_args {
1101     char **argv;        /* Command to be executed by child, with args */
1102     int    pipe_fd[2];  /* Pipe used to synchronize parent and child */
1105 static int verbose;
1107 static void
1108 usage(char *pname)
1110     fprintf(stderr, "Usage: %s [options] cmd [arg...]\en\en", pname);
1111     fprintf(stderr, "Create a child process that executes a shell "
1112             "command in a new user namespace,\en"
1113             "and possibly also other new namespace(s).\en\en");
1114     fprintf(stderr, "Options can be:\en\en");
1115 #define fpe(str) fprintf(stderr, "    %s", str);
1116     fpe("\-i          New IPC namespace\en");
1117     fpe("\-m          New mount namespace\en");
1118     fpe("\-n          New network namespace\en");
1119     fpe("\-p          New PID namespace\en");
1120     fpe("\-u          New UTS namespace\en");
1121     fpe("\-U          New user namespace\en");
1122     fpe("\-M uid_map  Specify UID map for user namespace\en");
1123     fpe("\-G gid_map  Specify GID map for user namespace\en");
1124     fpe("\-z          Map user\(aqs UID and GID to 0 in user namespace\en");
1125     fpe("            (equivalent to: \-M \(aq0 <uid> 1\(aq \-G \(aq0 <gid> 1\(aq)\en");
1126     fpe("\-v          Display verbose messages\en");
1127     fpe("\en");
1128     fpe("If \-z, \-M, or \-G is specified, \-U is required.\en");
1129     fpe("It is not permitted to specify both \-z and either \-M or \-G.\en");
1130     fpe("\en");
1131     fpe("Map strings for \-M and \-G consist of records of the form:\en");
1132     fpe("\en");
1133     fpe("    ID\-inside\-ns   ID\-outside\-ns   len\en");
1134     fpe("\en");
1135     fpe("A map string can contain multiple records, separated"
1136         " by commas;\en");
1137     fpe("the commas are replaced by newlines before writing"
1138         " to map files.\en");
1140     exit(EXIT_FAILURE);
1143 /* Update the mapping file \(aqmap_file\(aq, with the value provided in
1144    \(aqmapping\(aq, a string that defines a UID or GID mapping. A UID or
1145    GID mapping consists of one or more newline\-delimited records
1146    of the form:
1148        ID_inside\-ns    ID\-outside\-ns   length
1150    Requiring the user to supply a string that contains newlines is
1151    of course inconvenient for command\-line use. Thus, we permit the
1152    use of commas to delimit records in this string, and replace them
1153    with newlines before writing the string to the file. */
1155 static void
1156 update_map(char *mapping, char *map_file)
1158     int fd;
1159     size_t map_len;     /* Length of \(aqmapping\(aq */
1161     /* Replace commas in mapping string with newlines. */
1163     map_len = strlen(mapping);
1164     for (int j = 0; j < map_len; j++)
1165         if (mapping[j] == \(aq,\(aq)
1166             mapping[j] = \(aq\en\(aq;
1168     fd = open(map_file, O_RDWR);
1169     if (fd == \-1) {
1170         fprintf(stderr, "ERROR: open %s: %s\en", map_file,
1171                 strerror(errno));
1172         exit(EXIT_FAILURE);
1173     }
1175     if (write(fd, mapping, map_len) != map_len) {
1176         fprintf(stderr, "ERROR: write %s: %s\en", map_file,
1177                 strerror(errno));
1178         exit(EXIT_FAILURE);
1179     }
1181     close(fd);
1184 /* Linux 3.19 made a change in the handling of setgroups(2) and the
1185    \(aqgid_map\(aq file to address a security issue. The issue allowed
1186    *unprivileged* users to employ user namespaces in order to drop
1187    The upshot of the 3.19 changes is that in order to update the
1188    \(aqgid_maps\(aq file, use of the setgroups() system call in this
1189    user namespace must first be disabled by writing "deny" to one of
1190    the /proc/PID/setgroups files for this namespace.  That is the
1191    purpose of the following function. */
1193 static void
1194 proc_setgroups_write(pid_t child_pid, char *str)
1196     char setgroups_path[PATH_MAX];
1197     int fd;
1199     snprintf(setgroups_path, PATH_MAX, "/proc/%jd/setgroups",
1200             (intmax_t) child_pid);
1202     fd = open(setgroups_path, O_RDWR);
1203     if (fd == \-1) {
1205         /* We may be on a system that doesn\(aqt support
1206            /proc/PID/setgroups. In that case, the file won\(aqt exist,
1207            and the system won\(aqt impose the restrictions that Linux 3.19
1208            added. That\(aqs fine: we don\(aqt need to do anything in order
1209            to permit \(aqgid_map\(aq to be updated.
1211            However, if the error from open() was something other than
1212            the ENOENT error that is expected for that case,  let the
1213            user know. */
1215         if (errno != ENOENT)
1216             fprintf(stderr, "ERROR: open %s: %s\en", setgroups_path,
1217                 strerror(errno));
1218         return;
1219     }
1221     if (write(fd, str, strlen(str)) == \-1)
1222         fprintf(stderr, "ERROR: write %s: %s\en", setgroups_path,
1223             strerror(errno));
1225     close(fd);
1228 static int              /* Start function for cloned child */
1229 childFunc(void *arg)
1231     struct child_args *args = arg;
1232     char ch;
1234     /* Wait until the parent has updated the UID and GID mappings.
1235        See the comment in main(). We wait for end of file on a
1236        pipe that will be closed by the parent process once it has
1237        updated the mappings. */
1239     close(args\->pipe_fd[1]);    /* Close our descriptor for the write
1240                                    end of the pipe so that we see EOF
1241                                    when parent closes its descriptor. */
1242     if (read(args\->pipe_fd[0], &ch, 1) != 0) {
1243         fprintf(stderr,
1244                 "Failure in child: read from pipe returned != 0\en");
1245         exit(EXIT_FAILURE);
1246     }
1248     close(args\->pipe_fd[0]);
1250     /* Execute a shell command. */
1252     printf("About to exec %s\en", args\->argv[0]);
1253     execvp(args\->argv[0], args\->argv);
1254     errExit("execvp");
1257 #define STACK_SIZE (1024 * 1024)
1259 static char child_stack[STACK_SIZE];    /* Space for child\(aqs stack */
1262 main(int argc, char *argv[])
1264     int flags, opt, map_zero;
1265     pid_t child_pid;
1266     struct child_args args;
1267     char *uid_map, *gid_map;
1268     const int MAP_BUF_SIZE = 100;
1269     char map_buf[MAP_BUF_SIZE];
1270     char map_path[PATH_MAX];
1272     /* Parse command\-line options. The initial \(aq+\(aq character in
1273        the final getopt() argument prevents GNU\-style permutation
1274        of command\-line options. That\(aqs useful, since sometimes
1275        the \(aqcommand\(aq to be executed by this program itself
1276        has command\-line options. We don\(aqt want getopt() to treat
1277        those as options to this program. */
1279     flags = 0;
1280     verbose = 0;
1281     gid_map = NULL;
1282     uid_map = NULL;
1283     map_zero = 0;
1284     while ((opt = getopt(argc, argv, "+imnpuUM:G:zv")) != \-1) {
1285         switch (opt) {
1286         case \(aqi\(aq: flags |= CLONE_NEWIPC;        break;
1287         case \(aqm\(aq: flags |= CLONE_NEWNS;         break;
1288         case \(aqn\(aq: flags |= CLONE_NEWNET;        break;
1289         case \(aqp\(aq: flags |= CLONE_NEWPID;        break;
1290         case \(aqu\(aq: flags |= CLONE_NEWUTS;        break;
1291         case \(aqv\(aq: verbose = 1;                  break;
1292         case \(aqz\(aq: map_zero = 1;                 break;
1293         case \(aqM\(aq: uid_map = optarg;             break;
1294         case \(aqG\(aq: gid_map = optarg;             break;
1295         case \(aqU\(aq: flags |= CLONE_NEWUSER;       break;
1296         default:  usage(argv[0]);
1297         }
1298     }
1300     /* \-M or \-G without \-U is nonsensical */
1302     if (((uid_map != NULL || gid_map != NULL || map_zero) &&
1303                 !(flags & CLONE_NEWUSER)) ||
1304             (map_zero && (uid_map != NULL || gid_map != NULL)))
1305         usage(argv[0]);
1307     args.argv = &argv[optind];
1309     /* We use a pipe to synchronize the parent and child, in order to
1310        ensure that the parent sets the UID and GID maps before the child
1311        calls execve(). This ensures that the child maintains its
1312        capabilities during the execve() in the common case where we
1313        want to map the child\(aqs effective user ID to 0 in the new user
1314        namespace. Without this synchronization, the child would lose
1315        its capabilities if it performed an execve() with nonzero
1316        user IDs (see the capabilities(7) man page for details of the
1317        transformation of a process\(aqs capabilities during execve()). */
1319     if (pipe(args.pipe_fd) == \-1)
1320         errExit("pipe");
1322     /* Create the child in new namespace(s). */
1324     child_pid = clone(childFunc, child_stack + STACK_SIZE,
1325                       flags | SIGCHLD, &args);
1326     if (child_pid == \-1)
1327         errExit("clone");
1329     /* Parent falls through to here. */
1331     if (verbose)
1332         printf("%s: PID of child created by clone() is %jd\en",
1333                 argv[0], (intmax_t) child_pid);
1335     /* Update the UID and GID maps in the child. */
1337     if (uid_map != NULL || map_zero) {
1338         snprintf(map_path, PATH_MAX, "/proc/%jd/uid_map",
1339                 (intmax_t) child_pid);
1340         if (map_zero) {
1341             snprintf(map_buf, MAP_BUF_SIZE, "0 %jd 1",
1342                     (intmax_t) getuid());
1343             uid_map = map_buf;
1344         }
1345         update_map(uid_map, map_path);
1346     }
1348     if (gid_map != NULL || map_zero) {
1349         proc_setgroups_write(child_pid, "deny");
1351         snprintf(map_path, PATH_MAX, "/proc/%jd/gid_map",
1352                 (intmax_t) child_pid);
1353         if (map_zero) {
1354             snprintf(map_buf, MAP_BUF_SIZE, "0 %ld 1",
1355                     (intmax_t) getgid());
1356             gid_map = map_buf;
1357         }
1358         update_map(gid_map, map_path);
1359     }
1361     /* Close the write end of the pipe, to signal to the child that we
1362        have updated the UID and GID maps. */
1364     close(args.pipe_fd[1]);
1366     if (waitpid(child_pid, NULL, 0) == \-1)      /* Wait for child */
1367         errExit("waitpid");
1369     if (verbose)
1370         printf("%s: terminating\en", argv[0]);
1372     exit(EXIT_SUCCESS);
1375 .SH SEE ALSO
1376 .BR newgidmap (1),      \" From the shadow package
1377 .BR newuidmap (1),      \" From the shadow package
1378 .BR clone (2),
1379 .BR ptrace (2),
1380 .BR setns (2),
1381 .BR unshare (2),
1382 .BR proc (5),
1383 .BR subgid (5),         \" From the shadow package
1384 .BR subuid (5),         \" From the shadow package
1385 .BR capabilities (7),
1386 .BR cgroup_namespaces (7),
1387 .BR credentials (7),
1388 .BR namespaces (7),
1389 .BR pid_namespaces (7)
1391 The kernel source file
1392 .IR Documentation/admin\-guide/namespaces/resource\-control.rst .