mini-sentry: Building a Small gVisor-Style Userspace Kernel in Go

I built a small userspace kernel in Go to understand how gVisor works. I’d been reading about gVisor for months, but reading the design didn’t tell me why it was built the way it is. Building a small version did, mostly one segfault at a time.

mini-sentry sits between a sandboxed process and the Linux kernel, intercepts every system call, and handles it in Go. The sandboxed process thinks it’s talking to Linux. It’s actually talking to my code. It isn’t a container runtime or a syscall filter.

Why gVisor’s design is interesting

Google runs gVisor under App Engine, Cloud Run, Cloud Functions and GKE Sandbox, between untrusted workloads and the host kernel. The security idea is simple: if a sandboxed process uses a kernel exploit, it hits Go code that reimplements the kernel’s interface, not the real kernel.

gVisor is also about two hundred thousand lines of Go, and the architecture is hard to see from the source. I wanted the core ideas without the production concerns: syscall interception, handling syscalls in userspace, filesystem virtualization and process isolation.

Architecture

mini-sentry uses the same layers as gVisor, cut down:

┌──────────────────────────────────────────┐
│  Guest Process (sandboxed)               │
│  Thinks it's talking to Linux            │
└─────────────────┬────────────────────────┘
                  │ syscall
┌─────────────────▼────────────────────────┐
│  Platform (ptrace or seccomp)            │
│  Intercepts syscalls, reads registers    │
└─────────────────┬────────────────────────┘
                  │ SyscallArgs
┌─────────────────▼────────────────────────┐
│  Sentry (Go handlers)                   │
│  The userspace kernel. Handles read,     │
│  write, openat, stat, socket, etc.       │
└─────────────────┬────────────────────────┘
                  │ RPC
┌─────────────────▼────────────────────────┐
│  Gofer (separate process)                │
│  Serves files over Unix socket.          │
│  Filesystem security boundary.           │
└──────────────────────────────────────────┘
  • Platform: intercepts syscalls from the sandboxed process, using either PTRACE_SYSEMU or SECCOMP_RET_USER_NOTIF (seccomp is much faster, see below). It reads the registers and passes them up without interpreting anything.
  • Sentry: the userspace kernel. It has a table-based syscall dispatch (like gVisor’s SyscallTable.Lookup()), an fd table, and handlers for about sixty syscalls. When the guest calls read(fd, buf, count), the Sentry serves data from its virtual filesystem. getpid() returns 1. The real kernel never sees these calls.
  • Gofer: a separate process that does all filesystem access. It talks to the Sentry over a Unix socket with a gob-encoded wire protocol. If an attacker fully compromises the Sentry, they still only get the files the Gofer was told to serve. This mirrors gVisor’s LISAFS architecture, and I think it’s the most important security decision in the design.

The ptrace interception loop

The ptrace platform is a short loop:

func (p *PtracePlatform) interceptLoop(pid int) (int, error) {
    for {
        // Resume child, stop at next syscall entry, SKIP the real syscall
        ptraceSysemu(pid, 0)

        // Wait for child to stop
        syscall.Wait4(pid, &ws, 0, nil)

        // Read registers → syscall number + args
        unix.PtraceGetRegs(pid, &regs)
        sc := regsToSyscall(&regs)

        // Let the Sentry handle it
        ret, action := p.sentry.HandleSyscall(pid, sc)

        // Write return value back into RAX
        setSyscallReturn(&regs, ret)
        unix.PtraceSetRegs(pid, &regs)
    }
}

The key piece is PTRACE_SYSEMU (constant 31). PTRACE_SYSCALL stops the child on syscall entry and exit and actually runs the syscall. PTRACE_SYSEMU stops only on entry and tells the kernel to skip the syscall. Whatever you write into RAX is the result the child sees, so the tracer effectively is the kernel.

Some syscalls have to reach the real kernel

The first version crashed immediately.

The cause was arch_prctl(SET_FS), which sets the FS register used for thread-local storage. That’s kernel-managed state, and register tricks from userspace can’t fake it. The same goes for mmap, brk, mprotect and signal handling: they change the process’s real memory and execution state, so the real kernel has to run them.

So the Sentry emulates some syscalls and passes the rest through to the kernel. Passthrough is harder than it sounds with PTRACE_SYSEMU. By the time the tracer sees the entry stop, the kernel has already moved the instruction pointer past the syscall instruction and marked the call as skipped. Resuming the child doesn’t make the kernel run it.

The fix:

  1. Rewind the instruction pointer by two bytes, the width of the syscall instruction on x86_64.
  2. Restore RAX to the original syscall number. The kernel overwrote it with -ENOSYS during the SYSEMU stop.
  3. Resume with PTRACE_SYSCALL instead of PTRACE_SYSEMU.

The child re-executes the instruction, the kernel runs the syscall for real, and the tracer gets a syscall-exit stop with the result in RAX.

