Hijacking Signals in Go - Notes from a Tiny gVisor

I’ve been writing a toy version of gVisor, Google’s userspace kernel, to learn how it intercepts syscalls. The project is github.com/mtclinton/mini-sentry. The idea: if a sandboxed Linux program calls write(), the kernel doesn’t handle it, my Go code does. That’s gVisor’s security model. A kernel exploit inside write() doesn’t matter if the kernel never runs write().

Most of the project went more easily than I expected. PTRACE_SYSEMU catches every syscall before the kernel touches it, my Go handlers fill in a return value, and I resume the guest. A few hundred lines of that gave me a sandbox that could run static Linux binaries against a fake filesystem, and for a while I thought I was mostly done.

Then I tried to make signals work, and that took the next three phases of the project. These are my notes from that.

Syscall interception in one page

Before signals, the design is simple. PTRACE_SYSEMU is a ptrace operation that stops the tracee every time it’s about to make a syscall, skips the real call, and lets the tracer write a return value straight into RAX:

// simplified loop
for {
    ptraceSysemu(pid, 0)  // raw ptrace(31, ...): x/sys has no SYSEMU wrapper
    wait4(pid, &ws)
    regs := readRegs(pid)
    ret := sentry.HandleSyscall(regs)
    regs.Rax = uint64(ret)
    writeRegs(pid, regs)
}

If I want the kernel to handle something, say mmap, which touches page tables you can’t fake from userspace, I rewind RIP by two bytes (the width of the syscall instruction) and step with PTRACE_SYSCALL instead. The kernel runs it and I read the result.

That’s enough to emulate read, write, openat, getdents64, getpid, getuid and a dozen related calls. The sandbox could print “hello” and read fake files from an in-memory VFS.

Phase 3a: tracking rt_sigaction doesn’t deliver anything

On the surface, rt_sigaction(2) is just a table write. The kernel keeps an array of sigaction structs, one per signal, and rt_sigaction(SIGUSR1, &act, NULL) writes slot 10. Emulating it looks easy:

func (s *Sentry) sysRtSigaction(pid int, sc SyscallArgs) uint64 {
    signum := int(sc.Args[0])
    buf := readFromChild(pid, sc.Args[1], sigactionSize)
    s.signals.SetAction(signum, decodeAction(buf))
    return 0
}

The problem is that this only tracks state. The kernel still owns delivery. When something sends SIGUSR1, the kernel looks at its own sigaction table, not mine, and runs whatever handler was installed before I started intercepting anything. My copy of the table had no effect on behavior.

This phase also forced me to understand gVisor’s Task and ThreadGroup split, because I had to reproduce it. Signal masks and pending queues are per-thread; the sigaction table is per-thread-group. gVisor has a Task struct for the per-thread part and a ThreadGroup for the shared part. Mine are ThreadState and ThreadGroup. It’s also why kill(pid, sig) can pick any thread in the group while tkill targets exactly one: the routing check looks at every per-thread mask in the group.

At the end of Phase 3a I had a mirror of the signal state that didn’t deliver a single signal.

Phase 3b: building the signal frame myself

To own delivery, the Sentry has to build the signal frame itself. On x86_64 that’s struct rt_sigframe, about 1032 bytes, and it has to match the kernel’s layout byte for byte:

+0x000 pretcode        pointer to rt_sigreturn trampoline
+0x008 ucontext        { flags, link, stack, mcontext (RAX..RIP..), sigmask }   (304 bytes)
+0x138 siginfo         { si_signo, si_code, si_pid, si_uid, ... }
+0x1C8 fpstate         { 512-byte FXSAVE area }

The contract:

  1. Write the frame onto the guest’s stack.
  2. Point RSP at it, set RIP to the handler, and resume the guest.
  3. The handler runs and returns with ret, which pops pretcode and lands in a small trampoline that calls rt_sigreturn.
  4. rt_sigreturn is the inverse of frame construction: it reads the frame back, restores the registers from before the handler, and the interrupted code carries on.

In mini-sentry, BuildRtSigframe writes the frame with process_vm_writev and sysRtSigreturn reads it back with process_vm_readv. The round trip is about 600 lines across frame_amd64.go, deliver_amd64.go and handlers_signals_amd64.go, and most of it is byte-layout bookkeeping. Owning delivery means matching the kernel’s struct offsets exactly.

