bwrap

来自百合仙子's Wiki
跳转到导航 跳转到搜索


让文件系统只读

bwrap --unshare-all --die-with-parent --ro-bind / / --dev /dev --proc /proc --tmpfs /tmp zsh

尽可能隔离

bwrap --unshare-all --die-with-parent --ro-bind / / --tmpfs /sys --tmpfs /home --tmpfs /tmp --tmpfs /run --proc /proc --dev /dev /bin/bash

允许联网:

bwrap --unshare-all --share-net --die-with-parent --ro-bind / / --tmpfs /sys --tmpfs /home --tmpfs /tmp --tmpfs /run --proc /proc --dev /dev /bin/bash

运行 GUI 程序

WPS Office

bwrap --unshare-all --die-with-parent --ro-bind / / --tmpfs /sys --tmpfs /home --tmpfs /tmp --tmpfs /var/tmp --tmpfs /run --proc /proc --dev /dev --ro-bind ~/.fonts ~/.fonts --ro-bind ~/.config/fontconfig ~/.config/fontconfig --bind ~/.cache/fontconfig ~/.cache/fontconfig --ro-bind ~/.Xauthority ~/.Xauthority --ro-bind /tmp/.X11-unix /tmp/.X11-unix --ro-bind /run/user/$UID/bus /run/user/$UID/bus bash

要支持 OpenGL 程序(如火狐的 WebRender),需要 --ro-bind /dev/dri /dev/dri 并去掉 --tmpfs /sys

运行 Debian chroot

建立

先使用 root 用户创建好 chroot:

debootstrap stable rootfs-debian http://deb.debian.org/debian/

并分配好 subuid 和 subgid。

清空 chroot 中的 /run 和 /dev 目录。将整个目录树移到目标用户,并 chown 到目标 subuid。

通过 setfacl 为需要使用的 subuid 授权:

# root
setfacl -m u:100000:x ~
# _apt
setfacl -m u:100100:x ~
setfacl -m u:100100:rx rootfs-debian
# 第一个普通用户
setfacl -m u:101000:x ~
setfacl -m u:101000:rx rootfs-debian

运行

进入该 chroot 工作的脚本:

#!/bin/bash -e

user="$(id -un)"
group="$(id -gn)"

# Create a new user namespace in the background with a dummy process just to
# keep it alive. Cannot use --map-auto here.
unshare -U sh -c "sleep 30" &
child_pid=$!

# Set {uid,gid}_map in new user namespace to max allowed range.
# Need to have appropriate entries for user in /etc/subuid and /etc/subgid.
# shellcheck disable=SC2046
newuidmap $child_pid 0 $(grep "^${user}:" /etc/subuid | cut -d : -f 2- | tr : ' ')
# shellcheck disable=SC2046
newgidmap $child_pid 0 $(grep "^${group}:" /etc/subgid | cut -d : -f 2- | tr : ' ')

# Tell Bubblewrap to use our user namespace through fd 5.
5< /proc/$child_pid/ns/user bwrap \
  --userns 5 \
  --cap-add ALL \
  --uid 0 \
  --gid 0 \
  --unshare-ipc --unshare-pid --unshare-uts --unshare-cgroup --share-net \
  --die-with-parent --bind rootfs-debian / --tmpfs /sys --tmpfs /tmp --tmpfs /run --proc /proc --dev /dev \
  -- \
  /bin/bash -l

也可以使用 unshare 命令进入该 chroot(注意:未挂载运行时目录):

unshare --map-auto -S 0 -G 0 -R rootfs-debian /bin/bash -l

问题处理

在 systemd-nspawn 下无法挂载 proc

报错如下:

bwrap: Can't mount proc on /newroot/proc: Operation not permitted

解决方法是在 nspawn 里、bwrap 外找个地方挂载 proc:[1]

sudo mkdir /run/proc
sudo mount -t proc proc /run/proc

参见

外部链接

参考资料