]> git.ipfire.org Git - thirdparty/man-pages.git/blob - man7/user_namespaces.7
user_namespaces.7: Add "Restrictions on mount namespaces" section
[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 .\" Permission is granted to make and distribute verbatim copies of this
5 .\" manual provided the copyright notice and this permission notice are
6 .\" preserved on all copies.
7 .\"
8 .\" Permission is granted to copy and distribute modified versions of this
9 .\" manual under the conditions for verbatim copying, provided that the
10 .\" entire resulting derived work is distributed under the terms of a
11 .\" permission notice identical to this one.
12 .\"
13 .\" Since the Linux kernel and libraries are constantly changing, this
14 .\" manual page may be incorrect or out-of-date. The author(s) assume no
15 .\" responsibility for errors or omissions, or for damages resulting from
16 .\" the use of the information contained herein. The author(s) may not
17 .\" have taken the same level of care in the production of this manual,
18 .\" which is licensed free of charge, as they might when working
19 .\" professionally.
20 .\"
21 .\" Formatted or processed versions of this manual, if unaccompanied by
22 .\" the source, must acknowledge the copyright and authors of this work.
23 .\"
24 .\"
25 .TH USER_NAMESPACES 7 2013-01-14 "Linux" "Linux Programmer's Manual"
26 .SH NAME
27 user_namespaces \- overview of Linux user_namespaces
28 .SH DESCRIPTION
29 For an overview of namespaces, see
30 .BR namespaces (7).
31
32 User namespaces isolate security-related identifiers and attributes,
33 in particular,
34 user IDs and group IDs (see
35 .BR credentials (7),
36 the root directory,
37 keys (see
38 .BR keyctl (2)),
39 .\" FIXME: This page says very little about the interaction
40 .\" of user namespaces and keys. Add something on this topic.
41 and capabilities (see
42 .BR capabilities (7)).
43 A process's user and group IDs can be different
44 inside and outside a user namespace.
45 In particular,
46 a process can have a normal unprivileged user ID outside a user namespace
47 while at the same time having a user ID of 0 inside the namespace;
48 in other words,
49 the process has full privileges for operations inside the user namespace,
50 but is unprivileged for operations outside the namespace.
51 .\"
52 .\" ============================================================
53 .\"
54 .SS Nested namespaces, namespace membership
55 User namespaces can be nested;
56 that is, each user namespace\(emexcept the initial ("root")
57 namespace\(emhas a parent user namespace,
58 and can have zero or more child user namespaces.
59 The parent user namespace is the user namespace
60 of the process that creates the user namespace via a call to
61 .BR unshare (2)
62 or
63 .BR clone (2)
64 with the
65 .BR CLONE_NEWUSER
66 flag.
67
68 The kernel imposes (since version 3.11) a limit of 32 nested levels of
69 .\" commit 8742f229b635bf1c1c84a3dfe5e47c814c20b5c8
70 user namespaces.
71 .\" FIXME Explain the rationale for this limit. (What is the rationale?)
72 Calls to
73 .BR unshare (2)
74 or
75 .BR clone (2)
76 that would cause this limit to be exceeded fail with the error
77 .BR EUSERS .
78
79 Each process is a member of exactly one user namespace.
80 A process created via
81 .BR fork (2)
82 or
83 .BR clone (2)
84 without the
85 .BR CLONE_NEWUSER
86 flag is a member of the same user namespace as its parent.
87 A single-threaded process can join another user namespace with
88 .BR setns (2)
89 if it has the
90 .BR CAP_SYS_ADMIN
91 in that namespace;
92 upon doing so, it gains a full set of capabilities in that namespace.
93
94 A call to
95 .BR clone (2)
96 or
97 .BR unshare (2)
98 with the
99 .BR CLONE_NEWUSER
100 flag makes the new child process (for
101 .BR clone (2))
102 or the caller (for
103 .BR unshare (2))
104 a member of the new user namespace created by the call.
105 .\"
106 .\" ============================================================
107 .\"
108 .SS Capabilities
109 The child process created by
110 .BR clone (2)
111 with the
112 .BR CLONE_NEWUSER
113 flag starts out with a complete set
114 of capabilities in the new user namespace.
115 Likewise, a process that creates a new user namespace using
116 .BR unshare (2)
117 or joins an existing user namespace using
118 .BR setns (2)
119 gains a full set of capabilities in that namespace.
120 On the other hand,
121 that process has no capabilities in the parent (in the case of
122 .BR clone (2))
123 or previous (in the case of
124 .BR unshare (2)
125 and
126 .BR setns (2))
127 user namespace,
128 even if the new namespace is created or joined by the root user
129 (i.e., a process with user ID 0 in the root namespace).
130
131 Note that a call to
132 .BR execve (2)
133 will cause a process's capabilities to be recalculated (see
134 .BR capabilities (7)),
135 so that usually, unless it has a user ID of 0 within the namespace,
136 it will lose all capabilities.
137 See the discussion of user and group ID mappings, below.
138
139 A call to
140 .BR clone (2),
141 .BR unshare (2),
142 or
143 .BR setns (2)
144 using the
145 .BR CLONE_NEWUSER
146 flag sets the "securebits" flags
147 (see
148 .BR capabilities (7))
149 to their default values (all flags disabled) in the child (for
150 .BR clone (2))
151 or caller (for
152 .BR unshare (2),
153 or
154 .BR setns (2)).
155 Note that because the caller no longer has capabilities
156 in its original user namespace after a call to
157 .BR setns (2),
158 it is not possible for a process to reset its "securebits" flags while
159 retaining its user namespace membership by using a pair of
160 .BR setns (2)
161 calls to move to another user namespace and then return to
162 its original user namespace.
163
164 Having a capability inside a user namespace
165 permits a process to perform operations (that require privilege)
166 only on resources governed by that namespace.
167 The rules for determining whether or not a process has a capability
168 in a particular user namespace are as follows:
169 .IP 1. 3
170 A process has a capability inside a user namespace
171 if it is a member of that namespace and
172 it has the capability in its effective capability set.
173 A process can gain capabilities in its effective capability
174 set in various ways.
175 For example, it may execute a set-user-ID program or an
176 executable with associated file capabilities.
177 In addition,
178 a process may gain capabilities via the effect of
179 .BR clone (2),
180 .BR unshare (2),
181 or
182 .BR setns (2),
183 as already described.
184 .\" In the 3.8 sources, see security/commoncap.c::cap_capable():
185 .IP 2.
186 If a process has a capability in a user namespace,
187 then it has that capability in all child (and further removed descendant)
188 namespaces as well.
189 .IP 3.
190 .\" * The owner of the user namespace in the parent of the
191 .\" * user namespace has all caps.
192 When a user namespace is created, the kernel records the effective
193 user ID of the creating process as being the "owner" of the namespace.
194 .\" (and likewise associates the effective group ID of the creating process
195 .\" with the namespace).
196 A process that resides
197 in the parent of the user namespace
198 .\" See kernel commit 520d9eabce18edfef76a60b7b839d54facafe1f9 for a fix
199 .\" on this point
200 and whose effective user ID matches the owner of the namespace
201 has all capabilities in the namespace.
202 .\" This includes the case where the process executes a set-user-ID
203 .\" program that confers the effective UID of the creator of the namespace.
204 By virtue of the previous rule,
205 this means that the process has all capabilities in all
206 further removed descendant user namespaces as well.
207 .\"
208 .\" ============================================================
209 .\"
210 .SS Interaction of user namespaces and other types of namespaces
211 Starting in Linux 3.8, unprivileged processes can create user namespaces,
212 and mount, PID, IPC, network, and UTS namespaces can be created with just the
213 .B CAP_SYS_ADMIN
214 capability in the caller's user namespace.
215
216 If
217 .BR CLONE_NEWUSER
218 is specified along with other
219 .B CLONE_NEW*
220 flags in a single
221 .BR clone (2)
222 or
223 .BR unshare (2)
224 call, the user namespace is guaranteed to be created first,
225 giving the child
226 .RB ( clone (2))
227 or caller
228 .RB ( unshare (2))
229 privileges over the remaining namespaces created by the call.
230 Thus, it is possible for an unprivileged caller to specify this combination
231 of flags.
232
233 When a new IPC, mount, network, PID, or UTS namespace is created via
234 .BR clone (2)
235 or
236 .BR unshare (2),
237 the kernel records the user namespace of the creating process against
238 the new namespace.
239 (This association can't be changed.)
240 When a process in the new namespace subsequently performs
241 privileged operations that operate on global
242 resources isolated by the namespace,
243 the permission checks are performed according to the process's capabilities
244 in the user namespace that the kernel associated with the new namespace.
245 .\"
246 .\" ============================================================
247 .\"
248 .SS Restrictions on mount namespaces
249
250 Note the following points with respect to mount namespaces:
251 .IP * 3
252 A mount namespace has an owner user namespace.
253 A mount namespace whose owner user namespace is different from
254 the owner user namespace of its parent mount namespace is
255 considered a less privileged mount namespace.
256 .IP *
257 When creating a less privileged mount namespace,
258 shared mounts are reduced to slave mounts.
259 This ensures that mappings performed in less
260 privileged mount namespaces will not propagate to more privileged
261 mount namespaces.
262 .IP *
263 .\" FIXME .
264 .\" What does "come as a single unit from more privileged mount" mean?
265 Mounts that come as a single unit from more privileged mount are
266 locked together and may not be separated in a less privileged mount
267 namespace.
268 .IP *
269 The
270 .BR mount (2)
271 flags
272 .BR MS_RDONLY ,
273 .BR MS_NOSUID ,
274 .BR MS_NOEXEC ,
275 and the "atime" flags
276 .RB ( MS_NOATIME ,
277 .BR MS_NODIRATIME ,
278 .BR MS_RELATIME)
279 settings become locked
280 .\" commit 9566d6742852c527bf5af38af5cbb878dad75705
281 .\" Author: Eric W. Biederman <ebiederm@xmission.com>
282 .\" Date: Mon Jul 28 17:26:07 2014 -0700
283 .\"
284 .\" mnt: Correct permission checks in do_remount
285 .\"
286 when propagated from a more privileged to
287 a less privileged mount namespace,
288 and may not be changed in the less privileged mount namespace.
289 .IP *
290 .\" (As of 3.18-rc1 (in Al Viro's 2014-08-30 vfs.git#for-next tree))
291 A file or directory that is a mount point in one namespace that is not
292 a mount point in another namespace, may be renamed, unlinked, or removed
293 .RB ( rmdir (2))
294 in the mount namespace in which it is not a mount point
295 (subject to the usual permission checks).
296 .IP
297 Previously, attempting to unlink, rename, or remove a file or directory
298 that was a mount point in another mount namespace would result in the error
299 .BR EBUSY .
300 That behavior had technical problems of enforcement (e.g., for NFS)
301 and permitted denial-of-service attacks against more privileged users.
302 (i.e., preventing individual files from being updated
303 by bind mounting on top of them).
304 .\"
305 .\" ============================================================
306 .\"
307 .SS User and group ID mappings: uid_map and gid_map
308 When a user namespace is created,
309 it starts out without a mapping of user IDs (group IDs)
310 to the parent user namespace.
311 The
312 .IR /proc/[pid]/uid_map
313 and
314 .IR /proc/[pid]/gid_map
315 files (available since Linux 3.5)
316 .\" commit 22d917d80e842829d0ca0a561967d728eb1d6303
317 expose the mappings for user and group IDs
318 inside the user namespace for the process
319 .IR pid .
320 These files can be read to view the mappings in a user namespace and
321 written to (once) to define the mappings.
322
323 The description in the following paragraphs explains the details for
324 .IR uid_map ;
325 .IR gid_map
326 is exactly the same,
327 but each instance of "user ID" is replaced by "group ID".
328
329 The
330 .I uid_map
331 file exposes the mapping of user IDs from the user namespace
332 of the process
333 .IR pid
334 to the user namespace of the process that opened
335 .IR uid_map
336 (but see a qualification to this point below).
337 In other words, processes that are in different user namespaces
338 will potentially see different values when reading from a particular
339 .I uid_map
340 file, depending on the user ID mappings for the user namespaces
341 of the reading processes.
342
343 Each line in the
344 .I uid_map
345 file specifies a 1-to-1 mapping of a range of contiguous
346 user IDs between two user namespaces.
347 (When a user namespace is first created, this file is empty.)
348 The specification in each line takes the form of
349 three numbers delimited by white space.
350 The first two numbers specify the starting user ID in
351 each of the two user namespaces.
352 The third number specifies the length of the mapped range.
353 In detail, the fields are interpreted as follows:
354 .IP (1) 4
355 The start of the range of user IDs in
356 the user namespace of the process
357 .IR pid .
358 .IP (2)
359 The start of the range of user
360 IDs to which the user IDs specified by field one map.
361 How field two is interpreted depends on whether the process that opened
362 .I uid_map
363 and the process
364 .IR pid
365 are in the same user namespace, as follows:
366 .RS
367 .IP a) 3
368 If the two processes are in different user namespaces:
369 field two is the start of a range of
370 user IDs in the user namespace of the process that opened
371 .IR uid_map .
372 .IP b)
373 If the two processes are in the same user namespace:
374 field two is the start of the range of
375 user IDs in the parent user namespace of the process
376 .IR pid .
377 This case enables the opener of
378 .I uid_map
379 (the common case here is opening
380 .IR /proc/self/uid_map )
381 to see the mapping of user IDs into the user namespace of the process
382 that created this user namespace.
383 .RE
384 .IP (3)
385 The length of the range of user IDs that is mapped between the two
386 user namespaces.
387 .PP
388 System calls that return user IDs (group IDs)\(emfor example,
389 .BR getuid (2),
390 .BR getgid (2),
391 and the credential fields in the structure returned by
392 .BR stat (2)\(emreturn
393 the user ID (group ID) mapped into the caller's user namespace.
394
395 When a process accesses a file, its user and group IDs
396 are mapped into the initial user namespace for the purpose of permission
397 checking and assigning IDs when creating a file.
398 When a process retrieves file user and group IDs via
399 .BR stat (2),
400 the IDs are mapped in the opposite direction,
401 to produce values relative to the process user and group ID mappings.
402
403 The initial user namespace has no parent namespace,
404 but, for consistency, the kernel provides dummy user and group
405 ID mapping files for this namespace.
406 Looking at the
407 .I uid_map
408 file
409 .RI ( gid_map
410 is the same) from a shell in the initial namespace shows:
411
412 .in +4n
413 .nf
414 $ \fBcat /proc/$$/uid_map\fP
415 0 0 4294967295
416 .fi
417 .in
418
419 This mapping tells us
420 that the range starting at user ID 0 in this namespace
421 maps to a range starting at 0 in the (nonexistent) parent namespace,
422 and the length of the range is the largest 32-bit unsigned integer.
423 .\"
424 .\" ============================================================
425 .\"
426 .SS Defining user and group ID mappings: writing to uid_map and gid_map
427 .PP
428 After the creation of a new user namespace, the
429 .I uid_map
430 file of
431 .I one
432 of the processes in the namespace may be written to
433 .I once
434 to define the mapping of user IDs in the new user namespace.
435 An attempt to write more than once to a
436 .I uid_map
437 file in a user namespace fails with the error
438 .BR EPERM .
439 Similar rules apply for
440 .I gid_map
441 files.
442
443 The lines written to
444 .IR uid_map
445 .RI ( gid_map )
446 must conform to the following rules:
447 .IP * 3
448 The three fields must be valid numbers,
449 and the last field must be greater than 0.
450 .IP *
451 Lines are terminated by newline characters.
452 .IP *
453 There is an (arbitrary) limit on the number of lines in the file.
454 As at Linux 3.8, the limit is five lines.
455 In addition, the number of bytes written to
456 the file must be less than the system page size,
457 .\" FIXME(Eric): the restriction "less than" rather than "less than or equal"
458 .\" seems strangely arbitrary. Furthermore, the comment does not agree
459 .\" with the code in kernel/user_namespace.c. Which is correct?
460 and the write must be performed at the start of the file (i.e.,
461 .BR lseek (2)
462 and
463 .BR pwrite (2)
464 can't be used to write to nonzero offsets in the file).
465 .IP *
466 The range of user IDs (group IDs)
467 specified in each line cannot overlap with the ranges
468 in any other lines.
469 In the initial implementation (Linux 3.8), this requirement was
470 satisfied by a simplistic implementation that imposed the further
471 requirement that
472 the values in both field 1 and field 2 of successive lines must be
473 in ascending numerical order,
474 which prevented some otherwise valid maps from being created.
475 Linux 3.9 and later
476 .\" commit 0bd14b4fd72afd5df41e9fd59f356740f22fceba
477 fix this limitation, allowing any valid set of nonoverlapping maps.
478 .IP *
479 At least one line must be written to the file.
480 .PP
481 Writes that violate the above rules fail with the error
482 .BR EINVAL .
483
484 In order for a process to write to the
485 .I /proc/[pid]/uid_map
486 .RI ( /proc/[pid]/gid_map )
487 file, all of the following requirements must be met:
488 .IP 1. 3
489 The writing process must have the
490 .BR CAP_SETUID
491 .RB ( CAP_SETGID )
492 capability in the user namespace of the process
493 .IR pid .
494 .IP 2.
495 The writing process must be in either the user namespace of the process
496 .I pid
497 or inside the parent user namespace of the process
498 .IR pid .
499 .IP 3.
500 The mapped user IDs (group IDs) must in turn have a mapping
501 in the parent user namespace.
502 .IP 4.
503 One of the following is true:
504 .RS
505 .IP * 3
506 The data written to
507 .I uid_map
508 .RI ( gid_map )
509 consists of a single line that maps the writing process's filesystem user ID
510 (group ID) in the parent user namespace to a user ID (group ID)
511 in the user namespace.
512 The usual case here is that this single line provides a mapping for user ID
513 of the process that created the namespace.
514 .IP * 3
515 The process has the
516 .BR CAP_SETUID
517 .RB ( CAP_SETGID )
518 capability in the parent user namespace.
519 Thus, a privileged process can make mappings to arbitrary user IDs (group IDs)
520 in the parent user namespace.
521 .RE
522 .PP
523 Writes that violate the above rules fail with the error
524 .BR EPERM .
525 .\"
526 .\" ============================================================
527 .\"
528 .SS Unmapped user and group IDs
529 .PP
530 There are various places where an unmapped user ID (group ID)
531 may be exposed to user space.
532 For example, the first process in a new user namespace may call
533 .BR getuid ()
534 before a user ID mapping has been defined for the namespace.
535 In most such cases, an unmapped user ID is converted
536 .\" from_kuid_munged(), from_kgid_munged()
537 to the overflow user ID (group ID);
538 the default value for the overflow user ID (group ID) is 65534.
539 See the descriptions of
540 .IR /proc/sys/kernel/overflowuid
541 and
542 .IR /proc/sys/kernel/overflowgid
543 in
544 .BR proc (5).
545
546 The cases where unmapped IDs are mapped in this fashion include
547 system calls that return user IDs
548 .RB ( getuid (2)
549 .BR getgid (2),
550 and similar),
551 credentials passed over a UNIX domain socket,
552 .\" also SO_PEERCRED
553 credentials returned by
554 .BR stat (2),
555 .BR waitid (2),
556 and the System V IPC "ctl"
557 .B IPC_STAT
558 operations,
559 credentials exposed by
560 .IR /proc/PID/status
561 and the files in
562 .IR /proc/sysvipc/* ,
563 credentials returned via the
564 .I si_uid
565 field in the
566 .I siginfo_t
567 received with a signal (see
568 .BR sigaction (2)),
569 credentials written to the process accounting file (see
570 .BR acct (5)),
571 and credentials returned with POSIX message queue notifications (see
572 .BR mq_notify (3)).
573
574 There is one notable case where unmapped user and group IDs are
575 .I not
576 .\" from_kuid(), from_kgid()
577 .\" Also F_GETOWNER_UIDS is an exception
578 converted to the corresponding overflow ID value.
579 When viewing a
580 .I uid_map
581 or
582 .I gid_map
583 file in which there is no mapping for the second field,
584 that field is displayed as 4294967295 (\-1 as an unsigned integer);
585 .\"
586 .\" ============================================================
587 .\"
588 .SS Set-user-ID and set-group-ID programs
589 .PP
590 When a process inside a user namespace executes
591 a set-user-ID (set-group-ID) program,
592 the process's effective user (group) ID inside the namespace is changed
593 to whatever value is mapped for the user (group) ID of the file.
594 However, if either the user
595 .I or
596 the group ID of the file has no mapping inside the namespace,
597 the set-user-ID (set-group-ID) bit is silently ignored:
598 the new program is executed,
599 but the process's effective user (group) ID is left unchanged.
600 (This mirrors the semantics of executing a set-user-ID or set-group-ID
601 program that resides on a filesystem that was mounted with the
602 .BR MS_NOSUID
603 flag, as described in
604 .BR mount (2).)
605 .\"
606 .\" ============================================================
607 .\"
608 .SS Miscellaneous
609 .PP
610 When a process's user and group IDs are passed over a UNIX domain socket
611 to a process in a different user namespace (see the description of
612 .B SCM_CREDENTIALS
613 in
614 .BR unix (7)),
615 they are translated into the corresponding values as per the
616 receiving process's user and group ID mappings.
617 .\"
618 .SH CONFORMING TO
619 Namespaces are a Linux-specific feature.
620 .\"
621 .SH NOTES
622 Over the years, there have been a lot of features that have been added
623 to the Linux kernel that have been made available only to privileged users
624 because of their potential to confuse set-user-ID-root applications.
625 In general, it becomes safe to allow the root user in a user namespace to
626 use those features because it is impossible, while in a user namespace,
627 to gain more privilege than the root user of a user namespace has.
628 .\"
629 .\" ============================================================
630 .\"
631 .SS Availability
632 Use of user namespaces requires a kernel that is configured with the
633 .B CONFIG_USER_NS
634 option.
635 User namespaces require support in a range of subsystems across
636 the kernel.
637 When an unsupported subsystem is configured into the kernel,
638 it is not possible to configure user namespaces support.
639
640 As at Linux 3.8, most relevant subsystems supported user namespaces,
641 but a number of filesystems did not have the infrastructure needed
642 to map user and group IDs between user namespaces.
643 Linux 3.9 added the required infrastructure support for many of
644 the remaining unsupported filesystems
645 (Plan 9 (9P), Andrew File System (AFS), Ceph, CIFS, CODA, NFS, and OCFS2).
646 Linux 3.11 added support the last of the unsupported major filesystems,
647 .\" commit d6970d4b726cea6d7a9bc4120814f95c09571fc3
648 XFS.
649 .\"
650 .SH EXAMPLE
651 The program below is designed to allow experimenting with
652 user namespaces, as well as other types of namespaces.
653 It creates namespaces as specified by command-line options and then executes
654 a command inside those namespaces.
655 The comments and
656 .I usage()
657 function inside the program provide a full explanation of the program.
658 The following shell session demonstrates its use.
659
660 First, we look at the run-time environment:
661
662 .in +4n
663 .nf
664 $ \fBuname -rs\fP # Need Linux 3.8 or later
665 Linux 3.8.0
666 $ \fBid -u\fP # Running as unprivileged user
667 1000
668 $ \fBid -g\fP
669 1000
670 .fi
671 .in
672
673 Now start a new shell in new user
674 .RI ( \-U ),
675 mount
676 .RI ( \-m ),
677 and PID
678 .RI ( \-p )
679 namespaces, with user ID
680 .RI ( \-M )
681 and group ID
682 .RI ( \-G )
683 1000 mapped to 0 inside the user namespace:
684
685 .in +4n
686 .nf
687 $ \fB./userns_child_exec -p -m -U -M '0 1000 1' -G '0 1000 1' bash\fP
688 .fi
689 .in
690
691 The shell has PID 1, because it is the first process in the new
692 PID namespace:
693
694 .in +4n
695 .nf
696 bash$ \fBecho $$\fP
697 1
698 .fi
699 .in
700
701 Inside the user namespace, the shell has user and group ID 0,
702 and a full set of permitted and effective capabilities:
703
704 .in +4n
705 .nf
706 bash$ \fBcat /proc/$$/status | egrep '^[UG]id'\fP
707 Uid: 0 0 0 0
708 Gid: 0 0 0 0
709 bash$ \fBcat /proc/$$/status | egrep '^Cap(Prm|Inh|Eff)'\fP
710 CapInh: 0000000000000000
711 CapPrm: 0000001fffffffff
712 CapEff: 0000001fffffffff
713 .fi
714 .in
715
716 Mounting a new
717 .I /proc
718 filesystem and listing all of the processes visible
719 in the new PID namespace shows that the shell can't see
720 any processes outside the PID namespace:
721
722 .in +4n
723 .nf
724 bash$ \fBmount -t proc proc /proc\fP
725 bash$ \fBps ax\fP
726 PID TTY STAT TIME COMMAND
727 1 pts/3 S 0:00 bash
728 22 pts/3 R+ 0:00 ps ax
729 .fi
730 .in
731 .SS Program source
732 \&
733 .nf
734 /* userns_child_exec.c
735
736 Licensed under GNU General Public License v2 or later
737
738 Create a child process that executes a shell command in new
739 namespace(s); allow UID and GID mappings to be specified when
740 creating a user namespace.
741 */
742 #define _GNU_SOURCE
743 #include <sched.h>
744 #include <unistd.h>
745 #include <stdlib.h>
746 #include <sys/wait.h>
747 #include <signal.h>
748 #include <fcntl.h>
749 #include <stdio.h>
750 #include <string.h>
751 #include <limits.h>
752 #include <errno.h>
753
754 /* A simple error\-handling function: print an error message based
755 on the value in \(aqerrno\(aq and terminate the calling process */
756
757 #define errExit(msg) do { perror(msg); exit(EXIT_FAILURE); \\
758 } while (0)
759
760 struct child_args {
761 char **argv; /* Command to be executed by child, with args */
762 int pipe_fd[2]; /* Pipe used to synchronize parent and child */
763 };
764
765 static int verbose;
766
767 static void
768 usage(char *pname)
769 {
770 fprintf(stderr, "Usage: %s [options] cmd [arg...]\\n\\n", pname);
771 fprintf(stderr, "Create a child process that executes a shell "
772 "command in a new user namespace,\\n"
773 "and possibly also other new namespace(s).\\n\\n");
774 fprintf(stderr, "Options can be:\\n\\n");
775 #define fpe(str) fprintf(stderr, " %s", str);
776 fpe("\-i New IPC namespace\\n");
777 fpe("\-m New mount namespace\\n");
778 fpe("\-n New network namespace\\n");
779 fpe("\-p New PID namespace\\n");
780 fpe("\-u New UTS namespace\\n");
781 fpe("\-U New user namespace\\n");
782 fpe("\-M uid_map Specify UID map for user namespace\\n");
783 fpe("\-G gid_map Specify GID map for user namespace\\n");
784 fpe("\-z Map user\(aqs UID and GID to 0 in user namespace\\n");
785 fpe(" (equivalent to: \-M \(aq0 <uid> 1\(aq \-G \(aq0 <gid> 1\(aq)\\n");
786 fpe("\-v Display verbose messages\\n");
787 fpe("\\n");
788 fpe("If \-z, \-M, or \-G is specified, \-U is required.\\n");
789 fpe("It is not permitted to specify both \-z and either \-M or \-G.\\n");
790 fpe("\\n");
791 fpe("Map strings for \-M and \-G consist of records of the form:\\n");
792 fpe("\\n");
793 fpe(" ID\-inside\-ns ID\-outside\-ns len\\n");
794 fpe("\\n");
795 fpe("A map string can contain multiple records, separated"
796 " by commas;\\n");
797 fpe("the commas are replaced by newlines before writing"
798 " to map files.\\n");
799
800 exit(EXIT_FAILURE);
801 }
802
803 /* Update the mapping file \(aqmap_file\(aq, with the value provided in
804 \(aqmapping\(aq, a string that defines a UID or GID mapping. A UID or
805 GID mapping consists of one or more newline\-delimited records
806 of the form:
807
808 ID_inside\-ns ID\-outside\-ns length
809
810 Requiring the user to supply a string that contains newlines is
811 of course inconvenient for command\-line use. Thus, we permit the
812 use of commas to delimit records in this string, and replace them
813 with newlines before writing the string to the file. */
814
815 static void
816 update_map(char *mapping, char *map_file)
817 {
818 int fd, j;
819 size_t map_len; /* Length of \(aqmapping\(aq */
820
821 /* Replace commas in mapping string with newlines */
822
823 map_len = strlen(mapping);
824 for (j = 0; j < map_len; j++)
825 if (mapping[j] == \(aq,\(aq)
826 mapping[j] = \(aq\\n\(aq;
827
828 fd = open(map_file, O_RDWR);
829 if (fd == \-1) {
830 fprintf(stderr, "ERROR: open %s: %s\\n", map_file,
831 strerror(errno));
832 exit(EXIT_FAILURE);
833 }
834
835 if (write(fd, mapping, map_len) != map_len) {
836 fprintf(stderr, "ERROR: write %s: %s\\n", map_file,
837 strerror(errno));
838 exit(EXIT_FAILURE);
839 }
840
841 close(fd);
842 }
843
844 static int /* Start function for cloned child */
845 childFunc(void *arg)
846 {
847 struct child_args *args = (struct child_args *) arg;
848 char ch;
849
850 /* Wait until the parent has updated the UID and GID mappings.
851 See the comment in main(). We wait for end of file on a
852 pipe that will be closed by the parent process once it has
853 updated the mappings. */
854
855 close(args\->pipe_fd[1]); /* Close our descriptor for the write
856 end of the pipe so that we see EOF
857 when parent closes its descriptor */
858 if (read(args\->pipe_fd[0], &ch, 1) != 0) {
859 fprintf(stderr,
860 "Failure in child: read from pipe returned != 0\\n");
861 exit(EXIT_FAILURE);
862 }
863
864 /* Execute a shell command */
865
866 printf("About to exec %s\\n", args\->argv[0]);
867 execvp(args\->argv[0], args\->argv);
868 errExit("execvp");
869 }
870
871 #define STACK_SIZE (1024 * 1024)
872
873 static char child_stack[STACK_SIZE]; /* Space for child\(aqs stack */
874
875 int
876 main(int argc, char *argv[])
877 {
878 int flags, opt, map_zero;
879 pid_t child_pid;
880 struct child_args args;
881 char *uid_map, *gid_map;
882 const int MAP_BUF_SIZE = 100;
883 char map_buf[MAP_BUF_SIZE];
884 char map_path[PATH_MAX];
885
886 /* Parse command\-line options. The initial \(aq+\(aq character in
887 the final getopt() argument prevents GNU\-style permutation
888 of command\-line options. That\(aqs useful, since sometimes
889 the \(aqcommand\(aq to be executed by this program itself
890 has command\-line options. We don\(aqt want getopt() to treat
891 those as options to this program. */
892
893 flags = 0;
894 verbose = 0;
895 gid_map = NULL;
896 uid_map = NULL;
897 map_zero = 0;
898 while ((opt = getopt(argc, argv, "+imnpuUM:G:zv")) != \-1) {
899 switch (opt) {
900 case \(aqi\(aq: flags |= CLONE_NEWIPC; break;
901 case \(aqm\(aq: flags |= CLONE_NEWNS; break;
902 case \(aqn\(aq: flags |= CLONE_NEWNET; break;
903 case \(aqp\(aq: flags |= CLONE_NEWPID; break;
904 case \(aqu\(aq: flags |= CLONE_NEWUTS; break;
905 case \(aqv\(aq: verbose = 1; break;
906 case \(aqz\(aq: map_zero = 1; break;
907 case \(aqM\(aq: uid_map = optarg; break;
908 case \(aqG\(aq: gid_map = optarg; break;
909 case \(aqU\(aq: flags |= CLONE_NEWUSER; break;
910 default: usage(argv[0]);
911 }
912 }
913
914 /* \-M or \-G without \-U is nonsensical */
915
916 if (((uid_map != NULL || gid_map != NULL || map_zero) &&
917 !(flags & CLONE_NEWUSER)) ||
918 (map_zero && (uid_map != NULL || gid_map != NULL)))
919 usage(argv[0]);
920
921 args.argv = &argv[optind];
922
923 /* We use a pipe to synchronize the parent and child, in order to
924 ensure that the parent sets the UID and GID maps before the child
925 calls execve(). This ensures that the child maintains its
926 capabilities during the execve() in the common case where we
927 want to map the child\(aqs effective user ID to 0 in the new user
928 namespace. Without this synchronization, the child would lose
929 its capabilities if it performed an execve() with nonzero
930 user IDs (see the capabilities(7) man page for details of the
931 transformation of a process\(aqs capabilities during execve()). */
932
933 if (pipe(args.pipe_fd) == \-1)
934 errExit("pipe");
935
936 /* Create the child in new namespace(s) */
937
938 child_pid = clone(childFunc, child_stack + STACK_SIZE,
939 flags | SIGCHLD, &args);
940 if (child_pid == \-1)
941 errExit("clone");
942
943 /* Parent falls through to here */
944
945 if (verbose)
946 printf("%s: PID of child created by clone() is %ld\\n",
947 argv[0], (long) child_pid);
948
949 /* Update the UID and GID maps in the child */
950
951 if (uid_map != NULL || map_zero) {
952 snprintf(map_path, PATH_MAX, "/proc/%ld/uid_map",
953 (long) child_pid);
954 if (map_zero) {
955 snprintf(map_buf, MAP_BUF_SIZE, "0 %ld 1", (long) getuid());
956 uid_map = map_buf;
957 }
958 update_map(uid_map, map_path);
959 }
960 if (gid_map != NULL || map_zero) {
961 snprintf(map_path, PATH_MAX, "/proc/%ld/gid_map",
962 (long) child_pid);
963 if (map_zero) {
964 snprintf(map_buf, MAP_BUF_SIZE, "0 %ld 1", (long) getgid());
965 gid_map = map_buf;
966 }
967 update_map(gid_map, map_path);
968 }
969
970 /* Close the write end of the pipe, to signal to the child that we
971 have updated the UID and GID maps */
972
973 close(args.pipe_fd[1]);
974
975 if (waitpid(child_pid, NULL, 0) == \-1) /* Wait for child */
976 errExit("waitpid");
977
978 if (verbose)
979 printf("%s: terminating\\n", argv[0]);
980
981 exit(EXIT_SUCCESS);
982 }
983 .fi
984 .SH SEE ALSO
985 .BR newgidmap (1), \" From the shadow package
986 .BR newuidmap (1), \" From the shadow package
987 .BR clone (2),
988 .BR setns (2),
989 .BR unshare (2),
990 .BR proc (5),
991 .BR subgid (5), \" From the shadow package
992 .BR subuid (5), \" From the shadow package
993 .BR credentials (7),
994 .BR capabilities (7),
995 .BR namespaces (7),
996 .BR pid_namespaces (7)
997 .sp
998 The kernel source file
999 .IR Documentation/namespaces/resource-control.txt .