我有一个小程序,尝试在取消共享后创建一个假终端.输出为:
uid before unshare:5000 uid after unshare:0 Grant pt Error: : Permission denied
代码:
#define _GNU_SOURCE #include <sys/mount.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <fcntl.h> #include <errno.h> #include <sched.h> void set_uid_map(pid_t pid,int inside_id,int outside_id,int length) { char path[256]; sprintf(path,"/proc/%d/uid_map",getpid()); FILE* uid_map = fopen(path,"w"); fprintf(uid_map,"%d %d %d",inside_id,outside_id,length); fclose(uid_map); } void set_gid_map(pid_t pid,"/proc/%d/gid_map",getpid()); FILE* gid_map = fopen(path,"w"); fprintf(gid_map,length); fclose(gid_map); } int main(void) { int master; int flag = 0; flag |= CLONE_NEWUSER; flag |= CLONE_NEWNS; flag |= CLONE_NEWIPC; flag |= CLONE_NEWNET; flag |= CLONE_NEWUTS; flag |= CLONE_NEWPID; printf("uid before unshare:%d \n",(int) getuid()); unshare(flag); set_uid_map(getpid(),5000,1); set_gid_map(getpid(),1); printf("uid after unshare:%d \n",(int) getuid()); if ( ( master = posix_openpt(O_RDWR | O_NOCTTY) ) < 0) perror("Openpt Error: "); if ( grantpt(master) < 0 ) perror("Grant pt Error: "); unlockpt(master); return 0; } // main
解决方法
既然我有同样的问题,我也研究了这个.这是我的发现:
grantpt(3)尝试确保从属伪终端将其组设置为特殊的tty组(或编译glibc时的任何TTY_GROUP):
static int tty_gid = -1; if (__glibc_unlikely (tty_gid == -1)) { char *grtmpbuf; struct group grbuf; size_t grbuflen = __sysconf (_SC_GETGR_R_SIZE_MAX); struct group *p; /* Get the group ID of the special `tty' group. */ if (grbuflen == (size_t) -1L) /* `sysconf' does not support _SC_GETGR_R_SIZE_MAX. Try a moderate value. */ grbuflen = 1024; grtmpbuf = (char *) __alloca (grbuflen); __getgrnam_r (TTY_GROUP,&grbuf,grtmpbuf,grbuflen,&p); if (p != NULL) tty_gid = p->gr_gid; } gid_t gid = tty_gid == -1 ? __getgid () : tty_gid; /* Make sure the group of the device is that special group. */ if (st.st_gid != gid) { if (__chown (buf,uid,gid) < 0) goto helper; }
在我的系统上,tty组是5.但是,该组没有映射到您的用户名空间,并且chown(2)失败,因为GID 5不存在. glibc然后落回执行pt_chown帮助器,这也是失败的.我没有看到为什么它失败的细节,但我认为这是因为它是setuid的人,除非你将root用户映射到您的用户名称空间.这里是显示失败操作的strace输出:
[pid 30] chown("/dev/pts/36",1000,5) = -1 EINVAL (Invalid argument)
>映射所需的组(即tty),如果打开用户命名空间的二进制文件中没有CAP_SYS_ADMIN,这可能是不可能的>使用subuid和subgids与newuidmap(1)和newgidmap(1),使这些组可用(这可能会工作,但我还没有测试).>进行更改,以避免chown(2)调用失败,例如通过使用安装命名空间并将/ etc / groups中的tty组的GID更改为用户的GID.>避免chown(2)调用,例如通过使st.st_gid!= gid检查false;这可以通过从目标装载命名空间的/ etc / groups中删除tty组来实现.当然这可能会导致其他问题.