我有一个小程序,试图在取消共享后创建一个伪终端。输出是:
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, int inside_id, int outside_id, int length) {
char path[256];
sprintf(path, "/proc/%d/gid_map", getpid());
FILE* gid_map = fopen(path, "w");
fprintf(gid_map, "%d %d %d", inside_id, outside_id, 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(), 0, 5000, 1);
set_gid_map(getpid(), 0, 5000, 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
如果我删除flag |= CLONE_NEWUSER;
,则不会报告错误。你能帮忙解释一下为什么会这样吗?提前谢谢!
答案 0 :(得分:5)
由于我有同样的问题,我也研究了这个问题。以下是我的发现:
grantpt(3)
尝试确保slave伪终端将其组设置为特殊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
帮助程序,它也失败了。我没有查看它失败原因的详细信息,但我认为它是因为除非您将root用户映射到用户命名空间,否则它是setuid nobody。这里的strace输出显示失败的操作:
[pid 30] chown("/dev/pts/36", 1000, 5) = -1 EINVAL (Invalid argument)
为您提供了几种解决此问题的方法:
tty
),这在打开用户名称空间的二进制文件中没有CAP_SYS_ADMIN
时可能无法实现newuidmap(1)
和newgidmap(1)
一起使用以使这些组可用(这可能有用,但我还没有对其进行测试)。chown(2)
来电失败,例如使用mount命名空间并将tty
中/etc/groups
组的GID更改为用户的GID。chown(2)
来电,例如通过使st.st_gid != gid
检查为false;这应该可以通过从目标装载命名空间tty
中删除/etc/groups
组来实现。当然,这可能会导致其他问题。