// simplified: error checks elided
func (p *PtracePlatform) passthroughSyscall(pid int, regs *unix.PtraceRegs) error {
    var ws syscall.WaitStatus
    rewindSyscallInstruction(regs) // RIP -= 2 on amd64
    restoreSyscallNumber(regs)     // RAX = orig_rax
    unix.PtraceSetRegs(pid, regs)

    // Entry stop (real this time)
    syscall.PtraceSyscall(pid, 0)
    syscall.Wait4(pid, &ws, 0, nil)

    // Exit stop — kernel ran the syscall, result is in RAX
    syscall.PtraceSyscall(pid, 0)
    syscall.Wait4(pid, &ws, 0, nil)
    return nil
}

This is close to what gVisor’s ptrace platform does to inject the Sentry’s own syscalls into its stub processes (gVisor never hands the application’s syscalls to the host). I got there on my own, after the segfault and some late-night reading of kernel source, which was satisfying.

Seccomp: 37 times the throughput of ptrace

The ptrace platform has a built-in cost: every syscall, including ones the kernel could handle by itself, needs a context switch to the tracer. In a tight getpid() benchmark, ptrace does about 17,000 calls per second.

The seccomp platform sorts syscalls in the kernel with a BPF filter before they reach userspace:

  • Syscalls the Sentry handles (read, write, openat and so on) get SECCOMP_RET_USER_NOTIF, which pauses the child and notifies the Sentry.
  • Everything else (mmap, brk, futex and the rest of memory management) gets SECCOMP_RET_ALLOW and goes straight to the kernel. The Sentry never wakes up for them.

Setting this up takes some work. The seccomp() call has to be made by the process the filter applies to, but the notification fd has to end up in the Sentry. So:

  1. The parent fork-and-execs /proc/self/exe with an environment variable set.
  2. The child installs the filter.
  3. The child sends the listener fd back over a Unix socket with SCM_RIGHTS.
  4. The child calls execve on the real target program.

Under seccomp the benchmark does 640,000 getpid() calls per second, against 17,000 under ptrace: about 37 times as many. This compares the cost of interception, not two handler implementations: in benchmark mode getpid is on the filter’s allow list, so under seccomp these are native calls that never reach the Sentry, while under ptrace every one is intercepted. That difference is the whole point of the seccomp design: for passthrough syscalls the Sentry stays asleep while the kernel does its normal work. gVisor moved from ptrace to its systrap platform (built on SECCOMP_RET_TRAP and shared memory) for the same reason.

The Gofer as a security boundary

The principle behind the Gofer is simple: the process that handles untrusted input shouldn’t be the one with access to sensitive resources.

The parent creates a Unix socketpair and fork-and-execs itself with MINI_SENTRY_GOFER=1. The child runs a request-response loop, serving files from an in-memory store or from a host directory given by --gofer-root. The Sentry sends RPCs (open, read, stat, list) and the Gofer replies with file data or errors. The wire protocol is length-prefixed gob encoding over the socket, which is simple and gives an attacker little to work with.

The Gofer also handles two security details:

  • --gofer-deny blocks specific paths.
  • Symlinks are resolved on both sides with filepath.EvalSymlinks, which blocks the classic escape where a symlink points outside the served directory.

Network virtualization

The Sentry also intercepts socket(), connect(), sendto(), recvfrom() and the sockopt family. When the guest calls connect(fd, addr, len), the Sentry parses the sockaddr_in, checks the destination against --net-allow and --net-deny, and if allowed, does a real net.Dial from the Sentry process. The guest gets a virtual file descriptor backed by a net.Conn that the Sentry owns. The real kernel never sees the guest’s network calls.

Testing

The failure modes here are subtle, and missing one can mean a sandbox escape, so the tests come at it from several directions:

  • a Go guest program that checks sandbox identity and VFS operations;
  • static C binaries (echo, cat, ls, pwd) that test real programs under interception;
  • an adversarial edge-case binary that probes the boundaries;
  • a stress test for sustained operation;
  • a syscall fuzzer that fires ten thousand random syscalls;
  • Go fuzz tests on the path resolver, the wire protocol and syscall argument parsing;
  • property-based tests for invariants, such as deny rules always blocking and virtual files always overriding host files.

All eighteen integration checks run in CI on every push.

What I learned

  1. You can’t emulate everything from userspace. PTRACE_SYSEMU looks like total control, but some syscalls change kernel state so basic (page tables, TLS registers, signal masks) that they have to reach the real kernel. The SYSEMU-to-SYSCALL passthrough isn’t obvious until your sandbox segfaults on its first arch_prctl.
  2. Interception cost dominates. Ptrace is simple and correct, but it pays a context switch on every syscall. Seccomp with USER_NOTIF lets the kernel handle routine calls and sends only the interesting ones to the Sentry. The 37x gap comes from a different architecture, not from tuning.
  3. Building it teaches what reading the source doesn’t. gVisor’s code assumes invariants it never explains. Writing the core loop and watching it break is how I found them.

The source is at github.com/mtclinton/mini-sentry. To run it:

make build && make guest && ./mini-sentry ./cmd/guest/guest

Seccomp mode: ./mini-sentry --platform=seccomp ./cmd/guest/guest. The benchmark behind the numbers above: ./mini-sentry --benchmark ./cmd/guest/guest.