aboutsummaryrefslogtreecommitdiffhomepage
path: root/internal/app/setuid
diff options
context:
space:
mode:
authorOphestra <cat@gensokyo.uk>2025-04-12 10:54:24 +0900
committerOphestra <cat@gensokyo.uk>2025-04-12 10:54:24 +0900
commit0d7c1a9a4356614f035225aeb24e66421879a99b (patch)
treec490cfd0f75fbf0218045e277812fb5b6173d4e3 /internal/app/setuid
parentae6f5ede1928c9d0a2d480b6a924914e8599529f (diff)
app: rename app implementation package
Signed-off-by: Ophestra <cat@gensokyo.uk>
Diffstat (limited to 'internal/app/setuid')
-rw-r--r--internal/app/setuid/app.go82
-rw-r--r--internal/app/setuid/app_nixos_test.go142
-rw-r--r--internal/app/setuid/app_pd_test.go223
-rw-r--r--internal/app/setuid/app_stub_test.go134
-rw-r--r--internal/app/setuid/app_test.go148
-rw-r--r--internal/app/setuid/errors.go182
-rw-r--r--internal/app/setuid/export_test.go24
-rw-r--r--internal/app/setuid/process.go195
-rw-r--r--internal/app/setuid/seal.go573
-rw-r--r--internal/app/setuid/shim.go181
-rw-r--r--internal/app/setuid/strings.go19
11 files changed, 1903 insertions, 0 deletions
diff --git a/internal/app/setuid/app.go b/internal/app/setuid/app.go
new file mode 100644
index 00000000..472d06ea
--- /dev/null
+++ b/internal/app/setuid/app.go
@@ -0,0 +1,82 @@
+package setuid
+
+import (
+ "context"
+ "fmt"
+ "log"
+ "sync"
+
+ "git.gensokyo.uk/security/fortify/fst"
+ "git.gensokyo.uk/security/fortify/internal/fmsg"
+ "git.gensokyo.uk/security/fortify/internal/sys"
+)
+
+func New(ctx context.Context, os sys.State) (fst.App, error) {
+ a := new(app)
+ a.sys = os
+ a.ctx = ctx
+
+ id := new(fst.ID)
+ err := fst.NewAppID(id)
+ a.id = newID(id)
+
+ return a, err
+}
+
+func MustNew(ctx context.Context, os sys.State) fst.App {
+ a, err := New(ctx, os)
+ if err != nil {
+ log.Fatalf("cannot create app: %v", err)
+ }
+ return a
+}
+
+type app struct {
+ id *stringPair[fst.ID]
+ sys sys.State
+ ctx context.Context
+
+ *outcome
+ mu sync.RWMutex
+}
+
+func (a *app) ID() fst.ID { a.mu.RLock(); defer a.mu.RUnlock(); return a.id.unwrap() }
+
+func (a *app) String() string {
+ if a == nil {
+ return "(invalid app)"
+ }
+
+ a.mu.RLock()
+ defer a.mu.RUnlock()
+
+ if a.outcome != nil {
+ if a.outcome.user.uid == nil {
+ return fmt.Sprintf("(sealed app %s with invalid uid)", a.id)
+ }
+ return fmt.Sprintf("(sealed app %s as uid %s)", a.id, a.outcome.user.uid)
+ }
+
+ return fmt.Sprintf("(unsealed app %s)", a.id)
+}
+
+func (a *app) Seal(config *fst.Config) (fst.SealedApp, error) {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+
+ if a.outcome != nil {
+ panic("app sealed twice")
+ }
+ if config == nil {
+ return nil, fmsg.WrapError(ErrConfig,
+ "attempted to seal app with nil config")
+ }
+
+ seal := new(outcome)
+ seal.id = a.id
+ err := seal.finalise(a.ctx, a.sys, config)
+ if err == nil {
+ a.outcome = seal
+ }
+ return seal, err
+}
diff --git a/internal/app/setuid/app_nixos_test.go b/internal/app/setuid/app_nixos_test.go
new file mode 100644
index 00000000..6469f235
--- /dev/null
+++ b/internal/app/setuid/app_nixos_test.go
@@ -0,0 +1,142 @@
+package setuid_test
+
+import (
+ "git.gensokyo.uk/security/fortify/acl"
+ "git.gensokyo.uk/security/fortify/dbus"
+ "git.gensokyo.uk/security/fortify/fst"
+ "git.gensokyo.uk/security/fortify/sandbox"
+ "git.gensokyo.uk/security/fortify/system"
+)
+
+var testCasesNixos = []sealTestCase{
+ {
+ "nixos chromium direct wayland", new(stubNixOS),
+ &fst.Config{
+ ID: "org.chromium.Chromium",
+ Path: "/nix/store/yqivzpzzn7z5x0lq9hmbzygh45d8rhqd-chromium-start",
+ Confinement: fst.ConfinementConfig{
+ AppID: 1, Groups: []string{}, Username: "u0_a1",
+ Outer: "/var/lib/persist/module/fortify/0/1",
+ Sandbox: &fst.SandboxConfig{
+ Userns: true, Net: true, MapRealUID: true, DirectWayland: true, Env: nil, AutoEtc: true,
+ Filesystem: []*fst.FilesystemConfig{
+ {Src: "/bin", Must: true}, {Src: "/usr/bin", Must: true},
+ {Src: "/nix/store", Must: true}, {Src: "/run/current-system", Must: true},
+ {Src: "/sys/block"}, {Src: "/sys/bus"}, {Src: "/sys/class"}, {Src: "/sys/dev"}, {Src: "/sys/devices"},
+ {Src: "/run/opengl-driver", Must: true}, {Src: "/dev/dri", Device: true},
+ },
+ Cover: []string{"/var/run/nscd"},
+ },
+ SystemBus: &dbus.Config{
+ Talk: []string{"org.bluez", "org.freedesktop.Avahi", "org.freedesktop.UPower"},
+ Filter: true,
+ },
+ SessionBus: &dbus.Config{
+ Talk: []string{
+ "org.freedesktop.FileManager1", "org.freedesktop.Notifications",
+ "org.freedesktop.ScreenSaver", "org.freedesktop.secrets",
+ "org.kde.kwalletd5", "org.kde.kwalletd6",
+ },
+ Own: []string{
+ "org.chromium.Chromium.*",
+ "org.mpris.MediaPlayer2.org.chromium.Chromium.*",
+ "org.mpris.MediaPlayer2.chromium.*",
+ },
+ Call: map[string]string{}, Broadcast: map[string]string{},
+ Filter: true,
+ },
+ Enablements: system.EWayland | system.EDBus | system.EPulse,
+ },
+ },
+ fst.ID{
+ 0x8e, 0x2c, 0x76, 0xb0,
+ 0x66, 0xda, 0xbe, 0x57,
+ 0x4c, 0xf0, 0x73, 0xbd,
+ 0xb4, 0x6e, 0xb5, 0xc1,
+ },
+ system.New(1000001).
+ Ensure("/tmp/fortify.1971", 0711).
+ Ensure("/tmp/fortify.1971/tmpdir", 0700).UpdatePermType(system.User, "/tmp/fortify.1971/tmpdir", acl.Execute).
+ Ensure("/tmp/fortify.1971/tmpdir/1", 01700).UpdatePermType(system.User, "/tmp/fortify.1971/tmpdir/1", acl.Read, acl.Write, acl.Execute).
+ Ensure("/run/user/1971/fortify", 0700).UpdatePermType(system.User, "/run/user/1971/fortify", acl.Execute).
+ Ensure("/run/user/1971", 0700).UpdatePermType(system.User, "/run/user/1971", acl.Execute). // this is ordered as is because the previous Ensure only calls mkdir if XDG_RUNTIME_DIR is unset
+ UpdatePermType(system.EWayland, "/run/user/1971/wayland-0", acl.Read, acl.Write, acl.Execute).
+ Ephemeral(system.Process, "/run/user/1971/fortify/8e2c76b066dabe574cf073bdb46eb5c1", 0700).UpdatePermType(system.Process, "/run/user/1971/fortify/8e2c76b066dabe574cf073bdb46eb5c1", acl.Execute).
+ Link("/run/user/1971/pulse/native", "/run/user/1971/fortify/8e2c76b066dabe574cf073bdb46eb5c1/pulse").
+ CopyFile(nil, "/home/ophestra/xdg/config/pulse/cookie", 256, 256).
+ Ephemeral(system.Process, "/tmp/fortify.1971/8e2c76b066dabe574cf073bdb46eb5c1", 0711).
+ MustProxyDBus("/tmp/fortify.1971/8e2c76b066dabe574cf073bdb46eb5c1/bus", &dbus.Config{
+ Talk: []string{
+ "org.freedesktop.FileManager1", "org.freedesktop.Notifications",
+ "org.freedesktop.ScreenSaver", "org.freedesktop.secrets",
+ "org.kde.kwalletd5", "org.kde.kwalletd6",
+ },
+ Own: []string{
+ "org.chromium.Chromium.*",
+ "org.mpris.MediaPlayer2.org.chromium.Chromium.*",
+ "org.mpris.MediaPlayer2.chromium.*",
+ },
+ Call: map[string]string{}, Broadcast: map[string]string{},
+ Filter: true,
+ }, "/tmp/fortify.1971/8e2c76b066dabe574cf073bdb46eb5c1/system_bus_socket", &dbus.Config{
+ Talk: []string{
+ "org.bluez",
+ "org.freedesktop.Avahi",
+ "org.freedesktop.UPower",
+ },
+ Filter: true,
+ }).
+ UpdatePerm("/tmp/fortify.1971/8e2c76b066dabe574cf073bdb46eb5c1/bus", acl.Read, acl.Write).
+ UpdatePerm("/tmp/fortify.1971/8e2c76b066dabe574cf073bdb46eb5c1/system_bus_socket", acl.Read, acl.Write),
+ &sandbox.Params{
+ Uid: 1971,
+ Gid: 100,
+ Flags: sandbox.FAllowNet | sandbox.FAllowUserns,
+ Dir: "/var/lib/persist/module/fortify/0/1",
+ Path: "/nix/store/yqivzpzzn7z5x0lq9hmbzygh45d8rhqd-chromium-start",
+ Args: []string{"/nix/store/yqivzpzzn7z5x0lq9hmbzygh45d8rhqd-chromium-start"},
+ Env: []string{
+ "DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1971/bus",
+ "DBUS_SYSTEM_BUS_ADDRESS=unix:path=/run/dbus/system_bus_socket",
+ "HOME=/var/lib/persist/module/fortify/0/1",
+ "PULSE_COOKIE=" + fst.Tmp + "/pulse-cookie",
+ "PULSE_SERVER=unix:/run/user/1971/pulse/native",
+ "SHELL=/run/current-system/sw/bin/zsh",
+ "TERM=xterm-256color",
+ "USER=u0_a1",
+ "WAYLAND_DISPLAY=wayland-0",
+ "XDG_RUNTIME_DIR=/run/user/1971",
+ "XDG_SESSION_CLASS=user",
+ "XDG_SESSION_TYPE=tty",
+ },
+ Ops: new(sandbox.Ops).
+ Proc("/proc").
+ Tmpfs(fst.Tmp, 4096, 0755).
+ Dev("/dev").Mqueue("/dev/mqueue").
+ Bind("/bin", "/bin", 0).
+ Bind("/usr/bin", "/usr/bin", 0).
+ Bind("/nix/store", "/nix/store", 0).
+ Bind("/run/current-system", "/run/current-system", 0).
+ Bind("/sys/block", "/sys/block", sandbox.BindOptional).
+ Bind("/sys/bus", "/sys/bus", sandbox.BindOptional).
+ Bind("/sys/class", "/sys/class", sandbox.BindOptional).
+ Bind("/sys/dev", "/sys/dev", sandbox.BindOptional).
+ Bind("/sys/devices", "/sys/devices", sandbox.BindOptional).
+ Bind("/run/opengl-driver", "/run/opengl-driver", 0).
+ Bind("/dev/dri", "/dev/dri", sandbox.BindDevice|sandbox.BindWritable|sandbox.BindOptional).
+ Etc("/etc", "8e2c76b066dabe574cf073bdb46eb5c1").
+ Tmpfs("/run/user", 4096, 0755).
+ Tmpfs("/run/user/1971", 8388608, 0700).
+ Bind("/tmp/fortify.1971/tmpdir/1", "/tmp", sandbox.BindWritable).
+ Bind("/var/lib/persist/module/fortify/0/1", "/var/lib/persist/module/fortify/0/1", sandbox.BindWritable).
+ Place("/etc/passwd", []byte("u0_a1:x:1971:100:Fortify:/var/lib/persist/module/fortify/0/1:/run/current-system/sw/bin/zsh\n")).
+ Place("/etc/group", []byte("fortify:x:100:\n")).
+ Bind("/run/user/1971/wayland-0", "/run/user/1971/wayland-0", 0).
+ Bind("/run/user/1971/fortify/8e2c76b066dabe574cf073bdb46eb5c1/pulse", "/run/user/1971/pulse/native", 0).
+ Place(fst.Tmp+"/pulse-cookie", nil).
+ Bind("/tmp/fortify.1971/8e2c76b066dabe574cf073bdb46eb5c1/bus", "/run/user/1971/bus", 0).
+ Bind("/tmp/fortify.1971/8e2c76b066dabe574cf073bdb46eb5c1/system_bus_socket", "/run/dbus/system_bus_socket", 0).
+ Tmpfs("/var/run/nscd", 8192, 0755),
+ },
+ },
+}
diff --git a/internal/app/setuid/app_pd_test.go b/internal/app/setuid/app_pd_test.go
new file mode 100644
index 00000000..c4ab5797
--- /dev/null
+++ b/internal/app/setuid/app_pd_test.go
@@ -0,0 +1,223 @@
+package setuid_test
+
+import (
+ "os"
+
+ "git.gensokyo.uk/security/fortify/acl"
+ "git.gensokyo.uk/security/fortify/dbus"
+ "git.gensokyo.uk/security/fortify/fst"
+ "git.gensokyo.uk/security/fortify/sandbox"
+ "git.gensokyo.uk/security/fortify/system"
+)
+
+var testCasesPd = []sealTestCase{
+ {
+ "nixos permissive defaults no enablements", new(stubNixOS),
+ &fst.Config{
+ Confinement: fst.ConfinementConfig{
+ AppID: 0,
+ Username: "chronos",
+ Outer: "/home/chronos",
+ },
+ },
+ fst.ID{
+ 0x4a, 0x45, 0x0b, 0x65,
+ 0x96, 0xd7, 0xbc, 0x15,
+ 0xbd, 0x01, 0x78, 0x0e,
+ 0xb9, 0xa6, 0x07, 0xac,
+ },
+ system.New(1000000).
+ Ensure("/tmp/fortify.1971", 0711).
+ Ensure("/tmp/fortify.1971/tmpdir", 0700).UpdatePermType(system.User, "/tmp/fortify.1971/tmpdir", acl.Execute).
+ Ensure("/tmp/fortify.1971/tmpdir/0", 01700).UpdatePermType(system.User, "/tmp/fortify.1971/tmpdir/0", acl.Read, acl.Write, acl.Execute),
+ &sandbox.Params{
+ Flags: sandbox.FAllowNet | sandbox.FAllowUserns | sandbox.FAllowTTY,
+ Dir: "/home/chronos",
+ Path: "/run/current-system/sw/bin/zsh",
+ Args: []string{"/run/current-system/sw/bin/zsh"},
+ Env: []string{
+ "HOME=/home/chronos",
+ "SHELL=/run/current-system/sw/bin/zsh",
+ "TERM=xterm-256color",
+ "USER=chronos",
+ "XDG_RUNTIME_DIR=/run/user/65534",
+ "XDG_SESSION_CLASS=user",
+ "XDG_SESSION_TYPE=tty",
+ },
+ Ops: new(sandbox.Ops).
+ Proc("/proc").
+ Tmpfs(fst.Tmp, 4096, 0755).
+ Dev("/dev").Mqueue("/dev/mqueue").
+ Bind("/bin", "/bin", sandbox.BindWritable).
+ Bind("/boot", "/boot", sandbox.BindWritable).
+ Bind("/home", "/home", sandbox.BindWritable).
+ Bind("/lib", "/lib", sandbox.BindWritable).
+ Bind("/lib64", "/lib64", sandbox.BindWritable).
+ Bind("/nix", "/nix", sandbox.BindWritable).
+ Bind("/root", "/root", sandbox.BindWritable).
+ Bind("/run", "/run", sandbox.BindWritable).
+ Bind("/srv", "/srv", sandbox.BindWritable).
+ Bind("/sys", "/sys", sandbox.BindWritable).
+ Bind("/usr", "/usr", sandbox.BindWritable).
+ Bind("/var", "/var", sandbox.BindWritable).
+ Bind("/dev/kvm", "/dev/kvm", sandbox.BindWritable|sandbox.BindDevice|sandbox.BindOptional).
+ Tmpfs("/run/user/1971", 8192, 0755).
+ Tmpfs("/run/dbus", 8192, 0755).
+ Etc("/etc", "4a450b6596d7bc15bd01780eb9a607ac").
+ Tmpfs("/run/user", 4096, 0755).
+ Tmpfs("/run/user/65534", 8388608, 0700).
+ Bind("/tmp/fortify.1971/tmpdir/0", "/tmp", sandbox.BindWritable).
+ Bind("/home/chronos", "/home/chronos", sandbox.BindWritable).
+ Place("/etc/passwd", []byte("chronos:x:65534:65534:Fortify:/home/chronos:/run/current-system/sw/bin/zsh\n")).
+ Place("/etc/group", []byte("fortify:x:65534:\n")).
+ Tmpfs("/var/run/nscd", 8192, 0755),
+ },
+ },
+ {
+ "nixos permissive defaults chromium", new(stubNixOS),
+ &fst.Config{
+ ID: "org.chromium.Chromium",
+ Args: []string{"zsh", "-c", "exec chromium "},
+ Confinement: fst.ConfinementConfig{
+ AppID: 9,
+ Groups: []string{"video"},
+ Username: "chronos",
+ Outer: "/home/chronos",
+ SessionBus: &dbus.Config{
+ Talk: []string{
+ "org.freedesktop.Notifications",
+ "org.freedesktop.FileManager1",
+ "org.freedesktop.ScreenSaver",
+ "org.freedesktop.secrets",
+ "org.kde.kwalletd5",
+ "org.kde.kwalletd6",
+ "org.gnome.SessionManager",
+ },
+ Own: []string{
+ "org.chromium.Chromium.*",
+ "org.mpris.MediaPlayer2.org.chromium.Chromium.*",
+ "org.mpris.MediaPlayer2.chromium.*",
+ },
+ Call: map[string]string{
+ "org.freedesktop.portal.*": "*",
+ },
+ Broadcast: map[string]string{
+ "org.freedesktop.portal.*": "@/org/freedesktop/portal/*",
+ },
+ Filter: true,
+ },
+ SystemBus: &dbus.Config{
+ Talk: []string{
+ "org.bluez",
+ "org.freedesktop.Avahi",
+ "org.freedesktop.UPower",
+ },
+ Filter: true,
+ },
+ Enablements: system.EWayland | system.EDBus | system.EPulse,
+ },
+ },
+ fst.ID{
+ 0xeb, 0xf0, 0x83, 0xd1,
+ 0xb1, 0x75, 0x91, 0x17,
+ 0x82, 0xd4, 0x13, 0x36,
+ 0x9b, 0x64, 0xce, 0x7c,
+ },
+ system.New(1000009).
+ Ensure("/tmp/fortify.1971", 0711).
+ Ensure("/tmp/fortify.1971/tmpdir", 0700).UpdatePermType(system.User, "/tmp/fortify.1971/tmpdir", acl.Execute).
+ Ensure("/tmp/fortify.1971/tmpdir/9", 01700).UpdatePermType(system.User, "/tmp/fortify.1971/tmpdir/9", acl.Read, acl.Write, acl.Execute).
+ Ephemeral(system.Process, "/tmp/fortify.1971/ebf083d1b175911782d413369b64ce7c", 0711).
+ Wayland(new(*os.File), "/tmp/fortify.1971/ebf083d1b175911782d413369b64ce7c/wayland", "/run/user/1971/wayland-0", "org.chromium.Chromium", "ebf083d1b175911782d413369b64ce7c").
+ Ensure("/run/user/1971/fortify", 0700).UpdatePermType(system.User, "/run/user/1971/fortify", acl.Execute).
+ Ensure("/run/user/1971", 0700).UpdatePermType(system.User, "/run/user/1971", acl.Execute). // this is ordered as is because the previous Ensure only calls mkdir if XDG_RUNTIME_DIR is unset
+ Ephemeral(system.Process, "/run/user/1971/fortify/ebf083d1b175911782d413369b64ce7c", 0700).UpdatePermType(system.Process, "/run/user/1971/fortify/ebf083d1b175911782d413369b64ce7c", acl.Execute).
+ Link("/run/user/1971/pulse/native", "/run/user/1971/fortify/ebf083d1b175911782d413369b64ce7c/pulse").
+ CopyFile(new([]byte), "/home/ophestra/xdg/config/pulse/cookie", 256, 256).
+ MustProxyDBus("/tmp/fortify.1971/ebf083d1b175911782d413369b64ce7c/bus", &dbus.Config{
+ Talk: []string{
+ "org.freedesktop.Notifications",
+ "org.freedesktop.FileManager1",
+ "org.freedesktop.ScreenSaver",
+ "org.freedesktop.secrets",
+ "org.kde.kwalletd5",
+ "org.kde.kwalletd6",
+ "org.gnome.SessionManager",
+ },
+ Own: []string{
+ "org.chromium.Chromium.*",
+ "org.mpris.MediaPlayer2.org.chromium.Chromium.*",
+ "org.mpris.MediaPlayer2.chromium.*",
+ },
+ Call: map[string]string{
+ "org.freedesktop.portal.*": "*",
+ },
+ Broadcast: map[string]string{
+ "org.freedesktop.portal.*": "@/org/freedesktop/portal/*",
+ },
+ Filter: true,
+ }, "/tmp/fortify.1971/ebf083d1b175911782d413369b64ce7c/system_bus_socket", &dbus.Config{
+ Talk: []string{
+ "org.bluez",
+ "org.freedesktop.Avahi",
+ "org.freedesktop.UPower",
+ },
+ Filter: true,
+ }).
+ UpdatePerm("/tmp/fortify.1971/ebf083d1b175911782d413369b64ce7c/bus", acl.Read, acl.Write).
+ UpdatePerm("/tmp/fortify.1971/ebf083d1b175911782d413369b64ce7c/system_bus_socket", acl.Read, acl.Write),
+ &sandbox.Params{
+ Flags: sandbox.FAllowNet | sandbox.FAllowUserns | sandbox.FAllowTTY,
+ Dir: "/home/chronos",
+ Path: "/run/current-system/sw/bin/zsh",
+ Args: []string{"zsh", "-c", "exec chromium "},
+ Env: []string{
+ "DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/65534/bus",
+ "DBUS_SYSTEM_BUS_ADDRESS=unix:path=/run/dbus/system_bus_socket",
+ "HOME=/home/chronos",
+ "PULSE_COOKIE=" + fst.Tmp + "/pulse-cookie",
+ "PULSE_SERVER=unix:/run/user/65534/pulse/native",
+ "SHELL=/run/current-system/sw/bin/zsh",
+ "TERM=xterm-256color",
+ "USER=chronos",
+ "WAYLAND_DISPLAY=wayland-0",
+ "XDG_RUNTIME_DIR=/run/user/65534",
+ "XDG_SESSION_CLASS=user",
+ "XDG_SESSION_TYPE=tty",
+ },
+ Ops: new(sandbox.Ops).
+ Proc("/proc").
+ Tmpfs(fst.Tmp, 4096, 0755).
+ Dev("/dev").Mqueue("/dev/mqueue").
+ Bind("/bin", "/bin", sandbox.BindWritable).
+ Bind("/boot", "/boot", sandbox.BindWritable).
+ Bind("/home", "/home", sandbox.BindWritable).
+ Bind("/lib", "/lib", sandbox.BindWritable).
+ Bind("/lib64", "/lib64", sandbox.BindWritable).
+ Bind("/nix", "/nix", sandbox.BindWritable).
+ Bind("/root", "/root", sandbox.BindWritable).
+ Bind("/run", "/run", sandbox.BindWritable).
+ Bind("/srv", "/srv", sandbox.BindWritable).
+ Bind("/sys", "/sys", sandbox.BindWritable).
+ Bind("/usr", "/usr", sandbox.BindWritable).
+ Bind("/var", "/var", sandbox.BindWritable).
+ Bind("/dev/dri", "/dev/dri", sandbox.BindWritable|sandbox.BindDevice|sandbox.BindOptional).
+ Bind("/dev/kvm", "/dev/kvm", sandbox.BindWritable|sandbox.BindDevice|sandbox.BindOptional).
+ Tmpfs("/run/user/1971", 8192, 0755).
+ Tmpfs("/run/dbus", 8192, 0755).
+ Etc("/etc", "ebf083d1b175911782d413369b64ce7c").
+ Tmpfs("/run/user", 4096, 0755).
+ Tmpfs("/run/user/65534", 8388608, 0700).
+ Bind("/tmp/fortify.1971/tmpdir/9", "/tmp", sandbox.BindWritable).
+ Bind("/home/chronos", "/home/chronos", sandbox.BindWritable).
+ Place("/etc/passwd", []byte("chronos:x:65534:65534:Fortify:/home/chronos:/run/current-system/sw/bin/zsh\n")).
+ Place("/etc/group", []byte("fortify:x:65534:\n")).
+ Bind("/tmp/fortify.1971/ebf083d1b175911782d413369b64ce7c/wayland", "/run/user/65534/wayland-0", 0).
+ Bind("/run/user/1971/fortify/ebf083d1b175911782d413369b64ce7c/pulse", "/run/user/65534/pulse/native", 0).
+ Place(fst.Tmp+"/pulse-cookie", nil).
+ Bind("/tmp/fortify.1971/ebf083d1b175911782d413369b64ce7c/bus", "/run/user/65534/bus", 0).
+ Bind("/tmp/fortify.1971/ebf083d1b175911782d413369b64ce7c/system_bus_socket", "/run/dbus/system_bus_socket", 0).
+ Tmpfs("/var/run/nscd", 8192, 0755),
+ },
+ },
+}
diff --git a/internal/app/setuid/app_stub_test.go b/internal/app/setuid/app_stub_test.go
new file mode 100644
index 00000000..0b414f25
--- /dev/null
+++ b/internal/app/setuid/app_stub_test.go
@@ -0,0 +1,134 @@
+package setuid_test
+
+import (
+ "fmt"
+ "io/fs"
+ "log"
+ "os/user"
+ "strconv"
+
+ "git.gensokyo.uk/security/fortify/fst"
+)
+
+// fs methods are not implemented using a real FS
+// to help better understand filesystem access behaviour
+type stubNixOS struct {
+ lookPathErr map[string]error
+ usernameErr map[string]error
+}
+
+func (s *stubNixOS) Getuid() int { return 1971 }
+func (s *stubNixOS) Getgid() int { return 100 }
+func (s *stubNixOS) TempDir() string { return "/tmp" }
+func (s *stubNixOS) MustExecutable() string { return "/run/wrappers/bin/fortify" }
+func (s *stubNixOS) Exit(code int) { panic("called exit on stub with code " + strconv.Itoa(code)) }
+func (s *stubNixOS) EvalSymlinks(path string) (string, error) { return path, nil }
+func (s *stubNixOS) Uid(aid int) (int, error) { return 1000000 + 0*10000 + aid, nil }
+
+func (s *stubNixOS) Println(v ...any) { log.Println(v...) }
+func (s *stubNixOS) Printf(format string, v ...any) { log.Printf(format, v...) }
+
+func (s *stubNixOS) LookupEnv(key string) (string, bool) {
+ switch key {
+ case "SHELL":
+ return "/run/current-system/sw/bin/zsh", true
+ case "TERM":
+ return "xterm-256color", true
+ case "WAYLAND_DISPLAY":
+ return "wayland-0", true
+ case "PULSE_COOKIE":
+ return "", false
+ case "HOME":
+ return "/home/ophestra", true
+ case "XDG_CONFIG_HOME":
+ return "/home/ophestra/xdg/config", true
+ default:
+ panic(fmt.Sprintf("attempted to access unexpected environment variable %q", key))
+ }
+}
+
+func (s *stubNixOS) LookPath(file string) (string, error) {
+ if s.lookPathErr != nil {
+ if err, ok := s.lookPathErr[file]; ok {
+ return "", err
+ }
+ }
+
+ switch file {
+ case "zsh":
+ return "/run/current-system/sw/bin/zsh", nil
+ default:
+ panic(fmt.Sprintf("attempted to look up unexpected executable %q", file))
+ }
+}
+
+func (s *stubNixOS) LookupGroup(name string) (*user.Group, error) {
+ switch name {
+ case "video":
+ return &user.Group{Gid: "26", Name: "video"}, nil
+ default:
+ return nil, user.UnknownGroupError(name)
+ }
+}
+
+func (s *stubNixOS) ReadDir(name string) ([]fs.DirEntry, error) {
+ switch name {
+ case "/":
+ return stubDirEntries("bin", "boot", "dev", "etc", "home", "lib",
+ "lib64", "nix", "proc", "root", "run", "srv", "sys", "tmp", "usr", "var")
+ case "/run":
+ return stubDirEntries("agetty.reload", "binfmt", "booted-system",
+ "credentials", "cryptsetup", "current-system", "dbus", "host", "keys",
+ "libvirt", "libvirtd.pid", "lock", "log", "lvm", "mount", "NetworkManager",
+ "nginx", "nixos", "nscd", "opengl-driver", "pppd", "resolvconf", "sddm",
+ "store", "syncoid", "system", "systemd", "tmpfiles.d", "udev", "udisks2",
+ "user", "utmp", "virtlogd.pid", "wrappers", "zed.pid", "zed.state")
+ case "/etc":
+ return stubDirEntries("alsa", "bashrc", "binfmt.d", "dbus-1", "default",
+ "ethertypes", "fonts", "fstab", "fuse.conf", "group", "host.conf", "hostid",
+ "hostname", "hostname.CHECKSUM", "hosts", "inputrc", "ipsec.d", "issue", "kbd",
+ "libblockdev", "locale.conf", "localtime", "login.defs", "lsb-release", "lvm",
+ "machine-id", "man_db.conf", "modprobe.d", "modules-load.d", "mtab", "nanorc",
+ "netgroup", "NetworkManager", "nix", "nixos", "NIXOS", "nscd.conf", "nsswitch.conf",
+ "opensnitchd", "os-release", "pam", "pam.d", "passwd", "pipewire", "pki", "polkit-1",
+ "profile", "protocols", "qemu", "resolv.conf", "resolvconf.conf", "rpc", "samba",
+ "sddm.conf", "secureboot", "services", "set-environment", "shadow", "shells", "ssh",
+ "ssl", "static", "subgid", "subuid", "sudoers", "sysctl.d", "systemd", "terminfo",
+ "tmpfiles.d", "udev", "udisks2", "UPower", "vconsole.conf", "X11", "zfs", "zinputrc",
+ "zoneinfo", "zprofile", "zshenv", "zshrc")
+ default:
+ panic(fmt.Sprintf("attempted to read unexpected directory %q", name))
+ }
+}
+
+func (s *stubNixOS) Stat(name string) (fs.FileInfo, error) {
+ switch name {
+ case "/var/run/nscd":
+ return nil, nil
+ case "/run/user/1971/pulse":
+ return nil, nil
+ case "/run/user/1971/pulse/native":
+ return stubFileInfoMode(0666), nil
+ case "/home/ophestra/.pulse-cookie":
+ return stubFileInfoIsDir(true), nil
+ case "/home/ophestra/xdg/config/pulse/cookie":
+ return stubFileInfoIsDir(false), nil
+ default:
+ panic(fmt.Sprintf("attempted to stat unexpected path %q", name))
+ }
+}
+
+func (s *stubNixOS) Open(name string) (fs.File, error) {
+ switch name {
+ default:
+ panic(fmt.Sprintf("attempted to open unexpected file %q", name))
+ }
+}
+
+func (s *stubNixOS) Paths() fst.Paths {
+ return fst.Paths{
+ SharePath: "/tmp/fortify.1971",
+ RuntimePath: "/run/user/1971",
+ RunDirPath: "/run/user/1971/fortify",
+ }
+}
diff --git a/internal/app/setuid/app_test.go b/internal/app/setuid/app_test.go
new file mode 100644
index 00000000..4454e6ff
--- /dev/null
+++ b/internal/app/setuid/app_test.go
@@ -0,0 +1,148 @@
+package setuid_test
+
+import (
+ "encoding/json"
+ "io/fs"
+ "reflect"
+ "testing"
+ "time"
+
+ "git.gensokyo.uk/security/fortify/fst"
+ "git.gensokyo.uk/security/fortify/internal/app/setuid"
+ "git.gensokyo.uk/security/fortify/internal/sys"
+ "git.gensokyo.uk/security/fortify/sandbox"
+ "git.gensokyo.uk/security/fortify/system"
+)
+
+type sealTestCase struct {
+ name string
+ os sys.State
+ config *fst.Config
+ id fst.ID
+ wantSys *system.I
+ wantContainer *sandbox.Params
+}
+
+func TestApp(t *testing.T) {
+ testCases := append(testCasesPd, testCasesNixos...)
+
+ for _, tc := range testCases {
+ t.Run(tc.name, func(t *testing.T) {
+ a := setuid.NewWithID(tc.id, tc.os)
+ var (
+ gotSys *system.I
+ gotContainer *sandbox.Params
+ )
+ if !t.Run("seal", func(t *testing.T) {
+ if sa, err := a.Seal(tc.config); err != nil {
+ t.Errorf("Seal: error = %v", err)
+ return
+ } else {
+ gotSys, gotContainer = setuid.AppIParams(a, sa)
+ }
+ }) {
+ return
+ }
+
+ t.Run("compare sys", func(t *testing.T) {
+ if !gotSys.Equal(tc.wantSys) {
+ t.Errorf("Seal: sys = %#v, want %#v",
+ gotSys, tc.wantSys)
+ }
+ })
+
+ t.Run("compare params", func(t *testing.T) {
+ if !reflect.DeepEqual(gotContainer, tc.wantContainer) {
+ t.Errorf("seal: params =\n%s\n, want\n%s",
+ mustMarshal(gotContainer), mustMarshal(tc.wantContainer))
+ }
+ })
+ })
+ }
+}
+
+func mustMarshal(v any) string {
+ if b, err := json.Marshal(v); err != nil {
+ panic(err.Error())
+ } else {
+ return string(b)
+ }
+}
+
+func stubDirEntries(names ...string) (e []fs.DirEntry, err error) {
+ e = make([]fs.DirEntry, len(names))
+ for i, name := range names {
+ e[i] = stubDirEntryPath(name)
+ }
+ return
+}
+
+type stubDirEntryPath string
+
+func (p stubDirEntryPath) Name() string {
+ return string(p)
+}
+
+func (p stubDirEntryPath) IsDir() bool {
+ panic("attempted to call IsDir")
+}
+
+func (p stubDirEntryPath) Type() fs.FileMode {
+ panic("attempted to call Type")
+}
+
+func (p stubDirEntryPath) Info() (fs.FileInfo, error) {
+ panic("attempted to call Info")
+}
+
+type stubFileInfoMode fs.FileMode
+
+func (s stubFileInfoMode) Name() string {
+ panic("attempted to call Name")
+}
+
+func (s stubFileInfoMode) Size() int64 {
+ panic("attempted to call Size")
+}
+
+func (s stubFileInfoMode) Mode() fs.FileMode {
+ return fs.FileMode(s)
+}
+
+func (s stubFileInfoMode) ModTime() time.Time {
+ panic("attempted to call ModTime")
+}
+
+func (s stubFileInfoMode) IsDir() bool {
+ panic("attempted to call IsDir")
+}
+
+func (s stubFileInfoMode) Sys() any {
+ panic("attempted to call Sys")
+}
+
+type stubFileInfoIsDir bool
+
+func (s stubFileInfoIsDir) Name() string {
+ panic("attempted to call Name")
+}
+
+func (s stubFileInfoIsDir) Size() int64 {
+ panic("attempted to call Size")
+}
+
+func (s stubFileInfoIsDir) Mode() fs.FileMode {
+ panic("attempted to call Mode")
+}
+
+func (s stubFileInfoIsDir) ModTime() time.Time {
+ panic("attempted to call ModTime")
+}
+
+func (s stubFileInfoIsDir) IsDir() bool {
+ return bool(s)
+}
+
+func (s stubFileInfoIsDir) Sys() any {
+ panic("attempted to call Sys")
+}
diff --git a/internal/app/setuid/errors.go b/internal/app/setuid/errors.go
new file mode 100644
index 00000000..e6c9685c
--- /dev/null
+++ b/internal/app/setuid/errors.go
@@ -0,0 +1,182 @@
+package setuid
+
+import (
+ "errors"
+ "log"
+
+ "git.gensokyo.uk/security/fortify/fst"
+ "git.gensokyo.uk/security/fortify/internal/fmsg"
+)
+
+func PrintRunStateErr(rs *fst.RunState, runErr error) (code int) {
+ code = rs.ExitStatus()
+
+ if runErr != nil {
+ if rs.Time == nil {
+ fmsg.PrintBaseError(runErr, "cannot start app:")
+ } else {
+ var e *fmsg.BaseError
+ if !fmsg.AsBaseError(runErr, &e) {
+ log.Println("wait failed:", runErr)
+ } else {
+ // Wait only returns either *app.ProcessError or *app.StateStoreError wrapped in a *app.BaseError
+ var se *StateStoreError
+ if !errors.As(runErr, &se) {
+ // does not need special handling
+ log.Print(e.Message())
+ } else {
+ // inner error are either unwrapped store errors
+ // or joined errors returned by *appSealTx revert
+ // wrapped in *app.BaseError
+ var ej RevertCompoundError
+ if !errors.As(se.InnerErr, &ej) {
+ // does not require special handling
+ log.Print(e.Message())
+ } else {
+ errs := ej.Unwrap()
+
+ // every error here is wrapped in *app.BaseError
+ for _, ei := range errs {
+ var eb *fmsg.BaseError
+ if !errors.As(ei, &eb) {
+ // unreachable
+ log.Println("invalid error type returned by revert:", ei)
+ } else {
+ // print inner *app.BaseError message
+ log.Print(eb.Message())
+ }
+ }
+ }
+ }
+ }
+ }
+
+ if code == 0 {
+ code = 126
+ }
+ }
+
+ if rs.RevertErr != nil {
+ var stateStoreError *StateStoreError
+ if !errors.As(rs.RevertErr, &stateStoreError) || stateStoreError == nil {
+ fmsg.PrintBaseError(rs.RevertErr, "generic fault during cleanup:")
+ goto out
+ }
+
+ if stateStoreError.Err != nil {
+ if len(stateStoreError.Err) == 2 {
+ if stateStoreError.Err[0] != nil {
+ if joinedErrs, ok := stateStoreError.Err[0].(interface{ Unwrap() []error }); !ok {
+ fmsg.PrintBaseError(stateStoreError.Err[0], "generic fault during revert:")
+ } else {
+ for _, err := range joinedErrs.Unwrap() {
+ if err != nil {
+ fmsg.PrintBaseError(err, "fault during revert:")
+ }
+ }
+ }
+ }
+ if stateStoreError.Err[1] != nil {
+ log.Printf("cannot close store: %v", stateStoreError.Err[1])
+ }
+ } else {
+ log.Printf("fault during cleanup: %v",
+ errors.Join(stateStoreError.Err...))
+ }
+ }
+
+ if stateStoreError.OpErr != nil {
+ log.Printf("blind revert due to store fault: %v",
+ stateStoreError.OpErr)
+ }
+
+ if stateStoreError.DoErr != nil {
+ fmsg.PrintBaseError(stateStoreError.DoErr, "state store operation unsuccessful:")
+ }
+
+ if stateStoreError.Inner && stateStoreError.InnerErr != nil {
+ fmsg.PrintBaseError(stateStoreError.InnerErr, "cannot destroy state entry:")
+ }
+
+ out:
+ if code == 0 {
+ code = 128
+ }
+ }
+ if rs.WaitErr != nil {
+ fmsg.Verbosef("wait: %v", rs.WaitErr)
+ }
+ return
+}
+
+// StateStoreError is returned for a failed state save
+type StateStoreError struct {
+ // whether inner function was called
+ Inner bool
+ // returned by the Save/Destroy method of [state.Cursor]
+ InnerErr error
+ // returned by the Do method of [state.Store]
+ DoErr error
+ // stores an arbitrary store operation error
+ OpErr error
+ // stores arbitrary errors
+ Err []error
+}
+
+// save saves arbitrary errors in [StateStoreError] once.
+func (e *StateStoreError) save(errs ...error) {
+ if len(errs) == 0 || e.Err != nil {
+ panic("invalid call to save")
+ }
+ e.Err = errs
+}
+
+func (e *StateStoreError) equiv(a ...any) error {
+ if e.Inner && e.InnerErr == nil && e.DoErr == nil && e.OpErr == nil && errors.Join(e.Err...) == nil {
+ return nil
+ } else {
+ return fmsg.WrapErrorSuffix(e, a...)
+ }
+}
+
+func (e *StateStoreError) Error() string {
+ if e.Inner && e.InnerErr != nil {
+ return e.InnerErr.Error()
+ }
+ if e.DoErr != nil {
+ return e.DoErr.Error()
+ }
+ if e.OpErr != nil {
+ return e.OpErr.Error()
+ }
+ if err := errors.Join(e.Err...); err != nil {
+ return err.Error()
+ }
+
+ // equiv nullifies e for values where this is reached
+ panic("unreachable")
+}
+
+func (e *StateStoreError) Unwrap() (errs []error) {
+ errs = make([]error, 0, 3)
+ if e.InnerErr != nil {
+ errs = append(errs, e.InnerErr)
+ }
+ if e.DoErr != nil {
+ errs = append(errs, e.DoErr)
+ }
+ if e.OpErr != nil {
+ errs = append(errs, e.OpErr)
+ }
+ if err := errors.Join(e.Err...); err != nil {
+ errs = append(errs, err)
+ }
+ return
+}
+
+// A RevertCompoundError encapsulates errors returned by
+// the Revert method of [system.I].
+type RevertCompoundError interface {
+ Error() string
+ Unwrap() []error
+}
diff --git a/internal/app/setuid/export_test.go b/internal/app/setuid/export_test.go
new file mode 100644
index 00000000..77182863
--- /dev/null
+++ b/internal/app/setuid/export_test.go
@@ -0,0 +1,24 @@
+package setuid
+
+import (
+ "git.gensokyo.uk/security/fortify/fst"
+ "git.gensokyo.uk/security/fortify/internal/sys"
+ "git.gensokyo.uk/security/fortify/sandbox"
+ "git.gensokyo.uk/security/fortify/system"
+)
+
+func NewWithID(id fst.ID, os sys.State) fst.App {
+ a := new(app)
+ a.id = newID(&id)
+ a.sys = os
+ return a
+}
+
+func AppIParams(a fst.App, sa fst.SealedApp) (*system.I, *sandbox.Params) {
+ v := a.(*app)
+ seal := sa.(*outcome)
+ if v.outcome != seal || v.id != seal.id {
+ panic("broken app/outcome link")
+ }
+ return seal.sys, seal.container
+}
diff --git a/internal/app/setuid/process.go b/internal/app/setuid/process.go
new file mode 100644
index 00000000..e730225e
--- /dev/null
+++ b/internal/app/setuid/process.go
@@ -0,0 +1,195 @@
+package setuid
+
+import (
+ "context"
+ "encoding/gob"
+ "errors"
+ "log"
+ "os"
+ "os/exec"
+ "strconv"
+ "strings"
+ "syscall"
+ "time"
+
+ "git.gensokyo.uk/security/fortify/fst"
+ "git.gensokyo.uk/security/fortify/internal"
+ "git.gensokyo.uk/security/fortify/internal/fmsg"
+ "git.gensokyo.uk/security/fortify/internal/state"
+ "git.gensokyo.uk/security/fortify/sandbox"
+ "git.gensokyo.uk/security/fortify/system"
+)
+
+const shimWaitTimeout = 5 * time.Second
+
+func (seal *outcome) Run(rs *fst.RunState) error {
+ if !seal.f.CompareAndSwap(false, true) {
+ // run does much more than just starting a process; calling it twice, even if the first call fails, will result
+ // in inconsistent state that is impossible to clean up; return here to limit damage and hopefully give the
+ // other Run a chance to return
+ return errors.New("outcome: attempted to run twice")
+ }
+
+ if rs == nil {
+ panic("invalid state")
+ }
+
+ // read comp value early to allow for early failure
+ fsuPath := internal.MustFsuPath()
+
+ if err := seal.sys.Commit(seal.ctx); err != nil {
+ return err
+ }
+ store := state.NewMulti(seal.runDirPath)
+ deferredStoreFunc := func(c state.Cursor) error { return nil } // noop until state in store
+ defer func() {
+ var revertErr error
+ storeErr := new(StateStoreError)
+ storeErr.Inner, storeErr.DoErr = store.Do(seal.user.aid.unwrap(), func(c state.Cursor) {
+ revertErr = func() error {
+ storeErr.InnerErr = deferredStoreFunc(c)
+
+ var rt system.Enablement
+ ec := system.Process
+ if states, err := c.Load(); err != nil {
+ // revert per-process state here to limit damage
+ storeErr.OpErr = err
+ return seal.sys.Revert((*system.Criteria)(&ec))
+ } else {
+ if l := len(states); l == 0 {
+ ec |= system.User
+ } else {
+ fmsg.Verbosef("found %d instances, cleaning up without user-scoped operations", l)
+ }
+
+ // accumulate enablements of remaining launchers
+ for i, s := range states {
+ if s.Config != nil {
+ rt |= s.Config.Confinement.Enablements
+ } else {
+ log.Printf("state entry %d does not contain config", i)
+ }
+ }
+ }
+ ec |= rt ^ (system.EWayland | system.EX11 | system.EDBus | system.EPulse)
+ if fmsg.Load() {
+ if ec > 0 {
+ fmsg.Verbose("reverting operations scope", system.TypeString(ec))
+ }
+ }
+
+ return seal.sys.Revert((*system.Criteria)(&ec))
+ }()
+ })
+ storeErr.save(revertErr, store.Close())
+ rs.RevertErr = storeErr.equiv("error during cleanup:")
+ }()
+
+ ctx, cancel := context.WithCancel(seal.ctx)
+ defer cancel()
+ cmd := exec.CommandContext(ctx, fsuPath)
+ cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
+ cmd.Dir = "/" // container init enters final working directory
+ // shim runs in the same session as monitor; see shim.go for behaviour
+ cmd.Cancel = func() error { return cmd.Process.Signal(syscall.SIGCONT) }
+
+ var e *gob.Encoder
+ if fd, encoder, err := sandbox.Setup(&cmd.ExtraFiles); err != nil {
+ return fmsg.WrapErrorSuffix(err,
+ "cannot create shim setup pipe:")
+ } else {
+ e = encoder
+ cmd.Env = []string{
+ // passed through to shim by fsu
+ shimEnv + "=" + strconv.Itoa(fd),
+ // interpreted by fsu
+ "FORTIFY_APP_ID=" + seal.user.aid.String(),
+ }
+ }
+
+ if len(seal.user.supp) > 0 {
+ fmsg.Verbosef("attaching supplementary group ids %s", seal.user.supp)
+ // interpreted by fsu
+ cmd.Env = append(cmd.Env, "FORTIFY_GROUPS="+strings.Join(seal.user.supp, " "))
+ }
+
+ fmsg.Verbosef("setuid helper at %s", fsuPath)
+ fmsg.Suspend()
+ if err := cmd.Start(); err != nil {
+ return fmsg.WrapErrorSuffix(err,
+ "cannot start setuid wrapper:")
+ }
+ rs.SetStart()
+
+ // this prevents blocking forever on an early failure
+ waitErr, setupErr := make(chan error, 1), make(chan error, 1)
+ go func() { waitErr <- cmd.Wait(); cancel() }()
+ go func() { setupErr <- e.Encode(&shimParams{os.Getpid(), seal.container, seal.user.data, fmsg.Load()}) }()
+
+ select {
+ case err := <-setupErr:
+ if err != nil {
+ fmsg.Resume()
+ return fmsg.WrapErrorSuffix(err,
+ "cannot transmit shim config:")
+ }
+
+ case <-ctx.Done():
+ fmsg.Resume()
+ return fmsg.WrapError(syscall.ECANCELED,
+ "shim setup canceled")
+ }
+
+ // returned after blocking on waitErr
+ var earlyStoreErr = new(StateStoreError)
+ {
+ // shim accepted setup payload, create process state
+ sd := state.State{
+ ID: seal.id.unwrap(),
+ PID: cmd.Process.Pid,
+ Time: *rs.Time,
+ }
+ earlyStoreErr.Inner, earlyStoreErr.DoErr = store.Do(seal.user.aid.unwrap(), func(c state.Cursor) {
+ earlyStoreErr.InnerErr = c.Save(&sd, seal.ct)
+ })
+ }
+
+ // state in store at this point, destroy defunct state entry on return
+ deferredStoreFunc = func(c state.Cursor) error { return c.Destroy(seal.id.unwrap()) }
+
+ waitTimeout := make(chan struct{})
+ go func() { <-seal.ctx.Done(); time.Sleep(shimWaitTimeout); close(waitTimeout) }()
+
+ select {
+ case rs.WaitErr = <-waitErr:
+ rs.WaitStatus = cmd.ProcessState.Sys().(syscall.WaitStatus)
+ if fmsg.Load() {
+ switch {
+ case rs.Exited():
+ fmsg.Verbosef("process %d exited with code %d", cmd.Process.Pid, rs.ExitStatus())
+ case rs.CoreDump():
+ fmsg.Verbosef("process %d dumped core", cmd.Process.Pid)
+ case rs.Signaled():
+ fmsg.Verbosef("process %d got %s", cmd.Process.Pid, rs.Signal())
+ default:
+ fmsg.Verbosef("process %d exited with status %#x", cmd.Process.Pid, rs.WaitStatus)
+ }
+ }
+ case <-waitTimeout:
+ rs.WaitErr = syscall.ETIMEDOUT
+ fmsg.Resume()
+ log.Printf("process %d did not terminate", cmd.Process.Pid)
+ }
+
+ fmsg.Resume()
+ if seal.sync != nil {
+ if err := seal.sync.Close(); err != nil {
+ log.Printf("cannot close wayland security context: %v", err)
+ }
+ }
+ if seal.dbusMsg != nil {
+ seal.dbusMsg()
+ }
+
+ return earlyStoreErr.equiv("cannot save process state:")
+}
diff --git a/internal/app/setuid/seal.go b/internal/app/setuid/seal.go
new file mode 100644
index 00000000..92fbc2fa
--- /dev/null
+++ b/internal/app/setuid/seal.go
@@ -0,0 +1,573 @@
+package setuid
+
+import (
+ "bytes"
+ "context"
+ "encoding/gob"
+ "errors"
+ "fmt"
+ "io"
+ "io/fs"
+ "os"
+ "path"
+ "regexp"
+ "slices"
+ "strings"
+ "sync/atomic"
+ "syscall"
+
+ "git.gensokyo.uk/security/fortify/acl"
+ "git.gensokyo.uk/security/fortify/dbus"
+ "git.gensokyo.uk/security/fortify/fst"
+ "git.gensokyo.uk/security/fortify/internal"
+ "git.gensokyo.uk/security/fortify/internal/fmsg"
+ "git.gensokyo.uk/security/fortify/internal/sys"
+ "git.gensokyo.uk/security/fortify/sandbox"
+ "git.gensokyo.uk/security/fortify/sandbox/wl"
+ "git.gensokyo.uk/security/fortify/system"
+)
+
+const (
+ home = "HOME"
+ shell = "SHELL"
+
+ xdgConfigHome = "XDG_CONFIG_HOME"
+ xdgRuntimeDir = "XDG_RUNTIME_DIR"
+ xdgSessionClass = "XDG_SESSION_CLASS"
+ xdgSessionType = "XDG_SESSION_TYPE"
+
+ term = "TERM"
+ display = "DISPLAY"
+
+ pulseServer = "PULSE_SERVER"
+ pulseCookie = "PULSE_COOKIE"
+
+ dbusSessionBusAddress = "DBUS_SESSION_BUS_ADDRESS"
+ dbusSystemBusAddress = "DBUS_SYSTEM_BUS_ADDRESS"
+)
+
+var (
+ ErrConfig = errors.New("no configuration to seal")
+ ErrUser = errors.New("invalid aid")
+ ErrHome = errors.New("invalid home directory")
+ ErrName = errors.New("invalid username")
+
+ ErrXDisplay = errors.New(display + " unset")
+
+ ErrPulseCookie = errors.New("pulse cookie not present")
+ ErrPulseSocket = errors.New("pulse socket not present")
+ ErrPulseMode = errors.New("unexpected pulse socket mode")
+)
+
+var posixUsername = regexp.MustCompilePOSIX("^[a-z_]([A-Za-z0-9_-]{0,31}|[A-Za-z0-9_-]{0,30}\\$)$")
+
+// outcome stores copies of various parts of [fst.Config]
+type outcome struct {
+ // copied from initialising [app]
+ id *stringPair[fst.ID]
+ // copied from [sys.State] response
+ runDirPath string
+
+ // initial [fst.Config] gob stream for state data;
+ // this is prepared ahead of time as config is clobbered during seal creation
+ ct io.WriterTo
+ // dump dbus proxy message buffer
+ dbusMsg func()
+
+ user fsuUser
+ sys *system.I
+ ctx context.Context
+
+ container *sandbox.Params
+ env map[string]string
+ sync *os.File
+
+ f atomic.Bool
+}
+
+// shareHost holds optional share directory state that must not be accessed directly
+type shareHost struct {
+ // whether XDG_RUNTIME_DIR is used post fsu
+ useRuntimeDir bool
+ // process-specific directory in tmpdir, empty if unused
+ sharePath string
+ // process-specific directory in XDG_RUNTIME_DIR, empty if unused
+ runtimeSharePath string
+
+ seal *outcome
+ sc fst.Paths
+}
+
+// ensureRuntimeDir must be called if direct access to paths within XDG_RUNTIME_DIR is required
+func (share *shareHost) ensureRuntimeDir() {
+ if share.useRuntimeDir {
+ return
+ }
+ share.useRuntimeDir = true
+ share.seal.sys.Ensure(share.sc.RunDirPath, 0700)
+ share.seal.sys.UpdatePermType(system.User, share.sc.RunDirPath, acl.Execute)
+ share.seal.sys.Ensure(share.sc.RuntimePath, 0700) // ensure this dir in case XDG_RUNTIME_DIR is unset
+ share.seal.sys.UpdatePermType(system.User, share.sc.RuntimePath, acl.Execute)
+}
+
+// instance returns a process-specific share path within tmpdir
+func (share *shareHost) instance() string {
+ if share.sharePath != "" {
+ return share.sharePath
+ }
+ share.sharePath = path.Join(share.sc.SharePath, share.seal.id.String())
+ share.seal.sys.Ephemeral(system.Process, share.sharePath, 0711)
+ return share.sharePath
+}
+
+// runtime returns a process-specific share path within XDG_RUNTIME_DIR
+func (share *shareHost) runtime() string {
+ if share.runtimeSharePath != "" {
+ return share.runtimeSharePath
+ }
+ share.ensureRuntimeDir()
+ share.runtimeSharePath = path.Join(share.sc.RunDirPath, share.seal.id.String())
+ share.seal.sys.Ephemeral(system.Process, share.runtimeSharePath, 0700)
+ share.seal.sys.UpdatePerm(share.runtimeSharePath, acl.Execute)
+ return share.runtimeSharePath
+}
+
+// fsuUser stores post-fsu credentials and metadata
+type fsuUser struct {
+ // application id
+ aid *stringPair[int]
+ // target uid resolved by fid:aid
+ uid *stringPair[int]
+
+ // supplementary group ids
+ supp []string
+
+ // home directory host path
+ data string
+ // app user home directory
+ home string
+ // passwd database username
+ username string
+}
+
+func (seal *outcome) finalise(ctx context.Context, sys sys.State, config *fst.Config) error {
+ if seal.ctx != nil {
+ panic("finalise called twice")
+ }
+ seal.ctx = ctx
+
+ {
+ // encode initial configuration for state tracking
+ ct := new(bytes.Buffer)
+ if err := gob.NewEncoder(ct).Encode(config); err != nil {
+ return fmsg.WrapErrorSuffix(err,
+ "cannot encode initial config:")
+ }
+ seal.ct = ct
+ }
+
+ // allowed aid range 0 to 9999, this is checked again in fsu
+ if config.Confinement.AppID < 0 || config.Confinement.AppID > 9999 {
+ return fmsg.WrapError(ErrUser,
+ fmt.Sprintf("aid %d out of range", config.Confinement.AppID))
+ }
+
+ seal.user = fsuUser{
+ aid: newInt(config.Confinement.AppID),
+ data: config.Confinement.Outer,
+ home: config.Confinement.Inner,
+ username: config.Confinement.Username,
+ }
+ if seal.user.username == "" {
+ seal.user.username = "chronos"
+ } else if !posixUsername.MatchString(seal.user.username) ||
+ len(seal.user.username) >= internal.Sysconf_SC_LOGIN_NAME_MAX() {
+ return fmsg.WrapError(ErrName,
+ fmt.Sprintf("invalid user name %q", seal.user.username))
+ }
+ if seal.user.data == "" || !path.IsAbs(seal.user.data) {
+ return fmsg.WrapError(ErrHome,
+ fmt.Sprintf("invalid home directory %q", seal.user.data))
+ }
+ if seal.user.home == "" {
+ seal.user.home = seal.user.data
+ }
+ if u, err := sys.Uid(seal.user.aid.unwrap()); err != nil {
+ return err
+ } else {
+ seal.user.uid = newInt(u)
+ }
+ seal.user.supp = make([]string, len(config.Confinement.Groups))
+ for i, name := range config.Confinement.Groups {
+ if g, err := sys.LookupGroup(name); err != nil {
+ return fmsg.WrapError(err,
+ fmt.Sprintf("unknown group %q", name))
+ } else {
+ seal.user.supp[i] = g.Gid
+ }
+ }
+
+ // this also falls back to host path if encountering an invalid path
+ if !path.IsAbs(config.Confinement.Shell) {
+ config.Confinement.Shell = "/bin/sh"
+ if s, ok := sys.LookupEnv(shell); ok && path.IsAbs(s) {
+ config.Confinement.Shell = s
+ }
+ }
+ // do not use the value of shell before this point
+
+ // permissive defaults
+ if config.Confinement.Sandbox == nil {
+ fmsg.Verbose("sandbox configuration not supplied, PROCEED WITH CAUTION")
+
+ // fsu clears the environment so resolve paths early
+ if !path.IsAbs(config.Path) {
+ if len(config.Args) > 0 {
+ if p, err := sys.LookPath(config.Args[0]); err != nil {
+ return fmsg.WrapError(err, err.Error())
+ } else {
+ config.Path = p
+ }
+ } else {
+ config.Path = config.Confinement.Shell
+ }
+ }
+
+ conf := &fst.SandboxConfig{
+ Userns: true,
+ Net: true,
+ Tty: true,
+ AutoEtc: true,
+ }
+ // bind entries in /
+ if d, err := sys.ReadDir("/"); err != nil {
+ return err
+ } else {
+ b := make([]*fst.FilesystemConfig, 0, len(d))
+ for _, ent := range d {
+ p := "/" + ent.Name()
+ switch p {
+ case "/proc":
+ case "/dev":
+ case "/tmp":
+ case "/mnt":
+ case "/etc":
+
+ default:
+ b = append(b, &fst.FilesystemConfig{Src: p, Write: true, Must: true})
+ }
+ }
+ conf.Filesystem = append(conf.Filesystem, b...)
+ }
+
+ // hide nscd from sandbox if present
+ nscd := "/var/run/nscd"
+ if _, err := sys.Stat(nscd); !errors.Is(err, fs.ErrNotExist) {
+ conf.Cover = append(conf.Cover, nscd)
+ }
+ // bind GPU stuff
+ if config.Confinement.Enablements&(system.EX11|system.EWayland) != 0 {
+ conf.Filesystem = append(conf.Filesystem, &fst.FilesystemConfig{Src: "/dev/dri", Device: true})
+ }
+ // opportunistically bind kvm
+ conf.Filesystem = append(conf.Filesystem, &fst.FilesystemConfig{Src: "/dev/kvm", Device: true})
+
+ config.Confinement.Sandbox = conf
+ }
+
+ var mapuid, mapgid *stringPair[int]
+ {
+ var uid, gid int
+ var err error
+ seal.container, seal.env, err = config.Confinement.Sandbox.ToContainer(sys, &uid, &gid)
+ if err != nil {
+ return fmsg.WrapErrorSuffix(err,
+ "cannot initialise container configuration:")
+ }
+ if !path.IsAbs(config.Path) {
+ return fmsg.WrapError(syscall.EINVAL,
+ "invalid program path")
+ }
+ if len(config.Args) == 0 {
+ config.Args = []string{config.Path}
+ }
+ seal.container.Path = config.Path
+ seal.container.Args = config.Args
+
+ mapuid = newInt(uid)
+ mapgid = newInt(gid)
+ if seal.env == nil {
+ seal.env = make(map[string]string, 1<<6)
+ }
+ }
+
+ if !config.Confinement.Sandbox.AutoEtc {
+ if config.Confinement.Sandbox.Etc != "" {
+ seal.container.Bind(config.Confinement.Sandbox.Etc, "/etc", 0)
+ }
+ } else {
+ etcPath := config.Confinement.Sandbox.Etc
+ if etcPath == "" {
+ etcPath = "/etc"
+ }
+ seal.container.Etc(etcPath, seal.id.String())
+ }
+
+ // inner XDG_RUNTIME_DIR default formatting of `/run/user/%d` as mapped uid
+ innerRuntimeDir := path.Join("/run/user", mapuid.String())
+ seal.container.Tmpfs("/run/user", 1<<12, 0755)
+ seal.container.Tmpfs(innerRuntimeDir, 1<<23, 0700)
+ seal.env[xdgRuntimeDir] = innerRuntimeDir
+ seal.env[xdgSessionClass] = "user"
+ seal.env[xdgSessionType] = "tty"
+
+ share := &shareHost{seal: seal, sc: sys.Paths()}
+ seal.runDirPath = share.sc.RunDirPath
+ seal.sys = system.New(seal.user.uid.unwrap())
+
+ {
+ seal.sys.Ensure(share.sc.SharePath, 0711)
+ tmpdir := path.Join(share.sc.SharePath, "tmpdir")
+ seal.sys.Ensure(tmpdir, 0700)
+ seal.sys.UpdatePermType(system.User, tmpdir, acl.Execute)
+ tmpdirInst := path.Join(tmpdir, seal.user.aid.String())
+ seal.sys.Ensure(tmpdirInst, 01700)
+ seal.sys.UpdatePermType(system.User, tmpdirInst, acl.Read, acl.Write, acl.Execute)
+ // mount inner /tmp from share so it shares persistence and storage behaviour of host /tmp
+ seal.container.Bind(tmpdirInst, "/tmp", sandbox.BindWritable)
+ }
+
+ {
+ homeDir := "/var/empty"
+ if seal.user.home != "" {
+ homeDir = seal.user.home
+ }
+ username := "chronos"
+ if seal.user.username != "" {
+ username = seal.user.username
+ }
+ seal.container.Bind(seal.user.data, homeDir, sandbox.BindWritable)
+ seal.container.Dir = homeDir
+ seal.env["HOME"] = homeDir
+ seal.env["USER"] = username
+ seal.env[shell] = config.Confinement.Shell
+
+ seal.container.Place("/etc/passwd",
+ []byte(username+":x:"+mapuid.String()+":"+mapgid.String()+":Fortify:"+homeDir+":"+config.Confinement.Shell+"\n"))
+ seal.container.Place("/etc/group",
+ []byte("fortify:x:"+mapgid.String()+":\n"))
+ }
+
+ // pass TERM for proper terminal I/O in initial process
+ if t, ok := sys.LookupEnv(term); ok {
+ seal.env[term] = t
+ }
+
+ if config.Confinement.Enablements&system.EWayland != 0 {
+ // outer wayland socket (usually `/run/user/%d/wayland-%d`)
+ var socketPath string
+ if name, ok := sys.LookupEnv(wl.WaylandDisplay); !ok {
+ fmsg.Verbose(wl.WaylandDisplay + " is not set, assuming " + wl.FallbackName)
+ socketPath = path.Join(share.sc.RuntimePath, wl.FallbackName)
+ } else if !path.IsAbs(name) {
+ socketPath = path.Join(share.sc.RuntimePath, name)
+ } else {
+ socketPath = name
+ }
+
+ innerPath := path.Join(innerRuntimeDir, wl.FallbackName)
+ seal.env[wl.WaylandDisplay] = wl.FallbackName
+
+ if !config.Confinement.Sandbox.DirectWayland { // set up security-context-v1
+ appID := config.ID
+ if appID == "" {
+ // use instance ID in case app id is not set
+ appID = "uk.gensokyo.fortify." + seal.id.String()
+ }
+ // downstream socket paths
+ outerPath := path.Join(share.instance(), "wayland")
+ seal.sys.Wayland(&seal.sync, outerPath, socketPath, appID, seal.id.String())
+ seal.container.Bind(outerPath, innerPath, 0)
+ } else { // bind mount wayland socket (insecure)
+ fmsg.Verbose("direct wayland access, PROCEED WITH CAUTION")
+ share.ensureRuntimeDir()
+ seal.container.Bind(socketPath, innerPath, 0)
+ seal.sys.UpdatePermType(system.EWayland, socketPath, acl.Read, acl.Write, acl.Execute)
+ }
+ }
+
+ if config.Confinement.Enablements&system.EX11 != 0 {
+ if d, ok := sys.LookupEnv(display); !ok {
+ return fmsg.WrapError(ErrXDisplay,
+ "DISPLAY is not set")
+ } else {
+ seal.sys.ChangeHosts("#" + seal.user.uid.String())
+ seal.env[display] = d
+ seal.container.Bind("/tmp/.X11-unix", "/tmp/.X11-unix", 0)
+ }
+ }
+
+ if config.Confinement.Enablements&system.EPulse != 0 {
+ // PulseAudio runtime directory (usually `/run/user/%d/pulse`)
+ pulseRuntimeDir := path.Join(share.sc.RuntimePath, "pulse")
+ // PulseAudio socket (usually `/run/user/%d/pulse/native`)
+ pulseSocket := path.Join(pulseRuntimeDir, "native")
+
+ if _, err := sys.Stat(pulseRuntimeDir); err != nil {
+ if !errors.Is(err, fs.ErrNotExist) {
+ return fmsg.WrapErrorSuffix(err,
+ fmt.Sprintf("cannot access PulseAudio directory %q:", pulseRuntimeDir))
+ }
+ return fmsg.WrapError(ErrPulseSocket,
+ fmt.Sprintf("PulseAudio directory %q not found", pulseRuntimeDir))
+ }
+
+ if s, err := sys.Stat(pulseSocket); err != nil {
+ if !errors.Is(err, fs.ErrNotExist) {
+ return fmsg.WrapErrorSuffix(err,
+ fmt.Sprintf("cannot access PulseAudio socket %q:", pulseSocket))
+ }
+ return fmsg.WrapError(ErrPulseSocket,
+ fmt.Sprintf("PulseAudio directory %q found but socket does not exist", pulseRuntimeDir))
+ } else {
+ if m := s.Mode(); m&0o006 != 0o006 {
+ return fmsg.WrapError(ErrPulseMode,
+ fmt.Sprintf("unexpected permissions on %q:", pulseSocket), m)
+ }
+ }
+
+ // hard link pulse socket into target-executable share
+ innerPulseRuntimeDir := path.Join(share.runtime(), "pulse")
+ innerPulseSocket := path.Join(innerRuntimeDir, "pulse", "native")
+ seal.sys.Link(pulseSocket, innerPulseRuntimeDir)
+ seal.container.Bind(innerPulseRuntimeDir, innerPulseSocket, 0)
+ seal.env[pulseServer] = "unix:" + innerPulseSocket
+
+ // publish current user's pulse cookie for target user
+ if src, err := discoverPulseCookie(sys); err != nil {
+ // not fatal
+ fmsg.Verbose(strings.TrimSpace(err.(*fmsg.BaseError).Message()))
+ } else {
+ innerDst := fst.Tmp + "/pulse-cookie"
+ seal.env[pulseCookie] = innerDst
+ var payload *[]byte
+ seal.container.PlaceP(innerDst, &payload)
+ seal.sys.CopyFile(payload, src, 256, 256)
+ }
+ }
+
+ if config.Confinement.Enablements&system.EDBus != 0 {
+ // ensure dbus session bus defaults
+ if config.Confinement.SessionBus == nil {
+ config.Confinement.SessionBus = dbus.NewConfig(config.ID, true, true)
+ }
+
+ // downstream socket paths
+ sharePath := share.instance()
+ sessionPath, systemPath := path.Join(sharePath, "bus"), path.Join(sharePath, "system_bus_socket")
+
+ // configure dbus proxy
+ if f, err := seal.sys.ProxyDBus(
+ config.Confinement.SessionBus, config.Confinement.SystemBus,
+ sessionPath, systemPath,
+ ); err != nil {
+ return err
+ } else {
+ seal.dbusMsg = f
+ }
+
+ // share proxy sockets
+ sessionInner := path.Join(innerRuntimeDir, "bus")
+ seal.env[dbusSessionBusAddress] = "unix:path=" + sessionInner
+ seal.container.Bind(sessionPath, sessionInner, 0)
+ seal.sys.UpdatePerm(sessionPath, acl.Read, acl.Write)
+ if config.Confinement.SystemBus != nil {
+ systemInner := "/run/dbus/system_bus_socket"
+ seal.env[dbusSystemBusAddress] = "unix:path=" + systemInner
+ seal.container.Bind(systemPath, systemInner, 0)
+ seal.sys.UpdatePerm(systemPath, acl.Read, acl.Write)
+ }
+ }
+
+ for _, dest := range config.Confinement.Sandbox.Cover {
+ seal.container.Tmpfs(dest, 1<<13, 0755)
+ }
+
+ // append ExtraPerms last
+ for _, p := range config.Confinement.ExtraPerms {
+ if p == nil {
+ continue
+ }
+
+ if p.Ensure {
+ seal.sys.Ensure(p.Path, 0700)
+ }
+
+ perms := make(acl.Perms, 0, 3)
+ if p.Read {
+ perms = append(perms, acl.Read)
+ }
+ if p.Write {
+ perms = append(perms, acl.Write)
+ }
+ if p.Execute {
+ perms = append(perms, acl.Execute)
+ }
+ seal.sys.UpdatePermType(system.User, p.Path, perms...)
+ }
+
+ // flatten and sort env for deterministic behaviour
+ seal.container.Env = make([]string, 0, len(seal.env))
+ for k, v := range seal.env {
+ if strings.IndexByte(k, '=') != -1 {
+ return fmsg.WrapError(syscall.EINVAL,
+ fmt.Sprintf("invalid environment variable %s", k))
+ }
+ seal.container.Env = append(seal.container.Env, k+"="+v)
+ }
+ slices.Sort(seal.container.Env)
+
+ fmsg.Verbosef("created application seal for uid %s (%s) groups: %v, argv: %s",
+ seal.user.uid, seal.user.username, config.Confinement.Groups, seal.container.Args)
+
+ return nil
+}
+
+// discoverPulseCookie attempts various standard methods to discover the current user's PulseAudio authentication cookie
+func discoverPulseCookie(sys sys.State) (string, error) {
+ if p, ok := sys.LookupEnv(pulseCookie); ok {
+ return p, nil
+ }
+
+ // dotfile $HOME/.pulse-cookie
+ if p, ok := sys.LookupEnv(home); ok {
+ p = path.Join(p, ".pulse-cookie")
+ if s, err := sys.Stat(p); err != nil {
+ if !errors.Is(err, fs.ErrNotExist) {
+ return p, fmsg.WrapErrorSuffix(err,
+ fmt.Sprintf("cannot access PulseAudio cookie %q:", p))
+ }
+ // not found, try next method
+ } else if !s.IsDir() {
+ return p, nil
+ }
+ }
+
+ // $XDG_CONFIG_HOME/pulse/cookie
+ if p, ok := sys.LookupEnv(xdgConfigHome); ok {
+ p = path.Join(p, "pulse", "cookie")
+ if s, err := sys.Stat(p); err != nil {
+ if !errors.Is(err, fs.ErrNotExist) {
+ return p, fmsg.WrapErrorSuffix(err,
+ fmt.Sprintf("cannot access PulseAudio cookie %q:", p))
+ }
+ // not found, try next method
+ } else if !s.IsDir() {
+ return p, nil
+ }
+ }
+
+ return "", fmsg.WrapError(ErrPulseCookie,
+ fmt.Sprintf("cannot locate PulseAudio cookie (tried $%s, $%s/pulse/cookie, $%s/.pulse-cookie)",
+ pulseCookie, xdgConfigHome, home))
+}
diff --git a/internal/app/setuid/shim.go b/internal/app/setuid/shim.go
new file mode 100644
index 00000000..1717f812
--- /dev/null
+++ b/internal/app/setuid/shim.go
@@ -0,0 +1,181 @@
+package setuid
+
+import (
+ "context"
+ "errors"
+ "log"
+ "os"
+ "os/exec"
+ "os/signal"
+ "syscall"
+ "time"
+
+ "git.gensokyo.uk/security/fortify/internal"
+ "git.gensokyo.uk/security/fortify/internal/fmsg"
+ "git.gensokyo.uk/security/fortify/sandbox"
+ "git.gensokyo.uk/security/fortify/sandbox/seccomp"
+)
+
+/*
+#include <stdlib.h>
+#include <unistd.h>
+#include <stdio.h>
+#include <errno.h>
+#include <signal.h>
+
+static pid_t f_shim_param_ppid = -1;
+
+// this cannot unblock fmsg since Go code is not async-signal-safe
+static void f_shim_sigaction(int sig, siginfo_t *si, void *ucontext) {
+ if (sig != SIGCONT || si == NULL) {
+ // unreachable
+ fprintf(stderr, "sigaction: sa_sigaction got invalid siginfo\n");
+ return;
+ }
+
+ // monitor requests shim exit
+ if (si->si_pid == f_shim_param_ppid)
+ exit(254);
+
+ fprintf(stderr, "sigaction: got SIGCONT from process %d\n", si->si_pid);
+
+ // shim orphaned before monitor delivers a signal
+ if (getppid() != f_shim_param_ppid)
+ exit(3);
+}
+
+void f_shim_setup_cont_signal(pid_t ppid) {
+ struct sigaction new_action = {0}, old_action = {0};
+ if (sigaction(SIGCONT, NULL, &old_action) != 0)
+ return;
+ if (old_action.sa_handler != SIG_DFL) {
+ errno = ENOTRECOVERABLE;
+ return;
+ }
+
+ new_action.sa_sigaction = f_shim_sigaction;
+ if (sigemptyset(&new_action.sa_mask) != 0)
+ return;
+ new_action.sa_flags = SA_ONSTACK | SA_SIGINFO;
+
+ if (sigaction(SIGCONT, &new_action, NULL) != 0)
+ return;
+
+ errno = 0;
+ f_shim_param_ppid = ppid;
+}
+*/
+import "C"
+
+const shimEnv = "FORTIFY_SHIM"
+
+type shimParams struct {
+ // monitor pid, checked against ppid in signal handler
+ Monitor int
+
+ // finalised container params
+ Container *sandbox.Params
+ // path to outer home directory
+ Home string
+
+ // verbosity pass through
+ Verbose bool
+}
+
+// ShimMain is the main function of the shim process and runs as the unconstrained target user.
+func ShimMain() {
+ fmsg.Prepare("shim")
+
+ if err := sandbox.SetDumpable(sandbox.SUID_DUMP_DISABLE); err != nil {
+ log.Fatalf("cannot set SUID_DUMP_DISABLE: %s", err)
+ }
+
+ var (
+ params shimParams
+ closeSetup func() error
+ )
+ if f, err := sandbox.Receive(shimEnv, &params, nil); err != nil {
+ if errors.Is(err, sandbox.ErrInvalid) {
+ log.Fatal("invalid config descriptor")
+ }
+ if errors.Is(err, sandbox.ErrNotSet) {
+ log.Fatal("FORTIFY_SHIM not set")
+ }
+
+ log.Fatalf("cannot receive shim setup params: %v", err)
+ } else {
+ internal.InstallFmsg(params.Verbose)
+ closeSetup = f
+
+ // the Go runtime does not expose siginfo_t so SIGCONT is handled in C to check si_pid
+ if _, err = C.f_shim_setup_cont_signal(C.pid_t(params.Monitor)); err != nil {
+ log.Fatalf("cannot install SIGCONT handler: %v", err)
+ }
+
+ // pdeath_signal delivery is checked as if the dying process called kill(2), see kernel/exit.c
+ if _, _, errno := syscall.Syscall(syscall.SYS_PRCTL, syscall.PR_SET_PDEATHSIG, uintptr(syscall.SIGCONT), 0); errno != 0 {
+ log.Fatalf("cannot set parent-death signal: %v", errno)
+ }
+ }
+
+ if params.Container == nil || params.Container.Ops == nil {
+ log.Fatal("invalid container params")
+ }
+
+ // close setup socket
+ if err := closeSetup(); err != nil {
+ log.Printf("cannot close setup pipe: %v", err)
+ // not fatal
+ }
+
+ // ensure home directory as target user
+ if s, err := os.Stat(params.Home); err != nil {
+ if os.IsNotExist(err) {
+ if err = os.Mkdir(params.Home, 0700); err != nil {
+ log.Fatalf("cannot create home directory: %v", err)
+ }
+ } else {
+ log.Fatalf("cannot access home directory: %v", err)
+ }
+
+ // home directory is created, proceed
+ } else if !s.IsDir() {
+ log.Fatalf("path %q is not a directory", params.Home)
+ }
+
+ var name string
+ if len(params.Container.Args) > 0 {
+ name = params.Container.Args[0]
+ }
+ ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
+ defer stop() // unreachable
+ container := sandbox.New(ctx, name)
+ container.Params = *params.Container
+ container.Stdin, container.Stdout, container.Stderr = os.Stdin, os.Stdout, os.Stderr
+ container.Cancel = func(cmd *exec.Cmd) error { return cmd.Process.Signal(os.Interrupt) }
+ container.WaitDelay = 2 * time.Second
+
+ if err := container.Start(); err != nil {
+ fmsg.PrintBaseError(err, "cannot start container:")
+ os.Exit(1)
+ }
+ if err := container.Serve(); err != nil {
+ fmsg.PrintBaseError(err, "cannot configure container:")
+ }
+
+ if err := seccomp.Load(seccomp.PresetCommon); err != nil {
+ log.Fatalf("cannot load syscall filter: %v", err)
+ }
+
+ if err := container.Wait(); err != nil {
+ var exitError *exec.ExitError
+ if !errors.As(err, &exitError) {
+ if errors.Is(err, context.Canceled) {
+ os.Exit(2)
+ }
+ log.Printf("wait: %v", err)
+ os.Exit(127)
+ }
+ os.Exit(exitError.ExitCode())
+ }
+}
diff --git a/internal/app/setuid/strings.go b/internal/app/setuid/strings.go
new file mode 100644
index 00000000..f5b51344
--- /dev/null
+++ b/internal/app/setuid/strings.go
@@ -0,0 +1,19 @@
+package setuid
+
+import (
+ "strconv"
+
+ "git.gensokyo.uk/security/fortify/fst"
+)
+
+func newInt(v int) *stringPair[int] { return &stringPair[int]{v, strconv.Itoa(v)} }
+func newID(id *fst.ID) *stringPair[fst.ID] { return &stringPair[fst.ID]{*id, id.String()} }
+
+// stringPair stores a value and its string representation.
+type stringPair[T comparable] struct {
+ v T
+ s string
+}
+
+func (s *stringPair[T]) unwrap() T { return s.v }
+func (s *stringPair[T]) String() string { return s.s }