aboutsummaryrefslogtreecommitdiffhomepage
path: root/internal/sandbox/container.go
diff options
context:
space:
mode:
authorOphestra <cat@gensokyo.uk>2025-03-13 20:59:03 +0900
committerOphestra <cat@gensokyo.uk>2025-03-13 21:36:26 +0900
commit9b1a60b5c9f7a92abb632639117d61c5cbaf74f7 (patch)
tree0fa6b8dae30a9a687f0e465c7d0fc5e0f24b48b1 /internal/sandbox/container.go
parentbeb3918809f0743e2275f6a3f358f622cea73d6b (diff)
sandbox: native container tooling
This should eventually replace bwrap. Signed-off-by: Ophestra <cat@gensokyo.uk>
Diffstat (limited to 'internal/sandbox/container.go')
-rw-r--r--internal/sandbox/container.go212
1 files changed, 212 insertions, 0 deletions
diff --git a/internal/sandbox/container.go b/internal/sandbox/container.go
new file mode 100644
index 00000000..91db06ef
--- /dev/null
+++ b/internal/sandbox/container.go
@@ -0,0 +1,212 @@
+package sandbox
+
+import (
+ "context"
+ "encoding/gob"
+ "fmt"
+ "io"
+ "os"
+ "os/exec"
+ "path"
+ "strconv"
+ "syscall"
+
+ "git.gensokyo.uk/security/fortify/helper/proc"
+ "git.gensokyo.uk/security/fortify/helper/seccomp"
+ "git.gensokyo.uk/security/fortify/internal"
+ "git.gensokyo.uk/security/fortify/internal/fmsg"
+)
+
+type HardeningFlags uintptr
+
+const (
+ FAllowUserns HardeningFlags = 1 << iota
+ FAllowTTY
+ FAllowNet
+)
+
+func (flags HardeningFlags) seccomp(opts seccomp.SyscallOpts) seccomp.SyscallOpts {
+ if flags&FAllowUserns == 0 {
+ opts |= seccomp.FlagDenyNS
+ }
+ if flags&FAllowTTY == 0 {
+ opts |= seccomp.FlagDenyTTY
+ }
+ return opts
+}
+
+type (
+ // Container represents a container environment being prepared or run.
+ // None of [Container] methods are safe for concurrent use.
+ Container struct {
+ // Name of initial process in the container.
+ name string
+ // Cgroup fd, nil to disable.
+ Cgroup *int
+ // ExtraFiles passed through to initial process in the container,
+ // with behaviour identical to its [exec.Cmd] counterpart.
+ ExtraFiles []*os.File
+
+ InitParams
+ // Custom [exec.Cmd] initialisation function.
+ CommandContext func(ctx context.Context) (cmd *exec.Cmd)
+ // mapped uid in user namespace
+ Uid int
+ // mapped gid in user namespace
+ Gid int
+
+ // param encoder for shim and init
+ setup *gob.Encoder
+ // cancels cmd
+ cancel context.CancelFunc
+
+ Stdin io.Reader
+ Stdout io.Writer
+ Stderr io.Writer
+
+ cmd *exec.Cmd
+ ctx context.Context
+ }
+
+ InitParams struct {
+ // Working directory in the container.
+ Dir string
+ // Initial process environment.
+ Env []string
+ // Absolute path of initial process in the container. Overrides name.
+ Path string
+ // Initial process argv.
+ Args []string
+
+ // Hostname value in UTS namespace.
+ Hostname string
+ // Sequential container setup ops.
+ *Ops
+ // Extra seccomp options.
+ Seccomp seccomp.SyscallOpts
+
+ Flags HardeningFlags
+ }
+
+ Ops []Op
+ Op interface {
+ apply() error
+
+ Is(op Op) bool
+ fmt.Stringer
+ }
+)
+
+func (p *Container) Start() error {
+ if p.cmd != nil {
+ panic("attempted to start twice")
+ }
+
+ c, cancel := context.WithCancel(p.ctx)
+ p.cancel = cancel
+
+ var cloneFlags uintptr = syscall.CLONE_NEWIPC |
+ syscall.CLONE_NEWUTS |
+ syscall.CLONE_NEWCGROUP
+ if p.Flags&FAllowNet == 0 {
+ cloneFlags |= syscall.CLONE_NEWNET
+ }
+
+ // map to overflow id to work around ownership checks
+ if p.Uid < 1 {
+ p.Uid = OverflowUid()
+ }
+ if p.Gid < 1 {
+ p.Gid = OverflowGid()
+ }
+
+ p.cmd = p.CommandContext(c)
+ p.cmd.Stdin, p.cmd.Stdout, p.cmd.Stderr = p.Stdin, p.Stdout, p.Stderr
+ p.cmd.Dir = "/"
+ p.cmd.SysProcAttr = &syscall.SysProcAttr{
+ Setsid: p.Flags&FAllowTTY == 0,
+ Pdeathsig: syscall.SIGKILL,
+
+ Cloneflags: cloneFlags |
+ syscall.CLONE_NEWUSER |
+ syscall.CLONE_NEWPID |
+ syscall.CLONE_NEWNS,
+
+ UidMappings: []syscall.SysProcIDMap{{p.Uid, syscall.Getuid(), 1}},
+ GidMappings: []syscall.SysProcIDMap{{p.Gid, syscall.Getgid(), 1}},
+ // remain privileged for setup
+ AmbientCaps: []uintptr{CAP_SYS_ADMIN},
+
+ UseCgroupFD: p.Cgroup != nil,
+ }
+ if p.cmd.SysProcAttr.UseCgroupFD {
+ p.cmd.SysProcAttr.CgroupFD = *p.Cgroup
+ }
+
+ // place setup pipe before user supplied extra files, this is later restored by init
+ if fd, e, err := proc.Setup(&p.cmd.ExtraFiles); err != nil {
+ return fmsg.WrapErrorSuffix(err,
+ "cannot create shim setup pipe:")
+ } else {
+ p.setup = e
+ p.cmd.Env = []string{setupEnv + "=" + strconv.Itoa(fd)}
+ }
+ p.cmd.ExtraFiles = append(p.cmd.ExtraFiles, p.ExtraFiles...)
+
+ fmsg.Verbose("starting container init")
+ if err := p.cmd.Start(); err != nil {
+ return fmsg.WrapError(err, err.Error())
+ }
+ return nil
+}
+
+func (p *Container) Serve() error {
+ if p.setup == nil {
+ panic("invalid serve")
+ }
+
+ if p.Path != "" && !path.IsAbs(p.Path) {
+ return fmsg.WrapError(syscall.EINVAL,
+ fmt.Sprintf("invalid executable path %q", p.Path))
+ }
+
+ if p.Path == "" {
+ if p.name == "" {
+ p.Path = os.Getenv("SHELL")
+ if !path.IsAbs(p.Path) {
+ return fmsg.WrapError(syscall.EBADE,
+ "no command specified and $SHELL is invalid")
+ }
+ p.name = path.Base(p.Path)
+ } else if path.IsAbs(p.name) {
+ p.Path = p.name
+ } else if v, err := exec.LookPath(p.name); err != nil {
+ return fmsg.WrapError(err, err.Error())
+ } else {
+ p.Path = v
+ }
+ }
+
+ setup := p.setup
+ p.setup = nil
+ return setup.Encode(
+ &initParams{
+ p.InitParams,
+ len(p.ExtraFiles),
+ fmsg.Load(),
+ },
+ )
+}
+
+func (p *Container) Wait() error { defer p.cancel(); return p.cmd.Wait() }
+
+func New(ctx context.Context, name string, args ...string) *Container {
+ return &Container{name: name, ctx: ctx,
+ InitParams: InitParams{Args: append([]string{name}, args...), Dir: "/", Ops: new(Ops)},
+ CommandContext: func(ctx context.Context) (cmd *exec.Cmd) {
+ cmd = exec.CommandContext(ctx, internal.MustExecutable())
+ cmd.Args = []string{"init"}
+ return
+ },
+ }
+}