host: root-runner witness for the tenant syscall filter
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 file changed,
+389
−0
internal/host/syscallfilter_rootrunner_linux_test.go+389 −0
diff --git a/internal/host/syscallfilter_rootrunner_linux_test.go b/internal/host/syscallfilter_rootrunner_linux_test.go| new file mode 100644 |
| index 000000000..03b7b165b |
| --- /dev/null |
| +++ b/internal/host/syscallfilter_rootrunner_linux_test.go |
| @@ -0,0 +1,389 @@ |
| +//go:build linux && rootrunner |
| + |
| +package host |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "net" |
| + "net/http" |
| + "os" |
| + "os/exec" |
| + "os/user" |
| + "path/filepath" |
| + "strings" |
| + "syscall" |
| + "testing" |
| + "time" |
| + "unsafe" |
| + |
| + "golang.org/x/sys/unix" |
| + |
| + "github.com/carlosframework/platform/internal/instanceexec" |
| + "github.com/carlosframework/platform/internal/instancefs" |
| +) |
| + |
| +// TestRootSyscallFilterRuntimes is the kernel witness for the tenant |
| +// syscall filter (#527 Q5). It applies the embedded carlos-instance@ |
| +// namespace block, filter included, to transient units that run each |
| +// supported runtime as carlos and serve HTTP on a unix socket: Go (this |
| +// binary, which also runs the trampoline's own openat2 and Landlock calls |
| +// inside the unit), Node with libuv's io_uring forced on, Python, Ruby and |
| +// PHP. Every one must serve. Inside the units io_uring_setup and keyctl |
| +// must answer ENOSYS; a control unit with the filter lines removed must |
| +// see both reach the kernel, so the witness tells the two apart. |
| +// |
| +// Path-specific lines of the block (binds, InaccessiblePaths) are dropped: |
| +// their sources exist only on an installed box, and they shape mounts, not |
| +// syscalls. Static sites are served by the edge and run no unit. |
| +// |
| +// Network: this test runs apt-get to install the interpreters (Debian |
| +// mirrors). Nothing else leaves the box. |
| +func TestRootSyscallFilterRuntimes(t *testing.T) { |
| + if os.Geteuid() != 0 { |
| + t.Fatal("needs real root") |
| + } |
| + if b, err := os.ReadFile("/proc/1/comm"); err != nil || strings.TrimSpace(string(b)) != "systemd" { |
| + t.Fatalf("needs systemd as PID 1: %q %v", b, err) |
| + } |
| + ctx, cancel := context.WithTimeout(t.Context(), 9*time.Minute) |
| + defer cancel() |
| + sh := func(name string, args ...string) string { |
| + t.Helper() |
| + cmd := exec.CommandContext(ctx, name, args...) |
| + cmd.Env = append(os.Environ(), "DEBIAN_FRONTEND=noninteractive", "LC_ALL=C") |
| + out, err := cmd.CombinedOutput() |
| + if err != nil { |
| + t.Fatalf("%s %v: %v\n%s", name, args, err, out) |
| + } |
| + return string(out) |
| + } |
| + sh("apt-get", "update", "-q") |
| + sh("apt-get", "install", "-y", "-q", "--no-install-recommends", "nodejs", "python3", "ruby", "php-cli") |
| + for _, v := range [][]string{{"node", "--version"}, {"python3", "--version"}, {"ruby", "--version"}, {"php", "--version"}, {"systemctl", "--version"}, {"uname", "-a"}} { |
| + t.Logf("%s: %s", v[0], strings.SplitN(sh(v[0], v[1:]...), "\n", 2)[0]) |
| + } |
| + |
| + // carlos, as on a box; made here (and removed after) when absent. |
| + if _, err := user.Lookup("carlos"); err != nil { |
| + sh("useradd", "--system", "--user-group", "--no-create-home", "--shell", "/usr/sbin/nologin", "carlos") |
| + t.Cleanup(func() { _ = exec.Command("userdel", "carlos").Run() }) |
| + } |
| + // The block's TemporaryFileSystem= mount points, made when absent. |
| + for _, dir := range []string{"/data", "/run/carlos", "/opt/carlos", "/var/cache", "/var/lib"} { |
| + if _, err := os.Stat(dir); errors.Is(err, os.ErrNotExist) { |
| + if err := os.MkdirAll(dir, 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { _ = os.Remove(dir) }) |
| + } |
| + } |
| + |
| + block := syscallWitnessBlock(t) |
| + scratch, err := os.MkdirTemp("/srv", "scf-") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { _ = os.RemoveAll(scratch) }) |
| + if err := os.Chmod(scratch, 0o777); err != nil { |
| + t.Fatal(err) |
| + } |
| + exe, err := os.Executable() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + helper := filepath.Join(scratch, "w.test") |
| + sh("install", "-m", "0755", exe, helper) |
| + scripts := map[string]string{"node": nodeScript, "python": pythonScript, "ruby": rubyScript, "php": phpScript} |
| + for name, body := range scripts { |
| + if err := os.WriteFile(filepath.Join(scratch, name+".src"), []byte(body), 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + // What Landlock's ABI query answers outside any unit, as carlos: the |
| + // trampoline's scope must answer the same inside. |
| + outside := exec.CommandContext(ctx, helper, "-test.run=^TestRootSyscallFilterHelper$") |
| + outside.Env = []string{"SCF_MODE=outside", "SCF_DIR=" + scratch} |
| + outside.SysProcAttr = &syscall.SysProcAttr{Credential: carlosCred(t)} |
| + if out, err := outside.CombinedOutput(); err != nil { |
| + t.Fatalf("outside control: %v\n%s", err, out) |
| + } |
| + |
| + type runtime struct { |
| + name, exec string |
| + jit bool // the rootfs jit drop-in: MemoryDenyWriteExecute=no |
| + filtered bool |
| + } |
| + runtimes := []runtime{ |
| + {"go", helper + " -test.run=^TestRootSyscallFilterHelper$", false, true}, |
| + {"node", "/usr/bin/node " + scratch + "/node.src", true, true}, |
| + {"python", "/usr/bin/python3 " + scratch + "/python.src", false, true}, |
| + {"ruby", "/usr/bin/ruby " + scratch + "/ruby.src", false, true}, |
| + {"php", "/usr/bin/php " + scratch + "/php.src", false, true}, |
| + {"control", helper + " -test.run=^TestRootSyscallFilterHelper$", false, false}, |
| + } |
| + ctl := func(args ...string) (string, error) { |
| + out, err := exec.CommandContext(ctx, "systemctl", args...).CombinedOutput() |
| + return string(out), err |
| + } |
| + for _, rt := range runtimes { |
| + t.Run(rt.name, func(t *testing.T) { |
| + unit := "carlos-scf-" + rt.name + ".service" |
| + path := filepath.Join("/run/systemd/system", unit) |
| + if _, err := os.Lstat(path); !errors.Is(err, os.ErrNotExist) { |
| + t.Fatalf("%s already exists", path) |
| + } |
| + sock := filepath.Join(scratch, rt.name+".sock") |
| + mode := "filtered" |
| + var b strings.Builder |
| + fmt.Fprintf(&b, "[Service]\nType=simple\nUser=carlos\nGroup=carlos\nExecStart=%s\n", rt.exec) |
| + fmt.Fprintf(&b, "Environment=SCF_SOCK=%s SCF_DIR=%s SCF_NAME=%s UV_USE_IO_URING=1\n", sock, scratch, rt.name) |
| + for _, line := range block { |
| + if !rt.filtered && (strings.HasPrefix(line, "SystemCallFilter=") || strings.HasPrefix(line, "SystemCallErrorNumber=")) { |
| + continue |
| + } |
| + b.WriteString(line + "\n") |
| + } |
| + if !rt.filtered { |
| + mode = "control" |
| + } |
| + fmt.Fprintf(&b, "Environment=SCF_MODE=%s\n", mode) |
| + if rt.jit { |
| + b.WriteString("MemoryDenyWriteExecute=no\n") |
| + } |
| + fmt.Fprintf(&b, "BindPaths=%s\nReadWritePaths=%s\nTimeoutStopSec=20\n", scratch, scratch) |
| + if err := os.WriteFile(path, []byte(b.String()), 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { |
| + _, _ = ctl("stop", unit) |
| + _, _ = ctl("reset-failed", unit) |
| + _ = os.Remove(path) |
| + _, _ = ctl("daemon-reload") |
| + }) |
| + if out, err := ctl("daemon-reload"); err != nil { |
| + t.Fatal(out, err) |
| + } |
| + if out, err := ctl("start", unit); err != nil { |
| + t.Fatalf("start: %v %s\n%s", err, out, journalOf(unit)) |
| + } |
| + client := &http.Client{Timeout: 2 * time.Second, Transport: &http.Transport{DialContext: func(c context.Context, _, _ string) (net.Conn, error) { |
| + return (&net.Dialer{}).DialContext(c, "unix", sock) |
| + }}} |
| + deadline := time.Now().Add(60 * time.Second) |
| + for { |
| + resp, err := client.Get("http://app/") |
| + if err == nil { |
| + body, _ := io.ReadAll(resp.Body) |
| + resp.Body.Close() |
| + want := "ok:" + rt.name |
| + if !strings.HasPrefix(string(body), want) { |
| + t.Fatalf("%s answered %q, want %q\n%s", rt.name, body, want, journalOf(unit)) |
| + } |
| + t.Logf("%s served: %s", rt.name, strings.TrimSpace(string(body))) |
| + break |
| + } |
| + if st, _ := ctl("show", unit, "-p", "ActiveState", "--value"); strings.TrimSpace(st) == "failed" || strings.TrimSpace(st) == "inactive" { |
| + t.Fatalf("%s exited before serving: %s\n%s", rt.name, st, journalOf(unit)) |
| + } |
| + if time.Now().After(deadline) { |
| + t.Fatalf("%s never served: %v\n%s", rt.name, err, journalOf(unit)) |
| + } |
| + time.Sleep(100 * time.Millisecond) |
| + } |
| + if !rt.filtered { |
| + return |
| + } |
| + show, _ := ctl("show", unit, "-p", "SystemCallFilter,SystemCallErrorNumber,SystemCallArchitectures") |
| + for _, gone := range []string{"io_uring_setup", "io_uring_enter", "io_uring_register", "keyctl", "add_key", "request_key", "userfaultfd"} { |
| + if strings.Contains(show, " "+gone+" ") || strings.Contains(show, "="+gone+" ") { |
| + t.Errorf("effective allow-list still holds %s", gone) |
| + } |
| + } |
| + if !strings.Contains(show, "openat2") { |
| + t.Errorf("effective allow-list lacks openat2") |
| + } |
| + t.Logf("effective: SystemCallErrorNumber/Architectures: %s", lastLines(show, 2)) |
| + }) |
| + } |
| +} |
| + |
| +// syscallWitnessBlock is the embedded carlos-instance@ namespace block's |
| +// directives, less the path-specific ones, and must hold this build's |
| +// three syscall lines. |
| +func syscallWitnessBlock(t *testing.T) []string { |
| + t.Helper() |
| + raw, err := unitsFS.ReadFile("units/carlos-instance@.service") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + u := string(raw) |
| + start, end := strings.Index(u, "# --- the namespace"), strings.Index(u, "# --- per-service resources") |
| + if start < 0 || end < start { |
| + t.Fatal("namespace block markers missing") |
| + } |
| + var out []string |
| + for _, d := range directives(u[start:end]) { |
| + key, _, _ := strings.Cut(d, "=") |
| + switch key { |
| + case "BindPaths", "BindReadOnlyPaths", "InaccessiblePaths", "ReadWritePaths": |
| + continue |
| + } |
| + if strings.Contains(d, "%") { |
| + continue |
| + } |
| + out = append(out, d) |
| + } |
| + for _, want := range syscallBlock { |
| + found := false |
| + for _, d := range out { |
| + found = found || d == want |
| + } |
| + if !found { |
| + t.Fatalf("this build's block lacks %q", want) |
| + } |
| + } |
| + return out |
| +} |
| + |
| +func carlosCred(t *testing.T) *syscall.Credential { |
| + t.Helper() |
| + u, err := user.Lookup("carlos") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var uid, gid uint32 |
| + fmt.Sscan(u.Uid, &uid) |
| + fmt.Sscan(u.Gid, &gid) |
| + return &syscall.Credential{Uid: uid, Gid: gid} |
| +} |
| + |
| +func journalOf(unit string) string { |
| + out, _ := exec.Command("journalctl", "-u", unit, "--no-pager", "-n", "40", "-o", "cat").CombinedOutput() |
| + return string(out) |
| +} |
| + |
| +func lastLines(s string, n int) string { |
| + lines := strings.Split(strings.TrimSpace(s), "\n") |
| + if len(lines) > n { |
| + lines = lines[len(lines)-n:] |
| + } |
| + return strings.Join(lines, " ") |
| +} |
| + |
| +// TestRootSyscallFilterHelper runs inside the units (and once outside, as |
| +// carlos, for the Landlock control). In a filtered unit io_uring_setup, |
| +// keyctl and userfaultfd answer ENOSYS while instancefs's openat2 and the |
| +// trampoline's Landlock scope behave as they do outside; in the control |
| +// unit io_uring_setup and keyctl reach the kernel. Then it serves. |
| +func TestRootSyscallFilterHelper(t *testing.T) { |
| + mode, dir := os.Getenv("SCF_MODE"), os.Getenv("SCF_DIR") |
| + if mode == "" { |
| + t.Skip("helper only") |
| + } |
| + landlock := filepath.Join(dir, "landlock-outside") |
| + _, _, abiErr := unix.Syscall(unix.SYS_LANDLOCK_CREATE_RULESET, 0, 0, unix.LANDLOCK_CREATE_RULESET_VERSION) |
| + if mode == "outside" { |
| + if err := os.WriteFile(landlock, []byte(abiErr.Error()), 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + return |
| + } |
| + var params [120]byte |
| + _, _, ioErr := unix.Syscall(unix.SYS_IO_URING_SETUP, 0, uintptr(unsafe.Pointer(¶ms)), 0) |
| + _, _, keyErr := unix.Syscall(unix.SYS_KEYCTL, unix.KEYCTL_GET_KEYRING_ID, uintptr(^uint(1)), 0) |
| + _, _, ufErr := unix.Syscall(unix.SYS_USERFAULTFD, 0, 0, 0) |
| + report := fmt.Sprintf("io_uring_setup=%v keyctl=%v userfaultfd=%v", ioErr, keyErr, ufErr) |
| + switch mode { |
| + case "filtered": |
| + if ioErr != unix.ENOSYS || keyErr != unix.ENOSYS || ufErr != unix.ENOSYS { |
| + t.Fatalf("filter not in force: %s", report) |
| + } |
| + if err := instancefs.SelfCheck(dir); err != nil { |
| + t.Fatalf("instancefs openat2 under the filter: %v", err) |
| + } |
| + want, err := os.ReadFile(landlock) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if abiErr.Error() != string(want) { |
| + t.Fatalf("Landlock ABI query inside = %v, outside = %s", abiErr, want) |
| + } |
| + // The trampoline's own scope call, as it runs before every app. |
| + if err := instanceexec.ScopeAbstractUnix(); err != nil && string(want) == unix.Errno(0).Error() { |
| + t.Fatalf("ScopeAbstractUnix under the filter: %v", err) |
| + } |
| + report += fmt.Sprintf(" openat2=ok landlock=%v", abiErr) |
| + case "control": |
| + if ioErr == unix.ENOSYS || keyErr == unix.ENOSYS { |
| + t.Fatalf("control unit refuses without the filter, so the witness cannot tell: %s", report) |
| + } |
| + } |
| + ln, err := net.Listen("unix", os.Getenv("SCF_SOCK")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer ln.Close() |
| + srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { |
| + _, _ = io.WriteString(w, "ok:"+os.Getenv("SCF_NAME")+" "+report) |
| + })} |
| + _ = srv.Serve(ln) |
| +} |
| + |
| +// Each script checks io_uring_setup (425 on every Linux architecture) |
| +// where the language can make a raw call, exercises its async I/O, and |
| +// serves "ok:<name>" on $SCF_SOCK. |
| +const nodeScript = ` |
| +const fs = require('fs'), http = require('http'); |
| +(async () => { |
| + // libuv submits these through io_uring when UV_USE_IO_URING=1 and the |
| + // ring can be made; under the filter it must fall back, not fail. |
| + for (let i = 0; i < 50; i++) await fs.promises.readFile('/etc/os-release'); |
| + await fs.promises.writeFile(process.env.SCF_DIR + '/node.tmp', 'x'); |
| + await fs.promises.unlink(process.env.SCF_DIR + '/node.tmp'); |
| + http.createServer((q, s) => s.end('ok:node ' + process.version)).listen(process.env.SCF_SOCK); |
| +})().catch(e => { console.error(e); process.exit(1); }); |
| +` |
| + |
| +const pythonScript = ` |
| +import ctypes, errno, os, socketserver, http.server, threading |
| +libc = ctypes.CDLL(None, use_errno=True) |
| +buf = ctypes.create_string_buffer(120) |
| +r = libc.syscall(425, 0, buf) |
| +e = ctypes.get_errno() |
| +if r != -1 or e != errno.ENOSYS: |
| + raise SystemExit("io_uring_setup reached the kernel: r=%d errno=%d" % (r, e)) |
| +class H(http.server.BaseHTTPRequestHandler): |
| + def do_GET(self): |
| + b = b"ok:python io_uring_setup=ENOSYS" |
| + self.send_response(200); self.send_header("Content-Length", str(len(b))); self.end_headers(); self.wfile.write(b) |
| + def address_string(self): return "unix" |
| +class S(socketserver.ThreadingMixIn, socketserver.UnixStreamServer): pass |
| +S(os.environ["SCF_SOCK"], H).serve_forever() |
| +` |
| + |
| +const rubyScript = ` |
| +require 'socket' |
| +srv = UNIXServer.new(ENV['SCF_SOCK']) |
| +loop do |
| + Thread.new(srv.accept) do |c| |
| + while (l = c.gets) && l != "\r\n"; end |
| + b = "ok:ruby #{RUBY_VERSION}" |
| + c.write("HTTP/1.1 200 OK\r\nContent-Length: #{b.bytesize}\r\nConnection: close\r\n\r\n#{b}") |
| + c.close |
| + end |
| +end |
| +` |
| + |
| +const phpScript = `<?php |
| +$s = stream_socket_server("unix://" . getenv("SCF_SOCK"), $no, $str); |
| +if (!$s) { fwrite(STDERR, "$str\n"); exit(1); } |
| +while ($c = stream_socket_accept($s, -1)) { |
| + while (($l = fgets($c)) !== false && $l !== "\r\n") {} |
| + $b = "ok:php " . PHP_VERSION; |
| + fwrite($c, "HTTP/1.1 200 OK\r\nContent-Length: " . strlen($b) . "\r\nConnection: close\r\n\r\n" . $b); |
| + fclose($c); |
| +} |
| +` |