about summary refs log tree commit diff
diff options
context:
space:
mode:
authorPjotr Prins <pjotr.public12@thebird.nl>2026-09-26 13:09:25 +0000
committerPjotr Prins <pjotr.public12@thebird.nl>2026-09-26 13:09:25 +0000
commit2ff6ab0645463504fd101e73d3e4e2ab75a08c94 (patch)
tree5294b1b455b52fb194e1c9b8c25d80c0b85bfc23
downloadrun-guix-container-2ff6ab0645463504fd101e73d3e4e2ab75a08c94.tar.gz
run-guix-container: new tool
A C daemon (run as root) that starts Guix system containers on
request over a line-based network protocol, plus an unprivileged
Ruby client.

* START/KILL/LOG/FINGERPRINT protocol; one request per connection
* strict validation of store items before exec (HASH-run-container
  name, guile shebang, container markers, immutable store file)
* --fingerprint WORD identifies the daemon instance (random hash
  when unset); verified by clients and passed to containers in
  GUIX_CONTAINER_FINGERPRINT
* on SIGINT/SIGTERM: SIGTERM all started containers, 10s timeout,
  then SIGKILL
* container boot output appended to /var/log/guix-containers/
* unit tests for launcher and fingerprint logic
-rw-r--r--README.md258
-rwxr-xr-xbin/run-guix-container.rb176
-rwxr-xr-xbin/run-guix-system-containerbin0 -> 26936 bytes
-rw-r--r--bin/run-guix-system-container.c756
-rw-r--r--etc/ssh-container-key8
-rw-r--r--etc/ssh-container-key.pub1
-rwxr-xr-xtest/run.sh20
-rw-r--r--test/test.c115
8 files changed, 1334 insertions, 0 deletions
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..6d1a06e
--- /dev/null
+++ b/README.md
@@ -0,0 +1,258 @@
+# Guix system container daemon
+
+When developing system containers it is useful to be able to test them
+on the underlying host. Particularly when using AI agents. This little
+tool allows starting system containers through a network call. It
+validates the originating IP and whether this is a true container.
+
+Still, make sure this only runs on systems that have limited
+functionality. I use it on my reduced AI box where the agents run in
+containers.
+
+A daemon that starts Guix system containers (`guix system container ...`
+launchers from `/gnu/store`) on request.  You can run it by hand, but
+it is meant to run **as root from shepherd (Guix System) or systemd
+(Debian)**.
+
+## Network protocol
+
+Line based, one request per connection:
+
+```
+START <hash|/gnu/store/HASH-run-container> [<fingerprint>]\n
+→ OK <pid>\n      container started (detached)
+→ ERR <reason>\n  rejected
+KILL <pid>\n
+→ OK killed <pid>\n  SIGTERM sent to a container started by this daemon
+→ ERR <reason>\n  unknown pid, not ours, etc.
+LOG <hash|/gnu/store/HASH-run-container>\n
+→ OK\n + raw log contents   (boot output of the container)
+FINGERPRINT\n
+→ OK <fingerprint>\n  the daemon's fingerprint
+```
+
+The client `run-guix-container.rb` speaks this protocol:
+
+```sh
+./run-guix-container.rb --daemon 127.0.0.1:8989 HASH
+GUIX_CONTAINER_DAEMON=127.0.0.1:8989 ./run-guix-container.rb HASH
+./run-guix-container.rb --daemon 127.0.0.1:8989 --kill PID
+./run-guix-container.rb --daemon 127.0.0.1:8989 --log HASH
+```
+
+Inspect a running container (as root):
+
+```sh
+nsenter -at $PID /run/current-system/profile/bin/bash --login
+```
+
+## Daemon fingerprint
+
+Start the daemon with `--fingerprint WORD`, a short word or version
+like `v0.1`:
+
+```sh
+run-guix-system-container --listen 127.0.0.1 --port 8989 --fingerprint v0.1
+```
+
+If no fingerprint is given, the daemon generates a **random hash** at
+startup.  The fingerprint makes sure everyone talks to the daemon (and
+thus the containers) they expect:
+
+* clients can query it (`FINGERPRINT` command) or pass the expected
+  fingerprint with `START <hash> <fingerprint>` — a mismatch is
+  refused with `ERR fingerprint mismatch`
+* the client has `--fingerprint WORD`, which verifies the daemon via
+  `FINGERPRINT` before doing anything else
+* every started container receives the fingerprint in its
+  `GUIX_CONTAINER_FINGERPRINT` environment variable; a container OS
+  can show it at login (e.g. write it to `/etc/issue`), so an ssh
+  session immediately reveals which daemon generation started it
+
+## Shutdown behaviour
+
+On SIGINT or SIGTERM the daemon terminates the containers it started:
+SIGTERM to all of them, wait up to **10 seconds** for them to exit,
+then SIGKILL any survivors, and exit.  Containers started by a
+*previous* daemon instance are not tracked and not touched.
+
+## Access control
+
+The daemon listens on **one address only**, given by `--listen IP`
+(default `127.0.0.1`, i.e. loopback — only local clients can reach
+it).  Pass an explicit address to expose it further, e.g.
+`--listen 0.0.0.0` for all IPv4 interfaces, or a specific address such
+as `--listen 192.168.1.10`.  IPv6 addresses work too (`--listen ::1`).
+
+There is no per-client ACL: whoever can reach the listening address
+may start containers.  Restrict access at the network level (bind to a
+dedicated interface, firewall the port, or use a private network
+between the host and its containers).
+
+Every request is logged to stderr with a timestamp and client address.
+
+## Validation
+
+Before a container script is exec'd, the daemon verifies:
+
+* the name resolves to exactly `HASH-run-container` (32-char nix-base32
+  hash, unique in the store)
+* the file is a direct child of `/gnu/store`, executable, and
+  immutable (no write bits — Guix store items are `0555` root-owned)
+* the file is structurally a generated Guix system container launcher:
+  * first line is a guile shebang
+    (`#!/gnu/store/...-guile-.../bin/guile ...`) — this also rules out
+    ELF binaries, which start with `\x7fELF`
+  * it calls `call-with-container`, the container entry point
+  * it sets `GUIX_NEW_SYSTEM`, as generated system containers do
+  * it references `linux-container`
+
+  A regular binary, an ELF file, or a script that merely mentions
+  these strings but is not a generated launcher will not pass.
+
+## Build & install
+
+```sh
+cd bin
+gcc -O2 -Wall -o run-guix-system-container run-guix-system-container.c
+# Debian:
+sudo install -o root -g root -m 0755 run-guix-system-container /usr/local/bin/
+# Guix System: add it to a channel/package or keep it in a root-owned
+# directory, e.g. /run/current-system/profile/bin/
+
+# Run the unit tests:
+cd ../test && ./run.sh
+```
+
+## Running it
+
+### systemd (Debian)
+
+Basic unit, `/etc/systemd/system/guix-container-daemon.service`:
+
+```ini
+[Unit]
+Description=Guix system container launcher daemon
+After=network.target
+
+[Service]
+ExecStart=/usr/local/bin/run-guix-system-container --listen 127.0.0.1 --port 8989 --fingerprint v0.1
+Restart=on-failure
+
+[Install]
+WantedBy=multi-user.target
+```
+
+A hardened variant — the daemon only needs to read the store, listen
+on a socket, fork and exec, so most systemd sandboxing can be enabled
+(note: `ProtectSystem=strict` would hide `/gnu/store` unless made
+read-only-visible, which is the default anyway — keep it `read-only`):
+
+```ini
+[Unit]
+Description=Guix system container launcher daemon
+After=network.target
+
+[Service]
+ExecStart=/usr/local/bin/run-guix-system-container --listen 127.0.0.1 --port 8989 --fingerprint v0.1
+Restart=on-failure
+
+# Logging goes to stderr; let journald capture it.
+StandardOutput=journal
+StandardError=journal
+
+# The daemon forks detached containers (setsid), which must survive a
+# daemon restart — do not use KillMode=control-group here.
+KillMode=process
+
+# Sandbox: the daemon needs /gnu/store (read-only), /dev/null, the
+# socket, and nothing else writable.
+ProtectSystem=strict
+ReadOnlyPaths=/gnu/store
+ProtectHome=true
+PrivateTmp=true
+NoNewPrivileges=true
+ProtectKernelTunables=true
+ProtectKernelModules=true
+ProtectControlGroups=true
+RestrictAddressFamilies=AF_INET AF_INET6
+CapabilityBoundingSet=CAP_SETUID CAP_SETGID CAP_SYS_ADMIN
+RestrictSUIDSGID=true
+
+# Network filtering (cgroup BPF): only allow loopback traffic, deny
+# everything else — a second layer on top of --listen 127.0.0.1.
+IPAddressDeny=any
+IPAddressAllow=localhost
+# Optionally log traffic from/to the unit:
+IPAccounting=yes
+
+[Install]
+WantedBy=multi-user.target
+```
+
+Enable and watch the log:
+
+```sh
+sudo systemctl daemon-reload
+sudo systemctl enable --now guix-container-daemon
+sudo journalctl -u guix-container-daemon -f     # watch the log
+```
+
+### systemd network filtering
+
+Beyond `--listen`, systemd can restrict the unit's network at the
+cgroup level with `IPAddressAllow=` / `IPAddressDeny=` (enforced with
+BPF, applies to both directions, and to anything the unit's processes
+spawn — including the started containers, since they are children of
+the unit's cgroup):
+
+```ini
+# allow only loopback, deny everything else
+IPAddressDeny=any
+IPAddressAllow=localhost
+```
+
+Rules accept addresses, prefixes (`192.168.1.0/24`), and the special
+values `any` and `localhost`.  Order does not matter; the most
+specific match wins.  Combined with `RestrictAddressFamilies=` this
+gives belt-and-braces isolation: even a bug that made the daemon bind
+`0.0.0.0` could not be reached from outside.
+
+Two related options:
+
+* `PrivateNetwork=yes` — gives the unit its own network namespace;
+  then *nothing*, not even the host's loopback, can reach it except
+  via a veth/VRF setup.  Usually too strong for this daemon.
+* `IPAccounting=yes` — counts bytes in/out per unit, useful for
+  auditing.
+
+Note: containers started by the daemon inherit the unit's cgroup and
+thus its IPAddress rules — if containers need real network access,
+keep the rules on the daemon minimal or move started containers to a
+scope with `Delegate=` semantics.
+
+### shepherd (Guix System)
+
+Add a service to the OS configuration:
+
+```scheme
+(simple-service 'guix-container-da shepherd-root-service-type
+  (list (shepherd-service
+          (provision '(guix-container-daemon))
+          (requirement '(user-processes))
+          (start #~(make-forkexec-constructor
+                    (list #$(file-append my-tools "/bin/run-guix-system-container")
+                          "--listen" "127.0.0.1"
+                          "--port" "8989"
+                          "--fingerprint" "v0.1")
+                    #:log-file "/var/log/guix-container-daemon.log"))
+          (stop #~(make-kill-destructor)))))
+```
+
+## Files
+
+* `bin/run-guix-system-container.c` — the daemon.
+* `bin/run-guix-container.rb` — unprivileged client; validates the hash
+  locally before talking to the daemon.
+* `test/` — unit tests for the container-launcher and daemon
+  fingerprint logic (`test/run.sh`).
diff --git a/bin/run-guix-container.rb b/bin/run-guix-container.rb
new file mode 100755
index 0000000..c2e79e3
--- /dev/null
+++ b/bin/run-guix-container.rb
@@ -0,0 +1,176 @@
+#!/usr/bin/env ruby
+# run-guix-container.rb
+#
+# Start (or stop) a Guix system container by its store hash.
+#
+#   ./run-guix-container.rb HASH                # find + run the container
+#   ./run-guix-container.rb /gnu/store/HASH-...  # or a full store path
+#   ./run-guix-container.rb --kill PID           # stop a running container
+#   ./run-guix-container.rb --fingerprint v0.1   # verify the daemon first
+#
+# The script validates that:
+#   * the hash looks like a valid base32 Guix store hash (32 chars)
+#   * exactly one matching, executable container script exists in the store
+#   * the script is a Guix container launcher (uses linux-container)
+#
+# It then starts the container in one of two ways:
+#
+# 1. Network API: if --daemon HOST:PORT (or GUIX_CONTAINER_DAEMON) is
+#    given, it sends 'START <hash>' to a run-guix-system-container
+#    --serve daemon on the underlying host, which validates and starts
+#    the container with root privileges.  With --fingerprint WORD the
+#    daemon's fingerprint is checked first (FINGERPRINT command), so
+#    you never talk to a stale daemon by accident.
+# 2. Local sudo: otherwise it invokes sudo run-guix-system-container,
+#    which performs the same validation locally.
+
+STORE = '/gnu/store'
+LAUNCHER = 'run-guix-system-container'
+DEFAULT_DAEMON = '127.0.0.1:8989'
+HASH_RE = /\A[0-9a-z]{32}\z/
+
+def fail(msg)
+  warn "error: #{msg}"
+  exit 1
+end
+
+require 'socket'
+
+def talk_to_daemon(daemon, request)
+  host, port = daemon.split(':', 2)
+  fail "invalid daemon address: #{daemon}" if host.nil? || port.nil?
+  sock = TCPSocket.new(host, Integer(port))
+  sock.puts request
+  response = sock.gets.to_s.strip
+  sock.close
+  response
+end
+
+# Like talk_to_daemon, but reads the whole (possibly multi-line)
+# response — used for LOG, whose body follows the OK line.
+def fetch_from_daemon(daemon, request)
+  host, port = daemon.split(':', 2)
+  fail "invalid daemon address: #{daemon}" if host.nil? || port.nil?
+  sock = TCPSocket.new(host, Integer(port))
+  sock.puts request
+  sock.read
+ensure
+  sock&.close
+end
+
+# Ask the daemon for its fingerprint and compare it with EXPECTED.
+# Returns the daemon's fingerprint; fails on mismatch or protocol error.
+def verify_fingerprint(daemon, expected)
+  response = talk_to_daemon(daemon, 'FINGERPRINT')
+  fail "daemon fingerprint query failed: #{response}" unless response.start_with?('OK ')
+  got = response.split(' ', 2)[1].to_s
+  fail "daemon fingerprint mismatch: expected #{expected}, got #{got}" unless got == expected
+  got
+end
+
+arg = nil
+kill_pid = nil
+log_arg = nil
+fingerprint = nil
+daemon = ENV['GUIX_CONTAINER_DAEMON']
+
+while !ARGV.empty? && ARGV[0].start_with?('--')
+  case ARGV[0]
+  when '--daemon'
+    daemon = ARGV[1]
+    ARGV.shift(2)
+  when '--kill'
+    kill_pid = ARGV[1]
+    ARGV.shift(2)
+  when '--log'
+    log_arg = ARGV[1]
+    ARGV.shift(2)
+  when '--fingerprint'
+    fingerprint = ARGV[1]
+    ARGV.shift(2)
+  when '--daemon-local'
+    daemon ||= DEFAULT_DAEMON
+    ARGV.shift
+  else
+    fail "unknown option: #{ARGV[0]}"
+  end
+end
+arg = ARGV[0]
+
+# --log HASH: fetch and print a container's log from the daemon.
+if log_arg
+  fail "--log requires a daemon (--daemon HOST:PORT)" unless daemon
+  verify_fingerprint(daemon, fingerprint) if fingerprint
+  hash = log_arg.start_with?(STORE + '/') ? File.basename(log_arg).split('-', 2).first : log_arg
+  fail "not a valid store hash: #{hash}" unless hash =~ HASH_RE
+  out = fetch_from_daemon(daemon, "LOG #{hash}")
+  fail "daemon refused: #{out.lines.first&.strip}" unless out.start_with?("OK\n")
+  print out.split("\n", 2)[1].to_s
+  exit 0
+end
+
+# --kill PID: ask the daemon to terminate a container.
+if kill_pid
+  fail "--kill requires a daemon (--daemon HOST:PORT)" unless daemon
+  verify_fingerprint(daemon, fingerprint) if fingerprint
+  fail "invalid pid: #{kill_pid}" unless kill_pid =~ /\A\d+\z/
+  response = talk_to_daemon(daemon, "KILL #{kill_pid}")
+  puts response
+  fail "daemon refused: #{response}" unless response.start_with?('OK ')
+  exit 0
+end
+
+fail 'usage: run-guix-container.rb [--daemon HOST:PORT] HASH|/gnu/store/HASH-...' if arg.nil?
+
+hash =
+  if arg.start_with?(STORE + '/')
+    File.basename(arg).split('-', 2).first
+  else
+    arg
+  end
+
+fail "not a valid store hash: #{hash}" unless hash =~ HASH_RE
+
+# Collect all store entries starting with the hash. A valid nix-base32
+# hash is 32 chars, so no other store item can share the prefix.
+entries = Dir.glob(File.join(STORE, "#{hash}-*")).sort
+fail "no store item found for hash #{hash}" if entries.empty?
+
+# Only keep real files (the container launcher), not .drv or directories.
+candidates = entries.select do |path|
+  File.file?(path) && File.executable?(path) && !path.end_with?('.drv')
+end
+fail "hash #{hash} matches no executable store item" if candidates.empty?
+fail "hash #{hash} is ambiguous: #{candidates.join(' ')}" if candidates.size > 1
+
+container = candidates.first
+
+# Sanity check: it must be a Guix container launcher script (it uses the
+# (gnu build linux-container) module to set up namespaces).
+head = File.open(container, 'rb') { |f| f.read(4096) }
+fail "#{container} is not a Guix container script" unless head.include?('linux-container')
+
+# Start the container.
+if daemon
+  fp = verify_fingerprint(daemon, fingerprint) if fingerprint
+  puts "Starting container #{hash} via daemon #{daemon}" +
+       (fp ? " (fingerprint #{fp})" : '')
+  response = talk_to_daemon(daemon, "START #{hash}")
+  puts response
+  fail "daemon refused: #{response}" unless response.start_with?('OK ')
+  pid = response.split[1]
+  puts "Container running as PID #{pid}; inspect with:"
+  puts "  nsenter -at #{pid} /run/current-system/profile/bin/bash --login"
+  exit 0
+end
+
+# Local sudo path: the privileged launcher must be installed in PATH
+# (in a root-owned directory such as /usr/local/bin, see README).
+launcher = ENV.fetch('PATH', '').split(File::PATH_SEPARATOR)
+               .map { |d| File.join(d, LAUNCHER) }
+               .find { |p| File.file?(p) && File.executable?(p) }
+fail "launcher not found in PATH: #{LAUNCHER} (see README)" unless launcher
+
+puts "Starting container: #{container}"
+exec 'sudo', '--', launcher, container
+fail "exec failed for #{container}"
diff --git a/bin/run-guix-system-container b/bin/run-guix-system-container
new file mode 100755
index 0000000..a412e40
--- /dev/null
+++ b/bin/run-guix-system-container
Binary files differdiff --git a/bin/run-guix-system-container.c b/bin/run-guix-system-container.c
new file mode 100644
index 0000000..8323e90
--- /dev/null
+++ b/bin/run-guix-system-container.c
@@ -0,0 +1,756 @@
+/* run-guix-system-container.c — daemon that starts Guix system
+ * containers on request, meant to be run as root from shepherd (Guix
+ * System) or systemd (Debian).
+ *
+ * Usage:
+ *   run-guix-system-container [--listen IP] [--port N] [--fingerprint WORD]
+ *
+ * It listens on the given IP (default 127.0.0.1 — loopback only).
+ * Pass an explicit IP such as 0.0.0.0 to listen on all interfaces.
+ *
+ * The daemon has a FINGERPRINT: a short word or version (e.g. "v0.1")
+ * given with --fingerprint, or a random hash generated at startup when
+ * not specified.  Clients can verify they are talking to the daemon
+ * they expect (FINGERPRINT command, or "START <hash> <fingerprint>").
+ * The fingerprint is also passed to started containers in the
+ * GUIX_CONTAINER_FINGERPRINT environment variable, so a container can
+ * show which daemon generation started it (e.g. in /etc/issue).
+ *
+ * When the daemon receives SIGINT or SIGTERM it terminates the
+ * containers it started: SIGTERM, then after a 10 s timeout SIGKILL.
+ *
+ * Protocol (one line per connection):
+ *   START <hash|/gnu/store/HASH-run-container> [<fingerprint>]\n
+ *     → OK <pid>\n     container started
+ *     → ERR <reason>\n validation failure (a non-matching optional
+ *                     fingerprint yields "ERR fingerprint mismatch")
+ *   KILL <pid>\n
+ *     → OK killed <pid>\n  SIGTERM sent
+ *     → ERR <reason>\n   not a known container, etc.
+ *   LOG <hash|/gnu/store/HASH-run-container>\n
+ *     → OK\n + the raw contents of the container's log file
+ *       (LOG_DIR/HASH-run-container.log)
+ *     → ERR <reason>\n   no log file
+ *   FINGERPRINT\n
+ *     → OK <fingerprint>\n  the daemon's fingerprint
+ *
+ * Container stdout/stderr is appended to LOG_DIR (default
+ * /var/log/guix-containers) so boot failures can be diagnosed.
+ *
+ * Before exec'ing a container script it is verified that:
+ *   - the resolved name is exactly HASH-run-container (32-char nix-base32)
+ *   - the script contents reference linux-container
+ *   - the file is a direct child of /gnu/store, executable and immutable
+ *     (no write bits; Guix store items are 0555 root-owned)
+ *
+ * Build:  gcc -O2 -Wall -o run-guix-system-container run-guix-system-container.c
+ */
+
+#include <arpa/inet.h>
+#include <ctype.h>
+#include <dirent.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <netinet/in.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <sys/wait.h>
+#include <sys/socket.h>
+#include <time.h>
+#include <unistd.h>
+#include <stdarg.h>
+#include <stdint.h>
+
+#define PROGRAM "run-guix-system-container"
+#define STORE "/gnu/store/"
+#define DEFAULT_PORT 8989
+#define DEFAULT_LISTEN "127.0.0.1"
+#define MAX_LINE 256
+/* Container stdout/stderr is appended to LOG_DIR/<name>.log. */
+#define LOG_DIR "/var/log/guix-containers"
+
+/* Fingerprint of this daemon instance: a short word or version
+ * ("v0.1") given with --fingerprint, or a random hash when none is
+ * given.  Used to make sure clients talk to the daemon they expect,
+ * and passed to containers via GUIX_CONTAINER_FINGERPRINT. */
+static char daemon_fingerprint[33];
+
+/* Set when SIGINT/SIGTERM asks us to shut down. */
+static volatile sig_atomic_t stop_requested;
+
+static void logmsg(const char *fmt, ...)
+{
+	va_list ap;
+
+	flockfile(stderr);
+	fprintf(stderr, "[%d] ", (int)time(NULL));
+	va_start(ap, fmt);
+	vfprintf(stderr, fmt, ap);
+	va_end(ap);
+	fputc('\n', stderr);
+	funlockfile(stderr);
+}
+
+/* ------------------------------------------------------------------ */
+/* Fingerprint                                                        */
+/* ------------------------------------------------------------------ */
+
+/* A fingerprint must be a short word or version like "v0.1": 1–32
+ * printable characters, no whitespace or control characters. */
+static int valid_fingerprint(const char *s)
+{
+	size_t i, len = strlen(s);
+
+	if (len == 0 || len > sizeof(daemon_fingerprint) - 1)
+		return 0;
+	for (i = 0; i < len; i++)
+		if (isspace((unsigned char)s[i]) ||
+		    iscntrl((unsigned char)s[i]))
+			return 0;
+	return 1;
+}
+
+/* Generate a random 8-char hex fingerprint into daemon_fingerprint. */
+static void random_fingerprint(void)
+{
+	unsigned char rnd[4];
+	int fd = open("/dev/urandom", O_RDONLY);
+	size_t i;
+
+	if (fd < 0 || read(fd, rnd, sizeof(rnd)) != sizeof(rnd)) {
+		/* fallback: mix of time, pid and a stack address */
+		unsigned x = (unsigned)time(NULL) ^ ((unsigned)getpid() << 16) ^
+			(unsigned)(uintptr_t)&rnd;
+
+		for (i = 0; i < sizeof(rnd); i++) {
+			rnd[i] = (unsigned char)x;
+			x = x * 1103515245u + 12345u;
+		}
+	}
+	if (fd >= 0)
+		close(fd);
+	for (i = 0; i < sizeof(rnd); i++)
+		sprintf(daemon_fingerprint + i * 2, "%02x", rnd[i]);
+}
+
+/* ------------------------------------------------------------------ */
+/* Validation                                                          */
+/* ------------------------------------------------------------------ */
+
+static int is_nix_base32_hash(const char *s, size_t n)
+{
+	size_t i;
+
+	if (n != 32)
+		return 0;
+	for (i = 0; i < n; i++)
+		if (!isdigit((unsigned char)s[i]) &&
+		    !(s[i] >= 'a' && s[i] <= 'z'))
+			return 0;
+	return 1;
+}
+
+/* Resolve a 32-char hash to /gnu/store/HASH-run-container.
+ * Returns a malloc'd path or NULL. */
+static char *resolve_container(const char *hash)
+{
+	DIR *dir = opendir(STORE);
+	struct dirent *de;
+	char *found = NULL;
+	size_t prefix_len = strlen(hash) + 1;
+	char prefix[prefix_len + 1];
+
+	if (!dir)
+		return NULL;
+	memcpy(prefix, hash, prefix_len - 1);
+	prefix[prefix_len - 1] = '-';
+	prefix[prefix_len] = '\0';
+
+	while ((de = readdir(dir))) {
+		if (strncmp(de->d_name, prefix, prefix_len) != 0)
+			continue;
+		if (strcmp(de->d_name + prefix_len, "run-container") != 0)
+			continue;
+		if (found) {		/* ambiguous: more than one match */
+			free(found);
+			closedir(dir);
+			return NULL;
+		}
+		if (asprintf(&found, "%s%s", STORE, de->d_name) < 0)
+			found = NULL;
+	}
+	closedir(dir);
+	return found;
+}
+
+/* A generated Guix system container launcher is a guile script with a
+ * distinctive structure.  We require all of the following, so that no
+ * regular store binary or unrelated script passes:
+ *
+ *   1. first line is a guile shebang:
+ *        #!/gnu/store/...-guile-.../bin/guile ...
+ *      (this also rules out ELF binaries, which start with \x7fELF)
+ *   2. it calls (call-with-container ...), the container entry point
+ *   3. it sets GUIX_NEW_SYSTEM, as generated system containers do
+ *   4. it mentions linux-container (the module it uses)
+ */
+static int is_container_script(const char *path, const char *base)
+{
+	const char *dash = strchr(base, '-');
+	char buf[65536];
+	ssize_t n, i;
+	int fd, eol = 0;
+
+	/* The basename must be HASH-run-container: a 32-char nix-base32
+	 * hash, then a dash, then exactly "run-container". */
+	if (!dash || dash - base != 32 || strcmp(dash + 1, "run-container") != 0)
+		return 0;
+	if (!is_nix_base32_hash(base, dash - base))
+		return 0;
+
+	fd = open(path, O_RDONLY);
+	if (fd < 0)
+		return 0;
+	n = read(fd, buf, sizeof(buf) - 1);
+	close(fd);
+	if (n <= 0)
+		return 0;
+	buf[n] = '\0';
+
+	/* 1. guile shebang as the first line. */
+	if (strncmp(buf, "#!/gnu/store/", 13) != 0)
+		return 0;
+	for (i = 13; i < n && buf[i] != '\n'; i++)
+		;
+	if (i >= n)
+		return 0;
+	eol = i;
+	{
+		char shebang[65536];
+
+		memcpy(shebang, buf, eol);
+		shebang[eol] = '\0';
+		if (!strstr(shebang, "-guile-") ||
+		    !strstr(shebang, "/bin/guile"))
+			return 0;
+	}
+
+	/* 2-4. container entry point and generated-system markers. */
+	if (!strstr(buf, "call-with-container"))
+		return 0;
+	if (!strstr(buf, "GUIX_NEW_SYSTEM"))
+		return 0;
+	if (!strstr(buf, "linux-container"))
+		return 0;
+
+	return 1;
+}
+
+/* Full validation of a user-supplied argument (hash or store path).
+ * Returns a malloc'd container path, or NULL with *err pointing at a
+ * static error string. */
+static char *validate(const char *arg, const char **err)
+{
+	char *path, *base;
+	struct stat st;
+	size_t store_len = strlen(STORE);
+
+	*err = "invalid argument";
+	if (is_nix_base32_hash(arg, strlen(arg))) {
+		path = resolve_container(arg);
+		if (!path) {
+			*err = "no unique HASH-run-container found in the store";
+			return NULL;
+		}
+	} else {
+		if (strncmp(arg, STORE, store_len) != 0) {
+			*err = "path must be inside " STORE;
+			return NULL;
+		}
+		if (strchr(arg + store_len, '/')) {
+			*err = "path must be a direct child of " STORE;
+			return NULL;
+		}
+		path = strdup(arg);
+	}
+
+	base = path + store_len;
+
+	if (access(path, X_OK) != 0) {
+		*err = strerror(errno);
+		goto bad;
+	}
+
+	/* The file must be immutable: no write bits at all.  Guix store
+	 * items are created read-only (0555) by the daemon; if any write
+	 * bit is set the file may have been tampered with or replaced,
+	 * and we refuse to exec it. */
+	if (stat(path, &st) != 0) {
+		*err = strerror(errno);
+		goto bad;
+	}
+	if (st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)) {
+		*err = "container script is writable; refusing to run it";
+		goto bad;
+	}
+
+	if (!is_container_script(path, base)) {
+		*err = "not a Guix container launcher (HASH-run-container)";
+		goto bad;
+	}
+
+	return path;
+bad:
+	free(path);
+	return NULL;
+}
+
+/* ------------------------------------------------------------------ */
+/* Started-container tracking (for KILL)                              */
+/* ------------------------------------------------------------------ */
+
+static pid_t *started_pids;
+static size_t started_count, started_cap;
+
+static void track_pid(pid_t pid)
+{
+	if (started_count == started_cap) {
+		size_t cap = started_cap ? started_cap * 2 : 16;
+		pid_t *p = realloc(started_pids, cap * sizeof(*p));
+
+		if (!p)
+			return;		/* non-fatal: KILL falls back to /proc */
+		started_pids = p;
+		started_cap = cap;
+	}
+	started_pids[started_count++] = pid;
+}
+
+static void untrack_pid(pid_t pid)
+{
+	size_t i;
+
+	for (i = 0; i < started_count; i++)
+		if (started_pids[i] == pid) {
+			memmove(&started_pids[i], &started_pids[i + 1],
+				(started_count - i - 1) * sizeof(*started_pids));
+			started_count--;
+			return;
+		}
+}
+
+static int pid_tracked(pid_t pid)
+{
+	size_t i;
+
+	for (i = 0; i < started_count; i++)
+		if (started_pids[i] == pid)
+			return 1;
+	return 0;
+}
+
+/* Is a process still alive?  (kill(0) with EPERM also means alive.) */
+static int pid_alive(pid_t pid)
+{
+	return kill(pid, 0) == 0 || errno != ESRCH;
+}
+
+/* On shutdown, terminate the containers this daemon started: send
+ * SIGTERM to all of them, wait up to 10 s for them to exit, then
+ * SIGKILL the survivors. */
+static void shutdown_containers(void)
+{
+	size_t i;
+	int waited;
+
+	if (started_count == 0)
+		return;
+	logmsg("shutting down %zu container(s)", started_count);
+	for (i = 0; i < started_count; i++)
+		kill(started_pids[i], SIGTERM);
+	for (waited = 0; waited < 100; waited++) {	/* 100 x 100 ms = 10 s */
+		int alive = 0;
+
+		for (i = 0; i < started_count; i++)
+			if (pid_alive(started_pids[i]))
+				alive++;
+		if (alive == 0) {
+			logmsg("all containers exited");
+			return;
+		}
+		usleep(100 * 1000);
+	}
+	for (i = 0; i < started_count; i++)
+		if (pid_alive(started_pids[i])) {
+			logmsg("container %d did not exit within 10 s; sending SIGKILL",
+			       (int)started_pids[i]);
+			kill(started_pids[i], SIGKILL);
+		}
+}
+
+static void handle_stop(int sig)
+{
+	(void)sig;
+	stop_requested = 1;
+}
+
+/* Fallback for PIDs started by a previous daemon instance: the
+ * process must be a /gnu/store/HASH-run-container script. */
+static int pid_is_container(pid_t pid)
+{
+	char path[MAX_LINE], buf[MAX_LINE];
+	int fd;
+	ssize_t n;
+
+	snprintf(path, sizeof(path), "/proc/%d/cmdline", (int)pid);
+	fd = open(path, O_RDONLY);
+	if (fd < 0)
+		return 0;
+	n = read(fd, buf, sizeof(buf) - 1);
+	close(fd);
+	if (n <= 0)
+		return 0;
+	buf[n] = '\0';
+	return strstr(buf, "-run-container") != NULL;
+}
+
+/* Handle "KILL <pid>": terminate a container the daemon started
+ * (or a previous instance started). */
+static void kill_container(int fd, const char *arg, const char *client_ip)
+{
+	char *end;
+	long pid = strtol(arg, &end, 10);
+
+	if (*end || pid <= 1) {
+		dprintf(fd, "ERR invalid pid\n");
+		return;
+	}
+	if (!pid_tracked(pid) && !pid_is_container(pid)) {
+		logmsg("refused to kill %ld from %s: not a container",
+		       pid, client_ip);
+		dprintf(fd, "ERR not a container started by this daemon\n");
+		return;
+	}
+	if (kill((pid_t)pid, SIGTERM) != 0) {
+		logmsg("failed to kill %ld: %s", pid, strerror(errno));
+		dprintf(fd, "ERR %s\n", strerror(errno));
+		return;
+	}
+	untrack_pid((pid_t)pid);
+	logmsg("sent SIGTERM to %ld (client %s)", pid, client_ip);
+	dprintf(fd, "OK killed %ld\n", pid);
+}
+
+/* Handle "LOG <hash|path>": dump the container's log file. */
+static void send_log(int fd, const char *arg)
+{
+	char base[MAX_LINE], logpath[MAX_LINE * 2];
+	char buf[4096];
+	int log, n;
+	const char *slash;
+
+	if (is_nix_base32_hash(arg, strlen(arg))) {
+		snprintf(base, sizeof(base), "%s-run-container", arg);
+	} else {
+		slash = strrchr(arg, '/');
+		snprintf(base, sizeof(base), "%s",
+			 slash ? slash + 1 : arg);
+		if (!strstr(base, "-run-container")) {
+			dprintf(fd, "ERR expected HASH or HASH-run-container\n");
+			return;
+		}
+	}
+
+	snprintf(logpath, sizeof(logpath), "%s/%s.log", LOG_DIR, base);
+	log = open(logpath, O_RDONLY);
+	if (log < 0) {
+		dprintf(fd, "ERR no log for %s (%s)\n", base,
+			 strerror(errno));
+		return;
+	}
+	dprintf(fd, "OK\n");
+	while ((n = read(log, buf, sizeof(buf))) > 0)
+		write(fd, buf, n);
+	close(log);
+}
+
+/* ------------------------------------------------------------------ */
+/* Starting                                                            */
+/* ------------------------------------------------------------------ */
+
+/* Start a validated container script detached; returns its pid, or
+ * -1 on failure.  The container's stdout/stderr is appended to
+ * LOG_DIR/<basename>.log so boot failures can be diagnosed. */
+static pid_t start_container(const char *path)
+{
+	const char *base = strrchr(path, '/');
+	char logpath[MAX_LINE];
+	pid_t pid;
+
+	base = base ? base + 1 : path;
+
+	/* Prepared by the parent (running as root); ignore errors — we
+	 * fall back to /dev/null below. */
+mkdir(LOG_DIR, 0755);
+
+	pid = fork();
+	if (pid < 0)
+		return -1;
+	if (pid == 0) {
+		int devnull = open("/dev/null", O_RDWR);
+		int log = -1;
+
+		/* Let the container know which daemon instance (and thus
+		 * which fingerprint) started it, so it can show it. */
+		setenv("GUIX_CONTAINER_FINGERPRINT", daemon_fingerprint, 1);
+
+		snprintf(logpath, sizeof(logpath), "%s/%s.log", LOG_DIR, base);
+		log = open(logpath, O_WRONLY | O_CREAT | O_APPEND, 0644);
+		if (log >= 0) {
+			dup2(log, STDOUT_FILENO);
+			dup2(log, STDERR_FILENO);
+			if (log > 2)
+				close(log);
+		}
+		if (devnull >= 0) {
+			dup2(devnull, STDIN_FILENO);
+			if (devnull > 2)
+				close(devnull);
+		}
+		setsid();
+		execl(path, path, (char *)NULL);
+		_exit(127);
+	}
+	track_pid(pid);
+	return pid;
+}
+
+/* ------------------------------------------------------------------ */
+/* Server                                                              */
+/* ------------------------------------------------------------------ */
+
+/* Handle one connection: read "START <arg>\n", validate, start, reply. */
+static void handle_connection(int fd, const char *client_ip)
+{
+	char line[MAX_LINE], *p, *arg;
+	char *path;
+	const char *err;
+	pid_t pid;
+	ssize_t n;
+	char *fp_arg;
+
+	n = read(fd, line, sizeof(line) - 1);
+	if (n <= 0)
+		return;
+	line[n] = '\0';
+	p = strpbrk(line, "\r\n");
+	if (p)
+		*p = '\0';
+
+	if (strncmp(line, "FINGERPRINT", 11) == 0) {
+		dprintf(fd, "OK %s\n", daemon_fingerprint);
+		return;
+	}
+	if (strncmp(line, "LOG ", 4) == 0) {
+		send_log(fd, line + 4);
+		return;
+	}
+	if (strncmp(line, "KILL ", 5) == 0) {
+		kill_container(fd, line + 5, client_ip);
+		return;
+	}
+	if (strncmp(line, "START ", 6) != 0) {
+		dprintf(fd, "ERR expected 'START <hash|path> [fingerprint]', 'KILL <pid>', 'LOG <hash>' or 'FINGERPRINT'\n");
+		return;
+	}
+	arg = line + 6;
+
+	/* Optional second token: the fingerprint the client expects
+	 * this daemon to have. */
+	fp_arg = strchr(arg, ' ');
+	if (fp_arg) {
+		*fp_arg++ = '\0';
+		if (strcmp(fp_arg, daemon_fingerprint) != 0) {
+			logmsg("fingerprint mismatch from %s (got '%s')",
+			       client_ip, fp_arg);
+			dprintf(fd, "ERR fingerprint mismatch\n");
+			return;
+		}
+	}
+
+	path = validate(arg, &err);
+	if (!path) {
+		logmsg("rejected '%s' from %s: %s", arg, client_ip, err);
+		dprintf(fd, "ERR %s\n", err);
+		return;
+	}
+
+	pid = start_container(path);
+	if (pid < 0) {
+		logmsg("failed to start %s: %s", path, strerror(errno));
+		dprintf(fd, "ERR failed to start container\n");
+	} else {
+		logmsg("started %s as pid %d (client %s, fingerprint %s)", path,
+		       pid, client_ip, daemon_fingerprint);
+		dprintf(fd, "OK %d\n", pid);
+	}
+	free(path);
+}
+
+static int serve(const char *listen_ip, int port)
+{
+	struct sockaddr_in6 addr6;
+	struct sockaddr_in addr4;
+	struct sockaddr *sa;
+	socklen_t sa_len;
+	int family, srv, one = 1;
+	struct sigaction stop_action;
+
+	signal(SIGCHLD, SIG_IGN);	/* reap children automatically */
+
+	/* Shut down on SIGINT/SIGTERM: kill the containers we started.
+	 * No SA_RESTART, so accept() is interrupted and we notice. */
+	memset(&stop_action, 0, sizeof(stop_action));
+	stop_action.sa_handler = handle_stop;
+	sigemptyset(&stop_action.sa_mask);
+	sigaction(SIGINT, &stop_action, NULL);
+	sigaction(SIGTERM, &stop_action, NULL);
+
+	memset(&addr6, 0, sizeof(addr6));
+	memset(&addr4, 0, sizeof(addr4));
+
+	if (strchr(listen_ip, ':')) {	/* IPv6 address */
+		family = AF_INET6;
+		addr6.sin6_family = AF_INET6;
+		addr6.sin6_port = htons(port);
+		if (inet_pton(AF_INET6, listen_ip, &addr6.sin6_addr) != 1) {
+			fprintf(stderr, "invalid IPv6 address: %s\n",
+				listen_ip);
+			return 1;
+		}
+		sa = (struct sockaddr *)&addr6;
+		sa_len = sizeof(addr6);
+	} else {				/* IPv4 address */
+		family = AF_INET;
+		addr4.sin_family = AF_INET;
+		addr4.sin_port = htons(port);
+		if (inet_pton(AF_INET, listen_ip, &addr4.sin_addr) != 1) {
+			fprintf(stderr, "invalid IPv4 address: %s\n",
+				listen_ip);
+			return 1;
+		}
+		sa = (struct sockaddr *)&addr4;
+		sa_len = sizeof(addr4);
+	}
+
+	srv = socket(family, SOCK_STREAM, 0);
+	if (srv < 0) {
+		perror("socket");
+		return 1;
+	}
+	setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
+	if (family == AF_INET6)
+		setsockopt(srv, IPPROTO_IPV6, IPV6_V6ONLY, &one, sizeof(one));
+
+	if (bind(srv, sa, sa_len) != 0) {
+		perror("bind");
+		return 1;
+	}
+	if (listen(srv, 16) != 0) {
+		perror("listen");
+		return 1;
+	}
+
+	logmsg(PROGRAM " listening on [%s]:%d (fingerprint %s)", listen_ip,
+	       port, daemon_fingerprint);
+
+	for (;;) {
+		struct sockaddr_storage peer;
+		socklen_t peer_len = sizeof(peer);
+		char ip[INET6_ADDRSTRLEN];
+		int fd = accept(srv, (struct sockaddr *)&peer, &peer_len);
+		const void *src;
+
+		if (stop_requested)
+			break;
+		if (fd < 0) {
+			if (errno == EINTR)
+				continue;
+			logmsg("accept: %s", strerror(errno));
+			continue;
+		}
+		src = peer.ss_family == AF_INET6
+			? (void *)&((struct sockaddr_in6 *)&peer)->sin6_addr
+			: (void *)&((struct sockaddr_in *)&peer)->sin_addr;
+		inet_ntop(peer.ss_family, src, ip, sizeof(ip));
+
+		handle_connection(fd, ip);
+		close(fd);
+	}
+	shutdown_containers();
+	logmsg(PROGRAM " exiting");
+	return 0;
+}
+
+/* ------------------------------------------------------------------ */
+
+int main(int argc, char **argv)
+{
+	const char *listen_ip = DEFAULT_LISTEN;
+	const char *fp_opt = NULL;
+	int port = DEFAULT_PORT;
+	int i;
+
+	for (i = 1; i < argc; i++) {
+		if (strcmp(argv[i], "--listen") == 0 && i + 1 < argc) {
+			listen_ip = argv[++i];
+		} else if (strcmp(argv[i], "--port") == 0 && i + 1 < argc) {
+			char *end;
+			long p = strtol(argv[++i], &end, 10);
+
+			if (*end || p <= 0 || p > 65535) {
+				fprintf(stderr, "invalid port: %s\n", argv[i]);
+				return 1;
+			}
+			port = p;
+		} else if (strcmp(argv[i], "--fingerprint") == 0 && i + 1 < argc) {
+			fp_opt = argv[++i];
+		} else {
+			fprintf(stderr,
+				 "usage: %s [--listen IP] [--port N] [--fingerprint WORD]\n"
+				 "  --listen IP        address to listen on (default "
+				 DEFAULT_LISTEN ")\n"
+				 "  --port N           port (default %d)\n"
+				 "  --fingerprint WORD short word or version (e.g. v0.1)\n"
+				 "                     identifying this daemon; containers\n"
+				 "                     started here get it in the\n"
+				 "                     GUIX_CONTAINER_FINGERPRINT variable.\n"
+				 "                     Default: a random hash.\n",
+				 PROGRAM, DEFAULT_PORT);
+			return 1;
+		}
+	}
+
+	if (fp_opt) {
+		if (!valid_fingerprint(fp_opt)) {
+			fprintf(stderr, "invalid fingerprint: '%s' (1-32 printable chars, no whitespace)\n",
+				 fp_opt);
+			return 1;
+		}
+		strncpy(daemon_fingerprint, fp_opt, sizeof(daemon_fingerprint) - 1);
+		daemon_fingerprint[sizeof(daemon_fingerprint) - 1] = '\0';
+	} else {
+		random_fingerprint();
+	}
+
+	if (geteuid() != 0)
+		logmsg("warning: not running as root; containers started "
+		       "by this process may fail to map their user namespace");
+
+	return serve(listen_ip, port);
+}
diff --git a/etc/ssh-container-key b/etc/ssh-container-key
new file mode 100644
index 0000000..e332322
--- /dev/null
+++ b/etc/ssh-container-key
@@ -0,0 +1,8 @@
+-----BEGIN OPENSSH PRIVATE KEY-----
+b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAaAAAABNlY2RzYS
+1zaGEyLW5pc3RwMjU2AAAACG5pc3RwMjU2AAAAQQRU2LDTqGoRXSQBHG6Rem15yUki+5fA
+hxsFQGeRJZaMYpu8qlXFNMVy2gGGCvN52wTXp0nrB0L66goZCoBHMyBVAAAAoOYh7mzmIe
+5sAAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBFTYsNOoahFdJAEc
+bpF6bXnJSSL7l8CHGwVAZ5Elloxim7yqVcU0xXLaAYYK83nbBNenSesHQvrqChkKgEczIF
+UAAAAgVsarkBNdnkKkMYdaCL1geUZ5qLmBHlrBn/iQae35JtAAAAAId3JrQGJvc2E=
+-----END OPENSSH PRIVATE KEY-----
diff --git a/etc/ssh-container-key.pub b/etc/ssh-container-key.pub
new file mode 100644
index 0000000..2bc8d2e
--- /dev/null
+++ b/etc/ssh-container-key.pub
@@ -0,0 +1 @@
+ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBFTYsNOoahFdJAEcbpF6bXnJSSL7l8CHGwVAZ5Elloxim7yqVcU0xXLaAYYK83nbBNenSesHQvrqChkKgEczIFU= wrk@bosa
diff --git a/test/run.sh b/test/run.sh
new file mode 100755
index 0000000..1316bae
--- /dev/null
+++ b/test/run.sh
@@ -0,0 +1,20 @@
+#!/bin/sh
+# run.sh — build and run the run-guix-container unit tests.
+#
+# Usage: ./run.sh
+
+set -e
+
+here=$(cd "$(dirname "$0")" && pwd)
+tmp=$(mktemp -d)
+trap 'rm -rf "$tmp"' EXIT
+
+# Find a real generated container script in the store, if any.
+container=$(ls /gnu/store | grep -E '^[0-9a-z]{32}-run-container$' | head -1)
+if [ -n "$container" ]; then
+    container="/gnu/store/$container"
+fi
+
+cc -O2 -Wall -o "$tmp/test" "$here/test.c"
+
+"$tmp/test" "$container" "$tmp"
diff --git a/test/test.c b/test/test.c
new file mode 100644
index 0000000..18f003f
--- /dev/null
+++ b/test/test.c
@@ -0,0 +1,115 @@
+/* test.c — unit tests for run-guix-system-container.c
+ *
+ * Includes the daemon source with its main() renamed, then exercises
+ * the container-launcher fingerprinting — the security-relevant part
+ * that decides what the daemon will exec.
+ *
+ * Build & run:  ./run.sh
+ */
+
+/* Pull in the daemon under test (main renamed away). */
+#define main daemon_main
+#include "../bin/run-guix-system-container.c"
+#undef main
+
+static int failures;
+
+static void check_str(const char *name, int got, int want)
+{
+	printf("  %-58s %s\n", name, got == want ? "ok" : "FAIL");
+	if (got != want)
+		failures++;
+}
+
+/* ------------------------------------------------------------------ */
+/* Container launcher fingerprint                                      */
+/* ------------------------------------------------------------------ */
+
+static void test_fingerprint(const char *real_container, const char *tmpdir)
+{
+	char fake_shell[MAX_LINE], fake_guile[MAX_LINE];
+	FILE *f;
+
+	/* Fake 1: correct name, plain shell script mentioning the magic
+	 * strings in a comment. */
+	snprintf(fake_shell, sizeof(fake_shell),
+		 "%s/00000000000000000000000000000000-run-container", tmpdir);
+	f = fopen(fake_shell, "w");
+	fprintf(f, "#!/bin/sh\n"
+		  "echo fake; # call-with-container GUIX_NEW_SYSTEM linux-container\n");
+	fclose(f);
+
+	/* Fake 2: correct name, real guile shebang, but no
+	 * call-with-container call. */
+	snprintf(fake_guile, sizeof(fake_guile),
+		 "%s/11111111111111111111111111111111-run-container", tmpdir);
+	f = fopen(fake_guile, "w");
+	fprintf(f, "#!/gnu/store/0000000000000000000000000000000-guile-3.0.9/bin/guile --no-auto-compile\n"
+		  "(display \"not a container\")\n");
+	fclose(f);
+
+	printf("container fingerprint:\n");
+	if (real_container) {
+		const char *slash = strrchr(real_container, '/');
+		char base[MAX_LINE];
+
+		snprintf(base, sizeof(base), "%s",
+			 slash ? slash + 1 : real_container);
+		check_str("real generated container script",
+			  is_container_script(real_container, base), 1);
+	} else {
+		printf("  %-58s %s\n", "real generated container script",
+		       "SKIP (none in store)");
+	}
+
+	check_str("plain shell script with magic strings in a comment",
+		  is_container_script(fake_shell,
+				      "00000000000000000000000000000000-run-container"), 0);
+	check_str("guile script without call-with-container",
+		  is_container_script(fake_guile,
+				      "11111111111111111111111111111111-run-container"), 0);
+}
+
+/* ------------------------------------------------------------------ */
+/* Daemon fingerprint                                                 */
+/* ------------------------------------------------------------------ */
+
+static void test_daemon_fingerprint(void)
+{
+	char first[33];
+
+	printf("daemon fingerprint:\n");
+	check_str("valid: v0.1", valid_fingerprint("v0.1"), 1);
+	check_str("valid: 8 hex chars", valid_fingerprint("abcd1234"), 1);
+	check_str("empty string rejected", valid_fingerprint(""), 0);
+	check_str("too long rejected",
+		  valid_fingerprint("0123456789012345678901234567890123"), 0);
+	check_str("whitespace rejected", valid_fingerprint("v0 1"), 0);
+
+	strcpy(daemon_fingerprint, "");
+	random_fingerprint();
+	check_str("random fingerprint is 8 lowercase hex chars",
+		  strlen(daemon_fingerprint) == 8 &&
+		  strspn(daemon_fingerprint, "0123456789abcdef") == 8, 1);
+	strcpy(first, daemon_fingerprint);
+	random_fingerprint();
+	check_str("two random fingerprints differ",
+		  strcmp(first, daemon_fingerprint) != 0, 1);
+}
+
+/* ------------------------------------------------------------------ */
+
+int main(int argc, char **argv)
+{
+	/* argv[1]: a real *-run-container path in the store (or NULL)
+	 * argv[2]: temp dir for the fake scripts */
+
+	test_daemon_fingerprint();
+	test_fingerprint(argc > 1 ? argv[1] : NULL,
+			 argc > 2 ? argv[2] : "/tmp");
+
+	printf("\n%s (%d failure%s)\n",
+	       failures ? "FAILED" : "ALL TESTS PASSED", failures,
+	       failures == 1 ? "" : "s");
+	return failures != 0;
+}