From 011231af3bdfddc9ab82904b382336f0376efa7e Mon Sep 17 00:00:00 2001 From: Andrey Vagin Date: Mon, 20 Jul 2015 12:34:15 +0300 Subject: [PATCH] util: add ability to execute programs in a specified userns It's required for dumping tmpfs, where we use tar to save content. If we need to execute tar from a proper userns to get right uid-s and gid-s for files. Signed-off-by: Andrey Vagin Signed-off-by: Pavel Emelyanov --- include/util.h | 2 ++ util.c | 16 ++++++++++++++++ 2 files changed, 18 insertions(+) diff --git a/include/util.h b/include/util.h index 9470a894f..7e70a71a5 100644 --- a/include/util.h +++ b/include/util.h @@ -170,6 +170,8 @@ extern void *shmalloc(size_t bytes); extern void shfree_last(void *ptr); extern int cr_system(int in, int out, int err, char *cmd, char *const argv[]); +extern int cr_system_userns(int in, int out, int err, char *cmd, + char *const argv[], int userns_pid); extern int cr_daemon(int nochdir, int noclose, int *keep_fd, int close_fd); extern int is_root_user(void); diff --git a/util.c b/util.c index 7f2887e12..b916eca3c 100644 --- a/util.c +++ b/util.c @@ -37,6 +37,7 @@ #include "image.h" #include "vma.h" #include "mem.h" +#include "namespaces.h" #include "cr_options.h" #include "servicefd.h" @@ -506,6 +507,12 @@ void shfree_last(void *ptr) * If "out" or "err" are negative, a log file descriptor will be used. */ int cr_system(int in, int out, int err, char *cmd, char *const argv[]) +{ + return cr_system_userns(in, out, err, cmd, argv, -1); +} + +int cr_system_userns(int in, int out, int err, char *cmd, + char *const argv[], int userns_pid) { sigset_t blockmask, oldmask; int ret = -1, status; @@ -523,6 +530,15 @@ int cr_system(int in, int out, int err, char *cmd, char *const argv[]) pr_perror("fork() failed"); goto out; } else if (pid == 0) { + if (userns_pid > 0) { + if (switch_ns(userns_pid, &user_ns_desc, NULL)) + goto out_chld; + if (setuid(0) || setgid(0)) { + pr_perror("Unable to set uid or gid"); + goto out_chld; + } + } + if (out < 0) out = log_get_fd(); if (err < 0)