Namespaces
Linux namespaces wrap system resources, making processes within that namespace appear to have isolated instances of that resource. Changes can be made within the namespace that will not be visible outside, on the system.
Namespace types
The following namespaces are available in Linux:
- Cgroup - Provides a new Cgroup root directory for the process.
- IPC - Provides System V IPC and POSIX message queues.
- Network - Isolated network devices, IP stacks, routing tables, firewall rules, used ports, UNIX sockets, and more.
- Mount - Isolated mount records for the process, providing distinct single-directory hierarchies.
- PID - Provides a new PID tree, starting at 1 like a typical Linux system.
- Time - Provides 2 virtual clocks for the process:
CLOCK_MONOTONIC
, andCLOCK_BOOTTIME
. - User - Provides isolated user security identifiers and attributes, such as: UIDs, GIDs, keyrings, capabilities.
- UTS - Isolates the process' hostname and NIS domain name using sethostname and setdomainname.
For each namespace type, there is a man page, ex: man mount_namespaces or man user_namespaces.
Interacting with user namespaces
User namespaces, or namespaces where UID/GIDs are mapped, can be used to act as the root UID without elevated privilages.
Checking current ID maps
The current UID/GID maps can be set or edited using /proc/$$/uid_map and /proc/$$/gid_map.
user $
cat /proc/$$/uid_map
0 0 4294967295
$$
should resolve to the shell's PID. Any PID can be used to check uid/gid maps for a running process.Creating a new namespace
To create a new user namespace, mapped to the root user and group within the namespace:
user $
unshare --map-auto -S 0 -G 0
This new shell session has the following mapped UIDs:
root #
cat /proc/$$/uid_map
0 100000 65536
This does not map any UIDs within this namespace to ones on the host system, including the user running unshare.
Creating a new namespace with outside user privileges
To create a new shell session where root inside is mapped to the user running the command outside:
user $
unshare --map-auto --map-root
This can be set to an alias like
alias nsudo="unshare --map-auto --map-root "
.This new shell session has the following mapped UIDs:
root #
cat /proc/$$/uid_map
0 1000 1 1 100000 65536
Entering an existing namespace
If a process is already running in a namespace, nsenter can be used to interact with it.
To get root user context within a namespace running on PID 12345:
user $
nsenter --target 12345 --setuid 0 --setgid 0 --user
A command can be specified with nsenter, but if one is not specified, it will start a shell specified by ${SHELL}.
See also
- Cgroups — allow securely managing the system resource usage of processes
External resources
- namespaces(7) - man page for an overview of Linux namespaces
- Wikipedia article on Linux namespaces