I wrote both halves, wired up a guest test that did kill(getpid(), SIGUSR1) with a handler that atomically incremented a counter, ran it, and got:

runtime: newstack sp=0xc00000dbf8 stack=[0xc0000ce000, 0xc0000d6000]

Go’s stack guard was saying the stack pointer was outside the goroutine’s stack. This was the first of two bugs that cost me real time, and the more instructive one.

The Go compiler’s ABI wrapper

The guest test installed its handler like this:

act := sigactionKernel{
    Handler:  reflect.ValueOf(sigusr1Handler).Pointer(),
    Flags:    saSigInfo | saRestorer,
    Restorer: reflect.ValueOf(restoreRT).Pointer(),
}

sigusr1Handler was pure assembly, with no Go frame and no stack-growth check: LEAQ sigCounter, AX; MOVL $1, BX; LOCK; XADDL BX, (AX); RET. I wrote it in assembly because signal handlers can’t touch Go’s runtime. The kernel enters a signal handler using the SysV C ABI, but Go’s ABIInternal expects R14 to hold the current goroutine pointer, and on signal entry R14 holds whatever the interrupted code left there. A Go handler that touches any runtime function breaks immediately.

The bug was that reflect.ValueOf(fn).Pointer() didn’t return the address of my assembly. It returned the address of a compiler-generated wrapper. When a .s file defines sigusr1Handler and a .go file declares func sigusr1Handler(), the Go toolchain generates an ABIInternal shim:

sigusr1Handler:
    PUSHQ BP
    MOVQ  SP, BP
    CALL  sigusr1Handler.abi0    ; the real asm
    POPQ  BP
    RET

That PUSHQ BP and CALL move RSP by sixteen bytes. The counter handler didn’t care about RSP, but the same kind of wrapper had been installed as the sa_restorer. When the handler returned, it popped pretcode into RIP and landed in the restorer’s wrapper, not the real restoreRT:

W_restore:
    PUSHQ BP                   ; RSP -= 8
    MOVQ  SP, BP
    CALL  restoreRT.abi0       ; RSP -= 8 (pushes return addr)
    ; restoreRT.abi0: MOVQ $15, AX; SYSCALL

By the time the syscall instruction inside the real restoreRT ran, RSP was sixteen bytes below where sysRtSigreturn expected the frame. It read 1032 bytes of garbage, decoded a nonsense register set, and PTRACE_SETREGS loaded it into the tracee. The stack-guard panic was the first visible symptom of values corrupted three steps earlier, which describes most systems bugs.

The fix was to avoid the wrapper entirely:

GLOBL ·sigusr1HandlerPC(SB), RODATA, $8
DATA  ·sigusr1HandlerPC(SB)/8, $·sigusr1Handler(SB)

GLOBL ·restoreRTPC(SB), RODATA, $8
DATA  ·restoreRTPC(SB)/8, $·restoreRT(SB)

A GLOBL/DATA pair in the .s file exposes the raw ABI0 entry point as a plain uintptr. On the Go side I deleted the func sigusr1Handler() and func restoreRT() declarations so the compiler had no reason to generate wrappers, and installed the handler using the PC variable. Now the handler runs at the address the kernel wrote into the frame, RSP stays where rt_sigreturn expects it, and the round trip works.

I confirmed it with go tool objdump -s sigusr1Handler ./cmd/guest/guest. The wrapper entry sat a few dozen bytes above the raw handler, one with the PUSHQ BP / CALL prologue and one without. reflect.ValueOf had returned a valid pointer, just the wrong one.

Debugging this took about half a day, most of it in a disassembler.

PTRACE_SETREGS rejects CS=0

The second bug was shorter but no more obvious. After decoding the signal frame on rt_sigreturn, I wrote the restored registers back to the tracee:

var restored unix.PtraceRegs
readMContext(frame, &restored)
unix.PtraceSetRegs(pid, &restored)  // input/output error

PTRACE_SETREGS returned EIO. The frame’s mcontext includes cs, gs, fs and ss alongside the general-purpose registers, RIP, RSP and EFLAGS, but the cs and ss values that came back weren’t valid. restored.Cs was zero.

