1user_namespaces(7)     Miscellaneous Information Manual     user_namespaces(7)
2
3
4

NAME

6       user_namespaces - overview of Linux user namespaces
7

DESCRIPTION

9       For an overview of namespaces, see namespaces(7).
10
11       User namespaces isolate security-related identifiers and attributes, in
12       particular, user IDs and group IDs (see credentials(7)), the  root  di‐
13       rectory,  keys  (see  keyrings(7)),  and  capabilities  (see  capabili‐
14       ties(7)).  A process's user and group IDs can be different  inside  and
15       outside  a  user namespace.  In particular, a process can have a normal
16       unprivileged user ID outside a user namespace while at  the  same  time
17       having a user ID of 0 inside the namespace; in other words, the process
18       has full privileges for operations inside the user  namespace,  but  is
19       unprivileged for operations outside the namespace.
20
21   Nested namespaces, namespace membership
22       User  namespaces can be nested; that is, each user namespace—except the
23       initial ("root") namespace—has a parent user namespace,  and  can  have
24       zero  or  more child user namespaces.  The parent user namespace is the
25       user namespace of the process that creates the  user  namespace  via  a
26       call to unshare(2) or clone(2) with the CLONE_NEWUSER flag.
27
28       The  kernel  imposes  (since Linux 3.11) a limit of 32 nested levels of
29       user namespaces.  Calls to unshare(2) or clone(2) that would cause this
30       limit to be exceeded fail with the error EUSERS.
31
32       Each process is a member of exactly one user namespace.  A process cre‐
33       ated via fork(2) or clone(2) without the CLONE_NEWUSER flag is a member
34       of  the  same  user namespace as its parent.  A single-threaded process
35       can join another user namespace with setns(2) if it has the CAP_SYS_AD‐
36       MIN  in that namespace; upon doing so, it gains a full set of capabili‐
37       ties in that namespace.
38
39       A call to clone(2) or unshare(2) with the CLONE_NEWUSER flag makes  the
40       new  child process (for clone(2)) or the caller (for unshare(2)) a mem‐
41       ber of the new user namespace created by the call.
42
43       The NS_GET_PARENT ioctl(2)  operation  can  be  used  to  discover  the
44       parental relationship between user namespaces; see ioctl_ns(2).
45
46       A  task that changes one of its effective IDs will have its dumpability
47       reset to the value in /proc/sys/fs/suid_dumpable.  This may affect  the
48       ownership  of proc files of child processes and may thus cause the par‐
49       ent to lack the permissions to write to mapping  files  of  child  pro‐
50       cesses  running in a new user namespace.  In such cases making the par‐
51       ent process dumpable, using PR_SET_DUMPABLE in a call to prctl(2),  be‐
52       fore  creating a child process in a new user namespace may rectify this
53       problem.  See prctl(2) and proc(5) for details on how ownership is  af‐
54       fected.
55
56   Capabilities
57       The  child  process  created  by  clone(2)  with the CLONE_NEWUSER flag
58       starts out with a complete set of capabilities in the  new  user  name‐
59       space.  Likewise, a process that creates a new user namespace using un‐
60       share(2) or joins an existing user namespace  using  setns(2)  gains  a
61       full  set  of  capabilities in that namespace.  On the other hand, that
62       process has no capabilities in the parent (in the case of clone(2))  or
63       previous  (in the case of unshare(2) and setns(2)) user namespace, even
64       if the new namespace is created or joined by the  root  user  (i.e.,  a
65       process with user ID 0 in the root namespace).
66
67       Note that a call to execve(2) will cause a process's capabilities to be
68       recalculated in the usual way (see capabilities(7)).  Consequently, un‐
69       less  the  process has a user ID of 0 within the namespace, or the exe‐
70       cutable file has a nonempty inheritable capabilities mask, the  process
71       will  lose  all  capabilities.  See the discussion of user and group ID
72       mappings, below.
73
74       A call to clone(2) or unshare(2) using the CLONE_NEWUSER flag or a call
75       to  setns(2) that moves the caller into another user namespace sets the
76       "securebits" flags (see capabilities(7)) to their default  values  (all
77       flags  disabled)  in the child (for clone(2)) or caller (for unshare(2)
78       or setns(2)).  Note that because the caller no longer has  capabilities
79       in its original user namespace after a call to setns(2), it is not pos‐
80       sible for a process to reset its "securebits" flags while retaining its
81       user  namespace membership by using a pair of setns(2) calls to move to
82       another user namespace and then return to its original user namespace.
83
84       The rules for determining whether or not a process has a capability  in
85       a particular user namespace are as follows:
86
87       •  A process has a capability inside a user namespace if it is a member
88          of that namespace and it has the capability in its  effective  capa‐
89          bility  set.  A process can gain capabilities in its effective capa‐
90          bility set in various ways.  For example, it may execute a set-user-
91          ID  program  or an executable with associated file capabilities.  In
92          addition,  a  process  may  gain  capabilities  via  the  effect  of
93          clone(2), unshare(2), or setns(2), as already described.
94
95       •  If  a process has a capability in a user namespace, then it has that
96          capability in all child (and further removed descendant)  namespaces
97          as well.
98
99       •  When  a  user namespace is created, the kernel records the effective
100          user ID of the creating process as being the "owner"  of  the  name‐
101          space.   A  process that resides in the parent of the user namespace
102          and whose effective user ID matches the owner of the  namespace  has
103          all  capabilities in the namespace.  By virtue of the previous rule,
104          this means that the process has all capabilities in all further  re‐
105          moved  descendant  user  namespaces  as  well.  The NS_GET_OWNER_UID
106          ioctl(2) operation can be used to discover the user ID of the  owner
107          of the namespace; see ioctl_ns(2).
108
109   Effect of capabilities within a user namespace
110       Having  a  capability inside a user namespace permits a process to per‐
111       form operations (that require privilege) only on resources governed  by
112       that  namespace.   In  other words, having a capability in a user name‐
113       space permits a process to perform privileged operations  on  resources
114       that  are  governed  by (nonuser) namespaces owned by (associated with)
115       the user namespace (see the next subsection).
116
117       On the other hand, there are many privileged operations that affect re‐
118       sources  that  are not associated with any namespace type, for example,
119       changing the system (i.e., calendar) time (governed  by  CAP_SYS_TIME),
120       loading  a  kernel  module (governed by CAP_SYS_MODULE), and creating a
121       device (governed by CAP_MKNOD).  Only a process with privileges in  the
122       initial user namespace can perform such operations.
123
124       Holding  CAP_SYS_ADMIN  within the user namespace that owns a process's
125       mount namespace allows that process to create bind mounts and mount the
126       following types of filesystems:
127
128/proc (since Linux 3.8)
129/sys (since Linux 3.8)
130devpts (since Linux 3.9)
131tmpfs(5) (since Linux 3.9)
132ramfs (since Linux 3.9)
133mqueue (since Linux 3.9)
134bpf (since Linux 4.4)
135overlayfs (since Linux 5.11)
136
137       Holding  CAP_SYS_ADMIN  within the user namespace that owns a process's
138       cgroup namespace allows (since Linux 4.6) that process to the mount the
139       cgroup  version  2  filesystem  and  cgroup version 1 named hierarchies
140       (i.e., cgroup filesystems mounted with the "none,name=" option).
141
142       Holding CAP_SYS_ADMIN within the user namespace that owns  a  process's
143       PID  namespace  allows  (since  Linux  3.8) that process to mount /proc
144       filesystems.
145
146       Note, however, that mounting block-based filesystems can be  done  only
147       by a process that holds CAP_SYS_ADMIN in the initial user namespace.
148
149   Interaction of user namespaces and other types of namespaces
150       Starting  in  Linux  3.8,  unprivileged processes can create user name‐
151       spaces, and the other types of namespaces can be created with just  the
152       CAP_SYS_ADMIN capability in the caller's user namespace.
153
154       When  a nonuser namespace is created, it is owned by the user namespace
155       in which the creating process was a member at the time of the  creation
156       of  the  namespace.  Privileged operations on resources governed by the
157       nonuser namespace require that the process has the necessary  capabili‐
158       ties in the user namespace that owns the nonuser namespace.
159
160       If  CLONE_NEWUSER  is  specified along with other CLONE_NEW* flags in a
161       single clone(2) or unshare(2) call, the user namespace is guaranteed to
162       be  created  first,  giving the child (clone(2)) or caller (unshare(2))
163       privileges over the remaining namespaces created by the call.  Thus, it
164       is  possible  for an unprivileged caller to specify this combination of
165       flags.
166
167       When a new namespace (other than  a  user  namespace)  is  created  via
168       clone(2)  or  unshare(2),  the kernel records the user namespace of the
169       creating process as the owner of the new namespace.  (This  association
170       can't  be  changed.)   When a process in the new namespace subsequently
171       performs privileged operations that operate on  global  resources  iso‐
172       lated  by  the namespace, the permission checks are performed according
173       to the process's capabilities in the user namespace that the kernel as‐
174       sociated  with  the new namespace.  For example, suppose that a process
175       attempts to change the hostname (sethostname(2)), a  resource  governed
176       by  the  UTS  namespace.  In this case, the kernel will determine which
177       user namespace owns the process's UTS namespace, and check whether  the
178       process  has the required capability (CAP_SYS_ADMIN) in that user name‐
179       space.
180
181       The NS_GET_USERNS ioctl(2) operation can be used to discover  the  user
182       namespace that owns a nonuser namespace; see ioctl_ns(2).
183
184   User and group ID mappings: uid_map and gid_map
185       When  a  user  namespace is created, it starts out without a mapping of
186       user  IDs  (group   IDs)   to   the   parent   user   namespace.    The
187       /proc/pid/uid_map  and  /proc/pid/gid_map  files (available since Linux
188       3.5) expose the mappings for user and group IDs inside the  user  name‐
189       space  for  the  process pid.  These files can be read to view the map‐
190       pings in a user namespace and written to (once) to define the mappings.
191
192       The description in the following paragraphs explains  the  details  for
193       uid_map; gid_map is exactly the same, but each instance of "user ID" is
194       replaced by "group ID".
195
196       The uid_map file exposes the mapping of user IDs from  the  user  name‐
197       space  of  the  process  pid  to the user namespace of the process that
198       opened uid_map (but see a qualification to this point below).  In other
199       words, processes that are in different user namespaces will potentially
200       see different values when reading from a particular uid_map  file,  de‐
201       pending  on the user ID mappings for the user namespaces of the reading
202       processes.
203
204       Each line in the uid_map file specifies a 1-to-1 mapping of a range  of
205       contiguous  user  IDs  between two user namespaces.  (When a user name‐
206       space is first created, this file is empty.)  The specification in each
207       line  takes  the  form  of three numbers delimited by white space.  The
208       first two numbers specify the starting user ID in each of the two  user
209       namespaces.  The third number specifies the length of the mapped range.
210       In detail, the fields are interpreted as follows:
211
212       (1)  The start of the range of user IDs in the user  namespace  of  the
213            process pid.
214
215       (2)  The start of the range of user IDs to which the user IDs specified
216            by field one map.  How field two is interpreted depends on whether
217            the  process  that  opened  uid_map and the process pid are in the
218            same user namespace, as follows:
219
220            (a)  If the two processes are in different user namespaces:  field
221                 two is the start of a range of user IDs in the user namespace
222                 of the process that opened uid_map.
223
224            (b)  If the two processes are in the same  user  namespace:  field
225                 two  is the start of the range of user IDs in the parent user
226                 namespace of the process pid.  This case enables  the  opener
227                 of    uid_map    (the    common    case   here   is   opening
228                 /proc/self/uid_map) to see the mapping of user IDs  into  the
229                 user  namespace  of  the process that created this user name‐
230                 space.
231
232       (3)  The length of the range of user IDs that is mapped between the two
233            user namespaces.
234
235       System  calls  that return user IDs (group IDs)—for example, getuid(2),
236       getgid(2), and the credential  fields  in  the  structure  returned  by
237       stat(2)—return  the  user  ID  (group ID) mapped into the caller's user
238       namespace.
239
240       When a process accesses a file, its user and group IDs are mapped  into
241       the  initial  user namespace for the purpose of permission checking and
242       assigning IDs when creating a file.  When a process retrieves file user
243       and  group  IDs  via stat(2), the IDs are mapped in the opposite direc‐
244       tion, to produce values relative to the process user and group ID  map‐
245       pings.
246
247       The  initial  user  namespace has no parent namespace, but, for consis‐
248       tency, the kernel provides dummy user and group ID  mapping  files  for
249       this namespace.  Looking at the uid_map file (gid_map is the same) from
250       a shell in the initial namespace shows:
251
252           $ cat /proc/$$/uid_map
253                    0          0 4294967295
254
255       This mapping tells us that the range starting at  user  ID  0  in  this
256       namespace  maps  to  a  range starting at 0 in the (nonexistent) parent
257       namespace, and the length of the range is the largest  32-bit  unsigned
258       integer.  This leaves 4294967295 (the 32-bit signed -1 value) unmapped.
259       This is deliberate: (uid_t) -1 is used in several interfaces (e.g., se‐
260       treuid(2))  as  a  way to specify "no user ID".  Leaving (uid_t) -1 un‐
261       mapped and unusable guarantees that there will be no confusion when us‐
262       ing these interfaces.
263
264   Defining user and group ID mappings: writing to uid_map and gid_map
265       After  the creation of a new user namespace, the uid_map file of one of
266       the processes in the namespace may be written to  once  to  define  the
267       mapping  of  user  IDs  in the new user namespace.  An attempt to write
268       more than once to a uid_map file in a user namespace fails with the er‐
269       ror EPERM.  Similar rules apply for gid_map files.
270
271       The  lines  written  to uid_map (gid_map) must conform to the following
272       validity rules:
273
274       •  The three fields must be valid numbers, and the last field  must  be
275          greater than 0.
276
277       •  Lines are terminated by newline characters.
278
279       •  There  is a limit on the number of lines in the file.  In Linux 4.14
280          and earlier, this limit was (arbitrarily) set  at  5  lines.   Since
281          Linux  4.15,  the  limit  is  340 lines.  In addition, the number of
282          bytes written to the file must be less than the  system  page  size,
283          and  the  write  must  be  performed at the start of the file (i.e.,
284          lseek(2) and pwrite(2) can't be used to write to nonzero offsets  in
285          the file).
286
287       •  The  range  of  user  IDs  (group IDs) specified in each line cannot
288          overlap with the ranges in any other lines.  In the  initial  imple‐
289          mentation  (Linux 3.8), this requirement was satisfied by a simplis‐
290          tic implementation that imposed the  further  requirement  that  the
291          values  in  both  field 1 and field 2 of successive lines must be in
292          ascending numerical order, which prevented some otherwise valid maps
293          from being created.  Linux 3.9 and later fix this limitation, allow‐
294          ing any valid set of nonoverlapping maps.
295
296       •  At least one line must be written to the file.
297
298       Writes that violate the above rules fail with the error EINVAL.
299
300       In  order  for  a   process   to   write   to   the   /proc/pid/uid_map
301       (/proc/pid/gid_map)  file, all of the following permission requirements
302       must be met:
303
304       •  The writing process must have the CAP_SETUID (CAP_SETGID) capability
305          in the user namespace of the process pid.
306
307       •  The  writing  process  must  either  be in the user namespace of the
308          process pid or be in the parent user namespace of the process pid.
309
310       •  The mapped user IDs (group IDs) must in turn have a mapping  in  the
311          parent user namespace.
312
313       •  If updating /proc/pid/uid_map to create a mapping that maps UID 0 in
314          the parent namespace, then one of the following must be true:
315
316          (a)  if writing process is in the parent  user  namespace,  then  it
317               must have the CAP_SETFCAP capability in that user namespace; or
318
319          (b)  if the writing process is in the child user namespace, then the
320               process that created the  user  namespace  must  have  had  the
321               CAP_SETFCAP capability when the namespace was created.
322
323          This rule has been in place since Linux 5.12.  It eliminates an ear‐
324          lier security bug whereby a UID 0 process that lacks the CAP_SETFCAP
325          capability,  which is needed to create a binary with namespaced file
326          capabilities (as described in capabilities(7)),  could  nevertheless
327          create such a binary, by the following steps:
328
329          (1)  Create  a  new  user namespace with the identity mapping (i.e.,
330               UID 0 in the new user namespace maps to UID  0  in  the  parent
331               namespace),  so  that UID 0 in both namespaces is equivalent to
332               the same root user ID.
333
334          (2)  Since the child process  has  the  CAP_SETFCAP  capability,  it
335               could  create  a  binary with namespaced file capabilities that
336               would then be effective in the parent user  namespace  (because
337               the root user IDs are the same in the two namespaces).
338
339       •  One of the following two cases applies:
340
341          (a)  Either  the writing process has the CAP_SETUID (CAP_SETGID) ca‐
342               pability in the parent user namespace.
343
344               •  No further restrictions apply: the process can make mappings
345                  to  arbitrary  user IDs (group IDs) in the parent user name‐
346                  space.
347
348          (b)  Or otherwise all of the following restrictions apply:
349
350               •  The data written to uid_map (gid_map) must consist of a sin‐
351                  gle  line  that maps the writing process's effective user ID
352                  (group ID) in the parent user namespace to a user ID  (group
353                  ID) in the user namespace.
354
355               •  The  writing process must have the same effective user ID as
356                  the process that created the user namespace.
357
358               •  In the case of gid_map, use of the setgroups(2) system  call
359                  must first be denied by writing "deny" to the /proc/pid/set‐
360                  groups file (see below) before writing to gid_map.
361
362       Writes that violate the above rules fail with the error EPERM.
363
364   Project ID mappings: projid_map
365       Similarly to user and group ID  mappings,  it  is  possible  to  create
366       project  ID  mappings  for a user namespace.  (Project IDs are used for
367       disk quotas; see setquota(8) and quotactl(2).)
368
369       Project ID mappings are defined by writing to the  /proc/pid/projid_map
370       file (present since Linux 3.7).
371
372       The  validity rules for writing to the /proc/pid/projid_map file are as
373       for writing to the  uid_map  file;  violation  of  these  rules  causes
374       write(2) to fail with the error EINVAL.
375
376       The  permission  rules for writing to the /proc/pid/projid_map file are
377       as follows:
378
379       •  The writing process must either be in  the  user  namespace  of  the
380          process pid or be in the parent user namespace of the process pid.
381
382       •  The  mapped  project  IDs  must in turn have a mapping in the parent
383          user namespace.
384
385       Violation of these rules causes write(2) to fail with the error EPERM.
386
387   Interaction with system calls that change process UIDs or GIDs
388       In a user namespace where the uid_map file has not  been  written,  the
389       system calls that change user IDs will fail.  Similarly, if the gid_map
390       file has not been written, the system calls that change group IDs  will
391       fail.   After the uid_map and gid_map files have been written, only the
392       mapped values may be used in system calls that change  user  and  group
393       IDs.
394
395       For user IDs, the relevant system calls include setuid(2), setfsuid(2),
396       setreuid(2), and setresuid(2).  For  group  IDs,  the  relevant  system
397       calls  include  setgid(2),  setfsgid(2), setregid(2), setresgid(2), and
398       setgroups(2).
399
400       Writing "deny"  to  the  /proc/pid/setgroups  file  before  writing  to
401       /proc/pid/gid_map will permanently disable setgroups(2) in a user name‐
402       space  and  allow  writing  to  /proc/pid/gid_map  without  having  the
403       CAP_SETGID capability in the parent user namespace.
404
405   The /proc/pid/setgroups file
406       The  /proc/pid/setgroups  file displays the string "allow" if processes
407       in the user namespace that contains the process pid  are  permitted  to
408       employ the setgroups(2) system call; it displays "deny" if setgroups(2)
409       is not permitted in that user namespace.  Note that regardless  of  the
410       value  in the /proc/pid/setgroups file (and regardless of the process's
411       capabilities),  calls  to  setgroups(2)  are  also  not  permitted   if
412       /proc/pid/gid_map has not yet been set.
413
414       A  privileged  process  (one  with  the CAP_SYS_ADMIN capability in the
415       namespace) may write either of the strings "allow" or  "deny"  to  this
416       file  before  writing a group ID mapping for this user namespace to the
417       file /proc/pid/gid_map.  Writing the string "deny" prevents any process
418       in the user namespace from employing setgroups(2).
419
420       The essence of the restrictions described in the preceding paragraph is
421       that it is permitted to write to /proc/pid/setgroups only  so  long  as
422       calling  setgroups(2)  is  disallowed because /proc/pid/gid_map has not
423       been set.  This ensures that a process cannot transition from  a  state
424       where  setgroups(2) is allowed to a state where setgroups(2) is denied;
425       a process can transition only from  setgroups(2)  being  disallowed  to
426       setgroups(2) being allowed.
427
428       The  default  value  of this file in the initial user namespace is "al‐
429       low".
430
431       Once /proc/pid/gid_map has been written to (which has the effect of en‐
432       abling setgroups(2) in the user namespace), it is no longer possible to
433       disallow setgroups(2) by writing  "deny"  to  /proc/pid/setgroups  (the
434       write fails with the error EPERM).
435
436       A  child  user  namespace inherits the /proc/pid/setgroups setting from
437       its parent.
438
439       If the setgroups file has the value "deny", then the setgroups(2)  sys‐
440       tem  call  can't  subsequently  be reenabled (by writing "allow" to the
441       file) in this user namespace.  (Attempts to do so fail with  the  error
442       EPERM.)   This restriction also propagates down to all child user name‐
443       spaces of this user namespace.
444
445       The /proc/pid/setgroups file was added in Linux  3.19,  but  was  back‐
446       ported to many earlier stable kernel series, because it addresses a se‐
447       curity issue.  The issue  concerned  files  with  permissions  such  as
448       "rwx---rwx".  Such files give fewer permissions to "group" than they do
449       to "other".  This means that dropping groups using  setgroups(2)  might
450       allow  a process file access that it did not formerly have.  Before the
451       existence of user namespaces this was not a concern, since only a priv‐
452       ileged  process  (one  with  the CAP_SETGID capability) could call set‐
453       groups(2).  However, with the introduction of user namespaces,  it  be‐
454       came  possible for an unprivileged process to create a new namespace in
455       which the user had all privileges.  This then allowed formerly unprivi‐
456       leged  users to drop groups and thus gain file access that they did not
457       previously have.  The /proc/pid/setgroups file  was  added  to  address
458       this security issue, by denying any pathway for an unprivileged process
459       to drop groups with setgroups(2).
460
461   Unmapped user and group IDs
462       There are various places where an unmapped user ID (group  ID)  may  be
463       exposed  to  user  space.  For example, the first process in a new user
464       namespace may call getuid(2) before a user ID mapping has been  defined
465       for  the  namespace.   In  most such cases, an unmapped user ID is con‐
466       verted to the overflow user ID (group ID); the default  value  for  the
467       overflow  user  ID  (group  ID)  is  65534.   See  the  descriptions of
468       /proc/sys/kernel/overflowuid   and   /proc/sys/kernel/overflowgid    in
469       proc(5).
470
471       The  cases where unmapped IDs are mapped in this fashion include system
472       calls that return user IDs (getuid(2), getgid(2), and similar), creden‐
473       tials  passed  over  a  UNIX  domain  socket,  credentials  returned by
474       stat(2), waitid(2), and the System V  IPC  "ctl"  IPC_STAT  operations,
475       credentials    exposed   by   /proc/pid/status   and   the   files   in
476       /proc/sysvipc/*, credentials returned via the si_uid field in the  sig‐
477       info_t  received  with a signal (see sigaction(2)), credentials written
478       to the process accounting file (see acct(5)), and credentials  returned
479       with POSIX message queue notifications (see mq_notify(3)).
480
481       There  is  one  notable  case where unmapped user and group IDs are not
482       converted to the corresponding  overflow  ID  value.   When  viewing  a
483       uid_map  or  gid_map  file  in which there is no mapping for the second
484       field, that field is displayed as 4294967295 (-1 as an  unsigned  inte‐
485       ger).
486
487   Accessing files
488       In order to determine permissions when an unprivileged process accesses
489       a file, the process credentials (UID, GID) and the file credentials are
490       in  effect  mapped back to what they would be in the initial user name‐
491       space and then compared to determine the permissions that  the  process
492       has  on  the  file.  The same is also true of other objects that employ
493       the credentials plus permissions mask accessibility model, such as Sys‐
494       tem V IPC objects.
495
496   Operation of file-related capabilities
497       Certain  capabilities allow a process to bypass various kernel-enforced
498       restrictions when performing operations on files owned by  other  users
499       or   groups.   These  capabilities  are:  CAP_CHOWN,  CAP_DAC_OVERRIDE,
500       CAP_DAC_READ_SEARCH, CAP_FOWNER, and CAP_FSETID.
501
502       Within a user namespace, these capabilities allow a process  to  bypass
503       the  rules  if  the  process has the relevant capability over the file,
504       meaning that:
505
506       •  the process has the relevant effective capability in its user  name‐
507          space; and
508
509       •  the file's user ID and group ID both have valid mappings in the user
510          namespace.
511
512       The CAP_FOWNER capability is treated somewhat exceptionally: it  allows
513       a  process  to  bypass  the corresponding rules so long as at least the
514       file's user ID has a mapping in the user namespace  (i.e.,  the  file's
515       group ID does not need to have a valid mapping).
516
517   Set-user-ID and set-group-ID programs
518       When  a  process  inside  a user namespace executes a set-user-ID (set-
519       group-ID) program, the process's effective user (group) ID  inside  the
520       namespace  is  changed to whatever value is mapped for the user (group)
521       ID of the file.  However, if either the user or the  group  ID  of  the
522       file  has  no mapping inside the namespace, the set-user-ID (set-group-
523       ID) bit is silently ignored: the  new  program  is  executed,  but  the
524       process's  effective  user (group) ID is left unchanged.  (This mirrors
525       the semantics of executing a set-user-ID or set-group-ID  program  that
526       resides  on  a  filesystem that was mounted with the MS_NOSUID flag, as
527       described in mount(2).)
528
529   Miscellaneous
530       When a process's user and group IDs  are  passed  over  a  UNIX  domain
531       socket  to a process in a different user namespace (see the description
532       of SCM_CREDENTIALS in unix(7)), they are  translated  into  the  corre‐
533       sponding  values  as per the receiving process's user and group ID map‐
534       pings.
535

STANDARDS

537       Linux.
538

NOTES

540       Over the years, there have been a lot of features that have been  added
541       to  the  Linux  kernel that have been made available only to privileged
542       users because of their potential to confuse  set-user-ID-root  applica‐
543       tions.   In  general,  it becomes safe to allow the root user in a user
544       namespace to use those features because it is impossible,  while  in  a
545       user  namespace,  to  gain  more privilege than the root user of a user
546       namespace has.
547
548   Global root
549       The term "global root" is sometimes used as a shorthand for user  ID  0
550       in the initial user namespace.
551
552   Availability
553       Use  of  user  namespaces requires a kernel that is configured with the
554       CONFIG_USER_NS option.  User namespaces require support in a  range  of
555       subsystems across the kernel.  When an unsupported subsystem is config‐
556       ured into the kernel, it is not possible to configure  user  namespaces
557       support.
558
559       As  at  Linux  3.8, most relevant subsystems supported user namespaces,
560       but a number of filesystems did not have the infrastructure  needed  to
561       map  user  and  group IDs between user namespaces.  Linux 3.9 added the
562       required infrastructure support for many of the  remaining  unsupported
563       filesystems  (Plan  9 (9P), Andrew File System (AFS), Ceph, CIFS, CODA,
564       NFS, and OCFS2).  Linux 3.12 added support for the last of  the  unsup‐
565       ported major filesystems, XFS.
566

EXAMPLES

568       The  program  below  is designed to allow experimenting with user name‐
569       spaces, as well as other types of namespaces.  It creates namespaces as
570       specified  by  command-line  options and then executes a command inside
571       those namespaces.  The comments and usage() function inside the program
572       provide a full explanation of the program.  The following shell session
573       demonstrates its use.
574
575       First, we look at the run-time environment:
576
577           $ uname -rs     # Need Linux 3.8 or later
578           Linux 3.8.0
579           $ id -u         # Running as unprivileged user
580           1000
581           $ id -g
582           1000
583
584       Now start a new shell in new user (-U), mount (-m), and PID (-p)  name‐
585       spaces, with user ID (-M) and group ID (-G) 1000 mapped to 0 inside the
586       user namespace:
587
588           $ ./userns_child_exec -p -m -U -M '0 1000 1' -G '0 1000 1' bash
589
590       The shell has PID 1, because it is the first process  in  the  new  PID
591       namespace:
592
593           bash$ echo $$
594           1
595
596       Mounting  a new /proc filesystem and listing all of the processes visi‐
597       ble in the new PID namespace shows that the shell can't  see  any  pro‐
598       cesses outside the PID namespace:
599
600           bash$ mount -t proc proc /proc
601           bash$ ps ax
602             PID TTY      STAT   TIME COMMAND
603               1 pts/3    S      0:00 bash
604              22 pts/3    R+     0:00 ps ax
605
606       Inside  the  user  namespace,  the shell has user and group ID 0, and a
607       full set of permitted and effective capabilities:
608
609           bash$ cat /proc/$$/status | egrep '^[UG]id'
610           Uid: 0    0    0    0
611           Gid: 0    0    0    0
612           bash$ cat /proc/$$/status | egrep '^Cap(Prm|Inh|Eff)'
613           CapInh:   0000000000000000
614           CapPrm:   0000001fffffffff
615           CapEff:   0000001fffffffff
616
617   Program source
618
619       /* userns_child_exec.c
620
621          Licensed under GNU General Public License v2 or later
622
623          Create a child process that executes a shell command in new
624          namespace(s); allow UID and GID mappings to be specified when
625          creating a user namespace.
626       */
627       #define _GNU_SOURCE
628       #include <err.h>
629       #include <sched.h>
630       #include <unistd.h>
631       #include <stdint.h>
632       #include <stdlib.h>
633       #include <sys/wait.h>
634       #include <signal.h>
635       #include <fcntl.h>
636       #include <stdio.h>
637       #include <string.h>
638       #include <limits.h>
639       #include <errno.h>
640
641       struct child_args {
642           char **argv;        /* Command to be executed by child, with args */
643           int    pipe_fd[2];  /* Pipe used to synchronize parent and child */
644       };
645
646       static int verbose;
647
648       static void
649       usage(char *pname)
650       {
651           fprintf(stderr, "Usage: %s [options] cmd [arg...]\n\n", pname);
652           fprintf(stderr, "Create a child process that executes a shell "
653                   "command in a new user namespace,\n"
654                   "and possibly also other new namespace(s).\n\n");
655           fprintf(stderr, "Options can be:\n\n");
656       #define fpe(str) fprintf(stderr, "    %s", str);
657           fpe("-i          New IPC namespace\n");
658           fpe("-m          New mount namespace\n");
659           fpe("-n          New network namespace\n");
660           fpe("-p          New PID namespace\n");
661           fpe("-u          New UTS namespace\n");
662           fpe("-U          New user namespace\n");
663           fpe("-M uid_map  Specify UID map for user namespace\n");
664           fpe("-G gid_map  Specify GID map for user namespace\n");
665           fpe("-z          Map user's UID and GID to 0 in user namespace\n");
666           fpe("            (equivalent to: -M '0 <uid> 1' -G '0 <gid> 1')\n");
667           fpe("-v          Display verbose messages\n");
668           fpe("\n");
669           fpe("If -z, -M, or -G is specified, -U is required.\n");
670           fpe("It is not permitted to specify both -z and either -M or -G.\n");
671           fpe("\n");
672           fpe("Map strings for -M and -G consist of records of the form:\n");
673           fpe("\n");
674           fpe("    ID-inside-ns   ID-outside-ns   len\n");
675           fpe("\n");
676           fpe("A map string can contain multiple records, separated"
677               " by commas;\n");
678           fpe("the commas are replaced by newlines before writing"
679               " to map files.\n");
680
681           exit(EXIT_FAILURE);
682       }
683
684       /* Update the mapping file 'map_file', with the value provided in
685          'mapping', a string that defines a UID or GID mapping. A UID or
686          GID mapping consists of one or more newline-delimited records
687          of the form:
688
689              ID_inside-ns    ID-outside-ns   length
690
691          Requiring the user to supply a string that contains newlines is
692          of course inconvenient for command-line use. Thus, we permit the
693          use of commas to delimit records in this string, and replace them
694          with newlines before writing the string to the file. */
695
696       static void
697       update_map(char *mapping, char *map_file)
698       {
699           int fd;
700           size_t map_len;     /* Length of 'mapping' */
701
702           /* Replace commas in mapping string with newlines. */
703
704           map_len = strlen(mapping);
705           for (size_t j = 0; j < map_len; j++)
706               if (mapping[j] == ',')
707                   mapping[j] = '\n';
708
709           fd = open(map_file, O_RDWR);
710           if (fd == -1) {
711               fprintf(stderr, "ERROR: open %s: %s\n", map_file,
712                       strerror(errno));
713               exit(EXIT_FAILURE);
714           }
715
716           if (write(fd, mapping, map_len) != map_len) {
717               fprintf(stderr, "ERROR: write %s: %s\n", map_file,
718                       strerror(errno));
719               exit(EXIT_FAILURE);
720           }
721
722           close(fd);
723       }
724
725       /* Linux 3.19 made a change in the handling of setgroups(2) and the
726          'gid_map' file to address a security issue.  The issue allowed
727          *unprivileged* users to employ user namespaces in order to drop groups.
728          The upshot of the 3.19 changes is that in order to update the
729          'gid_maps' file, use of the setgroups() system call in this
730          user namespace must first be disabled by writing "deny" to one of
731          the /proc/PID/setgroups files for this namespace.  That is the
732          purpose of the following function. */
733
734       static void
735       proc_setgroups_write(pid_t child_pid, char *str)
736       {
737           char setgroups_path[PATH_MAX];
738           int fd;
739
740           snprintf(setgroups_path, PATH_MAX, "/proc/%jd/setgroups",
741                   (intmax_t) child_pid);
742
743           fd = open(setgroups_path, O_RDWR);
744           if (fd == -1) {
745
746               /* We may be on a system that doesn't support
747                  /proc/PID/setgroups. In that case, the file won't exist,
748                  and the system won't impose the restrictions that Linux 3.19
749                  added. That's fine: we don't need to do anything in order
750                  to permit 'gid_map' to be updated.
751
752                  However, if the error from open() was something other than
753                  the ENOENT error that is expected for that case,  let the
754                  user know. */
755
756               if (errno != ENOENT)
757                   fprintf(stderr, "ERROR: open %s: %s\n", setgroups_path,
758                       strerror(errno));
759               return;
760           }
761
762           if (write(fd, str, strlen(str)) == -1)
763               fprintf(stderr, "ERROR: write %s: %s\n", setgroups_path,
764                   strerror(errno));
765
766           close(fd);
767       }
768
769       static int              /* Start function for cloned child */
770       childFunc(void *arg)
771       {
772           struct child_args *args = arg;
773           char ch;
774
775           /* Wait until the parent has updated the UID and GID mappings.
776              See the comment in main(). We wait for end of file on a
777              pipe that will be closed by the parent process once it has
778              updated the mappings. */
779
780           close(args->pipe_fd[1]);    /* Close our descriptor for the write
781                                          end of the pipe so that we see EOF
782                                          when parent closes its descriptor. */
783           if (read(args->pipe_fd[0], &ch, 1) != 0) {
784               fprintf(stderr,
785                       "Failure in child: read from pipe returned != 0\n");
786               exit(EXIT_FAILURE);
787           }
788
789           close(args->pipe_fd[0]);
790
791           /* Execute a shell command. */
792
793           printf("About to exec %s\n", args->argv[0]);
794           execvp(args->argv[0], args->argv);
795           err(EXIT_FAILURE, "execvp");
796       }
797
798       #define STACK_SIZE (1024 * 1024)
799
800       static char child_stack[STACK_SIZE];    /* Space for child's stack */
801
802       int
803       main(int argc, char *argv[])
804       {
805           int flags, opt, map_zero;
806           pid_t child_pid;
807           struct child_args args;
808           char *uid_map, *gid_map;
809           const int MAP_BUF_SIZE = 100;
810           char map_buf[MAP_BUF_SIZE];
811           char map_path[PATH_MAX];
812
813           /* Parse command-line options. The initial '+' character in
814              the final getopt() argument prevents GNU-style permutation
815              of command-line options. That's useful, since sometimes
816              the 'command' to be executed by this program itself
817              has command-line options. We don't want getopt() to treat
818              those as options to this program. */
819
820           flags = 0;
821           verbose = 0;
822           gid_map = NULL;
823           uid_map = NULL;
824           map_zero = 0;
825           while ((opt = getopt(argc, argv, "+imnpuUM:G:zv")) != -1) {
826               switch (opt) {
827               case 'i': flags |= CLONE_NEWIPC;        break;
828               case 'm': flags |= CLONE_NEWNS;         break;
829               case 'n': flags |= CLONE_NEWNET;        break;
830               case 'p': flags |= CLONE_NEWPID;        break;
831               case 'u': flags |= CLONE_NEWUTS;        break;
832               case 'v': verbose = 1;                  break;
833               case 'z': map_zero = 1;                 break;
834               case 'M': uid_map = optarg;             break;
835               case 'G': gid_map = optarg;             break;
836               case 'U': flags |= CLONE_NEWUSER;       break;
837               default:  usage(argv[0]);
838               }
839           }
840
841           /* -M or -G without -U is nonsensical */
842
843           if (((uid_map != NULL || gid_map != NULL || map_zero) &&
844                       !(flags & CLONE_NEWUSER)) ||
845                   (map_zero && (uid_map != NULL || gid_map != NULL)))
846               usage(argv[0]);
847
848           args.argv = &argv[optind];
849
850           /* We use a pipe to synchronize the parent and child, in order to
851              ensure that the parent sets the UID and GID maps before the child
852              calls execve(). This ensures that the child maintains its
853              capabilities during the execve() in the common case where we
854              want to map the child's effective user ID to 0 in the new user
855              namespace. Without this synchronization, the child would lose
856              its capabilities if it performed an execve() with nonzero
857              user IDs (see the capabilities(7) man page for details of the
858              transformation of a process's capabilities during execve()). */
859
860           if (pipe(args.pipe_fd) == -1)
861               err(EXIT_FAILURE, "pipe");
862
863           /* Create the child in new namespace(s). */
864
865           child_pid = clone(childFunc, child_stack + STACK_SIZE,
866                             flags | SIGCHLD, &args);
867           if (child_pid == -1)
868               err(EXIT_FAILURE, "clone");
869
870           /* Parent falls through to here. */
871
872           if (verbose)
873               printf("%s: PID of child created by clone() is %jd\n",
874                       argv[0], (intmax_t) child_pid);
875
876           /* Update the UID and GID maps in the child. */
877
878           if (uid_map != NULL || map_zero) {
879               snprintf(map_path, PATH_MAX, "/proc/%jd/uid_map",
880                       (intmax_t) child_pid);
881               if (map_zero) {
882                   snprintf(map_buf, MAP_BUF_SIZE, "0 %jd 1",
883                           (intmax_t) getuid());
884                   uid_map = map_buf;
885               }
886               update_map(uid_map, map_path);
887           }
888
889           if (gid_map != NULL || map_zero) {
890               proc_setgroups_write(child_pid, "deny");
891
892               snprintf(map_path, PATH_MAX, "/proc/%jd/gid_map",
893                       (intmax_t) child_pid);
894               if (map_zero) {
895                   snprintf(map_buf, MAP_BUF_SIZE, "0 %ld 1",
896                           (intmax_t) getgid());
897                   gid_map = map_buf;
898               }
899               update_map(gid_map, map_path);
900           }
901
902           /* Close the write end of the pipe, to signal to the child that we
903              have updated the UID and GID maps. */
904
905           close(args.pipe_fd[1]);
906
907           if (waitpid(child_pid, NULL, 0) == -1)      /* Wait for child */
908               err(EXIT_FAILURE, "waitpid");
909
910           if (verbose)
911               printf("%s: terminating\n", argv[0]);
912
913           exit(EXIT_SUCCESS);
914       }
915

SEE ALSO

917       newgidmap(1), newuidmap(1), clone(2), ptrace(2), setns(2),  unshare(2),
918       proc(5),  subgid(5),  subuid(5), capabilities(7), cgroup_namespaces(7),
919       credentials(7), namespaces(7), pid_namespaces(7)
920
921       The   kernel   source   file   Documentation/admin-guide/namespaces/re‐
922       source-control.rst.
923
924
925
926Linux man-pages 6.04              2023-04-01                user_namespaces(7)
Impressum