This commit is contained in:
1 parent
3a99da196d
commit
d7613a4987
10 files changed
+603
-189
No files matched your search
+6
-4
@@ -75,12 +75,14 @@ fn build_inner(
|
||||
cmd: Option<String>,
|
||||
) -> Result<()> {
|
||||
let config = inject::inspect_config(image)?;
|
||||
let command = cmd.unwrap_or_else(|| inject::infer_command(&config));
|
||||
let exec_script =
|
||||
inject::build_exec_script(&command, &config.env, config.working_dir.as_deref());
|
||||
let argv = match cmd {
|
||||
Some(s) => vec!["/bin/sh".into(), "-c".into(), s],
|
||||
None => inject::infer_argv(&config),
|
||||
};
|
||||
inject::inject(
|
||||
mount_path,
|
||||
&exec_script,
|
||||
&argv,
|
||||
&config.env,
|
||||
config.user.as_deref(),
|
||||
config.working_dir.as_deref(),
|
||||
)?;
|
||||
|
||||
+42
-52
@@ -1,15 +1,14 @@
|
||||
//! Inject: inspect a podman image's config, infer the default command, and
|
||||
//! inject distro-agnostic /slim/ scripts (init + exec) into the mounted rootfs.
|
||||
//! Inject: inspect a podman image's config, infer the default command argv,
|
||||
//! and inject the slim init binary + null-delimited argv/env files into the
|
||||
//! mounted rootfs.
|
||||
|
||||
use anyhow::{Context, Result, anyhow};
|
||||
use serde::Deserialize;
|
||||
use std::fmt::Write as _;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
|
||||
use crate::command::cmd;
|
||||
|
||||
const SLIM_INIT: &str = include_str!("scripts/slim-init.sh");
|
||||
use crate::registry::init_binary_path;
|
||||
|
||||
#[derive(Debug, Default, Deserialize)]
|
||||
#[serde(rename_all = "PascalCase")]
|
||||
@@ -40,56 +39,38 @@ pub fn inspect_config(image: &str) -> Result<Config> {
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
/// Infer the command string from the image config.
|
||||
/// Infer the command argv from the image config.
|
||||
///
|
||||
/// Concatenates ENTRYPOINT + CMD (Docker semantics). If neither is present,
|
||||
/// falls back to `/bin/sh`.
|
||||
pub fn infer_command(config: &Config) -> String {
|
||||
let parts = config.entrypoint.iter().chain(config.cmd.iter());
|
||||
let parts: Vec<_> = parts.map(|s| s.as_str()).collect();
|
||||
|
||||
match &parts[..] {
|
||||
[] => "/bin/sh".into(),
|
||||
["/bin/sh" | "sh", "-c", cmd] => cmd.to_string(),
|
||||
_ => shell_join(&parts),
|
||||
}
|
||||
}
|
||||
|
||||
fn shell_escape(s: &str) -> String {
|
||||
format!("'{}'", s.replace('\'', "'\\''"))
|
||||
}
|
||||
|
||||
fn shell_join(parts: &[&str]) -> String {
|
||||
parts
|
||||
/// falls back to `["/bin/sh"]`.
|
||||
pub fn infer_argv(config: &Config) -> Vec<String> {
|
||||
let parts: Vec<String> = config
|
||||
.entrypoint
|
||||
.iter()
|
||||
.map(|p| shell_escape(p))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ")
|
||||
.chain(config.cmd.iter())
|
||||
.cloned()
|
||||
.collect();
|
||||
|
||||
if parts.is_empty() {
|
||||
vec!["/bin/sh".into()]
|
||||
} else {
|
||||
parts
|
||||
}
|
||||
}
|
||||
|
||||
/// Generate the /slim/exec script from a command string, env vars, and working dir.
|
||||
pub fn build_exec_script(command: &str, env: &[String], working_dir: Option<&str>) -> String {
|
||||
let mut lines = String::from("#!/bin/sh\n");
|
||||
if let Some(dir) = working_dir.filter(|d| !d.is_empty()) {
|
||||
_ = writeln!(&mut lines, "cd {} 2>/dev/null", shell_escape(dir));
|
||||
/// Join items as null-delimited bytes.
|
||||
pub fn null_delimited(items: &[String]) -> Vec<u8> {
|
||||
let mut data = Vec::new();
|
||||
for item in items {
|
||||
data.extend_from_slice(item.as_bytes());
|
||||
data.push(0);
|
||||
}
|
||||
for var in env {
|
||||
if let Some((key, val)) = var.split_once('=') {
|
||||
_ = writeln!(
|
||||
&mut lines,
|
||||
"export {}={}",
|
||||
shell_escape(key),
|
||||
shell_escape(val)
|
||||
);
|
||||
}
|
||||
}
|
||||
_ = writeln!(&mut lines, "exec /bin/sh -c {}", shell_escape(command));
|
||||
lines
|
||||
data
|
||||
}
|
||||
|
||||
/// Install `content` into the mounted rootfs at `<mount>/slim/<name>` with
|
||||
/// the given mode.
|
||||
fn install_into_rootfs(mount: &str, name: &str, mode: &str, content: &str) -> Result<()> {
|
||||
fn install_into_rootfs(mount: &str, name: &str, mode: &str, content: &[u8]) -> Result<()> {
|
||||
let temp = tempfile::NamedTempFile::new()?;
|
||||
fs::write(temp.path(), content)?;
|
||||
let src = temp.path().to_str().context("temp path is not UTF-8")?;
|
||||
@@ -100,25 +81,34 @@ fn install_into_rootfs(mount: &str, name: &str, mode: &str, content: &str) -> Re
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Inject /slim/init, /slim/exec, and optionally /slim/user and /slim/workdir
|
||||
/// into a mounted container image rootfs.
|
||||
/// Inject /slim/init (binary), /slim/exec (null-delimited argv), /slim/env
|
||||
/// (null-delimited env), and optionally /slim/user and /slim/workdir into a
|
||||
/// mounted container image rootfs.
|
||||
pub fn inject(
|
||||
mount_path: &Path,
|
||||
exec_script: &str,
|
||||
argv: &[String],
|
||||
env: &[String],
|
||||
user: Option<&str>,
|
||||
working_dir: Option<&str>,
|
||||
) -> Result<()> {
|
||||
let mount_str = mount_path.to_str().context("mount path is not UTF-8")?;
|
||||
|
||||
install_into_rootfs(mount_str, "init", "755", SLIM_INIT)?;
|
||||
install_into_rootfs(mount_str, "exec", "755", exec_script)?;
|
||||
let init_binary = fs::read(init_binary_path()?).context("Failed to read slim-init binary")?;
|
||||
let exec_data = null_delimited(argv);
|
||||
let env_data = null_delimited(env);
|
||||
|
||||
install_into_rootfs(mount_str, "init", "755", &init_binary)?;
|
||||
install_into_rootfs(mount_str, "exec", "644", &exec_data)?;
|
||||
if !env_data.is_empty() {
|
||||
install_into_rootfs(mount_str, "env", "644", &env_data)?;
|
||||
}
|
||||
|
||||
if let Some(user) = user.filter(|u| !u.is_empty()) {
|
||||
install_into_rootfs(mount_str, "user", "644", user)?;
|
||||
install_into_rootfs(mount_str, "user", "644", user.as_bytes())?;
|
||||
}
|
||||
|
||||
if let Some(dir) = working_dir.filter(|d| !d.is_empty()) {
|
||||
install_into_rootfs(mount_str, "workdir", "644", dir)?;
|
||||
install_into_rootfs(mount_str, "workdir", "644", dir.as_bytes())?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
|
||||
+3
-1
@@ -85,7 +85,9 @@ pub(crate) fn run(
|
||||
}
|
||||
|
||||
if let Some(cmd) = &cmd {
|
||||
let encoded = base64::engine::general_purpose::STANDARD.encode(cmd.as_bytes());
|
||||
let argv = ["/bin/sh".to_string(), "-c".to_string(), cmd.clone()];
|
||||
let data: Vec<u8> = argv.join("\0").into_bytes();
|
||||
let encoded = base64::engine::general_purpose::STANDARD.encode(&data);
|
||||
cmdline.push(format!("slim.cmd={encoded}"));
|
||||
}
|
||||
|
||||
|
||||
@@ -32,6 +32,12 @@ pub(crate) fn registry_base_dir() -> Result<PathBuf> {
|
||||
.context("Failed to create XDG_DATA_HOME subdirectory")
|
||||
}
|
||||
|
||||
pub(crate) fn init_binary_path() -> Result<PathBuf> {
|
||||
let base = xdg::BaseDirectories::with_prefix("slim-rs");
|
||||
base.get_data_file("slim-init")
|
||||
.context("slim-init not found in XDG data dir")
|
||||
}
|
||||
|
||||
pub(crate) fn registry_dir(image: &str) -> Result<PathBuf> {
|
||||
validate_image_name(image)?;
|
||||
let base = registry_base_dir()?;
|
||||
|
||||
@@ -1,121 +0,0 @@
|
||||
#!/bin/sh
|
||||
# slim universal init - distro-agnostic VM bootstrap.
|
||||
# Injected by `slim build` at /slim/init and invoked via init=/slim/init.
|
||||
|
||||
# === Helpers ===
|
||||
b64dec() {
|
||||
printf '%s' "$1" | base64 -d 2>/dev/null || printf '%s' "$1" | openssl base64 -d 2>/dev/null
|
||||
}
|
||||
|
||||
# === Devices & special filesystems ===
|
||||
[ -c /dev/console ] || mknod -m 600 /dev/console c 5 1
|
||||
mkdir -p /proc /sys /dev/pts /dev/shm
|
||||
mount -t proc proc /proc
|
||||
mount -t sysfs sysfs /sys
|
||||
mount -t devpts devpts /dev/pts
|
||||
mount -t tmpfs tmpfs /dev/shm
|
||||
mount -t tmpfs tmpfs /run -o mode=755
|
||||
mount -t tmpfs tmpfs /tmp -o mode=1777
|
||||
|
||||
# === cgroup2 ===
|
||||
mkdir -p /sys/fs/cgroup
|
||||
mount -t cgroup2 none /sys/fs/cgroup 2>/dev/null || echo "mount cgroup2 failed"
|
||||
# shellcheck disable=SC2013 # word-splitting is intentional: controllers are space-separated
|
||||
for c in $(cat /sys/fs/cgroup/cgroup.controllers 2>/dev/null); do
|
||||
echo "+$c" > /sys/fs/cgroup/cgroup.subtree_control 2>/dev/null || echo "enable cgroup controller $c failed"
|
||||
done
|
||||
|
||||
# === Rootless container prerequisites (best-effort) ===
|
||||
mount --make-rshared / 2>/dev/null || echo "make-rshared / failed"
|
||||
chmod u+s /usr/bin/newuidmap /usr/bin/newgidmap 2>/dev/null || echo "chmod newuidmap/newgidmap failed"
|
||||
|
||||
# === Timezone ===
|
||||
ln -sf /usr/share/zoneinfo/Europe/Stockholm /etc/localtime 2>/dev/null || echo "set timezone failed"
|
||||
|
||||
# === Networking (QEMU slirp: guest 10.0.2.15/24, gw 10.0.2.2, dns 10.0.2.3) ===
|
||||
ip link set lo up 2>/dev/null || echo "ip link set lo up failed"
|
||||
ip link set eth0 up 2>/dev/null || echo "ip link set eth0 up failed"
|
||||
ip addr add 10.0.2.15/24 dev eth0 2>/dev/null || echo "ip addr add eth0 failed"
|
||||
ip route add default via 10.0.2.2 2>/dev/null || echo "ip route add default failed"
|
||||
echo nameserver 10.0.2.3 > /etc/resolv.conf
|
||||
|
||||
# === 9p shares (host directories shared via --mount) ===
|
||||
# Each share is passed as slim.mount=<tag>:<base64(guest_path)> on the
|
||||
# kernel cmdline. The 9p tag is short (e.g. slim0) because mount_tag
|
||||
# has a ~31-byte limit; the guest path is base64-encoded.
|
||||
# Non-absolute guest paths are resolved against /slim/workdir (the
|
||||
# image's WORKINGDIR).
|
||||
SLIM_WORKDIR=""
|
||||
[ -f /slim/workdir ] && SLIM_WORKDIR=$(cat /slim/workdir 2>/dev/null)
|
||||
# shellcheck disable=SC2013 # word-splitting is intentional: cmdline tokens are space-separated
|
||||
for tok in $(cat /proc/cmdline 2>/dev/null); do
|
||||
case "$tok" in
|
||||
slim.mount=*)
|
||||
v=${tok#slim.mount=}
|
||||
tag=${v%%:*}
|
||||
dest_b64=${v#*:}
|
||||
dest=$(b64dec "$dest_b64") || echo "base64 decode failed"
|
||||
if [ -n "$tag" ] && [ -n "$dest" ]; then
|
||||
# Resolve relative paths against the image's WORKINGDIR
|
||||
case "$dest" in
|
||||
/*) ;;
|
||||
*) dest="${SLIM_WORKDIR:-/}/${dest}" ;;
|
||||
esac
|
||||
mkdir -p "$dest"
|
||||
mount -t 9p "$tag" "$dest" -o trans=virtio,version=9p2000.L 2>/dev/null \
|
||||
&& echo "mounted 9p '$tag' -> '$dest'" \
|
||||
|| echo "failed to mount 9p '$tag' -> '$dest'"
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
# === Drop privileges (respect USER directive from image config) ===
|
||||
# /slim/user may contain a username, uid, or uid:gid (OCI image spec).
|
||||
# Numeric uids are resolved to a username via /etc/passwd because BusyBox
|
||||
# su does not accept numeric arguments.
|
||||
SLIM_USER=""
|
||||
[ -f /slim/user ] && SLIM_USER=$(cat /slim/user 2>/dev/null)
|
||||
|
||||
# Resolve a numeric uid to a username from /etc/passwd.
|
||||
slim_resolve_user() {
|
||||
_u="$1"
|
||||
case "$_u" in
|
||||
*[!0-9]*) printf '%s' "$_u" ;;
|
||||
*)
|
||||
_resolved=$(awk -F: -v uid="$_u" '$3==uid{print $1; exit}' /etc/passwd 2>/dev/null)
|
||||
[ -n "$_resolved" ] && printf '%s' "$_resolved" || printf '%s' "$_u"
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
# Exec a command, dropping privileges if SLIM_USER is set.
|
||||
# When dropping privileges, run as a child (not exec) so PID 1 stays root
|
||||
# and can poweroff after the command exits — non-root cannot call poweroff.
|
||||
slim_exec() {
|
||||
_cmd="$1"
|
||||
if [ -z "$SLIM_USER" ]; then
|
||||
exec /bin/sh -c "$_cmd"
|
||||
fi
|
||||
_user="${SLIM_USER%%:*}"
|
||||
_user=$(slim_resolve_user "$_user")
|
||||
su "$_user" -c "$_cmd"
|
||||
poweroff -f
|
||||
}
|
||||
|
||||
# === Execute the configured command ===
|
||||
# If slim.cmd=<base64> is on the kernel cmdline, decode and exec it.
|
||||
# Otherwise, exec /slim/exec (generated from the image's CMD/ENTRYPOINT).
|
||||
# shellcheck disable=SC2013 # word-splitting is intentional: cmdline tokens are space-separated
|
||||
for tok in $(cat /proc/cmdline 2>/dev/null); do
|
||||
case "$tok" in
|
||||
slim.cmd=*)
|
||||
v=${tok#slim.cmd=}
|
||||
decoded=$(b64dec "$v") || echo "base64 decode failed"
|
||||
if [ -n "$decoded" ]; then
|
||||
slim_exec "$decoded"
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
done
|
||||
slim_exec "/slim/exec"
|
||||
Reference in new issue
Block a user