nspawn.c revision 849958d1ba3533c953fad46d4d41c0ec6e48316d
/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
/***
This file is part of systemd.
Copyright 2010 Lennart Poettering
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
systemd is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with systemd; If not, see <http://www.gnu.org/licenses/>.
***/
#include <signal.h>
#include <sched.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <sys/capability.h>
#include <getopt.h>
#include <termios.h>
#include <sys/signalfd.h>
#include <grp.h>
#include <sys/personality.h>
#ifdef HAVE_SELINUX
#endif
#ifdef HAVE_SECCOMP
#include <seccomp.h>
#endif
#ifdef HAVE_BLKID
#endif
#include "sd-daemon.h"
#include "sd-bus.h"
#include "sd-id128.h"
#include "sd-rtnl.h"
#include "log.h"
#include "util.h"
#include "mkdir.h"
#include "macro.h"
#include "audit.h"
#include "missing.h"
#include "cgroup-util.h"
#include "strv.h"
#include "path-util.h"
#include "loopback-setup.h"
#include "dev-setup.h"
#include "fdset.h"
#include "build.h"
#include "fileio.h"
#include "bus-util.h"
#include "bus-error.h"
#include "ptyfwd.h"
#include "bus-kernel.h"
#include "env-util.h"
#include "def.h"
#include "rtnl-util.h"
#include "udev-util.h"
#include "eventfd-util.h"
#include "blkid-util.h"
#include "gpt.h"
#include "siphash24.h"
#include "copy.h"
#ifdef HAVE_SECCOMP
#include "seccomp-util.h"
#endif
typedef enum ContainerStatus {
typedef enum LinkJournal {
} LinkJournal;
static char *arg_directory = NULL;
static sd_id128_t arg_uuid = {};
static char *arg_machine = NULL;
static const char *arg_selinux_context = NULL;
static const char *arg_selinux_apifs_context = NULL;
static bool arg_private_network = false;
static bool arg_read_only = false;
static bool arg_boot = false;
static uint64_t arg_retain =
(1ULL << CAP_CHOWN) |
(1ULL << CAP_DAC_OVERRIDE) |
(1ULL << CAP_DAC_READ_SEARCH) |
(1ULL << CAP_FOWNER) |
(1ULL << CAP_FSETID) |
(1ULL << CAP_IPC_OWNER) |
(1ULL << CAP_KILL) |
(1ULL << CAP_LEASE) |
(1ULL << CAP_LINUX_IMMUTABLE) |
(1ULL << CAP_NET_BIND_SERVICE) |
(1ULL << CAP_NET_BROADCAST) |
(1ULL << CAP_NET_RAW) |
(1ULL << CAP_SETGID) |
(1ULL << CAP_SETFCAP) |
(1ULL << CAP_SETPCAP) |
(1ULL << CAP_SETUID) |
(1ULL << CAP_SYS_ADMIN) |
(1ULL << CAP_SYS_CHROOT) |
(1ULL << CAP_SYS_NICE) |
(1ULL << CAP_SYS_PTRACE) |
(1ULL << CAP_SYS_TTY_CONFIG) |
(1ULL << CAP_SYS_RESOURCE) |
(1ULL << CAP_SYS_BOOT) |
(1ULL << CAP_AUDIT_WRITE) |
(1ULL << CAP_AUDIT_CONTROL) |
(1ULL << CAP_MKNOD);
static char **arg_bind_ro = NULL;
static char **arg_setenv = NULL;
static bool arg_quiet = false;
static bool arg_share_system = false;
static bool arg_register = true;
static bool arg_keep_unit = false;
static char **arg_network_interfaces = NULL;
static char **arg_network_macvlan = NULL;
static bool arg_network_veth = false;
static const char *arg_network_bridge = NULL;
static unsigned long arg_personality = 0xffffffffLU;
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"
" --version Print version string\n"
" -q --quiet Do not show status information\n"
" -D --directory=PATH Root directory for the container\n"
" -i --image=PATH File system device or image for the container\n"
" -b --boot Boot up full system (i.e. invoke init)\n"
" -u --user=USER Run the command under specified user or uid\n"
" -M --machine=NAME Set the machine name for the container\n"
" --uuid=UUID Set a specific machine UUID for the container\n"
" -S --slice=SLICE Place the container in the specified slice\n"
" --private-network Disable network in container\n"
" --network-interface=INTERFACE\n"
" Assign an existing network interface to the\n"
" container\n"
" --network-macvlan=INTERFACE\n"
" Create a macvlan network interface based on an\n"
" existing network interface to the container\n"
" --network-veth Add a virtual ethernet connection between host\n"
" and container\n"
" --network-bridge=INTERFACE\n"
" Add a virtual ethernet connection between host\n"
" and container and add it to an existing bridge on\n"
" the host\n"
" -Z --selinux-context=SECLABEL\n"
" Set the SELinux security context to be used by\n"
" processes in the container\n"
" -L --selinux-apifs-context=SECLABEL\n"
" Set the SELinux security context to be used by\n"
" --capability=CAP In addition to the default, retain specified\n"
" capability\n"
" --drop-capability=CAP Drop the specified capability from the default set\n"
" --link-journal=MODE Link up guest journal, one of no, auto, guest, host\n"
" -j Equivalent to --link-journal=host\n"
" --read-only Mount the root directory read-only\n"
" --bind=PATH[:PATH] Bind mount a file or directory from the host into\n"
" the container\n"
" --bind-ro=PATH[:PATH] Similar, but creates a read-only bind mount\n"
" --setenv=NAME=VALUE Pass an environment variable to PID 1\n"
" --share-system Share system namespaces with host\n"
" --register=BOOLEAN Register container as machine\n"
" --keep-unit Do not register a scope for the machine, reuse\n"
" the service unit nspawn is running in\n",
return 0;
}
enum {
ARG_VERSION = 0x100,
};
{}
};
int c, r;
switch (c) {
case 'h':
return help();
case ARG_VERSION:
return 0;
case 'D':
if (!arg_directory) {
log_error("Invalid root directory: %m");
return -ENOMEM;
}
break;
case 'i':
break;
case 'u':
if (!arg_user)
return log_oom();
break;
case ARG_NETWORK_BRIDGE:
/* fall through */
case ARG_NETWORK_VETH:
arg_network_veth = true;
arg_private_network = true;
break;
case ARG_NETWORK_INTERFACE:
return log_oom();
arg_private_network = true;
break;
case ARG_NETWORK_MACVLAN:
return log_oom();
/* fall through */
case ARG_PRIVATE_NETWORK:
arg_private_network = true;
break;
case 'b':
arg_boot = true;
break;
case ARG_UUID:
if (r < 0) {
return r;
}
break;
case 'S':
break;
case 'M':
arg_machine = NULL;
} else {
if (!hostname_is_valid(optarg)) {
return -EINVAL;
}
if (!arg_machine)
return log_oom();
break;
}
case 'Z':
break;
case 'L':
break;
case ARG_READ_ONLY:
arg_read_only = true;
break;
case ARG_CAPABILITY:
case ARG_DROP_CAPABILITY: {
_cleanup_free_ char *t;
if (!t)
return log_oom();
if (streq(t, "all")) {
if (c == ARG_CAPABILITY)
else
} else {
if (cap_from_name(t, &cap) < 0) {
log_error("Failed to parse capability %s.", t);
return -EINVAL;
}
if (c == ARG_CAPABILITY)
else
}
}
break;
}
case 'j':
break;
case ARG_LINK_JOURNAL:
else {
return -EINVAL;
}
break;
case ARG_BIND:
case ARG_BIND_RO: {
char *e;
char ***x;
if (e) {
b = strdup(e + 1);
} else {
}
if (!a || !b)
return log_oom();
if (!path_is_absolute(a) || !path_is_absolute(b)) {
return -EINVAL;
}
r = strv_extend(x, a);
if (r < 0)
return log_oom();
r = strv_extend(x, b);
if (r < 0)
return log_oom();
break;
}
case ARG_SETENV: {
char **n;
if (!env_assignment_is_valid(optarg)) {
return -EINVAL;
}
if (!n)
return log_oom();
arg_setenv = n;
break;
}
case 'q':
arg_quiet = true;
break;
case ARG_SHARE_SYSTEM:
arg_share_system = true;
break;
case ARG_REGISTER:
r = parse_boolean(optarg);
if (r < 0) {
return r;
}
arg_register = r;
break;
case ARG_KEEP_UNIT:
arg_keep_unit = true;
break;
case ARG_PERSONALITY:
if (arg_personality == 0xffffffffLU) {
return -EINVAL;
}
break;
case '?':
return -EINVAL;
default:
assert_not_reached("Unhandled option");
}
}
if (arg_share_system)
arg_register = false;
if (arg_boot && arg_share_system) {
log_error("--boot and --share-system may not be combined.");
return -EINVAL;
}
log_error("--keep-unit may not be used when invoked from a user session.");
return -EINVAL;
}
if (arg_directory && arg_image) {
log_error("--directory= and --image= may not be combined.");
return -EINVAL;
}
return 1;
}
typedef struct MountPoint {
const char *what;
const char *where;
const char *type;
const char *options;
unsigned long flags;
bool fatal;
} MountPoint;
static const MountPoint mount_table[] = {
{ "devpts", "/dev/pts", "devpts","newinstance,ptmxmode=0666,mode=620,gid=" STRINGIFY(TTY_GID), MS_NOSUID|MS_NOEXEC, true },
#ifdef HAVE_SELINUX
{ NULL, "/sys/fs/selinux", NULL, NULL, MS_BIND|MS_RDONLY|MS_REMOUNT, false }, /* Then, make it r/o */
#endif
};
unsigned k;
int r = 0;
for (k = 0; k < ELEMENTSOF(mount_table); k++) {
#ifdef HAVE_SELINUX
#endif
const char *o;
int t;
if (!where)
return log_oom();
t = path_is_mount_point(where, true);
if (t < 0) {
if (r == 0)
r = t;
continue;
}
/* Skip this entry if it is not a remount. */
if (mount_table[k].what && t > 0)
continue;
#ifdef HAVE_SELINUX
if (arg_selinux_apifs_context &&
if (!options)
return log_oom();
o = options;
} else
#endif
o = mount_table[k].options;
mount_table[k].type,
mount_table[k].flags,
o) < 0 &&
mount_table[k].fatal) {
if (r == 0)
r = -errno;
}
}
return r;
}
char **x, **y;
STRV_FOREACH_PAIR(x, y, l) {
char *where;
int r;
log_error("Failed to stat %s: %m", *x);
return -errno;
}
if (r == 0) {
log_error("The file types of %s and %s do not match. Refusing bind mount",
*x, where);
return -EINVAL;
}
if (r < 0) {
return r;
}
} else {
log_error("Failed to bind mount %s: %m", *x);
return -errno;
}
/* Create the mount point, but be conservative -- refuse to create block
* and char devices. */
else {
log_error("Refusing to create mountpoint for file: %s", *x);
return -ENOTSUP;
}
return -errno;
}
if (ro) {
r = bind_remount_recursive(where, true);
if (r < 0) {
return r;
}
}
}
return 0;
}
static int setup_timezone(const char *dest) {
char *z, *y;
int r;
/* Fix the timezone, if possible */
r = readlink_malloc("/etc/localtime", &p);
if (r < 0) {
log_warning("/etc/localtime is not a symlink, not updating container timezone.");
return 0;
}
z = path_startswith(p, "../usr/share/zoneinfo/");
if (!z)
z = path_startswith(p, "/usr/share/zoneinfo/");
if (!z) {
log_warning("/etc/localtime does not point into /usr/share/zoneinfo/, not updating container timezone.");
return 0;
}
if (!where)
return log_oom();
r = readlink_malloc(where, &q);
if (r >= 0) {
y = path_startswith(q, "../usr/share/zoneinfo/");
if (!y)
y = path_startswith(q, "/usr/share/zoneinfo/");
/* Already pointing to the right place? Then do nothing .. */
if (y && streq(y, z))
return 0;
}
if (!check)
return log_oom();
log_warning("Timezone %s does not exist in container, not updating container timezone.", z);
return 0;
}
if (!what)
return log_oom();
log_error("Failed to correct timezone of container: %m");
return 0;
}
return 0;
}
static int setup_resolv_conf(const char *dest) {
if (arg_private_network)
return 0;
/* Fix resolv.conf, if possible */
if (!where)
return log_oom();
/* We don't really care for the results of this really. If it
* fails, it fails, but meh... */
return 0;
}
snprintf(s, 37,
"%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",
return s;
}
static int setup_boot_id(const char *dest) {
sd_id128_t rnd = {};
char as_uuid[37];
int r;
if (arg_share_system)
return 0;
/* Generate a new randomized boot ID, so that each boot-up of
* the container gets a new one */
return log_oom();
r = sd_id128_randomize(&rnd);
if (r < 0) {
return r;
}
if (r < 0) {
return r;
}
log_error("Failed to bind mount boot id: %m");
r = -errno;
log_warning("Failed to make boot id read-only: %m");
return r;
}
static int copy_devnodes(const char *dest) {
static const char devnodes[] =
"null\0"
"zero\0"
"full\0"
"random\0"
"urandom\0"
"tty\0";
const char *d;
int r = 0;
u = umask(0000);
NULSTR_FOREACH(d, devnodes) {
return log_oom();
return -errno;
}
return -EIO;
return -errno;
}
}
return r;
}
static int setup_ptmx(const char *dest) {
_cleanup_free_ char *p = NULL;
if (!p)
return log_oom();
return -errno;
}
return 0;
}
const char *to;
int r;
u = umask(0000);
return -errno;
}
if (r < 0) {
return r;
}
* ptys can only exist on pts file systems. To have something
* to bind mount things on we create a device node first, and
* allows us to create that freely, while we cannot create
* matter here, since we mount it over anyway). */
return -errno;
}
return -errno;
}
return 0;
}
int r, fd, k;
union {
} control = {};
.msg_control = &control,
.msg_controllen = sizeof(control),
};
assert(kmsg_socket >= 0);
u = umask(0000);
* that writing blocks when nothing is reading. In order to
* avoid any problems with containers deadlocking due to this
return log_oom();
return -errno;
}
if (r < 0) {
return r;
}
return -errno;
}
if (fd < 0) {
log_error("Failed to open fifo: %m");
return -errno;
}
/* Store away the fd in the socket, so that it stays open as
* long as we run the child */
safe_close(fd);
if (k < 0) {
log_error("Failed to send FIFO fd: %m");
return -errno;
}
return 0;
}
static int setup_hostname(void) {
if (arg_share_system)
return 0;
return -errno;
return 0;
}
static int setup_journal(const char *directory) {
char *id;
int r;
if (!p)
return log_oom();
r = read_one_line_file(p, &b);
return 0;
else if (r < 0) {
return r;
}
return 0;
/* Verify validity */
if (r < 0) {
return r;
}
r = sd_id128_get_machine(&this_id);
if (r < 0) {
return r;
}
"Host and machine ids are equal (%s): refusing to link journals", id);
if (arg_link_journal == LINK_AUTO)
return 0;
return
-EEXIST;
}
if (arg_link_journal == LINK_NO)
return 0;
free(p);
if (!p || !q)
return log_oom();
if (path_is_mount_point(p, false) > 0) {
if (arg_link_journal != LINK_AUTO) {
log_error("%s: already a mount point, refusing to use for journal", p);
return -EEXIST;
}
return 0;
}
if (path_is_mount_point(q, false) > 0) {
if (arg_link_journal != LINK_AUTO) {
log_error("%s: already a mount point, refusing to use for journal", q);
return -EEXIST;
}
return 0;
}
r = readlink_and_make_absolute(p, &d);
if (r >= 0) {
if ((arg_link_journal == LINK_GUEST ||
arg_link_journal == LINK_AUTO) &&
path_equal(d, q)) {
r = mkdir_p(q, 0755);
if (r < 0)
log_warning("failed to create directory %s: %m", q);
return 0;
}
if (unlink(p) < 0) {
log_error("Failed to remove symlink %s: %m", p);
return -errno;
}
} else if (r == -EINVAL) {
if (arg_link_journal == LINK_GUEST &&
rmdir(p) < 0) {
log_error("%s already exists and is neither a symlink nor a directory", p);
return r;
} else {
log_error("Failed to remove %s: %m", p);
return -errno;
}
}
} else if (r != -ENOENT) {
log_error("readlink(%s) failed: %m", p);
return r;
}
if (arg_link_journal == LINK_GUEST) {
if (symlink(q, p) < 0) {
log_error("Failed to symlink %s to %s: %m", q, p);
return -errno;
}
r = mkdir_p(q, 0755);
if (r < 0)
log_warning("failed to create directory %s: %m", q);
return 0;
}
if (arg_link_journal == LINK_HOST) {
r = mkdir_p(p, 0755);
if (r < 0) {
log_error("Failed to create %s: %m", p);
return r;
}
return 0;
if (dir_is_empty(q) == 0)
log_warning("%s is not empty, proceeding anyway.", q);
r = mkdir_p(q, 0755);
if (r < 0) {
log_error("Failed to create %s: %m", q);
return r;
}
log_error("Failed to bind mount journal from host into guest: %m");
return -errno;
}
return 0;
}
const char *p;
if (!path)
return 0;
if (mkdir(p, 0755) < 0) {
log_error("Failed to create kdbus path: %m");
return -errno;
}
log_error("Failed to mount kdbus domain path: %m");
return -errno;
}
return 0;
}
static int drop_capabilities(void) {
return capability_bounding_set_drop(~arg_retain, false);
}
int r;
if (!arg_register)
return 0;
r = sd_bus_default_system(&bus);
if (r < 0) {
return r;
}
if (arg_keep_unit) {
r = sd_bus_call_method(
bus,
"org.freedesktop.machine1",
"/org/freedesktop/machine1",
"org.freedesktop.machine1.Manager",
"RegisterMachine",
&error,
NULL,
"sayssus",
"nspawn",
"container",
} else {
bus,
&m,
"org.freedesktop.machine1",
"/org/freedesktop/machine1",
"org.freedesktop.machine1.Manager",
"CreateMachine");
if (r < 0) {
return r;
}
m,
"sayssus",
"nspawn",
"container",
if (r < 0) {
return r;
}
if (r < 0) {
return r;
}
if (r < 0) {
return r;
}
}
if (r < 0) {
return r;
}
/* Allow the container to
* access and create the API
* device nodes, so that
* PrivateDevices= in the
* container can work
* fine */
/* Allow the container
* access to ptys. However,
* do not permit the
* container to ever create
* these device nodes. */
"char-pts", "rw",
/* Allow the container
* access to all kdbus
* devices. Again, the
* container cannot create
* these nodes, only use
* them. We use a pretty
* open match here, so that
* the kernel API can still
* change. */
"char-kdbus", "rw",
"char-kdbus/*", "rw");
if (r < 0) {
return r;
}
r = sd_bus_message_close_container(m);
if (r < 0) {
return r;
}
}
if (r < 0) {
return r;
}
return 0;
}
const char *path;
int r;
if (!arg_register)
return 0;
r = sd_bus_default_system(&bus);
if (r < 0) {
return r;
}
r = sd_bus_call_method(
bus,
"org.freedesktop.machine1",
"/org/freedesktop/machine1",
"org.freedesktop.machine1.Manager",
"GetMachineByPID",
&error,
&reply,
"u",
if (r < 0) {
/* Note that the machine might already have been
* cleaned up automatically, hence don't consider it a
* failure if we cannot get the machine object. */
return 0;
}
if (r < 0)
return bus_log_parse_error(r);
r = sd_bus_call_method(
bus,
"org.freedesktop.machine1",
path,
"org.freedesktop.machine1.Machine",
"Terminate",
&error,
NULL,
NULL);
if (r < 0) {
return 0;
}
return 0;
}
static int reset_audit_loginuid(void) {
_cleanup_free_ char *p = NULL;
int r;
if (arg_share_system)
return 0;
r = read_one_line_file("/proc/self/loginuid", &p);
if (r == -ENOENT)
return 0;
if (r < 0) {
return r;
}
/* Already reset? */
if (streq(p, "4294967295"))
return 0;
if (r < 0) {
log_error("Failed to reset audit login UID. This probably means that your kernel is too\n"
"old and you have audit enabled. Note that the auditing subsystem is known to\n"
"be incompatible with containers on old kernels. Please make sure to upgrade\n"
"your kernel or to off auditing with 'audit=0' on the kernel command line before\n"
"using systemd-nspawn. Sleeping for 5s... (%s)\n", strerror(-r));
sleep(5);
}
return 0;
}
int r;
uint8_t *v;
l = strlen(arg_machine);
sz = sizeof(sd_id128_t) + l;
/* fetch some persistent data unique to the host */
r = sd_id128_get_machine((sd_id128_t*) v);
if (r < 0)
return r;
/* combine with some data unique (on this host) to this
* container instance */
/* Let's hash the host machine ID plus the container name. We
* use a fixed, but originally randomly created hash key here. */
/* see eth_random_addr in the kernel */
return 0;
}
struct ether_addr mac;
int r;
if (!arg_private_network)
return 0;
if (!arg_network_veth)
return 0;
/* Use two different interface name prefixes depending whether
* we are in bridge mode or not. */
if (arg_network_bridge)
else
if (r < 0) {
log_error("Failed to generate predictable MAC address for host0");
return r;
}
r = sd_rtnl_open(&rtnl, 0);
if (r < 0) {
return r;
}
if (r < 0) {
return r;
}
if (r < 0) {
return r;
}
if (r < 0) {
return r;
}
if (r < 0) {
return r;
}
if (r < 0) {
return r;
}
if (r < 0) {
return r;
}
if (r < 0) {
return r;
}
if (r < 0) {
return r;
}
r = sd_rtnl_message_close_container(m);
if (r < 0) {
return r;
}
r = sd_rtnl_message_close_container(m);
if (r < 0) {
return r;
}
r = sd_rtnl_message_close_container(m);
if (r < 0) {
return r;
}
if (r < 0) {
return r;
}
return 0;
}
static int setup_bridge(const char veth_name[]) {
int r, bridge;
if (!arg_private_network)
return 0;
if (!arg_network_veth)
return 0;
if (!arg_network_bridge)
return 0;
if (bridge <= 0) {
return -errno;
}
r = sd_rtnl_open(&rtnl, 0);
if (r < 0) {
return r;
}
if (r < 0) {
return r;
}
if (r < 0) {
return r;
}
if (r < 0) {
return r;
}
if (r < 0) {
return r;
}
if (r < 0) {
return r;
}
return 0;
}
int ifi;
if (ifi <= 0) {
return -errno;
}
if (!d) {
return -errno;
}
if (udev_device_get_is_initialized(d) <= 0) {
return -EBUSY;
}
return ifi;
}
char **i;
int r;
if (!arg_private_network)
return 0;
return 0;
r = sd_rtnl_open(&rtnl, 0);
if (r < 0) {
return r;
}
if (!udev) {
log_error("Failed to connect to udev.");
return -ENOMEM;
}
int ifi;
if (ifi < 0)
return ifi;
if (r < 0) {
return r;
}
if (r < 0) {
return r;
}
if (r < 0) {
return r;
}
}
return 0;
}
char **i;
int r;
if (!arg_private_network)
return 0;
return 0;
r = sd_rtnl_open(&rtnl, 0);
if (r < 0) {
return r;
}
if (!udev) {
log_error("Failed to connect to udev.");
return -ENOMEM;
}
_cleanup_free_ char *n = NULL;
int ifi;
if (ifi < 0)
return ifi;
if (r < 0) {
return r;
}
if (r < 0) {
return r;
}
n = strappend("mv-", *i);
if (!n)
return log_oom();
r = sd_rtnl_message_append_string(m, IFLA_IFNAME, n);
if (r < 0) {
return r;
}
if (r < 0) {
return r;
}
if (r < 0) {
return r;
}
if (r < 0) {
return r;
}
if (r < 0) {
return r;
}
r = sd_rtnl_message_close_container(m);
if (r < 0) {
return r;
}
r = sd_rtnl_message_close_container(m);
if (r < 0) {
return r;
}
if (r < 0) {
return r;
}
}
return 0;
}
static int audit_still_doesnt_work_in_containers(void) {
#ifdef HAVE_SECCOMP
int r;
/*
Audit is broken in containers, much of the userspace audit
hookup will fail if running inside a container. We don't
care and just turn off creation of audit sockets.
This will make socket(AF_NETLINK, *, NETLINK_AUDIT) fail
with EAFNOSUPPORT which audit userspace uses as indication
that audit is disabled in the kernel.
*/
if (!seccomp)
return log_oom();
if (r < 0) {
goto finish;
}
r = seccomp_rule_add(
2,
if (r < 0) {
goto finish;
}
if (r < 0) {
goto finish;
}
r = seccomp_load(seccomp);
if (r < 0)
return r;
#else
return 0;
#endif
}
struct loop_info64 info = {
};
int r, nr;
if (fd < 0) {
return -errno;
}
return -errno;
}
char *p;
if (!p)
return log_oom();
*device_path = p;
*loop_nr = -1;
r = fd;
fd = -1;
return r;
}
return -EINVAL;
}
if (control < 0) {
log_error("Failed to open /dev/loop-control: %m");
return -errno;
}
if (nr < 0) {
log_error("Failed to allocate loop device: %m");
return -errno;
}
return log_oom();
if (loop < 0) {
return -errno;
}
return -errno;
}
if (arg_read_only)
return -errno;
}
*device_path = loopdev;
r = loop;
loop = -1;
return r;
}
static int dissect_image(
int fd,
char **root_device, bool *root_device_rw,
char **home_device, bool *home_device_rw,
char **srv_device, bool *srv_device_rw,
bool *secondary) {
#ifdef HAVE_BLKID
int r;
b = blkid_new_probe();
if (!b)
return log_oom();
errno = 0;
r = blkid_probe_set_device(b, fd, 0, 0);
if (r != 0) {
if (errno == 0)
return log_oom();
log_error("Failed to set device on blkid probe: %m");
return -errno;
}
errno = 0;
r = blkid_do_safeprobe(b);
if (r == -2 || r == 1) {
log_error("Failed to identify any partition table on %s.\n"
"Note that the disk image needs to follow http://www.freedesktop.org/wiki/Specifications/DiscoverablePartitionsSpec/ to be supported by systemd-nspawn.", arg_image);
return -EINVAL;
} else if (r != 0) {
if (errno == 0)
log_error("Failed to probe: %m");
return -errno;
}
log_error("Image %s does not carry a GUID Partition Table.\n"
"Note that the disk image needs to follow http://www.freedesktop.org/wiki/Specifications/DiscoverablePartitionsSpec/ to be supported by systemd-nspawn.", arg_image);
return -EINVAL;
}
errno = 0;
pl = blkid_probe_get_partitions(b);
if (!pl) {
if (errno == 0)
return log_oom();
return -errno;
}
if (!udev)
return log_oom();
log_error("Failed to stat block device: %m");
return -errno;
}
if (!d)
return log_oom();
e = udev_enumerate_new(udev);
if (!e)
return log_oom();
r = udev_enumerate_add_match_parent(e, d);
if (r < 0)
return log_oom();
r = udev_enumerate_scan_devices(e);
if (r < 0) {
return r;
}
_cleanup_udev_device_unref_ struct udev_device *q;
unsigned long long flags;
int nr;
errno = 0;
if (!q) {
if (!errno)
return -errno;
}
qn = udev_device_get_devnum(q);
continue;
continue;
node = udev_device_get_devnode(q);
if (!node)
continue;
if (!pp)
continue;
if (flags & GPT_FLAG_NO_AUTO)
continue;
if (nr < 0)
continue;
if (!stype)
continue;
continue;
continue;
if (!home)
return log_oom();
continue;
if (!srv)
return log_oom();
}
#ifdef GPT_ROOT_NATIVE
continue;
if (!root)
return log_oom();
}
#endif
#ifdef GPT_ROOT_SECONDARY
continue;
if (!secondary_root)
return log_oom();
}
#endif
}
if (!root && !secondary_root) {
log_error("Failed to identify root partition in disk image %s.\n"
"Note that the disk image needs to follow http://www.freedesktop.org/wiki/Specifications/DiscoverablePartitionsSpec/ to be supported by systemd-nspawn.", arg_image);
return -EINVAL;
}
if (root) {
*root_device = root;
*secondary = false;
} else if (secondary_root) {
*secondary = true;
}
if (home) {
*home_device = home;
}
if (srv) {
*srv_device = srv;
*srv_device_rw = srv_rw;
}
return 0;
#else
log_error("--image= is not supported, compiled without blkid support.");
return -ENOTSUP;
#endif
}
#ifdef HAVE_BLKID
const char *fstype, *p;
int r;
if (arg_read_only)
rw = false;
if (directory)
else
p = where;
errno = 0;
if (!b) {
if (errno == 0)
return log_oom();
return -errno;
}
errno = 0;
r = blkid_do_safeprobe(b);
if (r == -1 || r == 1) {
return -EINVAL;
} else if (r != 0) {
if (errno == 0)
return -errno;
}
errno = 0;
if (errno == 0)
return -errno;
}
log_error("nspawn currently does not support LUKS disk images.");
return -ENOTSUP;
}
return -errno;
}
return 0;
#else
log_error("--image= is not supported, compiled without blkid support.");
return -ENOTSUP;
#endif
}
static int mount_devices(
const char *where,
const char *root_device, bool root_device_rw,
const char *home_device, bool home_device_rw,
const char *srv_device, bool srv_device_rw) {
int r;
if (root_device) {
if (r < 0) {
return r;
}
}
if (home_device) {
if (r < 0) {
return r;
}
}
if (srv_device) {
if (r < 0) {
return r;
}
}
return 0;
}
if (nr < 0)
return;
}
if (control < 0)
return;
}
int pipe_fds[2];
log_error("Failed to allocate pipe: %m");
return -errno;
}
if (pid < 0) {
log_error("Failed to fork getent child: %m");
return -errno;
} else if (pid == 0) {
int nullfd;
if (pipe_fds[0] > 2)
safe_close(pipe_fds[0]);
if (nullfd < 0)
if (nullfd > 2)
close_all_fds(NULL, 0);
}
return pipe_fds[0];
}
static int change_uid_gid(char **_home) {
unsigned n_uids = 0;
int r;
/* Reset everything fully to 0, just in case */
log_error("setgroups() failed: %m");
return -errno;
}
if (setresgid(0, 0, 0) < 0) {
log_error("setregid() failed: %m");
return -errno;
}
if (setresuid(0, 0, 0) < 0) {
log_error("setreuid() failed: %m");
return -errno;
}
return 0;
}
/* First, get user credentials */
if (fd < 0)
return fd;
if (!f)
return log_oom();
fd = -1;
if (!ferror(f)) {
return -ESRCH;
}
log_error("Failed to read from getent: %m");
return -errno;
}
if (!x) {
return -EIO;
}
if (!u) {
return -EIO;
}
u++;
g = strchr(u, ':');
if (!g) {
return -EIO;
}
*g = 0;
g++;
x = strchr(g, ':');
if (!x) {
return -EIO;
}
*x = 0;
if (!h) {
return -EIO;
}
h++;
x = strchr(h, ':');
if (!x) {
return -EIO;
}
*x = 0;
if (r < 0) {
log_error("Failed to parse UID of user.");
return -EIO;
}
if (r < 0) {
log_error("Failed to parse GID of user.");
return -EIO;
}
if (!home)
return log_oom();
/* Second, get group memberships */
if (fd < 0)
return fd;
fclose(f);
if (!f)
return log_oom();
fd = -1;
if (!ferror(f)) {
return -ESRCH;
}
log_error("Failed to read from getent: %m");
return -errno;
}
/* Skip over the username and subsequent separator whitespace */
x = line;
x += strcspn(x, WHITESPACE);
x += strspn(x, WHITESPACE);
FOREACH_WORD(w, l, x, state) {
char c[l+1];
memcpy(c, w, l);
c[l] = 0;
return log_oom();
if (r < 0) {
log_error("Failed to parse group data from getent.");
return -EIO;
}
}
if (r < 0) {
return r;
}
if (r < 0 && r != -EEXIST) {
return r;
}
log_error("Failed to set auxiliary groups: %m");
return -errno;
}
log_error("setregid() failed: %m");
return -errno;
}
log_error("setreuid() failed: %m");
return -errno;
}
if (_home) {
}
return 0;
}
/*
* Return 0 in case the container is being rebooted, has been shut
* down or exited successfully. On failures a negative value is
* returned.
*
* The status of the container "CONTAINER_TERMINATED" or
* "CONTAINER_REBOOTED" will be saved in the container argument
*/
int r;
if (r < 0)
return r;
case CLD_EXITED:
if (r == 0) {
if (!arg_quiet)
log_debug("Container %s exited successfully.",
} else {
log_error("Container %s failed with error code %i.",
r = -1;
}
break;
case CLD_KILLED:
if (!arg_quiet)
log_info("Container %s has been shut down.",
r = 0;
break;
if (!arg_quiet)
log_info("Container %s is being rebooted.",
r = 0;
break;
}
/* CLD_KILLED fallthrough */
case CLD_DUMPED:
log_error("Container %s terminated by signal %s.",
r = -1;
break;
default:
log_error("Container %s failed due to unknown reason.",
r = -1;
break;
}
return r;
}
static void nop_handler(int sig) {}
_cleanup_free_ char *kdbus_domain = NULL, *device_path = NULL, *root_device = NULL, *home_device = NULL, *srv_device = NULL;
bool secondary = false;
log_open();
if (k < 0)
goto finish;
else if (k == 0) {
r = EXIT_SUCCESS;
goto finish;
}
if (!arg_image) {
if (arg_directory) {
char *p;
arg_directory = p;
} else
if (!arg_directory) {
log_error("Failed to determine path, please use -D.");
goto finish;
}
}
if (!arg_machine) {
if (!arg_machine) {
log_oom();
goto finish;
}
hostname_cleanup(arg_machine, false);
if (isempty(arg_machine)) {
log_error("Failed to determine machine name automatically, please use -M.");
goto finish;
}
}
if (geteuid() != 0) {
log_error("Need to be root.");
goto finish;
}
if (sd_booted() <= 0) {
log_error("Not running on a systemd system.");
goto finish;
}
log_close();
n_fd_passed = sd_listen_fds(false);
if (n_fd_passed > 0) {
k = fdset_new_listen_fds(&fds, false);
if (k < 0) {
goto finish;
}
}
log_open();
if (arg_directory) {
log_error("Spawning container on root directory not supported.");
goto finish;
}
if (arg_boot) {
if (path_is_os_tree(arg_directory) <= 0) {
log_error("Directory %s doesn't look like an OS root directory (/etc/os-release is missing). Refusing.", arg_directory);
goto finish;
}
} else {
const char *p;
p = strappenda(arg_directory,
log_error("Directory %s lacks the binary to execute or doesn't look like a binary tree. Refusing.", arg_directory);
goto finish;
}
}
} else {
char template[] = "/tmp/nspawn-root-XXXXXX";
log_error("Failed to create temporary directory: %m");
r = -errno;
goto finish;
}
if (!arg_directory) {
r = log_oom();
goto finish;
}
if (image_fd < 0) {
r = image_fd;
goto finish;
}
r = dissect_image(image_fd, &root_device, &root_device_rw, &home_device, &home_device_rw, &srv_device, &srv_device_rw, &secondary);
if (r < 0)
goto finish;
}
if (master < 0) {
log_error("Failed to acquire pseudo tty: %m");
goto finish;
}
if (!console) {
log_error("Failed to determine tty name: %m");
goto finish;
}
if (!arg_quiet)
log_info("Spawning container %s on %s.\nPress ^] three times within 1s to kill container.",
log_error("Failed to unlock tty: %m");
goto finish;
}
if (arg_share_system) {
if (!kdbus_domain) {
log_oom();
goto finish;
}
} else {
const char *ns;
if (r < 0)
else
}
}
log_error("Failed to create kmsg socket pair: %m");
goto finish;
}
sd_notify(0, "READY=1");
for (;;) {
.sa_flags = SA_NOCLDSTOP,
};
/* Child can be killed before execv(), so handle SIGCHLD
* in order to interrupt parent's blocking calls and
* give it a chance to call wait() and terminate. */
if (r < 0) {
log_error("Failed to change the signal mask: %m");
goto finish;
}
if (r < 0) {
log_error("Failed to install SIGCHLD handler: %m");
goto finish;
}
if (pid < 0) {
log_error("clone() failed, do you have namespace support enabled in your kernel? (You need UTS, IPC, PID and NET namespacing built in): %m");
else
log_error("clone() failed: %m");
r = pid;
goto finish;
}
if (pid == 0) {
/* child */
unsigned n_env = 2;
const char *envp[] = {
"PATH=" DEFAULT_PATH_SPLIT_USR,
"container=systemd-nspawn", /* LXC sets container=lxc, so follow the scheme here */
NULL, /* TERM */
NULL, /* HOME */
NULL, /* USER */
NULL, /* LOGNAME */
NULL, /* container_uuid */
NULL, /* LISTEN_FDS */
NULL, /* LISTEN_PID */
};
char **env_use;
n_env ++;
if (k != STDIN_FILENO) {
if (k >= 0) {
safe_close(k);
k = -EINVAL;
}
goto child_fail;
}
log_error("Failed to duplicate console: %m");
goto child_fail;
}
if (setsid() < 0) {
log_error("setsid() failed: %m");
goto child_fail;
}
if (reset_audit_loginuid() < 0)
goto child_fail;
log_error("PR_SET_PDEATHSIG failed: %m");
goto child_fail;
}
/* Mark everything as slave, so that we still
* receive mounts from the real root, but don't
* propagate mounts to the real root. */
log_error("MS_SLAVE|MS_REC failed: %m");
goto child_fail;
}
srv_device, srv_device_rw) < 0)
goto child_fail;
/* Turn directory into bind mount */
log_error("Failed to make bind mount: %m");
goto child_fail;
}
if (arg_read_only) {
k = bind_remount_recursive(arg_directory, true);
if (k < 0) {
goto child_fail;
}
}
if (mount_all(arg_directory) < 0)
goto child_fail;
if (copy_devnodes(arg_directory) < 0)
goto child_fail;
if (setup_ptmx(arg_directory) < 0)
goto child_fail;
if (audit_still_doesnt_work_in_containers() < 0)
goto child_fail;
goto child_fail;
goto child_fail;
if (setup_boot_id(arg_directory) < 0)
goto child_fail;
if (setup_timezone(arg_directory) < 0)
goto child_fail;
if (setup_resolv_conf(arg_directory) < 0)
goto child_fail;
if (setup_journal(arg_directory) < 0)
goto child_fail;
goto child_fail;
goto child_fail;
goto child_fail;
/* Tell the parent that we are ready, and that
* it can cgroupify us to that we lack access
* to certain devices and resources. */
if (r < 0)
goto child_fail;
if (chdir(arg_directory) < 0) {
goto child_fail;
}
log_error("mount(MS_MOVE) failed: %m");
goto child_fail;
}
if (chroot(".") < 0) {
log_error("chroot() failed: %m");
goto child_fail;
}
if (chdir("/") < 0) {
log_error("chdir() failed: %m");
goto child_fail;
}
umask(0022);
if (arg_private_network)
if (drop_capabilities() < 0) {
log_error("drop_capabilities() failed: %m");
goto child_fail;
}
r = change_uid_gid(&home);
if (r < 0)
goto child_fail;
log_oom();
goto child_fail;
}
char as_uuid[37];
if (asprintf((char**)(envp + n_env++), "container_uuid=%s", id128_format_as_uuid(arg_uuid, as_uuid)) < 0) {
log_oom();
goto child_fail;
}
}
if (fdset_size(fds) > 0) {
k = fdset_cloexec(fds, false);
if (k < 0) {
log_error("Failed to unset O_CLOEXEC for file descriptors.");
goto child_fail;
}
log_oom();
goto child_fail;
}
}
if (arg_personality != 0xffffffffLU) {
if (personality(arg_personality) < 0) {
log_error("personality() failed: %m");
goto child_fail;
}
} else if (secondary) {
if (personality(PER_LINUX32) < 0) {
log_error("personality() failed: %m");
goto child_fail;
}
}
#ifdef HAVE_SELINUX
if (arg_selinux_context)
goto child_fail;
}
#endif
if (!strv_isempty(arg_setenv)) {
char **n;
if (!n) {
log_oom();
goto child_fail;
}
env_use = n;
} else
/* Wait until the parent is ready with the setup, too... */
r = eventfd_parent_succeeded(eventfds[0]);
if (r < 0)
goto child_fail;
if (arg_boot) {
char **a;
size_t l;
/* Automatically search for the init system */
a = newa(char*, l + 1);
else {
}
log_error("execv() failed: %m");
/* Tell the parent that the setup failed, so he
* can clean up resources and terminate. */
}
/* Wait for the child event:
* If EVENTFD_CHILD_FAILED, the child will terminate soon.
* If EVENTFD_CHILD_SUCCEEDED, the child is reporting that
* it is ready with all it needs to do with priviliges.
* After we got the notification we can make the process
* join its cgroup which might limit what it can do */
if (r < 0)
goto check_container_status;
r = register_machine(pid);
if (r < 0)
goto finish;
r = move_network_interfaces(pid);
if (r < 0)
goto finish;
if (r < 0)
goto finish;
r = setup_bridge(veth_name);
if (r < 0)
goto finish;
r = setup_macvlan(pid);
if (r < 0)
goto finish;
/* Block SIGCHLD here, before notifying child.
* process_pty() will handle it with the other signals. */
if (r < 0)
goto finish;
/* Reset signal to default */
if (r < 0)
goto finish;
/* Notify the child that the parent is ready with all
* its setup, and that the child can now hand over
* control to the code to run inside the container. */
r = eventfd_send_state(eventfds[0],
if (r < 0)
goto finish;
if (k < 0) {
r = EXIT_FAILURE;
break;
}
if (!arg_quiet)
/* Kill if it is not dead yet anyway */
/* Redundant, but better safe than sorry */
pid = 0;
if (r < 0) {
r = EXIT_FAILURE;
break;
} else if (container_status == CONTAINER_TERMINATED)
break;
/* CONTAINER_REBOOTED, loop again */
}
if (pid > 0)
return r;
}