最後更新: 2020-01-29
介紹
unshare - run program with some namespaces unshared from parent
Usage
unshare [options] program [arguments]
Example
# Establish a user namespace as an unprivileged user with a root user within it.
unshare --map-root-user --user sh -c whoami
root
unshare --user sh -c whoami
nobody
# Establish a PID namespace, ensure we're PID 1 in it against newly mounted procfs instance.
unshare --user --fork --pid --mount-proc readlink /proc/self
1
OPTIONS
-m, --mount # mount namespace
--mount-proc # Just before running the program, mount the proc filesystem at mountpoint "/proc"
# (implies creating a new mount namespace)
# 使用 "--mount-proc" 時需要加上 "-U -p -f" unshare -U -p -f --mount-proc readlink /proc/self 1
-U, --user # user namespace
-r, --map-root-user # Run the program only after the current effective user and group IDs
# have been mapped to the superuser UID and GID in the newly created user namespace.
# This option implies --setgroups=deny
-p, --pid
-f, --fork # Fork the specified program as a child process of unshare rather than running it directly.
# creating a new pid namespace
# 沒有 --fork tim 24223 0.0 0.0 7288 696 pts/12 S+ 22:53 0:00 sleep 30
# 有 --fork tim 24212 0.0 0.0 7276 652 pts/12 S+ 22:53 0:00 unshare -U --fork sleep 30 tim 24213 0.0 0.0 7288 668 pts/12 S+ 22:53 0:00 sleep 30
-u, --uts[=file]
-n, --net
--setgroups allow|deny # callable with CAP_SETGID and CAP_SETGID in a user namespace
NS Lab
unshare -r -p -f --mount-proc /bin/bash
# 在新的 NS 內
id
uid=0(root) gid=0(root) groups=0(root),65534(nogroup)
cat /proc/self/uid_map
0 1003 1
grep -e Gid -e Uid /proc/1/status
Uid: 0 0 0 0 Gid: 0 0 0 0
# NS 外
grep -e Gid -e Uid /proc/new_ns_pid/status
Uid: 1003 1003 1003 1003 Gid: 1003 1003 1003 1003