The kernel rejects PTRACE_SETREGS with CS=0 on a 64-bit user task, because CS=0 is non-canonical and would crash userspace. The fix was to merge the restored fields into the live register set instead of replacing it:

regs, _ := unix.PtraceGetRegs(pid)
regs.Rax = restored.Rax
regs.Rip = restored.Rip
regs.Rsp = restored.Rsp
// ... GPRs, RIP, RSP, EFLAGS
// Do NOT touch Cs, Ss, Fs_base, Gs_base, Orig_rax
unix.PtraceSetRegs(pid, &regs)

Segment registers and orig_rax have to come from the state before rt_sigreturn. Handlers aren’t expected to change them anyway.

The lesson: the mcontext isn’t a complete register file. It’s the subset of user-visible state a signal handler might want to read or change. The kernel tracks the rest itself, and a userspace reimplementation has to remember that.

Phase 3c: routing signals to the right thread

The last phase made all of this work when the guest has more than one thread. The Go runtime creates OS threads with clone(CLONE_THREAD), and by default my tracer only attached to the first one. Every other thread ran untraced, so signals routed to them bypassed the Sentry and went straight to the kernel.

The fix was PTRACE_O_TRACECLONE. With it, the kernel stops the parent on every clone, reports a PTRACE_EVENT_CLONE with the new tid, and attaches the new thread automatically. I add the tid to my ThreadGroup, so every thread in the guest is traced and every syscall reaches the Sentry.

Routing then follows gVisor’s canReceiveSignalLocked:

  • kill(tgid, sig): walk the threads in a fixed order and pick the first one whose per-thread mask doesn’t block sig.
  • tkill(tid, sig): route to that tid.
  • Self-sends (kill(getpid(), sig) from inside the guest): resolve to the caller’s host tid using the ptrace-event metadata.

The test runs four goroutines. Each locks itself to an OS thread and calls tgkill(getpid(), gettid(), SIGUSR1). All four handlers fire, the counter goes from one to five, and the integration test passes.

arm64: delegate instead of reimplementing

Everything above is amd64-specific. When I looked at porting it to arm64, I decided not to.

On arm64, the rt_sigreturn trampoline lives in the vDSO, which my Sentry doesn’t parse. Building the frame myself would mean reimplementing a chunk of the kernel’s signal path without learning much new. So arm64 works differently:

  • The Sentry mirrors signal dispositions (as on amd64) and passes rt_sigaction through to the kernel.
  • To deliver a signal, the Sentry calls syscall.Kill(guestPid, sig).
  • The kernel’s own signal path runs from there: it builds the frame, runs the handler, and the vDSO trampoline calls rt_sigreturn, which the kernel handles without involving the Sentry.

That’s a different architectural choice, and I think it matches a trade-off gVisor makes too. gVisor doesn’t delegate on amd64 because its security depends on not delegating: if the host kernel runs the guest’s handler logic, a kernel exploit in that path is back on the table. For a learning project the trade-off is different, and delegating was a better use of my evenings than reimplementing everything and getting stuck without arm64 hardware.

Both approaches are legitimate, but a project should decide which one it’s using at the start. Either you own the contract or you delegate it, not both and not partially.

What I learned

  1. Signals are where a userspace kernel stops being a diagram. You can fake syscalls by writing into RAX, but signals require matching the kernel’s contracts byte for byte: frame layouts, register conventions, vDSO trampolines. Every gap in the abstraction shows up here.
  2. Toolchains leak into the ABI without telling you. The Go compiler’s ABIInternal wrapper was invisible until it broke things, at the worst possible level of the stack. Wherever the host toolchain meets a low-level ABI (signal entry, syscall trampolines, FFI), assume the compiler is doing something helpful that you’ll have to undo.
  3. Reimplement or delegate: decide first. gVisor reimplements because its security model requires it. I delegated on arm64 because I only needed to understand it. Everything else follows from that first choice.

The source is at github.com/mtclinton/mini-sentry. The signal subsystem starts in signals.go; the amd64 frame code is in frame_amd64.go and handlers_signals_amd64.go. ADRs 001–003 under docs/adr/ walk through the Phase 3 design decisions in the order they happened, bugs included.

For the earlier parts (the ptrace loop, the seccomp platform, the Gofer), see the first mini-sentry post. This one picks up where that one stops.