From b14690aa77b3d5f86c4d1b1965675d6d82789e32 Mon Sep 17 00:00:00 2001 From: Ophestra Date: Thu, 28 Aug 2025 01:07:51 +0900 Subject: internal/app: remove seal interface This further cleans up the package for the restructure. Signed-off-by: Ophestra --- internal/app/app.go | 94 ++++-- internal/app/app_linux.go | 81 ------ internal/app/app_linux_test.go | 106 ------- internal/app/app_test.go | 106 +++++++ internal/app/container.go | 252 ++++++++++++++++ internal/app/container_linux.go | 252 ---------------- internal/app/export_linux_test.go | 23 -- internal/app/export_test.go | 22 ++ internal/app/process.go | 229 +++++++++++++++ internal/app/process_linux.go | 201 ------------- internal/app/seal.go | 590 ++++++++++++++++++++++++++++++++++++++ internal/app/seal_linux.go | 590 -------------------------------------- internal/app/shim.go | 183 ++++++++++++ internal/app/shim_linux.go | 183 ------------ 14 files changed, 1452 insertions(+), 1460 deletions(-) delete mode 100644 internal/app/app_linux.go delete mode 100644 internal/app/app_linux_test.go create mode 100644 internal/app/app_test.go create mode 100644 internal/app/container.go delete mode 100644 internal/app/container_linux.go delete mode 100644 internal/app/export_linux_test.go create mode 100644 internal/app/export_test.go create mode 100644 internal/app/process.go delete mode 100644 internal/app/process_linux.go create mode 100644 internal/app/seal.go delete mode 100644 internal/app/seal_linux.go create mode 100644 internal/app/shim.go delete mode 100644 internal/app/shim_linux.go diff --git a/internal/app/app.go b/internal/app/app.go index d59b145d..17b4103d 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -2,35 +2,81 @@ package app import ( - "syscall" - "time" + "context" + "fmt" + "log" + "sync" + + "hakurei.app/hst" + "hakurei.app/internal/app/state" + "hakurei.app/internal/sys" ) -type SealedApp interface { - // Run commits sealed system setup and starts the app process. - Run(rs *RunState) error +func New(ctx context.Context, os sys.State) (*App, error) { + a := new(App) + a.sys = os + a.ctx = ctx + + id := new(state.ID) + err := state.NewAppID(id) + a.id = newID(id) + + return a, err +} + +func MustNew(ctx context.Context, os sys.State) *App { + a, err := New(ctx, os) + if err != nil { + log.Fatalf("cannot create app: %v", err) + } + return a +} + +type App struct { + outcome *Outcome + + id *stringPair[state.ID] + sys sys.State + ctx context.Context + mu sync.RWMutex } -// RunState stores the outcome of a call to [SealedApp.Run]. -type RunState struct { - // Time is the exact point in time where the process was created. - // Location must be set to UTC. - // - // Time is nil if no process was ever created. - Time *time.Time - // RevertErr is stored by the deferred revert call. - RevertErr error - // WaitErr is the generic error value created by the standard library. - WaitErr error - - syscall.WaitStatus +// ID returns a copy of [state.ID] held by App. +func (a *App) ID() state.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) } -// SetStart stores the current time in [RunState] once. -func (rs *RunState) SetStart() { - if rs.Time != nil { - panic("attempted to store time twice") +// Seal determines the outcome of [hst.Config] as a [SealedApp]. +// Values stored in and referred to by [hst.Config] might be overwritten and must not be used again. +func (a *App) Seal(config *hst.Config) (*Outcome, error) { + a.mu.Lock() + defer a.mu.Unlock() + + if a.outcome != nil { + panic("app sealed twice") + } + + seal := new(Outcome) + seal.id = a.id + err := seal.finalise(a.ctx, a.sys, config) + if err == nil { + a.outcome = seal } - now := time.Now().UTC() - rs.Time = &now + return seal, err } diff --git a/internal/app/app_linux.go b/internal/app/app_linux.go deleted file mode 100644 index eebfacdc..00000000 --- a/internal/app/app_linux.go +++ /dev/null @@ -1,81 +0,0 @@ -package app - -import ( - "context" - "fmt" - "log" - "sync" - - "hakurei.app/hst" - "hakurei.app/internal/app/state" - "hakurei.app/internal/sys" -) - -func New(ctx context.Context, os sys.State) (*App, error) { - a := new(App) - a.sys = os - a.ctx = ctx - - id := new(state.ID) - err := state.NewAppID(id) - a.id = newID(id) - - return a, err -} - -func MustNew(ctx context.Context, os sys.State) *App { - a, err := New(ctx, os) - if err != nil { - log.Fatalf("cannot create app: %v", err) - } - return a -} - -type App struct { - id *stringPair[state.ID] - sys sys.State - ctx context.Context - - *outcome - mu sync.RWMutex -} - -// ID returns a copy of [state.ID] held by App. -func (a *App) ID() state.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) -} - -// Seal determines the outcome of [hst.Config] as a [SealedApp]. -// Values stored in and referred to by [hst.Config] might be overwritten and must not be used again. -func (a *App) Seal(config *hst.Config) (SealedApp, error) { - a.mu.Lock() - defer a.mu.Unlock() - - if a.outcome != nil { - panic("app sealed twice") - } - - 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/app_linux_test.go b/internal/app/app_linux_test.go deleted file mode 100644 index 8b96cfba..00000000 --- a/internal/app/app_linux_test.go +++ /dev/null @@ -1,106 +0,0 @@ -package app_test - -import ( - "encoding/json" - "io/fs" - "reflect" - "testing" - "time" - - "hakurei.app/container" - "hakurei.app/hst" - "hakurei.app/internal/app" - "hakurei.app/internal/app/state" - "hakurei.app/internal/hlog" - "hakurei.app/internal/sys" - "hakurei.app/system" -) - -type sealTestCase struct { - name string - os sys.State - config *hst.Config - id state.ID - wantSys *system.I - wantContainer *container.Params -} - -func TestApp(t *testing.T) { - testCases := append(testCasesPd, testCasesNixos...) - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - a := app.NewWithID(tc.id, tc.os) - var ( - gotSys *system.I - gotContainer *container.Params - ) - if !t.Run("seal", func(t *testing.T) { - if sa, err := a.Seal(tc.config); err != nil { - hlog.PrintBaseError(err, "got generic error:") - t.Errorf("Seal: error = %v", err) - return - } else { - gotSys, gotContainer = app.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/app_test.go b/internal/app/app_test.go new file mode 100644 index 00000000..8b96cfba --- /dev/null +++ b/internal/app/app_test.go @@ -0,0 +1,106 @@ +package app_test + +import ( + "encoding/json" + "io/fs" + "reflect" + "testing" + "time" + + "hakurei.app/container" + "hakurei.app/hst" + "hakurei.app/internal/app" + "hakurei.app/internal/app/state" + "hakurei.app/internal/hlog" + "hakurei.app/internal/sys" + "hakurei.app/system" +) + +type sealTestCase struct { + name string + os sys.State + config *hst.Config + id state.ID + wantSys *system.I + wantContainer *container.Params +} + +func TestApp(t *testing.T) { + testCases := append(testCasesPd, testCasesNixos...) + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + a := app.NewWithID(tc.id, tc.os) + var ( + gotSys *system.I + gotContainer *container.Params + ) + if !t.Run("seal", func(t *testing.T) { + if sa, err := a.Seal(tc.config); err != nil { + hlog.PrintBaseError(err, "got generic error:") + t.Errorf("Seal: error = %v", err) + return + } else { + gotSys, gotContainer = app.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/container.go b/internal/app/container.go new file mode 100644 index 00000000..cdefe170 --- /dev/null +++ b/internal/app/container.go @@ -0,0 +1,252 @@ +package app + +import ( + "errors" + "fmt" + "io/fs" + "maps" + "path" + "syscall" + + "hakurei.app/container" + "hakurei.app/container/seccomp" + "hakurei.app/hst" + "hakurei.app/internal/hlog" + "hakurei.app/internal/sys" + "hakurei.app/system/dbus" +) + +// in practice there should be less than 30 system mount points +const preallocateOpsCount = 1 << 5 + +// newContainer initialises [container.Params] via [hst.ContainerConfig]. +// Note that remaining container setup must be queued by the caller. +func newContainer(s *hst.ContainerConfig, os sys.State, prefix string, uid, gid *int) (*container.Params, map[string]string, error) { + if s == nil { + return nil, nil, hlog.WrapErr(syscall.EBADE, "invalid container configuration") + } + + params := &container.Params{ + Hostname: s.Hostname, + SeccompFlags: s.SeccompFlags, + SeccompPresets: s.SeccompPresets, + RetainSession: s.Tty, + HostNet: s.HostNet, + HostAbstract: s.HostAbstract, + + // the container is canceled when shim is requested to exit or receives an interrupt or termination signal; + // this behaviour is implemented in the shim + ForwardCancel: s.WaitDelay >= 0, + } + + as := &hst.ApplyState{ + AutoEtcPrefix: prefix, + } + { + ops := make(container.Ops, 0, preallocateOpsCount+len(s.Filesystem)) + params.Ops = &ops + as.Ops = &ops + } + + if s.Multiarch { + params.SeccompFlags |= seccomp.AllowMultiarch + } + + if !s.SeccompCompat { + params.SeccompPresets |= seccomp.PresetExt + } + if !s.Devel { + params.SeccompPresets |= seccomp.PresetDenyDevel + } + if !s.Userns { + params.SeccompPresets |= seccomp.PresetDenyNS + } + if !s.Tty { + params.SeccompPresets |= seccomp.PresetDenyTTY + } + + if s.MapRealUID { + params.Uid = os.Getuid() + *uid = params.Uid + params.Gid = os.Getgid() + *gid = params.Gid + } else { + *uid = container.OverflowUid() + *gid = container.OverflowGid() + } + + filesystem := s.Filesystem + var autoroot *hst.FSBind + // valid happens late, so root mount gets it here + if len(filesystem) > 0 && filesystem[0].Valid() && filesystem[0].Path().String() == container.FHSRoot { + // if the first element targets /, it is inserted early and excluded from path hiding + rootfs := filesystem[0].FilesystemConfig + filesystem = filesystem[1:] + rootfs.Apply(as) + + // autoroot requires special handling during path hiding + if b, ok := rootfs.(*hst.FSBind); ok && b.IsAutoRoot() { + autoroot = b + } + } + + params. + Proc(container.AbsFHSProc). + Tmpfs(hst.AbsTmp, 1<<12, 0755) + + if !s.Device { + params.DevWritable(container.AbsFHSDev, true) + } else { + params.Bind(container.AbsFHSDev, container.AbsFHSDev, container.BindWritable|container.BindDevice) + } + + /* retrieve paths and hide them if they're made available in the sandbox; + + this feature tries to improve user experience of permissive defaults, and + to warn about issues in custom configuration; it is NOT a security feature + and should not be treated as such, ALWAYS be careful with what you bind */ + var hidePaths []string + sc := os.Paths() + hidePaths = append(hidePaths, sc.RuntimePath.String(), sc.SharePath.String()) + _, systemBusAddr := dbus.Address() + if entries, err := dbus.Parse([]byte(systemBusAddr)); err != nil { + return nil, nil, err + } else { + // there is usually only one, do not preallocate + for _, entry := range entries { + if entry.Method != "unix" { + continue + } + for _, pair := range entry.Values { + if pair[0] == "path" { + if path.IsAbs(pair[1]) { + // get parent dir of socket + dir := path.Dir(pair[1]) + if dir == "." || dir == container.FHSRoot { + os.Printf("dbus socket %q is in an unusual location", pair[1]) + } + hidePaths = append(hidePaths, dir) + } else { + os.Printf("dbus socket %q is not absolute", pair[1]) + } + } + } + } + } + hidePathMatch := make([]bool, len(hidePaths)) + for i := range hidePaths { + if err := evalSymlinks(os, &hidePaths[i]); err != nil { + return nil, nil, err + } + } + + var hidePathSourceCount int + for i, c := range filesystem { + if !c.Valid() { + return nil, nil, fmt.Errorf("invalid filesystem at index %d", i) + } + c.Apply(as) + + // fs counter + hidePathSourceCount += len(c.Host()) + } + + // AutoRootOp is a collection of many BindMountOp internally + var autoRootEntries []fs.DirEntry + if autoroot != nil { + if d, err := os.ReadDir(autoroot.Source.String()); err != nil { + return nil, nil, err + } else { + // autoroot counter + hidePathSourceCount += len(d) + autoRootEntries = d + } + } + + hidePathSource := make([]*container.Absolute, 0, hidePathSourceCount) + + // fs append + for _, c := range filesystem { + // all entries already checked above + hidePathSource = append(hidePathSource, c.Host()...) + } + + // autoroot append + if autoroot != nil { + for _, ent := range autoRootEntries { + name := ent.Name() + if container.IsAutoRootBindable(name) { + hidePathSource = append(hidePathSource, autoroot.Source.Append(name)) + } + } + } + + // evaluated path, input path + hidePathSourceEval := make([][2]string, len(hidePathSource)) + for i, a := range hidePathSource { + if a == nil { + // unreachable + return nil, nil, syscall.ENOTRECOVERABLE + } + + hidePathSourceEval[i] = [2]string{a.String(), a.String()} + if err := evalSymlinks(os, &hidePathSourceEval[i][0]); err != nil { + return nil, nil, err + } + } + + for _, p := range hidePathSourceEval { + for i := range hidePaths { + // skip matched entries + if hidePathMatch[i] { + continue + } + + if ok, err := deepContainsH(p[0], hidePaths[i]); err != nil { + return nil, nil, err + } else if ok { + hidePathMatch[i] = true + os.Printf("hiding path %q from %q", hidePaths[i], p[1]) + } + } + } + + // cover matched paths + for i, ok := range hidePathMatch { + if ok { + if a, err := container.NewAbs(hidePaths[i]); err != nil { + var absoluteError *container.AbsoluteError + if !errors.As(err, &absoluteError) { + return nil, nil, err + } + if absoluteError == nil { + return nil, nil, syscall.ENOTRECOVERABLE + } + return nil, nil, fmt.Errorf("invalid path hiding candidate %q", absoluteError.Pathname) + } else { + params.Tmpfs(a, 1<<13, 0755) + } + } + } + + // no more ContainerConfig paths beyond this point + if !s.Device { + params. + Remount(container.AbsFHSDev, syscall.MS_RDONLY). + Tmpfs(container.AbsFHSDev.Append("shm"), 0, 01777) + } + + return params, maps.Clone(s.Env), nil +} + +func evalSymlinks(os sys.State, v *string) error { + if p, err := os.EvalSymlinks(*v); err != nil { + if !errors.Is(err, fs.ErrNotExist) { + return err + } + os.Printf("path %q does not yet exist", *v) + } else { + *v = p + } + return nil +} diff --git a/internal/app/container_linux.go b/internal/app/container_linux.go deleted file mode 100644 index cdefe170..00000000 --- a/internal/app/container_linux.go +++ /dev/null @@ -1,252 +0,0 @@ -package app - -import ( - "errors" - "fmt" - "io/fs" - "maps" - "path" - "syscall" - - "hakurei.app/container" - "hakurei.app/container/seccomp" - "hakurei.app/hst" - "hakurei.app/internal/hlog" - "hakurei.app/internal/sys" - "hakurei.app/system/dbus" -) - -// in practice there should be less than 30 system mount points -const preallocateOpsCount = 1 << 5 - -// newContainer initialises [container.Params] via [hst.ContainerConfig]. -// Note that remaining container setup must be queued by the caller. -func newContainer(s *hst.ContainerConfig, os sys.State, prefix string, uid, gid *int) (*container.Params, map[string]string, error) { - if s == nil { - return nil, nil, hlog.WrapErr(syscall.EBADE, "invalid container configuration") - } - - params := &container.Params{ - Hostname: s.Hostname, - SeccompFlags: s.SeccompFlags, - SeccompPresets: s.SeccompPresets, - RetainSession: s.Tty, - HostNet: s.HostNet, - HostAbstract: s.HostAbstract, - - // the container is canceled when shim is requested to exit or receives an interrupt or termination signal; - // this behaviour is implemented in the shim - ForwardCancel: s.WaitDelay >= 0, - } - - as := &hst.ApplyState{ - AutoEtcPrefix: prefix, - } - { - ops := make(container.Ops, 0, preallocateOpsCount+len(s.Filesystem)) - params.Ops = &ops - as.Ops = &ops - } - - if s.Multiarch { - params.SeccompFlags |= seccomp.AllowMultiarch - } - - if !s.SeccompCompat { - params.SeccompPresets |= seccomp.PresetExt - } - if !s.Devel { - params.SeccompPresets |= seccomp.PresetDenyDevel - } - if !s.Userns { - params.SeccompPresets |= seccomp.PresetDenyNS - } - if !s.Tty { - params.SeccompPresets |= seccomp.PresetDenyTTY - } - - if s.MapRealUID { - params.Uid = os.Getuid() - *uid = params.Uid - params.Gid = os.Getgid() - *gid = params.Gid - } else { - *uid = container.OverflowUid() - *gid = container.OverflowGid() - } - - filesystem := s.Filesystem - var autoroot *hst.FSBind - // valid happens late, so root mount gets it here - if len(filesystem) > 0 && filesystem[0].Valid() && filesystem[0].Path().String() == container.FHSRoot { - // if the first element targets /, it is inserted early and excluded from path hiding - rootfs := filesystem[0].FilesystemConfig - filesystem = filesystem[1:] - rootfs.Apply(as) - - // autoroot requires special handling during path hiding - if b, ok := rootfs.(*hst.FSBind); ok && b.IsAutoRoot() { - autoroot = b - } - } - - params. - Proc(container.AbsFHSProc). - Tmpfs(hst.AbsTmp, 1<<12, 0755) - - if !s.Device { - params.DevWritable(container.AbsFHSDev, true) - } else { - params.Bind(container.AbsFHSDev, container.AbsFHSDev, container.BindWritable|container.BindDevice) - } - - /* retrieve paths and hide them if they're made available in the sandbox; - - this feature tries to improve user experience of permissive defaults, and - to warn about issues in custom configuration; it is NOT a security feature - and should not be treated as such, ALWAYS be careful with what you bind */ - var hidePaths []string - sc := os.Paths() - hidePaths = append(hidePaths, sc.RuntimePath.String(), sc.SharePath.String()) - _, systemBusAddr := dbus.Address() - if entries, err := dbus.Parse([]byte(systemBusAddr)); err != nil { - return nil, nil, err - } else { - // there is usually only one, do not preallocate - for _, entry := range entries { - if entry.Method != "unix" { - continue - } - for _, pair := range entry.Values { - if pair[0] == "path" { - if path.IsAbs(pair[1]) { - // get parent dir of socket - dir := path.Dir(pair[1]) - if dir == "." || dir == container.FHSRoot { - os.Printf("dbus socket %q is in an unusual location", pair[1]) - } - hidePaths = append(hidePaths, dir) - } else { - os.Printf("dbus socket %q is not absolute", pair[1]) - } - } - } - } - } - hidePathMatch := make([]bool, len(hidePaths)) - for i := range hidePaths { - if err := evalSymlinks(os, &hidePaths[i]); err != nil { - return nil, nil, err - } - } - - var hidePathSourceCount int - for i, c := range filesystem { - if !c.Valid() { - return nil, nil, fmt.Errorf("invalid filesystem at index %d", i) - } - c.Apply(as) - - // fs counter - hidePathSourceCount += len(c.Host()) - } - - // AutoRootOp is a collection of many BindMountOp internally - var autoRootEntries []fs.DirEntry - if autoroot != nil { - if d, err := os.ReadDir(autoroot.Source.String()); err != nil { - return nil, nil, err - } else { - // autoroot counter - hidePathSourceCount += len(d) - autoRootEntries = d - } - } - - hidePathSource := make([]*container.Absolute, 0, hidePathSourceCount) - - // fs append - for _, c := range filesystem { - // all entries already checked above - hidePathSource = append(hidePathSource, c.Host()...) - } - - // autoroot append - if autoroot != nil { - for _, ent := range autoRootEntries { - name := ent.Name() - if container.IsAutoRootBindable(name) { - hidePathSource = append(hidePathSource, autoroot.Source.Append(name)) - } - } - } - - // evaluated path, input path - hidePathSourceEval := make([][2]string, len(hidePathSource)) - for i, a := range hidePathSource { - if a == nil { - // unreachable - return nil, nil, syscall.ENOTRECOVERABLE - } - - hidePathSourceEval[i] = [2]string{a.String(), a.String()} - if err := evalSymlinks(os, &hidePathSourceEval[i][0]); err != nil { - return nil, nil, err - } - } - - for _, p := range hidePathSourceEval { - for i := range hidePaths { - // skip matched entries - if hidePathMatch[i] { - continue - } - - if ok, err := deepContainsH(p[0], hidePaths[i]); err != nil { - return nil, nil, err - } else if ok { - hidePathMatch[i] = true - os.Printf("hiding path %q from %q", hidePaths[i], p[1]) - } - } - } - - // cover matched paths - for i, ok := range hidePathMatch { - if ok { - if a, err := container.NewAbs(hidePaths[i]); err != nil { - var absoluteError *container.AbsoluteError - if !errors.As(err, &absoluteError) { - return nil, nil, err - } - if absoluteError == nil { - return nil, nil, syscall.ENOTRECOVERABLE - } - return nil, nil, fmt.Errorf("invalid path hiding candidate %q", absoluteError.Pathname) - } else { - params.Tmpfs(a, 1<<13, 0755) - } - } - } - - // no more ContainerConfig paths beyond this point - if !s.Device { - params. - Remount(container.AbsFHSDev, syscall.MS_RDONLY). - Tmpfs(container.AbsFHSDev.Append("shm"), 0, 01777) - } - - return params, maps.Clone(s.Env), nil -} - -func evalSymlinks(os sys.State, v *string) error { - if p, err := os.EvalSymlinks(*v); err != nil { - if !errors.Is(err, fs.ErrNotExist) { - return err - } - os.Printf("path %q does not yet exist", *v) - } else { - *v = p - } - return nil -} diff --git a/internal/app/export_linux_test.go b/internal/app/export_linux_test.go deleted file mode 100644 index f7af527f..00000000 --- a/internal/app/export_linux_test.go +++ /dev/null @@ -1,23 +0,0 @@ -package app - -import ( - "hakurei.app/container" - "hakurei.app/internal/app/state" - "hakurei.app/internal/sys" - "hakurei.app/system" -) - -func NewWithID(id state.ID, os sys.State) *App { - a := new(App) - a.id = newID(&id) - a.sys = os - return a -} - -func AppIParams(a *App, sa SealedApp) (*system.I, *container.Params) { - seal := sa.(*outcome) - if a.outcome != seal || a.id != seal.id { - panic("broken app/outcome link") - } - return seal.sys, seal.container -} diff --git a/internal/app/export_test.go b/internal/app/export_test.go new file mode 100644 index 00000000..b7ee7f73 --- /dev/null +++ b/internal/app/export_test.go @@ -0,0 +1,22 @@ +package app + +import ( + "hakurei.app/container" + "hakurei.app/internal/app/state" + "hakurei.app/internal/sys" + "hakurei.app/system" +) + +func NewWithID(id state.ID, os sys.State) *App { + a := new(App) + a.id = newID(&id) + a.sys = os + return a +} + +func AppIParams(a *App, seal *Outcome) (*system.I, *container.Params) { + if a.outcome != seal || a.id != seal.id { + panic("broken app/outcome link") + } + return seal.sys, seal.container +} diff --git a/internal/app/process.go b/internal/app/process.go new file mode 100644 index 00000000..44355699 --- /dev/null +++ b/internal/app/process.go @@ -0,0 +1,229 @@ +package app + +import ( + "context" + "encoding/gob" + "errors" + "log" + "os" + "os/exec" + "strconv" + "strings" + "syscall" + "time" + + "hakurei.app/container" + "hakurei.app/internal" + "hakurei.app/internal/app/state" + "hakurei.app/internal/hlog" + "hakurei.app/system" +) + +const shimWaitTimeout = 5 * time.Second + +// RunState stores the outcome of a call to [Outcome.Run]. +type RunState struct { + // Time is the exact point in time where the process was created. + // Location must be set to UTC. + // + // Time is nil if no process was ever created. + Time *time.Time + // RevertErr is stored by the deferred revert call. + RevertErr error + // WaitErr is the generic error value created by the standard library. + WaitErr error + + syscall.WaitStatus +} + +// setStart stores the current time in [RunState] once. +func (rs *RunState) setStart() { + if rs.Time != nil { + panic("attempted to store time twice") + } + now := time.Now().UTC() + rs.Time = &now +} + +// Run commits deferred system setup and starts the container. +func (seal *Outcome) Run(rs *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 + hsuPath := internal.MustHsuPath() + + if err := seal.sys.Commit(seal.ctx); err != nil { + return err + } + store := state.NewMulti(seal.runDirPath.String()) + 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.identity.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 { + hlog.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.Enablements.Unwrap() + } else { + log.Printf("state entry %d does not contain config", i) + } + } + } + ec |= rt ^ (system.EWayland | system.EX11 | system.EDBus | system.EPulse) + if hlog.Load() { + if ec > 0 { + hlog.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, hsuPath) + cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr + cmd.Dir = container.FHSRoot // 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 := container.Setup(&cmd.ExtraFiles); err != nil { + return hlog.WrapErrSuffix(err, + "cannot create shim setup pipe:") + } else { + e = encoder + cmd.Env = []string{ + // passed through to shim by hsu + shimEnv + "=" + strconv.Itoa(fd), + // interpreted by hsu + "HAKUREI_APP_ID=" + seal.user.identity.String(), + } + } + + if len(seal.user.supp) > 0 { + hlog.Verbosef("attaching supplementary group ids %s", seal.user.supp) + // interpreted by hsu + cmd.Env = append(cmd.Env, "HAKUREI_GROUPS="+strings.Join(seal.user.supp, " ")) + } + + hlog.Verbosef("setuid helper at %s", hsuPath) + hlog.Suspend() + if err := cmd.Start(); err != nil { + return hlog.WrapErrSuffix(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.waitDelay, + seal.container, + hlog.Load(), + }) + }() + + select { + case err := <-setupErr: + if err != nil { + hlog.Resume() + return hlog.WrapErrSuffix(err, + "cannot transmit shim config:") + } + + case <-ctx.Done(): + hlog.Resume() + return hlog.WrapErr(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.identity.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 hlog.Load() { + switch { + case rs.Exited(): + hlog.Verbosef("process %d exited with code %d", cmd.Process.Pid, rs.ExitStatus()) + + case rs.CoreDump(): + hlog.Verbosef("process %d dumped core", cmd.Process.Pid) + + case rs.Signaled(): + hlog.Verbosef("process %d got %s", cmd.Process.Pid, rs.Signal()) + + default: + hlog.Verbosef("process %d exited with status %#x", cmd.Process.Pid, rs.WaitStatus) + } + } + case <-waitTimeout: + rs.WaitErr = syscall.ETIMEDOUT + hlog.Resume() + log.Printf("process %d did not terminate", cmd.Process.Pid) + } + + hlog.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/process_linux.go b/internal/app/process_linux.go deleted file mode 100644 index c7da4746..00000000 --- a/internal/app/process_linux.go +++ /dev/null @@ -1,201 +0,0 @@ -package app - -import ( - "context" - "encoding/gob" - "errors" - "log" - "os" - "os/exec" - "strconv" - "strings" - "syscall" - "time" - - "hakurei.app/container" - "hakurei.app/internal" - "hakurei.app/internal/app/state" - "hakurei.app/internal/hlog" - "hakurei.app/system" -) - -const shimWaitTimeout = 5 * time.Second - -func (seal *outcome) Run(rs *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 - hsuPath := internal.MustHsuPath() - - if err := seal.sys.Commit(seal.ctx); err != nil { - return err - } - store := state.NewMulti(seal.runDirPath.String()) - 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.identity.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 { - hlog.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.Enablements.Unwrap() - } else { - log.Printf("state entry %d does not contain config", i) - } - } - } - ec |= rt ^ (system.EWayland | system.EX11 | system.EDBus | system.EPulse) - if hlog.Load() { - if ec > 0 { - hlog.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, hsuPath) - cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr - cmd.Dir = container.FHSRoot // 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 := container.Setup(&cmd.ExtraFiles); err != nil { - return hlog.WrapErrSuffix(err, - "cannot create shim setup pipe:") - } else { - e = encoder - cmd.Env = []string{ - // passed through to shim by hsu - shimEnv + "=" + strconv.Itoa(fd), - // interpreted by hsu - "HAKUREI_APP_ID=" + seal.user.identity.String(), - } - } - - if len(seal.user.supp) > 0 { - hlog.Verbosef("attaching supplementary group ids %s", seal.user.supp) - // interpreted by hsu - cmd.Env = append(cmd.Env, "HAKUREI_GROUPS="+strings.Join(seal.user.supp, " ")) - } - - hlog.Verbosef("setuid helper at %s", hsuPath) - hlog.Suspend() - if err := cmd.Start(); err != nil { - return hlog.WrapErrSuffix(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.waitDelay, - seal.container, - hlog.Load(), - }) - }() - - select { - case err := <-setupErr: - if err != nil { - hlog.Resume() - return hlog.WrapErrSuffix(err, - "cannot transmit shim config:") - } - - case <-ctx.Done(): - hlog.Resume() - return hlog.WrapErr(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.identity.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 hlog.Load() { - switch { - case rs.Exited(): - hlog.Verbosef("process %d exited with code %d", cmd.Process.Pid, rs.ExitStatus()) - case rs.CoreDump(): - hlog.Verbosef("process %d dumped core", cmd.Process.Pid) - case rs.Signaled(): - hlog.Verbosef("process %d got %s", cmd.Process.Pid, rs.Signal()) - default: - hlog.Verbosef("process %d exited with status %#x", cmd.Process.Pid, rs.WaitStatus) - } - } - case <-waitTimeout: - rs.WaitErr = syscall.ETIMEDOUT - hlog.Resume() - log.Printf("process %d did not terminate", cmd.Process.Pid) - } - - hlog.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/seal.go b/internal/app/seal.go new file mode 100644 index 00000000..d6a23f2f --- /dev/null +++ b/internal/app/seal.go @@ -0,0 +1,590 @@ +package app + +import ( + "bytes" + "context" + "encoding/gob" + "errors" + "fmt" + "io" + "io/fs" + "os" + "path" + "slices" + "strconv" + "strings" + "sync/atomic" + "syscall" + "time" + + "hakurei.app/container" + "hakurei.app/hst" + "hakurei.app/internal/app/state" + "hakurei.app/internal/hlog" + "hakurei.app/internal/sys" + "hakurei.app/system" + "hakurei.app/system/acl" + "hakurei.app/system/dbus" + "hakurei.app/system/wayland" +) + +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 ( + ErrIdent = errors.New("invalid identity") + 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") +) + +// An Outcome is the runnable state of a hakurei container via [hst.Config]. +type Outcome struct { + // copied from initialising [app] + id *stringPair[state.ID] + // copied from [sys.State] + runDirPath *container.Absolute + + // initial [hst.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 hsuUser + sys *system.I + ctx context.Context + + waitDelay time.Duration + container *container.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 hsu + useRuntimeDir bool + // process-specific directory in tmpdir, empty if unused + sharePath *container.Absolute + // process-specific directory in XDG_RUNTIME_DIR, empty if unused + runtimeSharePath *container.Absolute + + seal *Outcome + sc hst.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.String(), 0700) + share.seal.sys.UpdatePermType(system.User, share.sc.RunDirPath.String(), acl.Execute) + share.seal.sys.Ensure(share.sc.RuntimePath.String(), 0700) // ensure this dir in case XDG_RUNTIME_DIR is unset + share.seal.sys.UpdatePermType(system.User, share.sc.RuntimePath.String(), acl.Execute) +} + +// instance returns a process-specific share path within tmpdir +func (share *shareHost) instance() *container.Absolute { + if share.sharePath != nil { + return share.sharePath + } + share.sharePath = share.sc.SharePath.Append(share.seal.id.String()) + share.seal.sys.Ephemeral(system.Process, share.sharePath.String(), 0711) + return share.sharePath +} + +// runtime returns a process-specific share path within XDG_RUNTIME_DIR +func (share *shareHost) runtime() *container.Absolute { + if share.runtimeSharePath != nil { + return share.runtimeSharePath + } + share.ensureRuntimeDir() + share.runtimeSharePath = share.sc.RunDirPath.Append(share.seal.id.String()) + share.seal.sys.Ephemeral(system.Process, share.runtimeSharePath.String(), 0700) + share.seal.sys.UpdatePerm(share.runtimeSharePath.String(), acl.Execute) + return share.runtimeSharePath +} + +// hsuUser stores post-hsu credentials and metadata +type hsuUser struct { + identity *stringPair[int] + // target uid resolved by hid:aid + uid *stringPair[int] + + // supplementary group ids + supp []string + + // app user home directory + home *container.Absolute + // passwd database username + username string +} + +func (seal *Outcome) finalise(ctx context.Context, sys sys.State, config *hst.Config) error { + if seal.ctx != nil { + panic("finalise called twice") + } + seal.ctx = ctx + + if config == nil { + return hlog.WrapErr(syscall.EINVAL, syscall.EINVAL.Error()) + } + if config.Home == nil { + return hlog.WrapErr(os.ErrInvalid, "invalid path to home directory") + } + + { + // encode initial configuration for state tracking + ct := new(bytes.Buffer) + if err := gob.NewEncoder(ct).Encode(config); err != nil { + return hlog.WrapErrSuffix(err, + "cannot encode initial config:") + } + seal.ct = ct + } + + // allowed identity range 0 to 9999, this is checked again in hsu + if config.Identity < 0 || config.Identity > 9999 { + return hlog.WrapErr(ErrIdent, + fmt.Sprintf("identity %d out of range", config.Identity)) + } + + seal.user = hsuUser{ + identity: newInt(config.Identity), + home: config.Home, + username: config.Username, + } + if seal.user.username == "" { + seal.user.username = "chronos" + } else if !isValidUsername(seal.user.username) { + return hlog.WrapErr(ErrName, + fmt.Sprintf("invalid user name %q", seal.user.username)) + } + if u, err := sys.Uid(seal.user.identity.unwrap()); err != nil { + return err + } else { + seal.user.uid = newInt(u) + } + seal.user.supp = make([]string, len(config.Groups)) + for i, name := range config.Groups { + if g, err := sys.LookupGroup(name); err != nil { + return hlog.WrapErr(err, + fmt.Sprintf("unknown group %q", name)) + } else { + seal.user.supp[i] = g.Gid + } + } + + // permissive defaults + if config.Container == nil { + hlog.Verbose("container configuration not supplied, PROCEED WITH CAUTION") + + if config.Shell == nil { + config.Shell = container.AbsFHSRoot.Append("bin", "sh") + s, _ := sys.LookupEnv(shell) + if a, err := container.NewAbs(s); err == nil { + config.Shell = a + } + } + + // hsu clears the environment so resolve paths early + if config.Path == nil { + if len(config.Args) > 0 { + if p, err := sys.LookPath(config.Args[0]); err != nil { + return hlog.WrapErr(err, err.Error()) + } else if config.Path, err = container.NewAbs(p); err != nil { + return hlog.WrapErr(err, err.Error()) + } + } else { + config.Path = config.Shell + } + } + + conf := &hst.ContainerConfig{ + Userns: true, + HostNet: true, + HostAbstract: true, + Tty: true, + + Filesystem: []hst.FilesystemConfigJSON{ + // autoroot, includes the home directory + {&hst.FSBind{ + Target: container.AbsFHSRoot, + Source: container.AbsFHSRoot, + Write: true, + Special: true, + }}, + }, + } + + // bind GPU stuff + if config.Enablements.Unwrap()&(system.EX11|system.EWayland) != 0 { + conf.Filesystem = append(conf.Filesystem, hst.FilesystemConfigJSON{FilesystemConfig: &hst.FSBind{Source: container.AbsFHSDev.Append("dri"), Device: true, Optional: true}}) + } + // opportunistically bind kvm + conf.Filesystem = append(conf.Filesystem, hst.FilesystemConfigJSON{FilesystemConfig: &hst.FSBind{Source: container.AbsFHSDev.Append("kvm"), Device: true, Optional: true}}) + + // hide nscd from container if present + nscd := container.AbsFHSVar.Append("run/nscd") + if _, err := sys.Stat(nscd.String()); !errors.Is(err, fs.ErrNotExist) { + conf.Filesystem = append(conf.Filesystem, hst.FilesystemConfigJSON{FilesystemConfig: &hst.FSEphemeral{Target: nscd}}) + } + + // do autoetc last + conf.Filesystem = append(conf.Filesystem, + hst.FilesystemConfigJSON{FilesystemConfig: &hst.FSBind{ + Target: container.AbsFHSEtc, + Source: container.AbsFHSEtc, + Special: true, + }}, + ) + + config.Container = conf + } + + // late nil checks for pd behaviour + if config.Shell == nil { + return hlog.WrapErr(syscall.EINVAL, "invalid shell path") + } + if config.Path == nil { + return hlog.WrapErr(syscall.EINVAL, "invalid program path") + } + + var mapuid, mapgid *stringPair[int] + { + var uid, gid int + var err error + seal.container, seal.env, err = newContainer(config.Container, sys, seal.id.String(), &uid, &gid) + seal.waitDelay = config.Container.WaitDelay + if err != nil { + return hlog.WrapErrSuffix(err, + "cannot initialise container configuration:") + } + if len(config.Args) == 0 { + config.Args = []string{config.Path.String()} + } + 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) + } + } + + // inner XDG_RUNTIME_DIR default formatting of `/run/user/%d` as mapped uid + innerRuntimeDir := container.AbsFHSRunUser.Append(mapuid.String()) + seal.env[xdgRuntimeDir] = innerRuntimeDir.String() + 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.String(), 0711) + + { + runtimeDir := share.sc.SharePath.Append("runtime") + seal.sys.Ensure(runtimeDir.String(), 0700) + seal.sys.UpdatePermType(system.User, runtimeDir.String(), acl.Execute) + runtimeDirInst := runtimeDir.Append(seal.user.identity.String()) + seal.sys.Ensure(runtimeDirInst.String(), 0700) + seal.sys.UpdatePermType(system.User, runtimeDirInst.String(), acl.Read, acl.Write, acl.Execute) + seal.container.Tmpfs(container.AbsFHSRunUser, 1<<12, 0755) + seal.container.Bind(runtimeDirInst, innerRuntimeDir, container.BindWritable) + } + + { + tmpdir := share.sc.SharePath.Append("tmpdir") + seal.sys.Ensure(tmpdir.String(), 0700) + seal.sys.UpdatePermType(system.User, tmpdir.String(), acl.Execute) + tmpdirInst := tmpdir.Append(seal.user.identity.String()) + seal.sys.Ensure(tmpdirInst.String(), 01700) + seal.sys.UpdatePermType(system.User, tmpdirInst.String(), 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, container.AbsFHSTmp, container.BindWritable) + } + + { + username := "chronos" + if seal.user.username != "" { + username = seal.user.username + } + seal.container.Dir = seal.user.home + seal.env["HOME"] = seal.user.home.String() + seal.env["USER"] = username + seal.env[shell] = config.Shell.String() + + seal.container.Place(container.AbsFHSEtc.Append("passwd"), + []byte(username+":x:"+mapuid.String()+":"+mapgid.String()+":Hakurei:"+seal.user.home.String()+":"+config.Shell.String()+"\n")) + seal.container.Place(container.AbsFHSEtc.Append("group"), + []byte("hakurei: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.Enablements.Unwrap()&system.EWayland != 0 { + // outer wayland socket (usually `/run/user/%d/wayland-%d`) + var socketPath *container.Absolute + if name, ok := sys.LookupEnv(wayland.WaylandDisplay); !ok { + hlog.Verbose(wayland.WaylandDisplay + " is not set, assuming " + wayland.FallbackName) + socketPath = share.sc.RuntimePath.Append(wayland.FallbackName) + } else if a, err := container.NewAbs(name); err != nil { + socketPath = share.sc.RuntimePath.Append(name) + } else { + socketPath = a + } + + innerPath := innerRuntimeDir.Append(wayland.FallbackName) + seal.env[wayland.WaylandDisplay] = wayland.FallbackName + + if !config.DirectWayland { // set up security-context-v1 + appID := config.ID + if appID == "" { + // use instance ID in case app id is not set + appID = "app.hakurei." + seal.id.String() + } + // downstream socket paths + outerPath := share.instance().Append("wayland") + seal.sys.Wayland(&seal.sync, outerPath.String(), socketPath.String(), appID, seal.id.String()) + seal.container.Bind(outerPath, innerPath, 0) + } else { // bind mount wayland socket (insecure) + hlog.Verbose("direct wayland access, PROCEED WITH CAUTION") + share.ensureRuntimeDir() + seal.container.Bind(socketPath, innerPath, 0) + seal.sys.UpdatePermType(system.EWayland, socketPath.String(), acl.Read, acl.Write, acl.Execute) + } + } + + if config.Enablements.Unwrap()&system.EX11 != 0 { + if d, ok := sys.LookupEnv(display); !ok { + return hlog.WrapErr(ErrXDisplay, + "DISPLAY is not set") + } else { + socketDir := container.AbsFHSTmp.Append(".X11-unix") + + // the socket file at `/tmp/.X11-unix/X%d` is typically owned by the priv user + // and not accessible by the target user + var socketPath *container.Absolute + if len(d) > 1 && d[0] == ':' { // `:%d` + if n, err := strconv.Atoi(d[1:]); err == nil && n >= 0 { + socketPath = socketDir.Append("X" + strconv.Itoa(n)) + } + } else if len(d) > 5 && strings.HasPrefix(d, "unix:") { // `unix:%s` + if a, err := container.NewAbs(d[5:]); err == nil { + socketPath = a + } + } + if socketPath != nil { + if _, err := sys.Stat(socketPath.String()); err != nil { + if !errors.Is(err, fs.ErrNotExist) { + return hlog.WrapErrSuffix(err, + fmt.Sprintf("cannot access X11 socket %q:", socketPath)) + } + } else { + seal.sys.UpdatePermType(system.EX11, socketPath.String(), acl.Read, acl.Write, acl.Execute) + if !config.Container.HostAbstract { + d = "unix:" + socketPath.String() + } + } + } + + seal.sys.ChangeHosts("#" + seal.user.uid.String()) + seal.env[display] = d + seal.container.Bind(socketDir, socketDir, 0) + } + } + + if config.Enablements.Unwrap()&system.EPulse != 0 { + // PulseAudio runtime directory (usually `/run/user/%d/pulse`) + pulseRuntimeDir := share.sc.RuntimePath.Append("pulse") + // PulseAudio socket (usually `/run/user/%d/pulse/native`) + pulseSocket := pulseRuntimeDir.Append("native") + + if _, err := sys.Stat(pulseRuntimeDir.String()); err != nil { + if !errors.Is(err, fs.ErrNotExist) { + return hlog.WrapErrSuffix(err, + fmt.Sprintf("cannot access PulseAudio directory %q:", pulseRuntimeDir)) + } + return hlog.WrapErr(ErrPulseSocket, + fmt.Sprintf("PulseAudio directory %q not found", pulseRuntimeDir)) + } + + if s, err := sys.Stat(pulseSocket.String()); err != nil { + if !errors.Is(err, fs.ErrNotExist) { + return hlog.WrapErrSuffix(err, + fmt.Sprintf("cannot access PulseAudio socket %q:", pulseSocket)) + } + return hlog.WrapErr(ErrPulseSocket, + fmt.Sprintf("PulseAudio directory %q found but socket does not exist", pulseRuntimeDir)) + } else { + if m := s.Mode(); m&0o006 != 0o006 { + return hlog.WrapErr(ErrPulseMode, + fmt.Sprintf("unexpected permissions on %q:", pulseSocket), m) + } + } + + // hard link pulse socket into target-executable share + innerPulseRuntimeDir := share.runtime().Append("pulse") + innerPulseSocket := innerRuntimeDir.Append("pulse", "native") + seal.sys.Link(pulseSocket.String(), innerPulseRuntimeDir.String()) + seal.container.Bind(innerPulseRuntimeDir, innerPulseSocket, 0) + seal.env[pulseServer] = "unix:" + innerPulseSocket.String() + + // publish current user's pulse cookie for target user + if src, err := discoverPulseCookie(sys); err != nil { + // not fatal + hlog.Verbose(strings.TrimSpace(err.(*hlog.BaseError).Message())) + } else { + innerDst := hst.AbsTmp.Append("/pulse-cookie") + seal.env[pulseCookie] = innerDst.String() + var payload *[]byte + seal.container.PlaceP(innerDst, &payload) + seal.sys.CopyFile(payload, src, 256, 256) + } + } + + if config.Enablements.Unwrap()&system.EDBus != 0 { + // ensure dbus session bus defaults + if config.SessionBus == nil { + config.SessionBus = dbus.NewConfig(config.ID, true, true) + } + + // downstream socket paths + sessionPath, systemPath := share.instance().Append("bus"), share.instance().Append("system_bus_socket") + + // configure dbus proxy + if f, err := seal.sys.ProxyDBus( + config.SessionBus, config.SystemBus, + sessionPath.String(), systemPath.String(), + ); err != nil { + return err + } else { + seal.dbusMsg = f + } + + // share proxy sockets + sessionInner := innerRuntimeDir.Append("bus") + seal.env[dbusSessionBusAddress] = "unix:path=" + sessionInner.String() + seal.container.Bind(sessionPath, sessionInner, 0) + seal.sys.UpdatePerm(sessionPath.String(), acl.Read, acl.Write) + if config.SystemBus != nil { + systemInner := container.AbsFHSRun.Append("dbus/system_bus_socket") + seal.env[dbusSystemBusAddress] = "unix:path=" + systemInner.String() + seal.container.Bind(systemPath, systemInner, 0) + seal.sys.UpdatePerm(systemPath.String(), acl.Read, acl.Write) + } + } + + // mount root read-only as the final setup Op + seal.container.Remount(container.AbsFHSRoot, syscall.MS_RDONLY) + + // append ExtraPerms last + for _, p := range config.ExtraPerms { + if p == nil || p.Path == nil { + continue + } + + if p.Ensure { + seal.sys.Ensure(p.Path.String(), 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.String(), 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 hlog.WrapErr(syscall.EINVAL, + fmt.Sprintf("invalid environment variable %s", k)) + } + seal.container.Env = append(seal.container.Env, k+"="+v) + } + slices.Sort(seal.container.Env) + + if hlog.Load() { + hlog.Verbosef("created application seal for uid %s (%s) groups: %v, argv: %s, ops: %d", + seal.user.uid, seal.user.username, config.Groups, seal.container.Args, len(*seal.container.Ops)) + } + + 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, hlog.WrapErrSuffix(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, hlog.WrapErrSuffix(err, + fmt.Sprintf("cannot access PulseAudio cookie %q:", p)) + } + // not found, try next method + } else if !s.IsDir() { + return p, nil + } + } + + return "", hlog.WrapErr(ErrPulseCookie, + fmt.Sprintf("cannot locate PulseAudio cookie (tried $%s, $%s/pulse/cookie, $%s/.pulse-cookie)", + pulseCookie, xdgConfigHome, home)) +} diff --git a/internal/app/seal_linux.go b/internal/app/seal_linux.go deleted file mode 100644 index be18a2ae..00000000 --- a/internal/app/seal_linux.go +++ /dev/null @@ -1,590 +0,0 @@ -package app - -import ( - "bytes" - "context" - "encoding/gob" - "errors" - "fmt" - "io" - "io/fs" - "os" - "path" - "slices" - "strconv" - "strings" - "sync/atomic" - "syscall" - "time" - - "hakurei.app/container" - "hakurei.app/hst" - "hakurei.app/internal/app/state" - "hakurei.app/internal/hlog" - "hakurei.app/internal/sys" - "hakurei.app/system" - "hakurei.app/system/acl" - "hakurei.app/system/dbus" - "hakurei.app/system/wayland" -) - -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 ( - ErrIdent = errors.New("invalid identity") - 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") -) - -// outcome stores copies of various parts of [hst.Config] -type outcome struct { - // copied from initialising [app] - id *stringPair[state.ID] - // copied from [sys.State] - runDirPath *container.Absolute - - // initial [hst.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 hsuUser - sys *system.I - ctx context.Context - - waitDelay time.Duration - container *container.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 hsu - useRuntimeDir bool - // process-specific directory in tmpdir, empty if unused - sharePath *container.Absolute - // process-specific directory in XDG_RUNTIME_DIR, empty if unused - runtimeSharePath *container.Absolute - - seal *outcome - sc hst.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.String(), 0700) - share.seal.sys.UpdatePermType(system.User, share.sc.RunDirPath.String(), acl.Execute) - share.seal.sys.Ensure(share.sc.RuntimePath.String(), 0700) // ensure this dir in case XDG_RUNTIME_DIR is unset - share.seal.sys.UpdatePermType(system.User, share.sc.RuntimePath.String(), acl.Execute) -} - -// instance returns a process-specific share path within tmpdir -func (share *shareHost) instance() *container.Absolute { - if share.sharePath != nil { - return share.sharePath - } - share.sharePath = share.sc.SharePath.Append(share.seal.id.String()) - share.seal.sys.Ephemeral(system.Process, share.sharePath.String(), 0711) - return share.sharePath -} - -// runtime returns a process-specific share path within XDG_RUNTIME_DIR -func (share *shareHost) runtime() *container.Absolute { - if share.runtimeSharePath != nil { - return share.runtimeSharePath - } - share.ensureRuntimeDir() - share.runtimeSharePath = share.sc.RunDirPath.Append(share.seal.id.String()) - share.seal.sys.Ephemeral(system.Process, share.runtimeSharePath.String(), 0700) - share.seal.sys.UpdatePerm(share.runtimeSharePath.String(), acl.Execute) - return share.runtimeSharePath -} - -// hsuUser stores post-hsu credentials and metadata -type hsuUser struct { - identity *stringPair[int] - // target uid resolved by hid:aid - uid *stringPair[int] - - // supplementary group ids - supp []string - - // app user home directory - home *container.Absolute - // passwd database username - username string -} - -func (seal *outcome) finalise(ctx context.Context, sys sys.State, config *hst.Config) error { - if seal.ctx != nil { - panic("finalise called twice") - } - seal.ctx = ctx - - if config == nil { - return hlog.WrapErr(syscall.EINVAL, syscall.EINVAL.Error()) - } - if config.Home == nil { - return hlog.WrapErr(os.ErrInvalid, "invalid path to home directory") - } - - { - // encode initial configuration for state tracking - ct := new(bytes.Buffer) - if err := gob.NewEncoder(ct).Encode(config); err != nil { - return hlog.WrapErrSuffix(err, - "cannot encode initial config:") - } - seal.ct = ct - } - - // allowed identity range 0 to 9999, this is checked again in hsu - if config.Identity < 0 || config.Identity > 9999 { - return hlog.WrapErr(ErrIdent, - fmt.Sprintf("identity %d out of range", config.Identity)) - } - - seal.user = hsuUser{ - identity: newInt(config.Identity), - home: config.Home, - username: config.Username, - } - if seal.user.username == "" { - seal.user.username = "chronos" - } else if !isValidUsername(seal.user.username) { - return hlog.WrapErr(ErrName, - fmt.Sprintf("invalid user name %q", seal.user.username)) - } - if u, err := sys.Uid(seal.user.identity.unwrap()); err != nil { - return err - } else { - seal.user.uid = newInt(u) - } - seal.user.supp = make([]string, len(config.Groups)) - for i, name := range config.Groups { - if g, err := sys.LookupGroup(name); err != nil { - return hlog.WrapErr(err, - fmt.Sprintf("unknown group %q", name)) - } else { - seal.user.supp[i] = g.Gid - } - } - - // permissive defaults - if config.Container == nil { - hlog.Verbose("container configuration not supplied, PROCEED WITH CAUTION") - - if config.Shell == nil { - config.Shell = container.AbsFHSRoot.Append("bin", "sh") - s, _ := sys.LookupEnv(shell) - if a, err := container.NewAbs(s); err == nil { - config.Shell = a - } - } - - // hsu clears the environment so resolve paths early - if config.Path == nil { - if len(config.Args) > 0 { - if p, err := sys.LookPath(config.Args[0]); err != nil { - return hlog.WrapErr(err, err.Error()) - } else if config.Path, err = container.NewAbs(p); err != nil { - return hlog.WrapErr(err, err.Error()) - } - } else { - config.Path = config.Shell - } - } - - conf := &hst.ContainerConfig{ - Userns: true, - HostNet: true, - HostAbstract: true, - Tty: true, - - Filesystem: []hst.FilesystemConfigJSON{ - // autoroot, includes the home directory - {&hst.FSBind{ - Target: container.AbsFHSRoot, - Source: container.AbsFHSRoot, - Write: true, - Special: true, - }}, - }, - } - - // bind GPU stuff - if config.Enablements.Unwrap()&(system.EX11|system.EWayland) != 0 { - conf.Filesystem = append(conf.Filesystem, hst.FilesystemConfigJSON{FilesystemConfig: &hst.FSBind{Source: container.AbsFHSDev.Append("dri"), Device: true, Optional: true}}) - } - // opportunistically bind kvm - conf.Filesystem = append(conf.Filesystem, hst.FilesystemConfigJSON{FilesystemConfig: &hst.FSBind{Source: container.AbsFHSDev.Append("kvm"), Device: true, Optional: true}}) - - // hide nscd from container if present - nscd := container.AbsFHSVar.Append("run/nscd") - if _, err := sys.Stat(nscd.String()); !errors.Is(err, fs.ErrNotExist) { - conf.Filesystem = append(conf.Filesystem, hst.FilesystemConfigJSON{FilesystemConfig: &hst.FSEphemeral{Target: nscd}}) - } - - // do autoetc last - conf.Filesystem = append(conf.Filesystem, - hst.FilesystemConfigJSON{FilesystemConfig: &hst.FSBind{ - Target: container.AbsFHSEtc, - Source: container.AbsFHSEtc, - Special: true, - }}, - ) - - config.Container = conf - } - - // late nil checks for pd behaviour - if config.Shell == nil { - return hlog.WrapErr(syscall.EINVAL, "invalid shell path") - } - if config.Path == nil { - return hlog.WrapErr(syscall.EINVAL, "invalid program path") - } - - var mapuid, mapgid *stringPair[int] - { - var uid, gid int - var err error - seal.container, seal.env, err = newContainer(config.Container, sys, seal.id.String(), &uid, &gid) - seal.waitDelay = config.Container.WaitDelay - if err != nil { - return hlog.WrapErrSuffix(err, - "cannot initialise container configuration:") - } - if len(config.Args) == 0 { - config.Args = []string{config.Path.String()} - } - 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) - } - } - - // inner XDG_RUNTIME_DIR default formatting of `/run/user/%d` as mapped uid - innerRuntimeDir := container.AbsFHSRunUser.Append(mapuid.String()) - seal.env[xdgRuntimeDir] = innerRuntimeDir.String() - 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.String(), 0711) - - { - runtimeDir := share.sc.SharePath.Append("runtime") - seal.sys.Ensure(runtimeDir.String(), 0700) - seal.sys.UpdatePermType(system.User, runtimeDir.String(), acl.Execute) - runtimeDirInst := runtimeDir.Append(seal.user.identity.String()) - seal.sys.Ensure(runtimeDirInst.String(), 0700) - seal.sys.UpdatePermType(system.User, runtimeDirInst.String(), acl.Read, acl.Write, acl.Execute) - seal.container.Tmpfs(container.AbsFHSRunUser, 1<<12, 0755) - seal.container.Bind(runtimeDirInst, innerRuntimeDir, container.BindWritable) - } - - { - tmpdir := share.sc.SharePath.Append("tmpdir") - seal.sys.Ensure(tmpdir.String(), 0700) - seal.sys.UpdatePermType(system.User, tmpdir.String(), acl.Execute) - tmpdirInst := tmpdir.Append(seal.user.identity.String()) - seal.sys.Ensure(tmpdirInst.String(), 01700) - seal.sys.UpdatePermType(system.User, tmpdirInst.String(), 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, container.AbsFHSTmp, container.BindWritable) - } - - { - username := "chronos" - if seal.user.username != "" { - username = seal.user.username - } - seal.container.Dir = seal.user.home - seal.env["HOME"] = seal.user.home.String() - seal.env["USER"] = username - seal.env[shell] = config.Shell.String() - - seal.container.Place(container.AbsFHSEtc.Append("passwd"), - []byte(username+":x:"+mapuid.String()+":"+mapgid.String()+":Hakurei:"+seal.user.home.String()+":"+config.Shell.String()+"\n")) - seal.container.Place(container.AbsFHSEtc.Append("group"), - []byte("hakurei: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.Enablements.Unwrap()&system.EWayland != 0 { - // outer wayland socket (usually `/run/user/%d/wayland-%d`) - var socketPath *container.Absolute - if name, ok := sys.LookupEnv(wayland.WaylandDisplay); !ok { - hlog.Verbose(wayland.WaylandDisplay + " is not set, assuming " + wayland.FallbackName) - socketPath = share.sc.RuntimePath.Append(wayland.FallbackName) - } else if a, err := container.NewAbs(name); err != nil { - socketPath = share.sc.RuntimePath.Append(name) - } else { - socketPath = a - } - - innerPath := innerRuntimeDir.Append(wayland.FallbackName) - seal.env[wayland.WaylandDisplay] = wayland.FallbackName - - if !config.DirectWayland { // set up security-context-v1 - appID := config.ID - if appID == "" { - // use instance ID in case app id is not set - appID = "app.hakurei." + seal.id.String() - } - // downstream socket paths - outerPath := share.instance().Append("wayland") - seal.sys.Wayland(&seal.sync, outerPath.String(), socketPath.String(), appID, seal.id.String()) - seal.container.Bind(outerPath, innerPath, 0) - } else { // bind mount wayland socket (insecure) - hlog.Verbose("direct wayland access, PROCEED WITH CAUTION") - share.ensureRuntimeDir() - seal.container.Bind(socketPath, innerPath, 0) - seal.sys.UpdatePermType(system.EWayland, socketPath.String(), acl.Read, acl.Write, acl.Execute) - } - } - - if config.Enablements.Unwrap()&system.EX11 != 0 { - if d, ok := sys.LookupEnv(display); !ok { - return hlog.WrapErr(ErrXDisplay, - "DISPLAY is not set") - } else { - socketDir := container.AbsFHSTmp.Append(".X11-unix") - - // the socket file at `/tmp/.X11-unix/X%d` is typically owned by the priv user - // and not accessible by the target user - var socketPath *container.Absolute - if len(d) > 1 && d[0] == ':' { // `:%d` - if n, err := strconv.Atoi(d[1:]); err == nil && n >= 0 { - socketPath = socketDir.Append("X" + strconv.Itoa(n)) - } - } else if len(d) > 5 && strings.HasPrefix(d, "unix:") { // `unix:%s` - if a, err := container.NewAbs(d[5:]); err == nil { - socketPath = a - } - } - if socketPath != nil { - if _, err := sys.Stat(socketPath.String()); err != nil { - if !errors.Is(err, fs.ErrNotExist) { - return hlog.WrapErrSuffix(err, - fmt.Sprintf("cannot access X11 socket %q:", socketPath)) - } - } else { - seal.sys.UpdatePermType(system.EX11, socketPath.String(), acl.Read, acl.Write, acl.Execute) - if !config.Container.HostAbstract { - d = "unix:" + socketPath.String() - } - } - } - - seal.sys.ChangeHosts("#" + seal.user.uid.String()) - seal.env[display] = d - seal.container.Bind(socketDir, socketDir, 0) - } - } - - if config.Enablements.Unwrap()&system.EPulse != 0 { - // PulseAudio runtime directory (usually `/run/user/%d/pulse`) - pulseRuntimeDir := share.sc.RuntimePath.Append("pulse") - // PulseAudio socket (usually `/run/user/%d/pulse/native`) - pulseSocket := pulseRuntimeDir.Append("native") - - if _, err := sys.Stat(pulseRuntimeDir.String()); err != nil { - if !errors.Is(err, fs.ErrNotExist) { - return hlog.WrapErrSuffix(err, - fmt.Sprintf("cannot access PulseAudio directory %q:", pulseRuntimeDir)) - } - return hlog.WrapErr(ErrPulseSocket, - fmt.Sprintf("PulseAudio directory %q not found", pulseRuntimeDir)) - } - - if s, err := sys.Stat(pulseSocket.String()); err != nil { - if !errors.Is(err, fs.ErrNotExist) { - return hlog.WrapErrSuffix(err, - fmt.Sprintf("cannot access PulseAudio socket %q:", pulseSocket)) - } - return hlog.WrapErr(ErrPulseSocket, - fmt.Sprintf("PulseAudio directory %q found but socket does not exist", pulseRuntimeDir)) - } else { - if m := s.Mode(); m&0o006 != 0o006 { - return hlog.WrapErr(ErrPulseMode, - fmt.Sprintf("unexpected permissions on %q:", pulseSocket), m) - } - } - - // hard link pulse socket into target-executable share - innerPulseRuntimeDir := share.runtime().Append("pulse") - innerPulseSocket := innerRuntimeDir.Append("pulse", "native") - seal.sys.Link(pulseSocket.String(), innerPulseRuntimeDir.String()) - seal.container.Bind(innerPulseRuntimeDir, innerPulseSocket, 0) - seal.env[pulseServer] = "unix:" + innerPulseSocket.String() - - // publish current user's pulse cookie for target user - if src, err := discoverPulseCookie(sys); err != nil { - // not fatal - hlog.Verbose(strings.TrimSpace(err.(*hlog.BaseError).Message())) - } else { - innerDst := hst.AbsTmp.Append("/pulse-cookie") - seal.env[pulseCookie] = innerDst.String() - var payload *[]byte - seal.container.PlaceP(innerDst, &payload) - seal.sys.CopyFile(payload, src, 256, 256) - } - } - - if config.Enablements.Unwrap()&system.EDBus != 0 { - // ensure dbus session bus defaults - if config.SessionBus == nil { - config.SessionBus = dbus.NewConfig(config.ID, true, true) - } - - // downstream socket paths - sessionPath, systemPath := share.instance().Append("bus"), share.instance().Append("system_bus_socket") - - // configure dbus proxy - if f, err := seal.sys.ProxyDBus( - config.SessionBus, config.SystemBus, - sessionPath.String(), systemPath.String(), - ); err != nil { - return err - } else { - seal.dbusMsg = f - } - - // share proxy sockets - sessionInner := innerRuntimeDir.Append("bus") - seal.env[dbusSessionBusAddress] = "unix:path=" + sessionInner.String() - seal.container.Bind(sessionPath, sessionInner, 0) - seal.sys.UpdatePerm(sessionPath.String(), acl.Read, acl.Write) - if config.SystemBus != nil { - systemInner := container.AbsFHSRun.Append("dbus/system_bus_socket") - seal.env[dbusSystemBusAddress] = "unix:path=" + systemInner.String() - seal.container.Bind(systemPath, systemInner, 0) - seal.sys.UpdatePerm(systemPath.String(), acl.Read, acl.Write) - } - } - - // mount root read-only as the final setup Op - seal.container.Remount(container.AbsFHSRoot, syscall.MS_RDONLY) - - // append ExtraPerms last - for _, p := range config.ExtraPerms { - if p == nil || p.Path == nil { - continue - } - - if p.Ensure { - seal.sys.Ensure(p.Path.String(), 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.String(), 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 hlog.WrapErr(syscall.EINVAL, - fmt.Sprintf("invalid environment variable %s", k)) - } - seal.container.Env = append(seal.container.Env, k+"="+v) - } - slices.Sort(seal.container.Env) - - if hlog.Load() { - hlog.Verbosef("created application seal for uid %s (%s) groups: %v, argv: %s, ops: %d", - seal.user.uid, seal.user.username, config.Groups, seal.container.Args, len(*seal.container.Ops)) - } - - 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, hlog.WrapErrSuffix(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, hlog.WrapErrSuffix(err, - fmt.Sprintf("cannot access PulseAudio cookie %q:", p)) - } - // not found, try next method - } else if !s.IsDir() { - return p, nil - } - } - - return "", hlog.WrapErr(ErrPulseCookie, - fmt.Sprintf("cannot locate PulseAudio cookie (tried $%s, $%s/pulse/cookie, $%s/.pulse-cookie)", - pulseCookie, xdgConfigHome, home)) -} diff --git a/internal/app/shim.go b/internal/app/shim.go new file mode 100644 index 00000000..33ede520 --- /dev/null +++ b/internal/app/shim.go @@ -0,0 +1,183 @@ +package app + +import ( + "context" + "errors" + "io" + "log" + "os" + "os/exec" + "os/signal" + "runtime" + "sync/atomic" + "syscall" + "time" + + "hakurei.app/container" + "hakurei.app/container/seccomp" + "hakurei.app/internal" + "hakurei.app/internal/hlog" +) + +//#include "shim-signal.h" +import "C" + +const shimEnv = "HAKUREI_SHIM" + +type shimParams struct { + // monitor pid, checked against ppid in signal handler + Monitor int + + // duration to wait for after interrupting a container's initial process before the container is killed; + // zero value defaults to [DefaultShimWaitDelay], values exceeding [MaxShimWaitDelay] becomes [MaxShimWaitDelay] + WaitDelay time.Duration + + // finalised container params + Container *container.Params + + // verbosity pass through + Verbose bool +} + +const ( + // ShimExitRequest is returned when the monitor process requests shim exit. + ShimExitRequest = 254 + // ShimExitOrphan is returned when the shim is orphaned before monitor delivers a signal. + ShimExitOrphan = 3 + + DefaultShimWaitDelay = 5 * time.Second + MaxShimWaitDelay = 30 * time.Second +) + +// ShimMain is the main function of the shim process and runs as the unconstrained target user. +func ShimMain() { + hlog.Prepare("shim") + + if err := container.SetDumpable(container.SUID_DUMP_DISABLE); err != nil { + log.Fatalf("cannot set SUID_DUMP_DISABLE: %s", err) + } + + var ( + params shimParams + closeSetup func() error + ) + if f, err := container.Receive(shimEnv, ¶ms, nil); err != nil { + if errors.Is(err, syscall.EBADF) { + log.Fatal("invalid config descriptor") + } + if errors.Is(err, container.ErrNotSet) { + log.Fatal("HAKUREI_SHIM not set") + } + + log.Fatalf("cannot receive shim setup params: %v", err) + } else { + internal.InstallOutput(params.Verbose) + closeSetup = f + } + + var signalPipe io.ReadCloser + // the Go runtime does not expose siginfo_t so SIGCONT is handled in C to check si_pid + if r, w, err := os.Pipe(); err != nil { + log.Fatalf("cannot pipe: %v", err) + } else if _, err = C.hakurei_shim_setup_cont_signal(C.pid_t(params.Monitor), C.int(w.Fd())); err != nil { + log.Fatalf("cannot install SIGCONT handler: %v", err) + } else { + defer runtime.KeepAlive(w) + signalPipe = r + } + + // 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) + } + + // signal handler outcome + var cancelContainer atomic.Pointer[context.CancelFunc] + go func() { + buf := make([]byte, 1) + for { + if _, err := signalPipe.Read(buf); err != nil { + log.Fatalf("cannot read from signal pipe: %v", err) + } + + switch buf[0] { + case 0: // got SIGCONT from monitor: shim exit requested + if fp := cancelContainer.Load(); params.Container.ForwardCancel && fp != nil && *fp != nil { + (*fp)() + // shim now bound by ShimWaitDelay, implemented below + continue + } + + // setup has not completed, terminate immediately + hlog.Resume() + os.Exit(ShimExitRequest) + return + + case 1: // got SIGCONT after adoption: monitor died before delivering signal + hlog.BeforeExit() + os.Exit(ShimExitOrphan) + return + + case 2: // unreachable + log.Println("sa_sigaction got invalid siginfo") + + case 3: // got SIGCONT from unexpected process: hopefully the terminal driver + log.Println("got SIGCONT from unexpected process") + + default: // unreachable + log.Fatalf("got invalid message %d from signal handler", buf[0]) + } + } + }() + + 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 + } + + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + cancelContainer.Store(&stop) + z := container.New(ctx) + z.Params = *params.Container + z.Stdin, z.Stdout, z.Stderr = os.Stdin, os.Stdout, os.Stderr + + z.WaitDelay = params.WaitDelay + if z.WaitDelay == 0 { + z.WaitDelay = DefaultShimWaitDelay + } + if z.WaitDelay > MaxShimWaitDelay { + z.WaitDelay = MaxShimWaitDelay + } + + if err := z.Start(); err != nil { + hlog.PrintBaseError(err, "cannot start container:") + os.Exit(1) + } + if err := z.Serve(); err != nil { + hlog.PrintBaseError(err, "cannot configure container:") + } + + if err := seccomp.Load( + seccomp.Preset(seccomp.PresetStrict, seccomp.AllowMultiarch), + seccomp.AllowMultiarch, + ); err != nil { + log.Fatalf("cannot load syscall filter: %v", err) + } + + if err := z.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/shim_linux.go b/internal/app/shim_linux.go deleted file mode 100644 index 33ede520..00000000 --- a/internal/app/shim_linux.go +++ /dev/null @@ -1,183 +0,0 @@ -package app - -import ( - "context" - "errors" - "io" - "log" - "os" - "os/exec" - "os/signal" - "runtime" - "sync/atomic" - "syscall" - "time" - - "hakurei.app/container" - "hakurei.app/container/seccomp" - "hakurei.app/internal" - "hakurei.app/internal/hlog" -) - -//#include "shim-signal.h" -import "C" - -const shimEnv = "HAKUREI_SHIM" - -type shimParams struct { - // monitor pid, checked against ppid in signal handler - Monitor int - - // duration to wait for after interrupting a container's initial process before the container is killed; - // zero value defaults to [DefaultShimWaitDelay], values exceeding [MaxShimWaitDelay] becomes [MaxShimWaitDelay] - WaitDelay time.Duration - - // finalised container params - Container *container.Params - - // verbosity pass through - Verbose bool -} - -const ( - // ShimExitRequest is returned when the monitor process requests shim exit. - ShimExitRequest = 254 - // ShimExitOrphan is returned when the shim is orphaned before monitor delivers a signal. - ShimExitOrphan = 3 - - DefaultShimWaitDelay = 5 * time.Second - MaxShimWaitDelay = 30 * time.Second -) - -// ShimMain is the main function of the shim process and runs as the unconstrained target user. -func ShimMain() { - hlog.Prepare("shim") - - if err := container.SetDumpable(container.SUID_DUMP_DISABLE); err != nil { - log.Fatalf("cannot set SUID_DUMP_DISABLE: %s", err) - } - - var ( - params shimParams - closeSetup func() error - ) - if f, err := container.Receive(shimEnv, ¶ms, nil); err != nil { - if errors.Is(err, syscall.EBADF) { - log.Fatal("invalid config descriptor") - } - if errors.Is(err, container.ErrNotSet) { - log.Fatal("HAKUREI_SHIM not set") - } - - log.Fatalf("cannot receive shim setup params: %v", err) - } else { - internal.InstallOutput(params.Verbose) - closeSetup = f - } - - var signalPipe io.ReadCloser - // the Go runtime does not expose siginfo_t so SIGCONT is handled in C to check si_pid - if r, w, err := os.Pipe(); err != nil { - log.Fatalf("cannot pipe: %v", err) - } else if _, err = C.hakurei_shim_setup_cont_signal(C.pid_t(params.Monitor), C.int(w.Fd())); err != nil { - log.Fatalf("cannot install SIGCONT handler: %v", err) - } else { - defer runtime.KeepAlive(w) - signalPipe = r - } - - // 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) - } - - // signal handler outcome - var cancelContainer atomic.Pointer[context.CancelFunc] - go func() { - buf := make([]byte, 1) - for { - if _, err := signalPipe.Read(buf); err != nil { - log.Fatalf("cannot read from signal pipe: %v", err) - } - - switch buf[0] { - case 0: // got SIGCONT from monitor: shim exit requested - if fp := cancelContainer.Load(); params.Container.ForwardCancel && fp != nil && *fp != nil { - (*fp)() - // shim now bound by ShimWaitDelay, implemented below - continue - } - - // setup has not completed, terminate immediately - hlog.Resume() - os.Exit(ShimExitRequest) - return - - case 1: // got SIGCONT after adoption: monitor died before delivering signal - hlog.BeforeExit() - os.Exit(ShimExitOrphan) - return - - case 2: // unreachable - log.Println("sa_sigaction got invalid siginfo") - - case 3: // got SIGCONT from unexpected process: hopefully the terminal driver - log.Println("got SIGCONT from unexpected process") - - default: // unreachable - log.Fatalf("got invalid message %d from signal handler", buf[0]) - } - } - }() - - 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 - } - - ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) - cancelContainer.Store(&stop) - z := container.New(ctx) - z.Params = *params.Container - z.Stdin, z.Stdout, z.Stderr = os.Stdin, os.Stdout, os.Stderr - - z.WaitDelay = params.WaitDelay - if z.WaitDelay == 0 { - z.WaitDelay = DefaultShimWaitDelay - } - if z.WaitDelay > MaxShimWaitDelay { - z.WaitDelay = MaxShimWaitDelay - } - - if err := z.Start(); err != nil { - hlog.PrintBaseError(err, "cannot start container:") - os.Exit(1) - } - if err := z.Serve(); err != nil { - hlog.PrintBaseError(err, "cannot configure container:") - } - - if err := seccomp.Load( - seccomp.Preset(seccomp.PresetStrict, seccomp.AllowMultiarch), - seccomp.AllowMultiarch, - ); err != nil { - log.Fatalf("cannot load syscall filter: %v", err) - } - - if err := z.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()) - } -} -- cgit v1.3.1