linux – unshare –map-root-user在安装后切换到原始uid / username教程
我正在使用unshare来创建每个进程挂载,这完全正常
unshare -m --map-root-user
但是,在创建了我的bind-mounts之后
mount --bind src dst
我想将UID更改为我的原始用户,以便whoami(和其他人)像echo $USER一样回应我的用户名.
我已经尝试过了答案
Simulate chroot with unshare
但是,在chroot /之后做su – user1,我得到了
su: Authentication failure
(Ignored)
setgid: Invalid argument
我在Ubuntu 18.04 Beta,Debian stretch,openSUSE-Leap-42.3上进行了测试.
这都一样.我猜这个内容已经发生了变化,因为这个答案是有效的.
什么是工作和正确的方法(当然没有真正的根)?
解决方法:
unshare(1)
命令无法执行此操作:
-r, –map-root-user
[…] As a mere convenience feature, it does not support more sophisticated use cases, such as mapping multiple ranges
of UIDs and GIDs.
补充组(如果有的话)(视频,……)无论如何都会丢失(或映射到nogroup).
通过再次更改为第二个新用户命名空间,可以恢复映射.这需要一个自定义程序,因为unshare(1)不会这样做.这是一个非常简约的C程序作为概念证明(仅限一个用户:uid / gid 1000/1000,零故障检查).我们称之为revertuid.c:
#define _GNU_SOURCE
#include <sched.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
int fd;
unshare(CLONE_NEWUSER);
fd=open("/proc/self/setgroups",O_WRONLY);
write(fd,"deny",4);
close(fd);
fd=open("/proc/self/uid_map",O_WRONLY);
write(fd,"1000 0 1",8);
close(fd);
fd=open("/proc/self/gid_map",O_WRONLY);
write(fd,"1000 0 1",8);
close(fd);
execvp(argv[1],argv+1);
}
它只是通过unshare -r -m完成映射的反向映射,这是不可避免的,能够成为root并使用mount,如下所示:
$strace unshare -r -m /bin/sleep 1 2>&1 |sed -n '/^unshare/,/^execve/p'
unshare(CLONE_NEWNS|CLONE_NEWUSER) = 0
open("/proc/self/setgroups", O_WRONLY) = 3
write(3, "deny", 4) = 4
close(3) = 0
open("/proc/self/uid_map", O_WRONLY) = 3
write(3, "0 1000 1", 8) = 8
close(3) = 0
open("/proc/self/gid_map", O_WRONLY) = 3
write(3, "0 1000 1", 8) = 8
close(3) = 0
execve("/bin/sleep", ["/bin/sleep", "1"], [/* 18 vars */]) = 0
所以这给了:
user@stretch-amd64:~$gcc -o revertuid revertuid.c
user@stretch-amd64:~$mkdir -p /tmp/src /tmp/dst
user@stretch-amd64:~$touch /tmp/src/file
user@stretch-amd64:~$ls /tmp/dst
user@stretch-amd64:~$id
uid=1000(user) gid=1000(user) groups=1000(user)
user@stretch-amd64:~$unshare -r -m
root@stretch-amd64:~# mount --bind /tmp/src /tmp/dst
root@stretch-amd64:~# ls /tmp/dst
file
root@stretch-amd64:~# exec ./revertuid bash
user@stretch-amd64:~$ls /tmp/dst
file
user@stretch-amd64:~$id
uid=1000(user) gid=1000(user) groups=1000(user)
或更短:
user@stretch-amd64:~$unshare -r -m sh -c 'mount --bind /tmp/src /tmp/dst; exec ./revertuid bash'
user@stretch-amd64:~$ls /tmp/dst
file
行为可能在内核3.19之后发生了变化,如user_namespaces(7)
所示:
The /proc/[pid]/setgroups file was added in Linux 3.19, but was
backported to many earlier stable kernel series, because it addresses
a security issue. The issue concerned files with permissions such as
“rwx—rwx”.