]> git.ipfire.org Git - thirdparty/man-pages.git/blob - man7/user_namespaces.7
user_namespaces.7: Describe the effect of file-related capabilities inside use namespaces
[thirdparty/man-pages.git] / man7 / user_namespaces.7
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 2019-03-06 "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)
64 or
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)
76 or
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)
84 or
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)
98 or
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.
107 .PP
108 The
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).
114 .\"
115 .\" ============================================================
116 .\"
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)
134 and
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).
139 .PP
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.
149 .PP
150 A call to
151 .BR clone (2),
152 .BR unshare (2),
153 or
154 .BR setns (2)
155 using the
156 .BR CLONE_NEWUSER
157 flag sets the "securebits" flags
158 (see
159 .BR capabilities (7))
160 to their default values (all flags disabled) in the child (for
161 .BR clone (2))
162 or caller (for
163 .BR unshare (2),
164 or
165 .BR setns (2)).
166 Note that because the caller no longer has capabilities
167 in its original user namespace after a call to
168 .BR setns (2),
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
171 .BR setns (2)
172 calls to move to another user namespace and then return to
173 its original user namespace.
174 .PP
175 The rules for determining whether or not a process has a capability
176 in a particular user namespace are as follows:
177 .IP 1. 3
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
182 set in various ways.
183 For example, it may execute a set-user-ID program or an
184 executable with associated file capabilities.
185 In addition,
186 a process may gain capabilities via the effect of
187 .BR clone (2),
188 .BR unshare (2),
189 or
190 .BR setns (2),
191 as already described.
192 .\" In the 3.8 sources, see security/commoncap.c::cap_capable():
193 .IP 2.
194 If a process has a capability in a user namespace,
195 then it has that capability in all child (and further removed descendant)
196 namespaces as well.
197 .IP 3.
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
207 .\" on this point
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.
215 The
216 .B NS_GET_OWNER_UID
217 .BR ioctl (2)
218 operation can be used to discover the user ID of the owner of the namespace;
219 see
220 .BR ioctl_ns (2).
221 .\"
222 .\" ============================================================
223 .\"
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).
232 .PP
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
236 .BR CAP_SYS_TIME ),
237 loading a kernel module (governed by
238 .BR CAP_SYS_MODULE ),
239 and creating a device (governed by
240 .BR CAP_MKNOD ).
241 Only a process with privileges in the
242 .I initial
243 user namespace can perform such operations.
244 .PP
245 Holding
246 .B CAP_SYS_ADMIN
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
251 .PP
252 .RS 4
253 .PD 0
254 .IP * 2
255 .IR /proc
256 (since Linux 3.8)
257 .IP *
258 .IR /sys
259 (since Linux 3.8)
260 .IP *
261 .IR devpts
262 (since Linux 3.9)
263 .IP *
264 .BR tmpfs (5)
265 (since Linux 3.9)
266 .IP *
267 .IR ramfs
268 (since Linux 3.9)
269 .IP *
270 .IR mqueue
271 (since Linux 3.9)
272 .IP *
273 .IR bpf
274 .\" commit b2197755b2633e164a439682fb05a9b5ea48f706
275 (since Linux 4.4)
276 .PD
277 .RE
278 .PP
279 Holding
280 .B CAP_SYS_ADMIN
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
286 .IR """none,name="""
287 option).
288 .PP
289 Holding
290 .B CAP_SYS_ADMIN
291 within the user namespace that owns a process's PID namespace
292 allows (since Linux 3.8)
293 that process to mount
294 .I /proc
295 filesystems.
296 .PP
297 Note however, that mounting block-based filesystems can be done
298 only by a process that holds
299 .BR CAP_SYS_ADMIN
300 in the initial user namespace.
301 .\"
302 .\" ============================================================
303 .\"
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
307 .B CAP_SYS_ADMIN
308 capability in the caller's user namespace.
309 .PP
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.
315 .PP
316 If
317 .BR CLONE_NEWUSER
318 is specified along with other
319 .B CLONE_NEW*
320 flags in a single
321 .BR clone (2)
322 or
323 .BR unshare (2)
324 call, the user namespace is guaranteed to be created first,
325 giving the child
326 .RB ( clone (2))
327 or caller
328 .RB ( unshare (2))
329 privileges over the remaining namespaces created by the call.
330 Thus, it is possible for an unprivileged caller to specify this combination
331 of flags.
332 .PP
333 When a new namespace (other than a user namespace) is created via
334 .BR clone (2)
335 or
336 .BR unshare (2),
337 the kernel records the user namespace of the creating process as the owner of
338 the new namespace.
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.
348 In this case,
349 the kernel will determine which user namespace owns
350 the process's UTS namespace, and check whether the process has the
351 required capability
352 .RB ( CAP_SYS_ADMIN )
353 in that user namespace.
354 .PP
355 The
356 .BR NS_GET_USERNS
357 .BR ioctl (2)
358 operation can be used to discover the user namespace
359 that owns a nonuser namespace; see
360 .BR ioctl_ns (2).
361 .\"
362 .\" ============================================================
363 .\"
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.
368 The
369 .IR /proc/[pid]/uid_map
370 and
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
376 .IR pid .
377 These files can be read to view the mappings in a user namespace and
378 written to (once) to define the mappings.
379 .PP
380 The description in the following paragraphs explains the details for
381 .IR uid_map ;
382 .IR gid_map
383 is exactly the same,
384 but each instance of "user ID" is replaced by "group ID".
385 .PP
386 The
387 .I uid_map
388 file exposes the mapping of user IDs from the user namespace
389 of the process
390 .IR pid
391 to the user namespace of the process that opened
392 .IR uid_map
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
396 .I uid_map
397 file, depending on the user ID mappings for the user namespaces
398 of the reading processes.
399 .PP
400 Each line in the
401 .I uid_map
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:
411 .IP (1) 4
412 The start of the range of user IDs in
413 the user namespace of the process
414 .IR pid .
415 .IP (2)
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
419 .I uid_map
420 and the process
421 .IR pid
422 are in the same user namespace, as follows:
423 .RS
424 .IP a) 3
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
428 .IR uid_map .
429 .IP b)
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
433 .IR pid .
434 This case enables the opener of
435 .I uid_map
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.
440 .RE
441 .IP (3)
442 The length of the range of user IDs that is mapped between the two
443 user namespaces.
444 .PP
445 System calls that return user IDs (group IDs)\(emfor example,
446 .BR getuid (2),
447 .BR getgid (2),
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.
451 .PP
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
456 .BR stat (2),
457 the IDs are mapped in the opposite direction,
458 to produce values relative to the process user and group ID mappings.
459 .PP
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.
463 Looking at the
464 .I uid_map
465 file
466 .RI ( gid_map
467 is the same) from a shell in the initial namespace shows:
468 .PP
469 .in +4n
470 .EX
471 $ \fBcat /proc/$$/uid_map\fP
472 0 0 4294967295
473 .EE
474 .in
475 .PP
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.
481 This is deliberate:
482 .IR "(uid_t)\ \-1"
483 is used in several interfaces (e.g.,
484 .BR setreuid (2))
485 as a way to specify "no user ID".
486 Leaving
487 .IR "(uid_t)\ \-1"
488 unmapped and unusable guarantees that there will be no
489 confusion when using these interfaces.
490 .\"
491 .\" ============================================================
492 .\"
493 .SS Defining user and group ID mappings: writing to uid_map and gid_map
494 .PP
495 After the creation of a new user namespace, the
496 .I uid_map
497 file of
498 .I one
499 of the processes in the namespace may be written to
500 .I once
501 to define the mapping of user IDs in the new user namespace.
502 An attempt to write more than once to a
503 .I uid_map
504 file in a user namespace fails with the error
505 .BR EPERM .
506 Similar rules apply for
507 .I gid_map
508 files.
509 .PP
510 The lines written to
511 .IR uid_map
512 .RI ( gid_map )
513 must conform to the following rules:
514 .IP * 3
515 The three fields must be valid numbers,
516 and the last field must be greater than 0.
517 .IP *
518 Lines are terminated by newline characters.
519 .IP *
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
523 set at 5 lines.
524 Since Linux 4.15,
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.,
530 .BR lseek (2)
531 and
532 .BR pwrite (2)
533 can't be used to write to nonzero offsets in the file).
534 .IP *
535 The range of user IDs (group IDs)
536 specified in each line cannot overlap with the ranges
537 in any other lines.
538 In the initial implementation (Linux 3.8), this requirement was
539 satisfied by a simplistic implementation that imposed the further
540 requirement that
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.
544 Linux 3.9 and later
545 .\" commit 0bd14b4fd72afd5df41e9fd59f356740f22fceba
546 fix this limitation, allowing any valid set of nonoverlapping maps.
547 .IP *
548 At least one line must be written to the file.
549 .PP
550 Writes that violate the above rules fail with the error
551 .BR EINVAL .
552 .PP
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:
557 .IP 1. 3
558 The writing process must have the
559 .BR CAP_SETUID
560 .RB ( CAP_SETGID )
561 capability in the user namespace of the process
562 .IR pid .
563 .IP 2.
564 The writing process must either be in the user namespace of the process
565 .I pid
566 or be in the parent user namespace of the process
567 .IR pid .
568 .IP 3.
569 The mapped user IDs (group IDs) must in turn have a mapping
570 in the parent user namespace.
571 .IP 4.
572 One of the following two cases applies:
573 .RS
574 .IP * 3
575 .IR Either
576 the writing process has the
577 .BR CAP_SETUID
578 .RB ( CAP_SETGID )
579 capability in the
580 .I parent
581 user namespace.
582 .RS
583 .IP + 3
584 No further restrictions apply:
585 the process can make mappings to arbitrary user IDs (group IDs)
586 in the parent user namespace.
587 .RE
588 .IP * 3
589 .IR Or
590 otherwise all of the following restrictions apply:
591 .RS
592 .IP + 3
593 The data written to
594 .I uid_map
595 .RI ( gid_map )
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.
600 .IP +
601 The writing process must have the same effective user ID as the process
602 that created the user namespace.
603 .IP +
604 In the case of
605 .IR gid_map ,
606 use of the
607 .BR setgroups (2)
608 system call must first be denied by writing
609 .RI \(dq deny \(dq
610 to the
611 .I /proc/[pid]/setgroups
612 file (see below) before writing to
613 .IR gid_map .
614 .RE
615 .RE
616 .PP
617 Writes that violate the above rules fail with the error
618 .BR EPERM .
619 .\"
620 .\" ============================================================
621 .\"
622 .SS Interaction with system calls that change process UIDs or GIDs
623 In a user namespace where the
624 .I uid_map
625 file has not been written, the system calls that change user IDs will fail.
626 Similarly, if the
627 .I gid_map
628 file has not been written, the system calls that change group IDs will fail.
629 After the
630 .I uid_map
631 and
632 .I gid_map
633 files have been written, only the mapped values may be used in
634 system calls that change user and group IDs.
635 .PP
636 For user IDs, the relevant system calls include
637 .BR setuid (2),
638 .BR setfsuid (2),
639 .BR setreuid (2),
640 and
641 .BR setresuid (2).
642 For group IDs, the relevant system calls include
643 .BR setgid (2),
644 .BR setfsgid (2),
645 .BR setregid (2),
646 .BR setresgid (2),
647 and
648 .BR setgroups (2).
649 .PP
650 Writing
651 .RI \(dq deny \(dq
652 to the
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
661 .BR setgroups (2)
662 in a user namespace and allow writing to
663 .I /proc/[pid]/gid_map
664 without having the
665 .BR CAP_SETGID
666 capability in the parent user namespace.
667 .\"
668 .\" ============================================================
669 .\"
670 .SS The /proc/[pid]/setgroups file
671 .\"
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
676 .\"
677 The
678 .I /proc/[pid]/setgroups
679 file displays the string
680 .RI \(dq allow \(dq
681 if processes in the user namespace that contains the process
682 .I pid
683 are permitted to employ the
684 .BR setgroups (2)
685 system call; it displays
686 .RI \(dq deny \(dq
687 if
688 .BR setgroups (2)
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
693 .BR setgroups (2)
694 are also not permitted if
695 .IR /proc/[pid]/gid_map
696 has not yet been set.
697 .PP
698 A privileged process (one with the
699 .BR CAP_SYS_ADMIN
700 capability in the namespace) may write either of the strings
701 .RI \(dq allow \(dq
702 or
703 .RI \(dq deny \(dq
704 to this file
705 .I before
706 writing a group ID mapping
707 for this user namespace to the file
708 .IR /proc/[pid]/gid_map .
709 Writing the string
710 .RI \(dq deny \(dq
711 prevents any process in the user namespace from employing
712 .BR setgroups (2).
713 .PP
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
718 .BR setgroups (2)
719 is disallowed because
720 .I /proc/[pid]gid_map
721 has not been set.
722 This ensures that a process cannot transition from a state where
723 .BR setgroups (2)
724 is allowed to a state where
725 .BR setgroups (2)
726 is denied;
727 a process can transition only from
728 .BR setgroups (2)
729 being disallowed to
730 .BR setgroups (2)
731 being allowed.
732 .PP
733 The default value of this file in the initial user namespace is
734 .RI \(dq allow \(dq.
735 .PP
736 Once
737 .IR /proc/[pid]/gid_map
738 has been written to
739 (which has the effect of enabling
740 .BR setgroups (2)
741 in the user namespace),
742 it is no longer possible to disallow
743 .BR setgroups (2)
744 by writing
745 .RI \(dq deny \(dq
746 to
747 .IR /proc/[pid]/setgroups
748 (the write fails with the error
749 .BR EPERM ).
750 .PP
751 A child user namespace inherits the
752 .IR /proc/[pid]/setgroups
753 setting from its parent.
754 .PP
755 If the
756 .I setgroups
757 file has the value
758 .RI \(dq deny \(dq,
759 then the
760 .BR setgroups (2)
761 system call can't subsequently be reenabled (by writing
762 .RI \(dq allow \(dq
763 to the file) in this user namespace.
764 (Attempts to do so fail with the error
765 .BR EPERM .)
766 This restriction also propagates down to all child user namespaces of
767 this user namespace.
768 .PP
769 The
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
777 .BR setgroups (2)
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
781 .BR CAP_SETGID
782 capability) could call
783 .BR setgroups (2).
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.
790 The
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
794 .BR setgroups (2).
795 .\"
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
800 .\"
801 .\" setgroups()
802 .\" * Must already have written to gid_map
803 .\" * /proc/PID/setgroups must be "allow"
804 .\"
805 .\" /proc/PID/gid_map -- writing
806 .\" * Must already have written "deny" to /proc/PID/setgroups
807 .\"
808 .\" ============================================================
809 .\"
810 .SS Unmapped user and group IDs
811 .PP
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
815 .BR getuid (2)
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
823 and
824 .IR /proc/sys/kernel/overflowgid
825 in
826 .BR proc (5).
827 .PP
828 The cases where unmapped IDs are mapped in this fashion include
829 system calls that return user IDs
830 .RB ( getuid (2),
831 .BR getgid (2),
832 and similar),
833 credentials passed over a UNIX domain socket,
834 .\" also SO_PEERCRED
835 credentials returned by
836 .BR stat (2),
837 .BR waitid (2),
838 and the System V IPC "ctl"
839 .B IPC_STAT
840 operations,
841 credentials exposed by
842 .IR /proc/[pid]/status
843 and the files in
844 .IR /proc/sysvipc/* ,
845 credentials returned via the
846 .I si_uid
847 field in the
848 .I siginfo_t
849 received with a signal (see
850 .BR sigaction (2)),
851 credentials written to the process accounting file (see
852 .BR acct (5)),
853 and credentials returned with POSIX message queue notifications (see
854 .BR mq_notify (3)).
855 .PP
856 There is one notable case where unmapped user and group IDs are
857 .I not
858 .\" from_kuid(), from_kgid()
859 .\" Also F_GETOWNER_UIDS is an exception
860 converted to the corresponding overflow ID value.
861 When viewing a
862 .I uid_map
863 or
864 .I gid_map
865 file in which there is no mapping for the second field,
866 that field is displayed as 4294967295 (\-1 as an unsigned integer).
867 .\"
868 .\" ============================================================
869 .\"
870 .SS Accessing files
871 .PP
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.
878 .\"
879 .\" ============================================================
880 .\"
881 .SS Operation of file-related capabilities
882 .PP
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:
887 .BR CAP_CHOWN ,
888 .BR CAP_DAC_OVERRIDE ,
889 .BR CAP_DAC_READ_SEARCH ,
890 .BR CAP_FOWNER ,
891 and
892 .BR CAP_FSETID .
893 .PP
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,
897 meaning that:
898 .IP * 3
899 the process has the relevant effective capability in its user namespace; and
900 .IP *
901 the file's user ID and group ID both have valid mappings
902 in the user namespace.
903 .PP
904 The
905 .BR CAP_FOWNER
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).
914 .\"
915 .\" ============================================================
916 .\"
917 .SS Set-user-ID and set-group-ID programs
918 .PP
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
924 .I or
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
931 .BR MS_NOSUID
932 flag, as described in
933 .BR mount (2).)
934 .\"
935 .\" ============================================================
936 .\"
937 .SS Miscellaneous
938 .PP
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
941 .B SCM_CREDENTIALS
942 in
943 .BR unix (7)),
944 they are translated into the corresponding values as per the
945 receiving process's user and group ID mappings.
946 .\"
947 .SH CONFORMING TO
948 Namespaces are a Linux-specific feature.
949 .\"
950 .SH NOTES
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.
957 .\"
958 .\" ============================================================
959 .\"
960 .SS Availability
961 Use of user namespaces requires a kernel that is configured with the
962 .B CONFIG_USER_NS
963 option.
964 User namespaces require support in a range of subsystems across
965 the kernel.
966 When an unsupported subsystem is configured into the kernel,
967 it is not possible to configure user namespaces support.
968 .PP
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
977 XFS.
978 .\"
979 .SH EXAMPLE
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.
984 The comments and
985 .I usage()
986 function inside the program provide a full explanation of the program.
987 The following shell session demonstrates its use.
988 .PP
989 First, we look at the run-time environment:
990 .PP
991 .in +4n
992 .EX
993 $ \fBuname \-rs\fP # Need Linux 3.8 or later
994 Linux 3.8.0
995 $ \fBid \-u\fP # Running as unprivileged user
996 1000
997 $ \fBid \-g\fP
998 1000
999 .EE
1000 .in
1001 .PP
1002 Now start a new shell in new user
1003 .RI ( \-U ),
1004 mount
1005 .RI ( \-m ),
1006 and PID
1007 .RI ( \-p )
1008 namespaces, with user ID
1009 .RI ( \-M )
1010 and group ID
1011 .RI ( \-G )
1012 1000 mapped to 0 inside the user namespace:
1013 .PP
1014 .in +4n
1015 .EX
1016 $ \fB./userns_child_exec \-p \-m \-U \-M '0 1000 1' \-G '0 1000 1' bash\fP
1017 .EE
1018 .in
1019 .PP
1020 The shell has PID 1, because it is the first process in the new
1021 PID namespace:
1022 .PP
1023 .in +4n
1024 .EX
1025 bash$ \fBecho $$\fP
1026 1
1027 .EE
1028 .in
1029 .PP
1030 Mounting a new
1031 .I /proc
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:
1035 .PP
1036 .in +4n
1037 .EX
1038 bash$ \fBmount \-t proc proc /proc\fP
1039 bash$ \fBps ax\fP
1040 PID TTY STAT TIME COMMAND
1041 1 pts/3 S 0:00 bash
1042 22 pts/3 R+ 0:00 ps ax
1043 .EE
1044 .in
1045 .PP
1046 Inside the user namespace, the shell has user and group ID 0,
1047 and a full set of permitted and effective capabilities:
1048 .PP
1049 .in +4n
1050 .EX
1051 bash$ \fBcat /proc/$$/status | egrep '^[UG]id'\fP
1052 Uid: 0 0 0 0
1053 Gid: 0 0 0 0
1054 bash$ \fBcat /proc/$$/status | egrep '^Cap(Prm|Inh|Eff)'\fP
1055 CapInh: 0000000000000000
1056 CapPrm: 0000001fffffffff
1057 CapEff: 0000001fffffffff
1058 .EE
1059 .in
1060 .SS Program source
1061 \&
1062 .EX
1063 /* userns_child_exec.c
1064
1065 Licensed under GNU General Public License v2 or later
1066
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.
1070 */
1071 #define _GNU_SOURCE
1072 #include <sched.h>
1073 #include <unistd.h>
1074 #include <stdlib.h>
1075 #include <sys/wait.h>
1076 #include <signal.h>
1077 #include <fcntl.h>
1078 #include <stdio.h>
1079 #include <string.h>
1080 #include <limits.h>
1081 #include <errno.h>
1082
1083 /* A simple error\-handling function: print an error message based
1084 on the value in \(aqerrno\(aq and terminate the calling process */
1085
1086 #define errExit(msg) do { perror(msg); exit(EXIT_FAILURE); \e
1087 } while (0)
1088
1089 struct child_args {
1090 char **argv; /* Command to be executed by child, with args */
1091 int pipe_fd[2]; /* Pipe used to synchronize parent and child */
1092 };
1093
1094 static int verbose;
1095
1096 static void
1097 usage(char *pname)
1098 {
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");
1116 fpe("\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");
1119 fpe("\en");
1120 fpe("Map strings for \-M and \-G consist of records of the form:\en");
1121 fpe("\en");
1122 fpe(" ID\-inside\-ns ID\-outside\-ns len\en");
1123 fpe("\en");
1124 fpe("A map string can contain multiple records, separated"
1125 " by commas;\en");
1126 fpe("the commas are replaced by newlines before writing"
1127 " to map files.\en");
1128
1129 exit(EXIT_FAILURE);
1130 }
1131
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
1135 of the form:
1136
1137 ID_inside\-ns ID\-outside\-ns length
1138
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. */
1143
1144 static void
1145 update_map(char *mapping, char *map_file)
1146 {
1147 int fd, j;
1148 size_t map_len; /* Length of \(aqmapping\(aq */
1149
1150 /* Replace commas in mapping string with newlines */
1151
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;
1156
1157 fd = open(map_file, O_RDWR);
1158 if (fd == \-1) {
1159 fprintf(stderr, "ERROR: open %s: %s\en", map_file,
1160 strerror(errno));
1161 exit(EXIT_FAILURE);
1162 }
1163
1164 if (write(fd, mapping, map_len) != map_len) {
1165 fprintf(stderr, "ERROR: write %s: %s\en", map_file,
1166 strerror(errno));
1167 exit(EXIT_FAILURE);
1168 }
1169
1170 close(fd);
1171 }
1172
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. */
1181
1182 static void
1183 proc_setgroups_write(pid_t child_pid, char *str)
1184 {
1185 char setgroups_path[PATH_MAX];
1186 int fd;
1187
1188 snprintf(setgroups_path, PATH_MAX, "/proc/%ld/setgroups",
1189 (long) child_pid);
1190
1191 fd = open(setgroups_path, O_RDWR);
1192 if (fd == \-1) {
1193
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.
1199
1200 However, if the error from open() was something other than
1201 the ENOENT error that is expected for that case, let the
1202 user know. */
1203
1204 if (errno != ENOENT)
1205 fprintf(stderr, "ERROR: open %s: %s\en", setgroups_path,
1206 strerror(errno));
1207 return;
1208 }
1209
1210 if (write(fd, str, strlen(str)) == \-1)
1211 fprintf(stderr, "ERROR: write %s: %s\en", setgroups_path,
1212 strerror(errno));
1213
1214 close(fd);
1215 }
1216
1217 static int /* Start function for cloned child */
1218 childFunc(void *arg)
1219 {
1220 struct child_args *args = (struct child_args *) arg;
1221 char ch;
1222
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. */
1227
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) {
1232 fprintf(stderr,
1233 "Failure in child: read from pipe returned != 0\en");
1234 exit(EXIT_FAILURE);
1235 }
1236
1237 close(args\->pipe_fd[0]);
1238
1239 /* Execute a shell command */
1240
1241 printf("About to exec %s\en", args\->argv[0]);
1242 execvp(args\->argv[0], args\->argv);
1243 errExit("execvp");
1244 }
1245
1246 #define STACK_SIZE (1024 * 1024)
1247
1248 static char child_stack[STACK_SIZE]; /* Space for child\(aqs stack */
1249
1250 int
1251 main(int argc, char *argv[])
1252 {
1253 int flags, opt, map_zero;
1254 pid_t child_pid;
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];
1260
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. */
1267
1268 flags = 0;
1269 verbose = 0;
1270 gid_map = NULL;
1271 uid_map = NULL;
1272 map_zero = 0;
1273 while ((opt = getopt(argc, argv, "+imnpuUM:G:zv")) != \-1) {
1274 switch (opt) {
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]);
1286 }
1287 }
1288
1289 /* \-M or \-G without \-U is nonsensical */
1290
1291 if (((uid_map != NULL || gid_map != NULL || map_zero) &&
1292 !(flags & CLONE_NEWUSER)) ||
1293 (map_zero && (uid_map != NULL || gid_map != NULL)))
1294 usage(argv[0]);
1295
1296 args.argv = &argv[optind];
1297
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()). */
1307
1308 if (pipe(args.pipe_fd) == \-1)
1309 errExit("pipe");
1310
1311 /* Create the child in new namespace(s) */
1312
1313 child_pid = clone(childFunc, child_stack + STACK_SIZE,
1314 flags | SIGCHLD, &args);
1315 if (child_pid == \-1)
1316 errExit("clone");
1317
1318 /* Parent falls through to here */
1319
1320 if (verbose)
1321 printf("%s: PID of child created by clone() is %ld\en",
1322 argv[0], (long) child_pid);
1323
1324 /* Update the UID and GID maps in the child */
1325
1326 if (uid_map != NULL || map_zero) {
1327 snprintf(map_path, PATH_MAX, "/proc/%ld/uid_map",
1328 (long) child_pid);
1329 if (map_zero) {
1330 snprintf(map_buf, MAP_BUF_SIZE, "0 %ld 1", (long) getuid());
1331 uid_map = map_buf;
1332 }
1333 update_map(uid_map, map_path);
1334 }
1335
1336 if (gid_map != NULL || map_zero) {
1337 proc_setgroups_write(child_pid, "deny");
1338
1339 snprintf(map_path, PATH_MAX, "/proc/%ld/gid_map",
1340 (long) child_pid);
1341 if (map_zero) {
1342 snprintf(map_buf, MAP_BUF_SIZE, "0 %ld 1", (long) getgid());
1343 gid_map = map_buf;
1344 }
1345 update_map(gid_map, map_path);
1346 }
1347
1348 /* Close the write end of the pipe, to signal to the child that we
1349 have updated the UID and GID maps */
1350
1351 close(args.pipe_fd[1]);
1352
1353 if (waitpid(child_pid, NULL, 0) == \-1) /* Wait for child */
1354 errExit("waitpid");
1355
1356 if (verbose)
1357 printf("%s: terminating\en", argv[0]);
1358
1359 exit(EXIT_SUCCESS);
1360 }
1361 .EE
1362 .SH SEE ALSO
1363 .BR newgidmap (1), \" From the shadow package
1364 .BR newuidmap (1), \" From the shadow package
1365 .BR clone (2),
1366 .BR ptrace (2),
1367 .BR setns (2),
1368 .BR unshare (2),
1369 .BR proc (5),
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),
1375 .BR namespaces (7),
1376 .BR pid_namespaces (7)
1377 .PP
1378 The kernel source file
1379 .IR Documentation/namespaces/resource-control.txt .