Path: blob/master/tools/testing/selftests/filesystems/nsfs/owner.c
26302 views
// SPDX-License-Identifier: GPL-2.01#define _GNU_SOURCE2#include <sched.h>3#include <unistd.h>4#include <stdio.h>5#include <stdlib.h>6#include <signal.h>7#include <errno.h>8#include <sys/types.h>9#include <sys/stat.h>10#include <fcntl.h>11#include <sys/ioctl.h>12#include <sys/prctl.h>13#include <sys/wait.h>1415#define NSIO 0xb716#define NS_GET_USERNS _IO(NSIO, 0x1)1718#define pr_err(fmt, ...) \19({ \20fprintf(stderr, "%s:%d:" fmt ": %m\n", \21__func__, __LINE__, ##__VA_ARGS__); \221; \23})2425int main(int argc, char *argvp[])26{27int pfd[2], ns, uns, init_uns;28struct stat st1, st2;29char path[128];30pid_t pid;31char c;3233if (pipe(pfd))34return 1;3536pid = fork();37if (pid < 0)38return pr_err("fork");39if (pid == 0) {40prctl(PR_SET_PDEATHSIG, SIGKILL);41if (unshare(CLONE_NEWUTS | CLONE_NEWUSER))42return pr_err("unshare");43close(pfd[0]);44close(pfd[1]);45while (1)46sleep(1);47return 0;48}49close(pfd[1]);50if (read(pfd[0], &c, 1) != 0)51return pr_err("Unable to read from pipe");52close(pfd[0]);5354snprintf(path, sizeof(path), "/proc/%d/ns/uts", pid);55ns = open(path, O_RDONLY);56if (ns < 0)57return pr_err("Unable to open %s", path);5859uns = ioctl(ns, NS_GET_USERNS);60if (uns < 0)61return pr_err("Unable to get an owning user namespace");6263if (fstat(uns, &st1))64return pr_err("fstat");6566snprintf(path, sizeof(path), "/proc/%d/ns/user", pid);67if (stat(path, &st2))68return pr_err("stat");6970if (st1.st_ino != st2.st_ino)71return pr_err("NS_GET_USERNS returned a wrong namespace");7273init_uns = ioctl(uns, NS_GET_USERNS);74if (uns < 0)75return pr_err("Unable to get an owning user namespace");7677if (ioctl(init_uns, NS_GET_USERNS) >= 0 || errno != EPERM)78return pr_err("Don't get EPERM");7980if (unshare(CLONE_NEWUSER))81return pr_err("unshare");8283if (ioctl(ns, NS_GET_USERNS) >= 0 || errno != EPERM)84return pr_err("Don't get EPERM");85if (ioctl(init_uns, NS_GET_USERNS) >= 0 || errno != EPERM)86return pr_err("Don't get EPERM");8788kill(pid, SIGKILL);89wait(NULL);90return 0;91}929394