chiark / gitweb /
nspawn: mount a new /proc instance in the container so that we don't see the hosts...
[elogind.git] / src / nspawn.c
index f8a190097ae1d0f1433a88833988f2a5b4837d71..8d7e0d03a973304662d8fbf757c7dae27356248f 100644 (file)
@@ -36,6 +36,7 @@
 #include <sys/epoll.h>
 #include <termios.h>
 #include <sys/signalfd.h>
+#include <grp.h>
 
 #include "log.h"
 #include "util.h"
 #include "strv.h"
 
 static char *arg_directory = NULL;
+static char *arg_user = NULL;
 
 static int help(void) {
 
         printf("%s [OPTIONS...] [PATH] [ARGUMENTS...]\n\n"
                "Spawn a minimal namespace container for debugging, testing and building.\n\n"
                "  -h --help            Show this help\n"
-               "  -D --directory=NAME  Root directory for the container\n",
+               "  -D --directory=NAME  Root directory for the container\n"
+               "  -u --user=USER       Run the command under specified user or uid\n",
                program_invocation_short_name);
 
         return 0;
@@ -62,6 +65,7 @@ static int parse_argv(int argc, char *argv[]) {
         static const struct option options[] = {
                 { "help",      no_argument,       NULL, 'h' },
                 { "directory", required_argument, NULL, 'D' },
+                { "user",      optional_argument, NULL, 'u' },
                 { NULL,        0,                 NULL, 0   }
         };
 
@@ -70,7 +74,7 @@ static int parse_argv(int argc, char *argv[]) {
         assert(argc >= 0);
         assert(argv);
 
-        while ((c = getopt_long(argc, argv, "+hD:", options, NULL)) >= 0) {
+        while ((c = getopt_long(argc, argv, "+hD:u:", options, NULL)) >= 0) {
 
                 switch (c) {
 
@@ -87,6 +91,15 @@ static int parse_argv(int argc, char *argv[]) {
 
                         break;
 
+                case 'u':
+                        free(arg_user);
+                        if (!(arg_user = strdup(optarg))) {
+                                log_error("Failed to duplicate user name.");
+                                return -ENOMEM;
+                        }
+
+                        break;
+
                 case '?':
                         return -EINVAL;
 
@@ -111,23 +124,25 @@ static int mount_all(const char *dest) {
         } MountPoint;
 
         static const MountPoint mount_table[] = {
-                { "proc",      "/proc",     "proc",      NULL,        MS_NOSUID|MS_NOEXEC|MS_NODEV, true },
-                { "/proc/sys", "/proc/sys", "bind",      NULL,        MS_BIND, true },                      /* Bind mount first */
-                { "/proc/sys", "/proc/sys", "bind",      NULL,        MS_BIND|MS_RDONLY|MS_REMOUNT, true }, /* Then, make it r/o */
-                { "sysfs",     "/sys",      "sysfs",     NULL,        MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_RDONLY, true },
-                { "tmpfs",     "/dev",      "tmpfs",     "mode=755",  MS_NOSUID, true },
-                { "/dev/pts",  "/dev/pts",  "bind",      NULL,        MS_BIND, true },
-                { "tmpfs",     "/dev/.run", "tmpfs",     "mode=755",  MS_NOSUID|MS_NOEXEC|MS_NODEV, true },
+                { "proc",      "/proc",     "proc",  NULL,       MS_NOSUID|MS_NOEXEC|MS_NODEV, true  },
+                { "/proc/sys", "/proc/sys", "bind",  NULL,       MS_BIND, true                       },   /* Bind mount first */
+                { "/proc/sys", "/proc/sys", "bind",  NULL,       MS_BIND|MS_RDONLY|MS_REMOUNT, true  },   /* Then, make it r/o */
+                { "/sys",      "/sys",      "bind",  NULL,       MS_BIND,                      true  },   /* Bind mount first */
+                { "/sys",      "/sys",      "bind",  NULL,       MS_BIND|MS_RDONLY|MS_REMOUNT, true  },   /* Then, make it r/o */
+                { "tmpfs",     "/dev",      "tmpfs", "mode=755", MS_NOSUID,                    true  },
+                { "/dev/pts",  "/dev/pts",  "bind",  NULL,       MS_BIND,                      true  },
+                { "tmpfs",     "/run",      "tmpfs", "mode=755", MS_NOSUID|MS_NODEV,           true  },
 #ifdef HAVE_SELINUX
-                { "selinux",   "/selinux",  "selinuxfs", NULL,        MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_RDONLY, false },
+                { "/selinux",  "/selinux",  "bind",  NULL,       MS_BIND,                      false },  /* Bind mount first */
+                { "/selinux",  "/selinux",  "bind",  NULL,       MS_BIND|MS_RDONLY|MS_REMOUNT, false },  /* Then, make it r/o */
 #endif
         };
 
         unsigned k;
         int r = 0;
+        char *where;
 
         for (k = 0; k < ELEMENTSOF(mount_table); k++) {
-                char *where;
                 int t;
 
                 if (asprintf(&where, "%s/%s", dest, mount_table[k].where) < 0) {
@@ -167,6 +182,13 @@ static int mount_all(const char *dest) {
                 free(where);
         }
 
+        /* Fix the timezone, if possible */
+        if (asprintf(&where, "%s/%s", dest, "/etc/localtime") >= 0) {
+                mount("/etc/localtime", where, "bind", MS_BIND, NULL);
+                mount("/etc/localtime", where, "bind", MS_BIND|MS_REMOUNT|MS_RDONLY, NULL);
+                free(where);
+        }
+
         return r;
 }
 
@@ -325,7 +347,7 @@ static int drop_capabilities(void) {
 
         unsigned long l;
 
-        for (l = 0; l <= MAX(63LU, (unsigned long) CAP_LAST_CAP); l ++) {
+        for (l = 0; l <= MAX(63LU, (unsigned long) CAP_LAST_CAP); l++) {
                 unsigned i;
 
                 for (i = 0; i < ELEMENTSOF(retain); i++)
@@ -340,7 +362,7 @@ static int drop_capabilities(void) {
                         /* If this capability is not known, EINVAL
                          * will be returned, let's ignore this. */
                         if (errno == EINVAL)
-                                continue;
+                                break;
 
                         log_error("PR_CAPBSET_DROP failed: %m");
                         return -errno;
@@ -367,11 +389,11 @@ static int is_os_tree(const char *path) {
 #define BUFFER_SIZE 1024
 
 static int process_pty(int master, sigset_t *mask) {
+
         char in_buffer[BUFFER_SIZE], out_buffer[BUFFER_SIZE];
         size_t in_buffer_full = 0, out_buffer_full = 0;
         struct epoll_event stdin_ev, stdout_ev, master_ev, signal_ev;
         bool stdin_readable = false, stdout_writable = false, master_readable = false, master_writable = false;
-        bool stdin_rhup = false, stdout_whup = false, master_rhup = false, master_whup = false;
         int ep = -1, signal_fd = -1, r;
 
         fd_nonblock(STDIN_FILENO, 1);
@@ -415,7 +437,7 @@ static int process_pty(int master, sigset_t *mask) {
                 goto finish;
         }
 
-        do {
+        for (;;) {
                 struct epoll_event ev[16];
                 ssize_t k;
                 int i, nfds;
@@ -435,30 +457,20 @@ static int process_pty(int master, sigset_t *mask) {
                 for (i = 0; i < nfds; i++) {
                         if (ev[i].data.fd == STDIN_FILENO) {
 
-                                if (!stdin_rhup && (ev[i].events & (EPOLLHUP|EPOLLIN)))
+                                if (ev[i].events & (EPOLLIN|EPOLLHUP))
                                         stdin_readable = true;
 
                         } else if (ev[i].data.fd == STDOUT_FILENO) {
 
-                                if (ev[i].events & EPOLLHUP) {
-                                        stdout_writable = false;
-                                        stdout_whup = true;
-                                }
-
-                                if (!stdout_whup && (ev[i].events & EPOLLOUT))
+                                if (ev[i].events & (EPOLLOUT|EPOLLHUP))
                                         stdout_writable = true;
 
                         } else if (ev[i].data.fd == master) {
 
-                                /* We don't connect EPOLLHUP to
-                                 * master_whup here, since EPOLLHUP
-                                 * can happen when noone has opened
-                                 * the other side */
-
-                                if (!master_rhup && (ev[i].events & (EPOLLHUP|EPOLLIN)))
+                                if (ev[i].events & (EPOLLIN|EPOLLHUP))
                                         master_readable = true;
 
-                                if (!master_whup && (ev[i].events & EPOLLOUT))
+                                if (ev[i].events & (EPOLLOUT|EPOLLHUP))
                                         master_writable = true;
 
                         } else if (ev[i].data.fd == signal_fd) {
@@ -468,11 +480,13 @@ static int process_pty(int master, sigset_t *mask) {
                                 if ((n = read(signal_fd, &sfsi, sizeof(sfsi))) != sizeof(sfsi)) {
 
                                         if (n >= 0) {
+                                                log_error("Failed to read from signalfd: invalid block size");
                                                 r = -EIO;
                                                 goto finish;
                                         }
 
                                         if (errno != EINTR && errno != EAGAIN) {
+                                                log_error("Failed to read from signalfd: %m");
                                                 r = -errno;
                                                 goto finish;
                                         }
@@ -482,11 +496,10 @@ static int process_pty(int master, sigset_t *mask) {
                                                 struct winsize ws;
 
                                                 /* The window size changed, let's forward that. */
-
                                                 if (ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) >= 0)
                                                         ioctl(master, TIOCSWINSZ, &ws);
                                         } else {
-                                                r = -EINTR;
+                                                r = 0;
                                                 goto finish;
                                         }
                                 }
@@ -502,35 +515,26 @@ static int process_pty(int master, sigset_t *mask) {
 
                                 if ((k = read(STDIN_FILENO, in_buffer + in_buffer_full, BUFFER_SIZE - in_buffer_full)) < 0) {
 
-                                        if (errno == EAGAIN)
+                                        if (errno == EAGAIN || errno == EPIPE || errno == ECONNRESET || errno == EIO)
                                                 stdin_readable = false;
-                                        else if (errno == EPIPE || errno == ECONNRESET || errno == EIO)
-                                                k = 0;
                                         else {
                                                 log_error("read(): %m");
+                                                r = -errno;
                                                 goto finish;
                                         }
                                 } else
                                         in_buffer_full += (size_t) k;
-
-                                if (k == 0) {
-                                        stdin_rhup = true;
-                                        stdin_readable = false;
-                                        shutdown(STDIN_FILENO, SHUT_RD);
-                                }
                         }
 
                         if (master_writable && in_buffer_full > 0) {
 
                                 if ((k = write(master, in_buffer, in_buffer_full)) < 0) {
 
-                                        if (errno == EAGAIN)
+                                        if (errno == EAGAIN || errno == EPIPE || errno == ECONNRESET || errno == EIO)
                                                 master_writable = false;
-                                        else if (errno == EPIPE || errno == ECONNRESET || errno == EIO) {
-                                                master_whup = true;
-                                                master_writable = false;
-                                        } else {
+                                        else {
                                                 log_error("write(): %m");
+                                                r = -errno;
                                                 goto finish;
                                         }
 
@@ -545,34 +549,26 @@ static int process_pty(int master, sigset_t *mask) {
 
                                 if ((k = read(master, out_buffer + out_buffer_full, BUFFER_SIZE - out_buffer_full)) < 0) {
 
-                                        if (errno == EAGAIN)
+                                        if (errno == EAGAIN || errno == EPIPE || errno == ECONNRESET || errno == EIO)
                                                 master_readable = false;
-                                        else if (errno == EPIPE || errno == ECONNRESET || errno == EIO)
-                                                k = 0;
                                         else {
                                                 log_error("read(): %m");
+                                                r = -errno;
                                                 goto finish;
                                         }
                                 }  else
                                         out_buffer_full += (size_t) k;
-
-                                if (k == 0) {
-                                        master_rhup = true;
-                                        master_readable = false;
-                                }
                         }
 
                         if (stdout_writable && out_buffer_full > 0) {
 
                                 if ((k = write(STDOUT_FILENO, out_buffer, out_buffer_full)) < 0) {
 
-                                        if (errno == EAGAIN)
-                                                stdout_writable = false;
-                                        else if (errno == EPIPE || errno == ECONNRESET || errno == EIO) {
-                                                stdout_whup = true;
+                                        if (errno == EAGAIN || errno == EPIPE || errno == ECONNRESET || errno == EIO)
                                                 stdout_writable = false;
-                                        else {
+                                        else {
                                                 log_error("write(): %m");
+                                                r = -errno;
                                                 goto finish;
                                         }
 
@@ -583,19 +579,7 @@ static int process_pty(int master, sigset_t *mask) {
                                 }
                         }
                 }
-
-                if (stdin_rhup && in_buffer_full <= 0 && !master_whup) {
-                        master_whup = true;
-                        master_writable = false;
-                }
-
-                if (master_rhup && out_buffer_full <= 0 && !stdout_whup) {
-                        stdout_whup = true;
-                        stdout_writable = false;
-                        shutdown(STDOUT_FILENO, SHUT_WR);
-                }
-
-        } while (!stdout_whup || !master_whup);
+        }
 
 finish:
         if (ep >= 0)
@@ -724,14 +708,19 @@ int main(int argc, char *argv[]) {
                 /* child */
 
                 const char *hn;
+                const char *home = NULL;
+                uid_t uid = (uid_t) -1;
+                gid_t gid = (gid_t) -1;
                 const char *envp[] = {
-                        "HOME=/root",
                         "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
-                        NULL,
+                        NULL, /* TERM */
+                        NULL, /* HOME */
+                        NULL, /* USER */
+                        NULL, /* LOGNAME */
                         NULL
                 };
 
-                envp[2] = strv_find_prefix(environ, "TERM=");
+                envp[1] = strv_find_prefix(environ, "TERM=");
 
                 close_nointr_nofail(master);
 
@@ -752,6 +741,10 @@ int main(int argc, char *argv[]) {
                 if (prctl(PR_SET_PDEATHSIG, SIGKILL) < 0)
                         goto child_fail;
 
+                /* Mark / as private, in case somebody marked it shared */
+                if (mount(NULL, "/", NULL, MS_PRIVATE|MS_REC, NULL) < 0)
+                        goto child_fail;
+
                 if (mount_all(arg_directory) < 0)
                         goto child_fail;
 
@@ -788,13 +781,53 @@ int main(int argc, char *argv[]) {
                 if (drop_capabilities() < 0)
                         goto child_fail;
 
+                if (arg_user) {
+
+                        if (get_user_creds((const char**)&arg_user, &uid, &gid, &home) < 0) {
+                                log_error("get_user_creds() failed: %m");
+                                goto child_fail;
+                        }
+
+                        if (mkdir_parents(home, 0775) < 0) {
+                                log_error("mkdir_parents() failed: %m");
+                                goto child_fail;
+                        }
+
+                        if (safe_mkdir(home, 0775, uid, gid) < 0) {
+                                log_error("safe_mkdir() failed: %m");
+                                goto child_fail;
+                        }
+
+                        if (initgroups((const char*)arg_user, gid) < 0) {
+                                log_error("initgroups() failed: %m");
+                                goto child_fail;
+                        }
+
+                        if (setresgid(gid, gid, gid) < 0) {
+                                log_error("setregid() failed: %m");
+                                goto child_fail;
+                        }
+
+                        if (setresuid(uid, uid, uid) < 0) {
+                                log_error("setreuid() failed: %m");
+                                goto child_fail;
+                        }
+                }
+
+                if ((asprintf((char**)(envp + 2), "HOME=%s", home? home: "/root") < 0) ||
+                    (asprintf((char**)(envp + 3), "USER=%s", arg_user? arg_user : "root") < 0) ||
+                    (asprintf((char**)(envp + 4), "LOGNAME=%s", arg_user? arg_user : "root") < 0)) {
+                    log_error("Out of memory");
+                    goto child_fail;
+                }
+
                 if ((hn = file_name_from_path(arg_directory)))
                         sethostname(hn, strlen(hn));
 
                 if (argc > optind)
                         execvpe(argv[optind], argv + optind, (char**) envp);
                 else {
-                        chdir("/root");
+                        chdir(home ? home : "/root");
                         execle("/bin/bash", "-bash", NULL, (char**) envp);
                 }