{
    "mode": "man",
    "parameter": "user_namespaces",
    "section": "7",
    "url": "https://www.chedong.com/phpMan.php/man/user_namespaces/7/json",
    "generated": "2026-10-09T18:27:39Z",
    "sections": {
        "NAME": {
            "content": "usernamespaces - overview of Linux user namespaces\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "For an overview of namespaces, see namespaces(7).\n\nUser  namespaces isolate security-related identifiers and attributes, in particular, user IDs\nand group IDs (see credentials(7)), the root directory, keys (see keyrings(7)), and capabili‐\nties (see capabilities(7)).  A process's user and group IDs can be different inside and  out‐\nside  a user namespace.  In particular, a process can have a normal unprivileged user ID out‐\nside a user namespace while at the same time having a user ID of 0 inside the  namespace;  in\nother words, the process has full privileges for operations inside the user namespace, but is\nunprivileged for operations outside the namespace.\n",
            "subsections": [
                {
                    "name": "Nested namespaces, namespace membership",
                    "content": "User namespaces can be nested; that is, each user namespace—except the initial (\"root\") name‐\nspace—has a parent user namespace, and can have zero or more child user namespaces.  The par‐\nent user namespace is the user namespace of the process that creates the user namespace via a\ncall to unshare(2) or clone(2) with the CLONENEWUSER flag.\n\nThe  kernel imposes (since Linux 3.11) a limit of 32 nested levels of user namespaces.  Calls\nto unshare(2) or clone(2) that would cause this limit to be exceeded fail with the error  EU‐\nSERS.\n\nEach  process  is  a  member of exactly one user namespace.  A process created via fork(2) or\nclone(2) without the CLONENEWUSER flag is a member of the same user namespace as its parent.\nA single-threaded process can join another  user  namespace  with  setns(2)  if  it  has  the\nCAPSYSADMIN  in  that namespace; upon doing so, it gains a full set of capabilities in that\nnamespace.\n\nA call to clone(2) or unshare(2) with the CLONENEWUSER flag makes the new child process (for\nclone(2)) or the caller (for unshare(2)) a member of the new user namespace  created  by  the\ncall.\n\nThe  NSGETPARENT  ioctl(2)  operation can be used to discover the parental relationship be‐\ntween user namespaces; see ioctlns(2).\n\nA task that changes one of its effective IDs will have its dumpability reset to the value  in\n/proc/sys/fs/suiddumpable.   This  may affect the ownership of proc files of child processes\nand may thus cause the parent to lack the permissions to write  to  mapping  files  of  child\nprocesses running in a new user namespace.  In such cases making the parent process dumpable,\nusing  PRSETDUMPABLE  in  a call to prctl(2), before creating a child process in a new user\nnamespace may rectify this problem.  See prctl(2) and proc(5) for details on how ownership is\naffected.\n"
                },
                {
                    "name": "Capabilities",
                    "content": "The child process created by clone(2) with the CLONENEWUSER flag starts out with a  complete\nset  of  capabilities in the new user namespace.  Likewise, a process that creates a new user\nnamespace using unshare(2) or joins an existing user namespace using setns(2)  gains  a  full\nset  of  capabilities in that namespace.  On the other hand, that process has no capabilities\nin the parent (in the case of clone(2)) or previous (in the case of unshare(2) and  setns(2))\nuser  namespace,  even  if  the  new namespace is created or joined by the root user (i.e., a\nprocess with user ID 0 in the root namespace).\n\nNote that a call to execve(2) will cause a process's capabilities to be recalculated  in  the\nusual  way (see capabilities(7)).  Consequently, unless the process has a user ID of 0 within\nthe namespace, or the executable file has  a  nonempty  inheritable  capabilities  mask,  the\nprocess will lose all capabilities.  See the discussion of user and group ID mappings, below.\n\nA  call  to  clone(2)  or  unshare(2) using the CLONENEWUSER flag or a call to setns(2) that\nmoves the caller into another user namespace  sets  the  \"securebits\"  flags  (see  capabili‐\nties(7))  to  their default values (all flags disabled) in the child (for clone(2)) or caller\n(for unshare(2) or setns(2)).  Note that because the caller no longer has capabilities in its\noriginal user namespace after a call to setns(2), it is not possible for a process  to  reset\nits  \"securebits\"  flags  while  retaining  its  user namespace membership by using a pair of\nsetns(2) calls to move to another user namespace and then return to its original  user  name‐\nspace.\n\nThe  rules  for  determining  whether  or not a process has a capability in a particular user\nnamespace are as follows:\n\n•  A process has a capability inside a user namespace if it is a member of that namespace and\nit has the capability in its effective capability set.  A process can gain capabilities in\nits effective capability set in various ways.  For example, it may execute  a  set-user-ID\nprogram  or  an  executable with associated file capabilities.  In addition, a process may\ngain capabilities via the effect of clone(2), unshare(2),  or  setns(2),  as  already  de‐\nscribed.\n\n•  If  a  process  has  a  capability in a user namespace, then it has that capability in all\nchild (and further removed descendant) namespaces as well.\n\n•  When a user namespace is created, the kernel records the effective user ID of the creating\nprocess as being the \"owner\" of the namespace.  A process that resides in  the  parent  of\nthe  user namespace and whose effective user ID matches the owner of the namespace has all\ncapabilities in the namespace.  By virtue of  the  previous  rule,  this  means  that  the\nprocess  has  all  capabilities in all further removed descendant user namespaces as well.\nThe NSGETOWNERUID ioctl(2) operation can be used to discover the user ID of  the  owner\nof the namespace; see ioctlns(2).\n"
                },
                {
                    "name": "Effect of capabilities within a user namespace",
                    "content": "Having a capability inside a user namespace permits a process to perform operations (that re‐\nquire  privilege) only on resources governed by that namespace.  In other words, having a ca‐\npability in a user namespace permits a process to perform privileged operations on  resources\nthat  are governed by (nonuser) namespaces owned by (associated with) the user namespace (see\nthe next subsection).\n\nOn the other hand, there are many privileged operations that affect resources  that  are  not\nassociated  with  any  namespace type, for example, changing the system (i.e., calendar) time\n(governed by CAPSYSTIME), loading a kernel module (governed by CAPSYSMODULE), and  creat‐\ning  a  device  (governed  by CAPMKNOD).  Only a process with privileges in the initial user\nnamespace can perform such operations.\n\nHolding CAPSYSADMIN within the user namespace that owns a process's mount namespace  allows\nthat process to create bind mounts and mount the following types of filesystems:\n\n•  /proc (since Linux 3.8)\n•  /sys (since Linux 3.8)\n•  devpts (since Linux 3.9)\n•  tmpfs(5) (since Linux 3.9)\n•  ramfs (since Linux 3.9)\n•  mqueue (since Linux 3.9)\n•  bpf (since Linux 4.4)\n•  overlayfs (since Linux 5.11)\n\nHolding CAPSYSADMIN within the user namespace that owns a process's cgroup namespace allows\n(since  Linux  4.6) that process to the mount the cgroup version 2 filesystem and cgroup ver‐\nsion 1 named hierarchies (i.e., cgroup filesystems mounted with the \"none,name=\" option).\n\nHolding CAPSYSADMIN within the user namespace that owns a process's  PID  namespace  allows\n(since Linux 3.8) that process to mount /proc filesystems.\n\nNote, however, that mounting block-based filesystems can be done only by a process that holds\nCAPSYSADMIN in the initial user namespace.\n"
                },
                {
                    "name": "Interaction of user namespaces and other types of namespaces",
                    "content": "Starting in Linux 3.8, unprivileged processes can create user namespaces, and the other types\nof  namespaces  can  be  created  with just the CAPSYSADMIN capability in the caller's user\nnamespace.\n\nWhen a nonuser namespace is created, it is owned by the user namespace in which the  creating\nprocess  was a member at the time of the creation of the namespace.  Privileged operations on\nresources governed by the nonuser namespace require that the process has the necessary  capa‐\nbilities in the user namespace that owns the nonuser namespace.\n\nIf  CLONENEWUSER  is specified along with other CLONENEW* flags in a single clone(2) or un‐\nshare(2) call, the user namespace is  guaranteed  to  be  created  first,  giving  the  child\n(clone(2))  or  caller  (unshare(2))  privileges over the remaining namespaces created by the\ncall.  Thus, it is possible for an unprivileged caller to specify this combination of flags.\n\nWhen a new namespace (other than a user namespace) is created via clone(2) or unshare(2), the\nkernel records the user namespace of the creating process as the owner of the new  namespace.\n(This  association  can't be changed.)  When a process in the new namespace subsequently per‐\nforms privileged operations that operate on global resources isolated by the  namespace,  the\npermission checks are performed according to the process's capabilities in the user namespace\nthat  the  kernel associated with the new namespace.  For example, suppose that a process at‐\ntempts to change the hostname (sethostname(2)), a resource governed by the UTS namespace.  In\nthis case, the kernel will determine which user namespace owns the process's  UTS  namespace,\nand  check whether the process has the required capability (CAPSYSADMIN) in that user name‐\nspace.\n\nThe NSGETUSERNS ioctl(2) operation can be used to discover the user namespace that  owns  a\nnonuser namespace; see ioctlns(2).\n"
                },
                {
                    "name": "User and group ID mappings: uid_map and gid_map",
                    "content": "When  a user namespace is created, it starts out without a mapping of user IDs (group IDs) to\nthe parent user namespace.  The  /proc/pid/uidmap  and  /proc/pid/gidmap  files  (available\nsince Linux 3.5) expose the mappings for user and group IDs inside the user namespace for the\nprocess pid.  These files can be read to view the mappings in a user namespace and written to\n(once) to define the mappings.\n\nThe  description in the following paragraphs explains the details for uidmap; gidmap is ex‐\nactly the same, but each instance of \"user ID\" is replaced by \"group ID\".\n\nThe uidmap file exposes the mapping of user IDs from the user namespace of the  process  pid\nto  the  user  namespace  of the process that opened uidmap (but see a qualification to this\npoint below).  In other words, processes that are in different user  namespaces  will  poten‐\ntially  see  different  values  when reading from a particular uidmap file, depending on the\nuser ID mappings for the user namespaces of the reading processes.\n\nEach line in the uidmap file specifies a 1-to-1 mapping of a range of  contiguous  user  IDs\nbetween  two  user namespaces.  (When a user namespace is first created, this file is empty.)\nThe specification in each line takes the form of three numbers delimited by white space.  The\nfirst two numbers specify the starting user ID in each of the two user namespaces.  The third\nnumber specifies the length of the mapped range.  In detail, the fields  are  interpreted  as\nfollows:\n\n(1)  The start of the range of user IDs in the user namespace of the process pid.\n\n(2)  The  start  of  the  range of user IDs to which the user IDs specified by field one map.\nHow field two is interpreted depends on whether the process that opened uidmap and  the\nprocess pid are in the same user namespace, as follows:\n\n(a)  If  the two processes are in different user namespaces: field two is the start of a\nrange of user IDs in the user namespace of the process that opened uidmap.\n\n(b)  If the two processes are in the same user namespace: field two is the start of  the\nrange  of  user IDs in the parent user namespace of the process pid.  This case en‐\nables the opener of uidmap (the common case here is opening /proc/self/uidmap) to\nsee the mapping of user IDs into the user namespace of  the  process  that  created\nthis user namespace.\n\n(3)  The length of the range of user IDs that is mapped between the two user namespaces.\n\nSystem calls that return user IDs (group IDs)—for example, getuid(2), getgid(2), and the cre‐\ndential fields in the structure returned by stat(2)—return the user ID (group ID) mapped into\nthe caller's user namespace.\n\nWhen a process accesses a file, its user and group IDs are mapped into the initial user name‐\nspace  for the purpose of permission checking and assigning IDs when creating a file.  When a\nprocess retrieves file user and group IDs via stat(2), the IDs are mapped in the opposite di‐\nrection, to produce values relative to the process user and group ID mappings.\n\nThe initial user namespace has no parent namespace, but, for consistency, the kernel provides\ndummy user and group ID mapping files for  this  namespace.   Looking  at  the  uidmap  file\n(gidmap is the same) from a shell in the initial namespace shows:\n\n$ cat /proc/$$/uidmap\n0          0 4294967295\n\nThis  mapping tells us that the range starting at user ID 0 in this namespace maps to a range\nstarting at 0 in the (nonexistent) parent namespace, and the  length  of  the  range  is  the\nlargest  32-bit  unsigned  integer.   This leaves 4294967295 (the 32-bit signed -1 value) un‐\nmapped.  This is deliberate: (uidt) -1 is used in several interfaces (e.g., setreuid(2))  as\na  way  to  specify  \"no  user ID\".  Leaving (uidt) -1 unmapped and unusable guarantees that\nthere will be no confusion when using these interfaces.\n"
                },
                {
                    "name": "Defining user and group ID mappings: writing to uid_map and gid_map",
                    "content": "After the creation of a new user namespace, the uidmap file of one of the processes  in  the\nnamespace may be written to once to define the mapping of user IDs in the new user namespace.\nAn attempt to write more than once to a uidmap file in a user namespace fails with the error\nEPERM.  Similar rules apply for gidmap files.\n\nThe lines written to uidmap (gidmap) must conform to the following validity rules:\n\n•  The three fields must be valid numbers, and the last field must be greater than 0.\n\n•  Lines are terminated by newline characters.\n\n•  There  is  a  limit  on  the number of lines in the file.  In Linux 4.14 and earlier, this\nlimit was (arbitrarily) set at 5 lines.  Since Linux 4.15, the limit is 340 lines.  In ad‐\ndition, the number of bytes written to the file must be less than the  system  page  size,\nand  the  write  must  be performed at the start of the file (i.e., lseek(2) and pwrite(2)\ncan't be used to write to nonzero offsets in the file).\n\n•  The range of user IDs (group IDs) specified in each line cannot overlap with the ranges in\nany other lines.  In the initial implementation (Linux 3.8), this requirement  was  satis‐\nfied  by  a simplistic implementation that imposed the further requirement that the values\nin both field 1 and field 2 of successive lines must  be  in  ascending  numerical  order,\nwhich  prevented  some  otherwise  valid maps from being created.  Linux 3.9 and later fix\nthis limitation, allowing any valid set of nonoverlapping maps.\n\n•  At least one line must be written to the file.\n\nWrites that violate the above rules fail with the error EINVAL.\n\nIn order for a process to write to the /proc/pid/uidmap (/proc/pid/gidmap) file, all of the\nfollowing permission requirements must be met:\n\n•  The writing process must have the CAPSETUID (CAPSETGID) capability in the user namespace\nof the process pid.\n\n•  The writing process must either be in the user namespace of the process pid or be  in  the\nparent user namespace of the process pid.\n\n•  The mapped user IDs (group IDs) must in turn have a mapping in the parent user namespace.\n\n•  If updating /proc/pid/uidmap to create a mapping that maps UID 0 in the parent namespace,\nthen one of the following must be true:\n\n(a)  if writing process is in the parent user namespace, then it must have the CAPSETFCAP\ncapability in that user namespace; or\n\n(b)  if  the writing process is in the child user namespace, then the process that created\nthe user namespace must have had the CAPSETFCAP capability when  the  namespace  was\ncreated.\n\nThis  rule  has  been  in  place  since Linux 5.12.  It eliminates an earlier security bug\nwhereby a UID 0 process that lacks the CAPSETFCAP capability, which is needed to create a\nbinary with namespaced file capabilities (as described in capabilities(7)),  could  never‐\ntheless create such a binary, by the following steps:\n\n(1)  Create  a  new  user namespace with the identity mapping (i.e., UID 0 in the new user\nnamespace maps to UID 0 in the parent namespace), so that UID 0 in both namespaces is\nequivalent to the same root user ID.\n\n(2)  Since the child process has the CAPSETFCAP capability, it could create a binary with\nnamespaced file capabilities that would then be effective in the  parent  user  name‐\nspace (because the root user IDs are the same in the two namespaces).\n\n•  One of the following two cases applies:\n\n(a)  Either  the  writing process has the CAPSETUID (CAPSETGID) capability in the parent\nuser namespace.\n\n•  No further restrictions apply: the process can make mappings to arbitrary user IDs\n(group IDs) in the parent user namespace.\n\n(b)  Or otherwise all of the following restrictions apply:\n\n•  The data written to uidmap (gidmap) must consist of a single line that maps  the\nwriting  process's  effective user ID (group ID) in the parent user namespace to a\nuser ID (group ID) in the user namespace.\n\n•  The writing process must have the same effective user ID as the process that  cre‐\nated the user namespace.\n\n•  In  the  case of gidmap, use of the setgroups(2) system call must first be denied\nby writing \"deny\" to the /proc/pid/setgroups file (see below)  before  writing  to\ngidmap.\n\nWrites that violate the above rules fail with the error EPERM.\n"
                },
                {
                    "name": "Project ID mappings: projid_map",
                    "content": "Similarly  to  user and group ID mappings, it is possible to create project ID mappings for a\nuser namespace.  (Project IDs are used for disk quotas; see setquota(8) and quotactl(2).)\n\nProject ID mappings are defined by writing to the /proc/pid/projidmap  file  (present  since\nLinux 3.7).\n\nThe  validity  rules  for  writing to the /proc/pid/projidmap file are as for writing to the\nuidmap file; violation of these rules causes write(2) to fail with the error EINVAL.\n\nThe permission rules for writing to the /proc/pid/projidmap file are as follows:\n\n•  The writing process must either be in the user namespace of the process pid or be  in  the\nparent user namespace of the process pid.\n\n•  The mapped project IDs must in turn have a mapping in the parent user namespace.\n\nViolation of these rules causes write(2) to fail with the error EPERM.\n"
                },
                {
                    "name": "Interaction with system calls that change process UIDs or GIDs",
                    "content": "In a user namespace where the uidmap file has not been written, the system calls that change\nuser  IDs  will  fail.  Similarly, if the gidmap file has not been written, the system calls\nthat change group IDs will fail.  After the uidmap and gidmap files have been written, only\nthe mapped values may be used in system calls that change user and group IDs.\n\nFor user IDs, the relevant system calls include setuid(2), setfsuid(2), setreuid(2), and  se‐\ntresuid(2).   For  group  IDs,  the relevant system calls include setgid(2), setfsgid(2), se‐\ntregid(2), setresgid(2), and setgroups(2).\n\nWriting \"deny\" to the /proc/pid/setgroups file before writing to /proc/pid/gidmap will  per‐\nmanently  disable  setgroups(2)  in  a  user namespace and allow writing to /proc/pid/gidmap\nwithout having the CAPSETGID capability in the parent user namespace.\n"
                },
                {
                    "name": "The _/proc/_pid_/setgroups_ file",
                    "content": "The /proc/pid/setgroups file displays the string \"allow\" if processes in the  user  namespace\nthat  contains  the process pid are permitted to employ the setgroups(2) system call; it dis‐\nplays \"deny\" if setgroups(2) is not permitted in that user namespace.  Note  that  regardless\nof  the value in the /proc/pid/setgroups file (and regardless of the process's capabilities),\ncalls to setgroups(2) are also not permitted if /proc/pid/gidmap has not yet been set.\n\nA privileged process (one with the CAPSYSADMIN capability in the namespace) may  write  ei‐\nther of the strings \"allow\" or \"deny\" to this file before writing a group ID mapping for this\nuser namespace to the file /proc/pid/gidmap.  Writing the string \"deny\" prevents any process\nin the user namespace from employing setgroups(2).\n\nThe  essence of the restrictions described in the preceding paragraph is that it is permitted\nto write to /proc/pid/setgroups only so long as calling setgroups(2)  is  disallowed  because\n/proc/pid/gidmap  has  not  been  set.  This ensures that a process cannot transition from a\nstate where setgroups(2) is allowed to a state where setgroups(2) is denied;  a  process  can\ntransition only from setgroups(2) being disallowed to setgroups(2) being allowed.\n\nThe default value of this file in the initial user namespace is \"allow\".\n\nOnce  /proc/pid/gidmap has been written to (which has the effect of enabling setgroups(2) in\nthe user namespace), it is no longer possible to disallow setgroups(2) by writing  \"deny\"  to\n/proc/pid/setgroups (the write fails with the error EPERM).\n\nA child user namespace inherits the /proc/pid/setgroups setting from its parent.\n\nIf  the  setgroups  file has the value \"deny\", then the setgroups(2) system call can't subse‐\nquently be reenabled (by writing \"allow\" to the file) in this user namespace.   (Attempts  to\ndo  so  fail  with the error EPERM.)  This restriction also propagates down to all child user\nnamespaces of this user namespace.\n\nThe /proc/pid/setgroups file was added in Linux 3.19, but was backported to many earlier sta‐\nble kernel series, because it addresses a security issue.  The  issue  concerned  files  with\npermissions  such  as \"rwx---rwx\".  Such files give fewer permissions to \"group\" than they do\nto \"other\".  This means that dropping groups using setgroups(2) might allow  a  process  file\naccess that it did not formerly have.  Before the existence of user namespaces this was not a\nconcern, since only a privileged process (one with the CAPSETGID capability) could call set‐\ngroups(2).   However, with the introduction of user namespaces, it became possible for an un‐\nprivileged process to create a new namespace in which the user had all privileges.  This then\nallowed formerly unprivileged users to drop groups and thus gain file access  that  they  did\nnot  previously have.  The /proc/pid/setgroups file was added to address this security issue,\nby denying any pathway for an unprivileged process to drop groups with setgroups(2).\n"
                },
                {
                    "name": "Unmapped user and group IDs",
                    "content": "There are various places where an unmapped user ID (group ID) may be exposed to  user  space.\nFor  example,  the  first process in a new user namespace may call getuid(2) before a user ID\nmapping has been defined for the namespace.  In most such cases, an unmapped user ID is  con‐\nverted  to the overflow user ID (group ID); the default value for the overflow user ID (group\nID) is 65534.   See  the  descriptions  of  /proc/sys/kernel/overflowuid  and  /proc/sys/ker‐\nnel/overflowgid in proc(5).\n\nThe cases where unmapped IDs are mapped in this fashion include system calls that return user\nIDs  (getuid(2),  getgid(2), and similar), credentials passed over a UNIX domain socket, cre‐\ndentials returned by stat(2), waitid(2), and the System V IPC \"ctl\" IPCSTAT operations, cre‐\ndentials exposed by /proc/pid/status and the files in /proc/sysvipc/*,  credentials  returned\nvia  the siuid field in the siginfot received with a signal (see sigaction(2)), credentials\nwritten to the process accounting file (see acct(5)), and  credentials  returned  with  POSIX\nmessage queue notifications (see mqnotify(3)).\n\nThere  is  one notable case where unmapped user and group IDs are not converted to the corre‐\nsponding overflow ID value.  When viewing a uidmap or gidmap file in which there is no map‐\nping for the second field, that field is displayed as 4294967295 (-1 as an unsigned integer).\n"
                },
                {
                    "name": "Accessing files",
                    "content": "In order to determine permissions when an unprivileged process accesses a file,  the  process\ncredentials  (UID, GID) and the file credentials are in effect mapped back to what they would\nbe in the initial user namespace and then compared to  determine  the  permissions  that  the\nprocess  has on the file.  The same is also true of other objects that employ the credentials\nplus permissions mask accessibility model, such as System V IPC objects.\n"
                },
                {
                    "name": "Operation of file-related capabilities",
                    "content": "Certain capabilities allow a process to bypass various kernel-enforced restrictions when per‐\nforming operations on files  owned  by  other  users  or  groups.   These  capabilities  are:\nCAPCHOWN, CAPDACOVERRIDE, CAPDACREADSEARCH, CAPFOWNER, and CAPFSETID.\n\nWithin  a  user  namespace,  these  capabilities  allow  a process to bypass the rules if the\nprocess has the relevant capability over the file, meaning that:\n\n•  the process has the relevant effective capability in its user namespace; and\n\n•  the file's user ID and group ID both have valid mappings in the user namespace.\n\nThe CAPFOWNER capability is treated somewhat exceptionally: it allows a  process  to  bypass\nthe  corresponding  rules  so  long  as at least the file's user ID has a mapping in the user\nnamespace (i.e., the file's group ID does not need to have a valid mapping).\n"
                },
                {
                    "name": "Set-user-ID and set-group-ID programs",
                    "content": "When a process inside a user namespace executes a  set-user-ID  (set-group-ID)  program,  the\nprocess's  effective  user  (group)  ID  inside the namespace is changed to whatever value is\nmapped for the user (group) ID of the file.  However, if either the user or the group  ID  of\nthe  file has no mapping inside the namespace, the set-user-ID (set-group-ID) bit is silently\nignored: the new program is executed, but the process's effective user (group) ID is left un‐\nchanged.  (This mirrors the semantics of executing a set-user-ID or set-group-ID program that\nresides on a filesystem that was mounted with the MSNOSUID flag, as described in mount(2).)\n"
                },
                {
                    "name": "Miscellaneous",
                    "content": "When a process's user and group IDs are passed over a UNIX domain socket to a  process  in  a\ndifferent user namespace (see the description of SCMCREDENTIALS in unix(7)), they are trans‐\nlated  into  the  corresponding  values as per the receiving process's user and group ID map‐\npings.\n"
                }
            ]
        },
        "STANDARDS": {
            "content": "Linux.\n",
            "subsections": []
        },
        "NOTES": {
            "content": "Over the years, there have been a lot of features that have been added to  the  Linux  kernel\nthat  have been made available only to privileged users because of their potential to confuse\nset-user-ID-root applications.  In general, it becomes safe to allow the root user in a  user\nnamespace  to use those features because it is impossible, while in a user namespace, to gain\nmore privilege than the root user of a user namespace has.\n",
            "subsections": [
                {
                    "name": "Global root",
                    "content": "The term \"global root\" is sometimes used as a shorthand for user ID 0  in  the  initial  user\nnamespace.\n"
                },
                {
                    "name": "Availability",
                    "content": "Use  of  user namespaces requires a kernel that is configured with the CONFIGUSERNS option.\nUser namespaces require support in a range of subsystems across the kernel.  When  an  unsup‐\nported  subsystem  is  configured into the kernel, it is not possible to configure user name‐\nspaces support.\n\nAs at Linux 3.8, most relevant subsystems supported user namespaces, but a number of filesys‐\ntems did not have the infrastructure needed to map user and  group  IDs  between  user  name‐\nspaces.  Linux 3.9 added the required infrastructure support for many of the remaining unsup‐\nported filesystems (Plan 9 (9P), Andrew File System (AFS), Ceph, CIFS, CODA, NFS, and OCFS2).\nLinux 3.12 added support for the last of the unsupported major filesystems, XFS.\n"
                }
            ]
        },
        "EXAMPLES": {
            "content": "The  program  below is designed to allow experimenting with user namespaces, as well as other\ntypes of namespaces.  It creates namespaces as specified by command-line options and then ex‐\necutes a command inside those namespaces.  The comments and usage() function inside the  pro‐\ngram provide a full explanation of the program.  The following shell session demonstrates its\nuse.\n\nFirst, we look at the run-time environment:\n\n$ uname -rs     # Need Linux 3.8 or later\nLinux 3.8.0\n$ id -u         # Running as unprivileged user\n1000\n$ id -g\n1000\n\nNow  start  a  new  shell in new user (-U), mount (-m), and PID (-p) namespaces, with user ID\n(-M) and group ID (-G) 1000 mapped to 0 inside the user namespace:\n\n$ ./usernschildexec -p -m -U -M '0 1000 1' -G '0 1000 1' bash\n\nThe shell has PID 1, because it is the first process in the new PID namespace:\n\nbash$ echo $$\n1\n\nMounting a new /proc filesystem and listing all of the processes visible in the new PID name‐\nspace shows that the shell can't see any processes outside the PID namespace:\n\nbash$ mount -t proc proc /proc\nbash$ ps ax\nPID TTY      STAT   TIME COMMAND\n1 pts/3    S      0:00 bash\n22 pts/3    R+     0:00 ps ax\n\nInside the user namespace, the shell has user and group ID 0, and a full set of permitted and\neffective capabilities:\n\nbash$ cat /proc/$$/status | egrep '^[UG]id'\nUid: 0    0    0    0\nGid: 0    0    0    0\nbash$ cat /proc/$$/status | egrep '^Cap(Prm|Inh|Eff)'\nCapInh:   0000000000000000\nCapPrm:   0000001fffffffff\nCapEff:   0000001fffffffff\n",
            "subsections": [
                {
                    "name": "Program source",
                    "content": "/* usernschildexec.c\n\nLicensed under GNU General Public License v2 or later\n\nCreate a child process that executes a shell command in new\nnamespace(s); allow UID and GID mappings to be specified when\ncreating a user namespace.\n*/\n#define GNUSOURCE\n#include <err.h>\n#include <sched.h>\n#include <unistd.h>\n#include <stdint.h>\n#include <stdlib.h>\n#include <sys/wait.h>\n#include <signal.h>\n#include <fcntl.h>\n#include <stdio.h>\n#include <string.h>\n#include <limits.h>\n#include <errno.h>\n\nstruct childargs {\nchar argv;        /* Command to be executed by child, with args */\nint    pipefd[2];  /* Pipe used to synchronize parent and child */\n};\n\nstatic int verbose;\n\nstatic void\nusage(char *pname)\n{\nfprintf(stderr, \"Usage: %s [options] cmd [arg...]\\n\\n\", pname);\nfprintf(stderr, \"Create a child process that executes a shell \"\n\"command in a new user namespace,\\n\"\n\"and possibly also other new namespace(s).\\n\\n\");\nfprintf(stderr, \"Options can be:\\n\\n\");\n#define fpe(str) fprintf(stderr, \"    %s\", str);\nfpe(\"-i          New IPC namespace\\n\");\nfpe(\"-m          New mount namespace\\n\");\nfpe(\"-n          New network namespace\\n\");\nfpe(\"-p          New PID namespace\\n\");\nfpe(\"-u          New UTS namespace\\n\");\nfpe(\"-U          New user namespace\\n\");\nfpe(\"-M uidmap  Specify UID map for user namespace\\n\");\nfpe(\"-G gidmap  Specify GID map for user namespace\\n\");\nfpe(\"-z          Map user's UID and GID to 0 in user namespace\\n\");\nfpe(\"            (equivalent to: -M '0 <uid> 1' -G '0 <gid> 1')\\n\");\nfpe(\"-v          Display verbose messages\\n\");\nfpe(\"\\n\");\nfpe(\"If -z, -M, or -G is specified, -U is required.\\n\");\nfpe(\"It is not permitted to specify both -z and either -M or -G.\\n\");\nfpe(\"\\n\");\nfpe(\"Map strings for -M and -G consist of records of the form:\\n\");\nfpe(\"\\n\");\nfpe(\"    ID-inside-ns   ID-outside-ns   len\\n\");\nfpe(\"\\n\");\nfpe(\"A map string can contain multiple records, separated\"\n\" by commas;\\n\");\nfpe(\"the commas are replaced by newlines before writing\"\n\" to map files.\\n\");\n\nexit(EXITFAILURE);\n}\n\n/* Update the mapping file 'mapfile', with the value provided in\n'mapping', a string that defines a UID or GID mapping. A UID or\nGID mapping consists of one or more newline-delimited records\nof the form:\n\nIDinside-ns    ID-outside-ns   length\n\nRequiring the user to supply a string that contains newlines is\nof course inconvenient for command-line use. Thus, we permit the\nuse of commas to delimit records in this string, and replace them\nwith newlines before writing the string to the file. */\n\nstatic void\nupdatemap(char *mapping, char *mapfile)\n{\nint fd;\nsizet maplen;     /* Length of 'mapping' */\n\n/* Replace commas in mapping string with newlines. */\n\nmaplen = strlen(mapping);\nfor (sizet j = 0; j < maplen; j++)\nif (mapping[j] == ',')\nmapping[j] = '\\n';\n\nfd = open(mapfile, ORDWR);\nif (fd == -1) {\nfprintf(stderr, \"ERROR: open %s: %s\\n\", mapfile,\nstrerror(errno));\nexit(EXITFAILURE);\n}\n\nif (write(fd, mapping, maplen) != maplen) {\nfprintf(stderr, \"ERROR: write %s: %s\\n\", mapfile,\nstrerror(errno));\nexit(EXITFAILURE);\n}\n\nclose(fd);\n}\n\n/* Linux 3.19 made a change in the handling of setgroups(2) and\nthe 'gidmap' file to address a security issue.  The issue\nallowed *unprivileged* users to employ user namespaces in\norder to drop groups.  The upshot of the 3.19 changes is that\nin order to update the 'gidmaps' file, use of the setgroups()\nsystem call in this user namespace must first be disabled by\nwriting \"deny\" to one of the /proc/PID/setgroups files for\nthis namespace.  That is the purpose of the following function.  */\n\nstatic void\nprocsetgroupswrite(pidt childpid, char *str)\n{\nchar setgroupspath[PATHMAX];\nint fd;\n\nsnprintf(setgroupspath, PATHMAX, \"/proc/%jd/setgroups\",\n(intmaxt) childpid);\n\nfd = open(setgroupspath, ORDWR);\nif (fd == -1) {\n\n/* We may be on a system that doesn't support\n/proc/PID/setgroups. In that case, the file won't exist,\nand the system won't impose the restrictions that Linux 3.19\nadded. That's fine: we don't need to do anything in order\nto permit 'gidmap' to be updated.\n\nHowever, if the error from open() was something other than\nthe ENOENT error that is expected for that case,  let the\nuser know. */\n\nif (errno != ENOENT)\nfprintf(stderr, \"ERROR: open %s: %s\\n\", setgroupspath,\nstrerror(errno));\nreturn;\n}\n\nif (write(fd, str, strlen(str)) == -1)\nfprintf(stderr, \"ERROR: write %s: %s\\n\", setgroupspath,\nstrerror(errno));\n\nclose(fd);\n}\n\nstatic int              /* Start function for cloned child */\nchildFunc(void *arg)\n{\nstruct childargs *args = arg;\nchar ch;\n\n/* Wait until the parent has updated the UID and GID mappings.\nSee the comment in main(). We wait for end of file on a\npipe that will be closed by the parent process once it has\nupdated the mappings. */\n\nclose(args->pipefd[1]);    /* Close our descriptor for the write\nend of the pipe so that we see EOF\nwhen parent closes its descriptor. */\nif (read(args->pipefd[0], &ch, 1) != 0) {\nfprintf(stderr,\n\"Failure in child: read from pipe returned != 0\\n\");\nexit(EXITFAILURE);\n}\n\nclose(args->pipefd[0]);\n\n/* Execute a shell command. */\n\nprintf(\"About to exec %s\\n\", args->argv[0]);\nexecvp(args->argv[0], args->argv);\nerr(EXITFAILURE, \"execvp\");\n}\n\n#define STACKSIZE (1024 * 1024)\n\nstatic char childstack[STACKSIZE];    /* Space for child's stack */\n\nint\nmain(int argc, char *argv[])\n{\nint flags, opt, mapzero;\npidt childpid;\nstruct childargs args;\nchar *uidmap, *gidmap;\nconst int MAPBUFSIZE = 100;\nchar mapbuf[MAPBUFSIZE];\nchar mappath[PATHMAX];\n\n/* Parse command-line options. The initial '+' character in\nthe final getopt() argument prevents GNU-style permutation\nof command-line options. That's useful, since sometimes\nthe 'command' to be executed by this program itself\nhas command-line options. We don't want getopt() to treat\nthose as options to this program. */\n\nflags = 0;\nverbose = 0;\ngidmap = NULL;\nuidmap = NULL;\nmapzero = 0;\nwhile ((opt = getopt(argc, argv, \"+imnpuUM:G:zv\")) != -1) {\nswitch (opt) {\ncase 'i': flags |= CLONENEWIPC;        break;\ncase 'm': flags |= CLONENEWNS;         break;\ncase 'n': flags |= CLONENEWNET;        break;\ncase 'p': flags |= CLONENEWPID;        break;\ncase 'u': flags |= CLONENEWUTS;        break;\ncase 'v': verbose = 1;                  break;\ncase 'z': mapzero = 1;                 break;\ncase 'M': uidmap = optarg;             break;\ncase 'G': gidmap = optarg;             break;\ncase 'U': flags |= CLONENEWUSER;       break;\ndefault:  usage(argv[0]);\n}\n}\n\n/* -M or -G without -U is nonsensical */\n\nif (((uidmap != NULL || gidmap != NULL || mapzero) &&\n!(flags & CLONENEWUSER)) ||\n(mapzero && (uidmap != NULL || gidmap != NULL)))\nusage(argv[0]);\n\nargs.argv = &argv[optind];\n\n/* We use a pipe to synchronize the parent and child, in order to\nensure that the parent sets the UID and GID maps before the child\ncalls execve(). This ensures that the child maintains its\ncapabilities during the execve() in the common case where we\nwant to map the child's effective user ID to 0 in the new user\nnamespace. Without this synchronization, the child would lose\nits capabilities if it performed an execve() with nonzero\nuser IDs (see the capabilities(7) man page for details of the\ntransformation of a process's capabilities during execve()). */\n\nif (pipe(args.pipefd) == -1)\nerr(EXITFAILURE, \"pipe\");\n\n/* Create the child in new namespace(s). */\n\nchildpid = clone(childFunc, childstack + STACKSIZE,\nflags | SIGCHLD, &args);\nif (childpid == -1)\nerr(EXITFAILURE, \"clone\");\n\n/* Parent falls through to here. */\n\nif (verbose)\nprintf(\"%s: PID of child created by clone() is %jd\\n\",\nargv[0], (intmaxt) childpid);\n\n/* Update the UID and GID maps in the child. */\n\nif (uidmap != NULL || mapzero) {\nsnprintf(mappath, PATHMAX, \"/proc/%jd/uidmap\",\n(intmaxt) childpid);\nif (mapzero) {\nsnprintf(mapbuf, MAPBUFSIZE, \"0 %jd 1\",\n(intmaxt) getuid());\nuidmap = mapbuf;\n}\nupdatemap(uidmap, mappath);\n}\n\nif (gidmap != NULL || mapzero) {\nprocsetgroupswrite(childpid, \"deny\");\n\nsnprintf(mappath, PATHMAX, \"/proc/%jd/gidmap\",\n(intmaxt) childpid);\nif (mapzero) {\nsnprintf(mapbuf, MAPBUFSIZE, \"0 %ld 1\",\n(intmaxt) getgid());\ngidmap = mapbuf;\n}\nupdatemap(gidmap, mappath);\n}\n\n/* Close the write end of the pipe, to signal to the child that we\nhave updated the UID and GID maps. */\n\nclose(args.pipefd[1]);\n\nif (waitpid(childpid, NULL, 0) == -1)      /* Wait for child */\nerr(EXITFAILURE, \"waitpid\");\n\nif (verbose)\nprintf(\"%s: terminating\\n\", argv[0]);\n\nexit(EXITSUCCESS);\n}\n"
                }
            ]
        },
        "SEE ALSO": {
            "content": "newgidmap(1), newuidmap(1), clone(2), ptrace(2), setns(2),  unshare(2),  proc(5),  subgid(5),\nsubuid(5),  capabilities(7),  cgroupnamespaces(7),  credentials(7), namespaces(7), pidname‐\nspaces(7)\n\nThe kernel source file Documentation/admin-guide/namespaces/resource-control.rst.\n\nLinux man-pages 6.7                          2024-02-25                           usernamespaces(7)",
            "subsections": []
        }
    },
    "summary": "usernamespaces - overview of Linux user namespaces",
    "flags": [],
    "examples": [
        "The  program  below is designed to allow experimenting with user namespaces, as well as other",
        "types of namespaces.  It creates namespaces as specified by command-line options and then ex‐",
        "ecutes a command inside those namespaces.  The comments and usage() function inside the  pro‐",
        "gram provide a full explanation of the program.  The following shell session demonstrates its",
        "use.",
        "First, we look at the run-time environment:",
        "$ uname -rs     # Need Linux 3.8 or later",
        "Linux 3.8.0",
        "$ id -u         # Running as unprivileged user",
        "1000",
        "$ id -g",
        "1000",
        "Now  start  a  new  shell in new user (-U), mount (-m), and PID (-p) namespaces, with user ID",
        "(-M) and group ID (-G) 1000 mapped to 0 inside the user namespace:",
        "$ ./usernschildexec -p -m -U -M '0 1000 1' -G '0 1000 1' bash",
        "The shell has PID 1, because it is the first process in the new PID namespace:",
        "bash$ echo $$",
        "Mounting a new /proc filesystem and listing all of the processes visible in the new PID name‐",
        "space shows that the shell can't see any processes outside the PID namespace:",
        "bash$ mount -t proc proc /proc",
        "bash$ ps ax",
        "PID TTY      STAT   TIME COMMAND",
        "1 pts/3    S      0:00 bash",
        "22 pts/3    R+     0:00 ps ax",
        "Inside the user namespace, the shell has user and group ID 0, and a full set of permitted and",
        "effective capabilities:",
        "bash$ cat /proc/$$/status | egrep '^[UG]id'",
        "Uid: 0    0    0    0",
        "Gid: 0    0    0    0",
        "bash$ cat /proc/$$/status | egrep '^Cap(Prm|Inh|Eff)'",
        "CapInh:   0000000000000000",
        "CapPrm:   0000001fffffffff",
        "CapEff:   0000001fffffffff",
        "/* usernschildexec.c",
        "Licensed under GNU General Public License v2 or later",
        "Create a child process that executes a shell command in new",
        "namespace(s); allow UID and GID mappings to be specified when",
        "creating a user namespace.",
        "*/",
        "#define GNUSOURCE",
        "#include <err.h>",
        "#include <sched.h>",
        "#include <unistd.h>",
        "#include <stdint.h>",
        "#include <stdlib.h>",
        "#include <sys/wait.h>",
        "#include <signal.h>",
        "#include <fcntl.h>",
        "#include <stdio.h>",
        "#include <string.h>",
        "#include <limits.h>",
        "#include <errno.h>",
        "struct childargs {",
        "char argv;        /* Command to be executed by child, with args */",
        "int    pipefd[2];  /* Pipe used to synchronize parent and child */",
        "};",
        "static int verbose;",
        "static void",
        "usage(char *pname)",
        "fprintf(stderr, \"Usage: %s [options] cmd [arg...]\\n\\n\", pname);",
        "fprintf(stderr, \"Create a child process that executes a shell \"",
        "\"command in a new user namespace,\\n\"",
        "\"and possibly also other new namespace(s).\\n\\n\");",
        "fprintf(stderr, \"Options can be:\\n\\n\");",
        "#define fpe(str) fprintf(stderr, \"    %s\", str);",
        "fpe(\"-i          New IPC namespace\\n\");",
        "fpe(\"-m          New mount namespace\\n\");",
        "fpe(\"-n          New network namespace\\n\");",
        "fpe(\"-p          New PID namespace\\n\");",
        "fpe(\"-u          New UTS namespace\\n\");",
        "fpe(\"-U          New user namespace\\n\");",
        "fpe(\"-M uidmap  Specify UID map for user namespace\\n\");",
        "fpe(\"-G gidmap  Specify GID map for user namespace\\n\");",
        "fpe(\"-z          Map user's UID and GID to 0 in user namespace\\n\");",
        "fpe(\"            (equivalent to: -M '0 <uid> 1' -G '0 <gid> 1')\\n\");",
        "fpe(\"-v          Display verbose messages\\n\");",
        "fpe(\"\\n\");",
        "fpe(\"If -z, -M, or -G is specified, -U is required.\\n\");",
        "fpe(\"It is not permitted to specify both -z and either -M or -G.\\n\");",
        "fpe(\"\\n\");",
        "fpe(\"Map strings for -M and -G consist of records of the form:\\n\");",
        "fpe(\"\\n\");",
        "fpe(\"    ID-inside-ns   ID-outside-ns   len\\n\");",
        "fpe(\"\\n\");",
        "fpe(\"A map string can contain multiple records, separated\"",
        "\" by commas;\\n\");",
        "fpe(\"the commas are replaced by newlines before writing\"",
        "\" to map files.\\n\");",
        "exit(EXITFAILURE);",
        "/* Update the mapping file 'mapfile', with the value provided in",
        "'mapping', a string that defines a UID or GID mapping. A UID or",
        "GID mapping consists of one or more newline-delimited records",
        "of the form:",
        "IDinside-ns    ID-outside-ns   length",
        "Requiring the user to supply a string that contains newlines is",
        "of course inconvenient for command-line use. Thus, we permit the",
        "use of commas to delimit records in this string, and replace them",
        "with newlines before writing the string to the file. */",
        "static void",
        "updatemap(char *mapping, char *mapfile)",
        "int fd;",
        "sizet maplen;     /* Length of 'mapping' */",
        "/* Replace commas in mapping string with newlines. */",
        "maplen = strlen(mapping);",
        "for (sizet j = 0; j < maplen; j++)",
        "if (mapping[j] == ',')",
        "mapping[j] = '\\n';",
        "fd = open(mapfile, ORDWR);",
        "if (fd == -1) {",
        "fprintf(stderr, \"ERROR: open %s: %s\\n\", mapfile,",
        "strerror(errno));",
        "exit(EXITFAILURE);",
        "if (write(fd, mapping, maplen) != maplen) {",
        "fprintf(stderr, \"ERROR: write %s: %s\\n\", mapfile,",
        "strerror(errno));",
        "exit(EXITFAILURE);",
        "close(fd);",
        "/* Linux 3.19 made a change in the handling of setgroups(2) and",
        "the 'gidmap' file to address a security issue.  The issue",
        "allowed *unprivileged* users to employ user namespaces in",
        "order to drop groups.  The upshot of the 3.19 changes is that",
        "in order to update the 'gidmaps' file, use of the setgroups()",
        "system call in this user namespace must first be disabled by",
        "writing \"deny\" to one of the /proc/PID/setgroups files for",
        "this namespace.  That is the purpose of the following function.  */",
        "static void",
        "procsetgroupswrite(pidt childpid, char *str)",
        "char setgroupspath[PATHMAX];",
        "int fd;",
        "snprintf(setgroupspath, PATHMAX, \"/proc/%jd/setgroups\",",
        "(intmaxt) childpid);",
        "fd = open(setgroupspath, ORDWR);",
        "if (fd == -1) {",
        "/* We may be on a system that doesn't support",
        "/proc/PID/setgroups. In that case, the file won't exist,",
        "and the system won't impose the restrictions that Linux 3.19",
        "added. That's fine: we don't need to do anything in order",
        "to permit 'gidmap' to be updated.",
        "However, if the error from open() was something other than",
        "the ENOENT error that is expected for that case,  let the",
        "user know. */",
        "if (errno != ENOENT)",
        "fprintf(stderr, \"ERROR: open %s: %s\\n\", setgroupspath,",
        "strerror(errno));",
        "return;",
        "if (write(fd, str, strlen(str)) == -1)",
        "fprintf(stderr, \"ERROR: write %s: %s\\n\", setgroupspath,",
        "strerror(errno));",
        "close(fd);",
        "static int              /* Start function for cloned child */",
        "childFunc(void *arg)",
        "struct childargs *args = arg;",
        "char ch;",
        "/* Wait until the parent has updated the UID and GID mappings.",
        "See the comment in main(). We wait for end of file on a",
        "pipe that will be closed by the parent process once it has",
        "updated the mappings. */",
        "close(args->pipefd[1]);    /* Close our descriptor for the write",
        "end of the pipe so that we see EOF",
        "when parent closes its descriptor. */",
        "if (read(args->pipefd[0], &ch, 1) != 0) {",
        "fprintf(stderr,",
        "\"Failure in child: read from pipe returned != 0\\n\");",
        "exit(EXITFAILURE);",
        "close(args->pipefd[0]);",
        "/* Execute a shell command. */",
        "printf(\"About to exec %s\\n\", args->argv[0]);",
        "execvp(args->argv[0], args->argv);",
        "err(EXITFAILURE, \"execvp\");",
        "#define STACKSIZE (1024 * 1024)",
        "static char childstack[STACKSIZE];    /* Space for child's stack */",
        "int",
        "main(int argc, char *argv[])",
        "int flags, opt, mapzero;",
        "pidt childpid;",
        "struct childargs args;",
        "char *uidmap, *gidmap;",
        "const int MAPBUFSIZE = 100;",
        "char mapbuf[MAPBUFSIZE];",
        "char mappath[PATHMAX];",
        "/* Parse command-line options. The initial '+' character in",
        "the final getopt() argument prevents GNU-style permutation",
        "of command-line options. That's useful, since sometimes",
        "the 'command' to be executed by this program itself",
        "has command-line options. We don't want getopt() to treat",
        "those as options to this program. */",
        "flags = 0;",
        "verbose = 0;",
        "gidmap = NULL;",
        "uidmap = NULL;",
        "mapzero = 0;",
        "while ((opt = getopt(argc, argv, \"+imnpuUM:G:zv\")) != -1) {",
        "switch (opt) {",
        "case 'i': flags |= CLONENEWIPC;        break;",
        "case 'm': flags |= CLONENEWNS;         break;",
        "case 'n': flags |= CLONENEWNET;        break;",
        "case 'p': flags |= CLONENEWPID;        break;",
        "case 'u': flags |= CLONENEWUTS;        break;",
        "case 'v': verbose = 1;                  break;",
        "case 'z': mapzero = 1;                 break;",
        "case 'M': uidmap = optarg;             break;",
        "case 'G': gidmap = optarg;             break;",
        "case 'U': flags |= CLONENEWUSER;       break;",
        "default:  usage(argv[0]);",
        "/* -M or -G without -U is nonsensical */",
        "if (((uidmap != NULL || gidmap != NULL || mapzero) &&",
        "!(flags & CLONENEWUSER)) ||",
        "(mapzero && (uidmap != NULL || gidmap != NULL)))",
        "usage(argv[0]);",
        "args.argv = &argv[optind];",
        "/* We use a pipe to synchronize the parent and child, in order to",
        "ensure that the parent sets the UID and GID maps before the child",
        "calls execve(). This ensures that the child maintains its",
        "capabilities during the execve() in the common case where we",
        "want to map the child's effective user ID to 0 in the new user",
        "namespace. Without this synchronization, the child would lose",
        "its capabilities if it performed an execve() with nonzero",
        "user IDs (see the capabilities(7) man page for details of the",
        "transformation of a process's capabilities during execve()). */",
        "if (pipe(args.pipefd) == -1)",
        "err(EXITFAILURE, \"pipe\");",
        "/* Create the child in new namespace(s). */",
        "childpid = clone(childFunc, childstack + STACKSIZE,",
        "flags | SIGCHLD, &args);",
        "if (childpid == -1)",
        "err(EXITFAILURE, \"clone\");",
        "/* Parent falls through to here. */",
        "if (verbose)",
        "printf(\"%s: PID of child created by clone() is %jd\\n\",",
        "argv[0], (intmaxt) childpid);",
        "/* Update the UID and GID maps in the child. */",
        "if (uidmap != NULL || mapzero) {",
        "snprintf(mappath, PATHMAX, \"/proc/%jd/uidmap\",",
        "(intmaxt) childpid);",
        "if (mapzero) {",
        "snprintf(mapbuf, MAPBUFSIZE, \"0 %jd 1\",",
        "(intmaxt) getuid());",
        "uidmap = mapbuf;",
        "updatemap(uidmap, mappath);",
        "if (gidmap != NULL || mapzero) {",
        "procsetgroupswrite(childpid, \"deny\");",
        "snprintf(mappath, PATHMAX, \"/proc/%jd/gidmap\",",
        "(intmaxt) childpid);",
        "if (mapzero) {",
        "snprintf(mapbuf, MAPBUFSIZE, \"0 %ld 1\",",
        "(intmaxt) getgid());",
        "gidmap = mapbuf;",
        "updatemap(gidmap, mappath);",
        "/* Close the write end of the pipe, to signal to the child that we",
        "have updated the UID and GID maps. */",
        "close(args.pipefd[1]);",
        "if (waitpid(childpid, NULL, 0) == -1)      /* Wait for child */",
        "err(EXITFAILURE, \"waitpid\");",
        "if (verbose)",
        "printf(\"%s: terminating\\n\", argv[0]);",
        "exit(EXITSUCCESS);"
    ],
    "see_also": [
        {
            "name": "newgidmap",
            "section": "1",
            "url": "https://www.chedong.com/phpMan.php/man/newgidmap/1/json"
        },
        {
            "name": "newuidmap",
            "section": "1",
            "url": "https://www.chedong.com/phpMan.php/man/newuidmap/1/json"
        },
        {
            "name": "clone",
            "section": "2",
            "url": "https://www.chedong.com/phpMan.php/man/clone/2/json"
        },
        {
            "name": "ptrace",
            "section": "2",
            "url": "https://www.chedong.com/phpMan.php/man/ptrace/2/json"
        },
        {
            "name": "setns",
            "section": "2",
            "url": "https://www.chedong.com/phpMan.php/man/setns/2/json"
        },
        {
            "name": "unshare",
            "section": "2",
            "url": "https://www.chedong.com/phpMan.php/man/unshare/2/json"
        },
        {
            "name": "proc",
            "section": "5",
            "url": "https://www.chedong.com/phpMan.php/man/proc/5/json"
        },
        {
            "name": "subgid",
            "section": "5",
            "url": "https://www.chedong.com/phpMan.php/man/subgid/5/json"
        },
        {
            "name": "subuid",
            "section": "5",
            "url": "https://www.chedong.com/phpMan.php/man/subuid/5/json"
        },
        {
            "name": "capabilities",
            "section": "7",
            "url": "https://www.chedong.com/phpMan.php/man/capabilities/7/json"
        },
        {
            "name": "cgroupnamespaces",
            "section": "7",
            "url": "https://www.chedong.com/phpMan.php/man/cgroupnamespaces/7/json"
        },
        {
            "name": "credentials",
            "section": "7",
            "url": "https://www.chedong.com/phpMan.php/man/credentials/7/json"
        },
        {
            "name": "namespaces",
            "section": "7",
            "url": "https://www.chedong.com/phpMan.php/man/namespaces/7/json"
        },
        {
            "name": "spaces",
            "section": "7",
            "url": "https://www.chedong.com/phpMan.php/man/spaces/7/json"
        }
    ]
}