github.com/alexfalkowski/go-linux/v2/seccomp constructs and loads classic-BPF syscall filters on native amd64 and arm64 Linux 7.0+. It uses seccomp(2) and PR_SET_NO_NEW_PRIVS. Loading requires kernel filter support, permission under existing security policy, and either no-new-privileges or effective CAP_SYS_ADMIN in the caller’s user namespace. These mechanisms do not constitute a complete sandbox.
Good for restricting the native syscalls a workload may invoke and delegating selected syscalls to a userspace supervisor. Callers choose filters that accommodate both the workload and the Go runtime. runc threat model.
Construction validates and copies instructions without a syscall or policy change. Supply the architecture for which the program’s syscall numbers were chosen. NativeArchitecture returns AMD64 or ARM64; other architectures return EOPNOTSUPP. New rejects an architecture that differs from the running Go program’s ABI, but cannot infer whether arbitrary instruction constants describe the caller’s intended syscalls. Use native constants with the native architecture.
For example, deny getpgid while allowing other native syscalls:
architecture, err := seccomp.NativeArchitecture()
if err != nil {
return err
}
filter, err := seccomp.New(architecture, []seccomp.Instruction{
{Code: seccomp.LoadWord, K: seccomp.SyscallOffset},
{Code: seccomp.JumpEqual, K: unix.SYS_GETPGID, Jf: 1},
{Code: seccomp.Return, K: uint32(seccomp.Errno) | uint32(unix.EACCES)},
{Code: seccomp.Return, K: uint32(seccomp.Allow)},
})
if err != nil {
return err
}
Imports are github.com/alexfalkowski/go-linux/v2/seccomp and golang.org/x/sys/unix; the latter supplies native syscall numbers and errno constants, without a copied syscall table. This small deny-list demonstrates mechanics, not a security policy. Production restrictions need a policy designed for the whole application. Executable examples demonstrate construction and action discovery safely.
The loader prepends an architecture check that terminates the entire process with SIGSYS on another audit ABI. On amd64 it also terminates calls carrying the x32 syscall bit, since x32 shares the x86-64 audit architecture. These guards cannot be removed or bypassed by jumps within the caller’s body. They also prevent exec into a different syscall ABI. The body starts with accumulator zero.
During development, perform loading and restricted work only in a disposable subprocess. Inside that child’s dedicated goroutine:
runtime.LockOSThread() // Intentionally never unlocked, including on failure.
options := seccomp.Options{
Synchronization: seccomp.AllThreads,
Privileges: seccomp.SetNoNewPrivileges,
}
if err := filter.Load(options); err != nil {
return err
}
// Continue the child's policy-compatible work here.
AllThreads requests kernel TSYNC for all existing threads of the calling process. Every thread must have a compatible filter tree; attaching identical filters separately can still create incompatible branches. A conflict returns *SynchronizationError with the refusing Linux ThreadID, and the new filter is not attached anywhere. Use errors.As for that case. There is no retry or fallback to a narrower scope. The caller coordinates competing loads and policy transitions.
CallingThread explicitly restricts only the loading thread. Lock its goroutine before loading and keep it locked until it exits; do not defer runtime.UnlockOSThread. Other existing threads keep their policies, and a new goroutine may run on one of those threads. This mode cannot promise restrictions for the whole Go program. Go destroys ordinary locked threads on goroutine exit; its startup thread may instead remain parked until process exit. Neither case rolls back restrictions inherited by descendants.
Privileges: seccomp.SetNoNewPrivileges requests that Load set the calling thread’s irreversible bit before attaching the filter. That change persists even if the subsequent seccomp call fails, including a TSYNC conflict. Successful TSYNC propagates the bit when it is set on the loading thread. By default, Load preserves the bit and requires that it already be set or that the caller have CAP_SYS_ADMIN. Invalid filters or options fail before any change. Flags: seccomp.LogNonAllow requests SECCOMP_FILTER_FLAG_LOG. Actual audit records depend on administrator policy.
Successful loads are irreversible. Repeated calls stack filters, subject to the kernel’s aggregate instruction limit. An Allow result leaves earlier higher-precedence denials in force. Filter is immutable, owns a copy of its instructions, and may be shared by concurrent loads. Kernel policy still needs caller coordination. Use a pointer and do not copy it after use. Nil and zero filters cannot be loaded.
The bounded representation supports aligned native-endian 32-bit absolute loads, constant loads, constant bitwise AND, unconditional forward jumps, unsigned equal/greater/greater-or-equal/bit-intersection comparisons, and constant returns. Programs contain 1 through MaxInstructions (4089) body instructions and end in Return. The reserved guard keeps the complete program within Linux’s 4096-instruction limit. Unknown opcodes, out-of-body jump targets, ignored nonzero fields, computed returns, index register operations, and scratch memory are rejected.
LoadWord.K is an aligned byte offset within the 64-byte seccomp_data. Named offsets select the syscall number, audit architecture, instruction pointer, and arguments. On both supported little-endian ABIs, argument n’s low/high words are at ArgumentsOffset+8*n and ArgumentsOffset+8*n+4. Every argument occupies 64 bits in seccomp data even when the syscall truncates it to 32 bits. Filters cannot dereference pointers, inspect path strings, or prevent pointer-content races. Handle scalar widths and alternate argument encodings deliberately.
Jt, Jf, and unconditional Jump.K count instructions skipped from the following instruction. Both conditional destinations must stay in the body. Return K contains uint32(action) combined with optional low 16-bit data:
| Action | Effect and data |
|---|---|
KillProcess |
Terminate the entire thread group with SIGSYS. Data must be zero. |
KillThread |
Terminate only the triggering thread. Data must be zero. This can strand locks and corrupt runtime state; prefer KillProcess for termination. |
Trap |
Deliver synchronous SIGSYS without executing the syscall; data is si_errno. Go’s synchronous fatal-signal path terminates the process; this package installs no signal handler. |
Errno |
Skip the syscall and return data as errno, clamped by Linux to 4095. Zero reports success without performing the operation. |
Notify |
Delegate the syscall to a userspace listener. Data must be zero. Load through Listen. |
Trace |
Notify an external PTRACE_O_TRACESECCOMP tracer with data, or return ENOSYS when no tracer is attached. This package manages no tracer. |
Log |
Allow and request logging, subject to host policy. Data must be zero. |
Allow |
Allow unless another stacked filter has higher precedence. Data must be zero. |
ActionAvailable probes a single named action without data. It returns false without an error for kernel EOPNOTSUPP and preserves other failures. Construction rejects unknown actions.
To adapt the filter above, set K in the seccomp.Errno return instruction to uint32(seccomp.Notify). Replace the entire old value, including the unix.EACCES bits, because Notify requires zero return data. Use Filter.Listen for a program containing Notify and Filter.Load for programs without it. For a separate workload, a dedicated locked goroutine can install the filter and start an ordinary exec.Cmd synchronously, then exit while the supervisor retains the listener:
// Run startWorker on a dedicated goroutine.
func startWorker(filter *seccomp.Filter, command *exec.Cmd) (*seccomp.Listener, error) {
runtime.LockOSThread() // Keep the thread locked until this goroutine exits.
listener, err := filter.Listen(seccomp.Options{
Synchronization: seccomp.CallingThread,
Privileges: seccomp.SetNoNewPrivileges,
})
if err != nil {
return nil, err
}
if err := command.Start(); err != nil {
return nil, errors.Join(err, listener.Close())
}
return listener, nil
}
The workload inherits the filter during clone and exec. The listener stays in the supervisor because it is close-on-exec. Keep the supervisor and its loader’s startup path able to perform their own system calls. The loader negotiates the kernel notification ABI before changing no-new-privileges or installing the filter. Listener creation requires CallingThread and preserves kernel errors, including EBUSY if the loading thread’s filter ancestry already has a listener.
Call Receive to obtain a notification ID, the target TID as seen in the receiver’s PID namespace, the audit architecture and syscall number, the instruction pointer, and six raw scalar registers. The TID is zero when the target is outside that namespace’s view. ValidateID checks whether a received request still awaits a reply. A successful check is a point-in-time observation, and target exit or signal interruption can make a later reply return ENOENT.
Respond(id, value) skips the syscall and returns a signed 64-bit value. Linux reserves values from -4095 through -1 for errno.RespondError(id, errno) skips the syscall and returns a positive Linux errno from 1 through 4095 to the target.Continue(id) lets the kernel execute the original syscall. A target may change bytes addressed by its arguments while the syscall is intercepted. Keep authorization in the kernel and use independent policy to enforce memory- or path-sensitive restrictions. When Notify and Trace both match, Notify takes precedence and continuing produces no seccomp event for the tracer. Keep Trace-mediated syscalls outside overlapping Notify rules or enforce required denials with a higher-precedence kernel action.The caller coordinates single replies when workers share a listener. Receive blocks an OS thread and preserves EINTR if the kernel interrupts it. ENOENT can mean a request vanished before delivery or the filter has no remaining target threads. Close makes the local listener unusable for new operations. An already blocked Receive retains its reference until the ioctl returns, so arrange for the workload to exit or another kernel event to release the wait. When the final reference is released, pending and future Notify results return ENOSYS. The filter stays installed.
A supervisor can answer a workload’s intercepted file-opening syscall with a file it already opened, such as a read-only configuration file. The supervisor chooses the file using application policy. It should grant only the access the target needs because the target receives a reference to the same open file description, with shared status flags and offset.
// From the supervisor, after receiving the request and selecting the file.
targetDescriptor, err := listener.AddFileAndRespond(request.ID, source, seccomp.FileOptions{})
AddFileAndRespond installs the file and returns the target descriptor as the intercepted syscall’s result in one Linux operation. The original syscall is skipped. AddFile installs the file immediately and leaves the request awaiting a reply. To return the descriptor separately, call Respond(request.ID, int64(targetDescriptor)). Once AddFile succeeds, a failed reply, an error reply, or closing the listener leaves the installed descriptor in the target. The target owns its descriptor, and the caller remains responsible for closing source.
Zero FileOptions use the lowest unused target descriptor and set close-on-exec atomically. Use InheritOnExec in Flags when the file should survive a target exec. Placement: seccomp.ReplaceDescriptor installs the file at TargetDescriptor, including slot zero, and closes a file already in that slot. A slot reserved by a concurrent allocation can cause EBUSY. Use exact placement only when the workload coordinates use of the selected slot.
Both operations can block until the target handles the request. They preserve kernel errors, including ENOENT for a stale ID, ESRCH if the target disappears with an installation queued, and EINTR if the kernel interrupts the ioctl. A failed atomic installation can leave a live request available for a reply. Coordinate workers handling the same ID and reconcile its state before retrying an interrupted operation. Closing the listener leaves an in-flight operation holding its reference. Linux 7.0 seccomp implementation.
On kernels without the atomic installation interruption fix, including Linux 7.0, a signal that interrupts a queued AddFileAndRespond can cause the target syscall to return success with descriptor 0 without installing a file. If Linux restarts the supervisor’s ioctl, the supervisor can receive EINPROGRESS or ENOENT instead of EINTR. Upstream Linux fix.
Listener flags, WAIT_KILLABLE_RECV, TSYNC_ESRCH, strict mode, speculative-execution opt-out, and policy compilation are outside the exposed operations. Linux 7.0 seccomp UAPI, seccomp_unotify(2).
A valid filter can crash or deadlock Go by denying scheduler, futex, memory, signal, time, I/O, or thread-exit syscalls. Runtime needs vary by Go release, architecture, enabled race instrumentation, and application behavior. The package does not silently add syscall exceptions or claim that an example filter is sufficient for a Go application. A successful load only establishes the requested kernel filter operation.
When clone/fork and exec are allowed, descendants inherit the creating thread’s filter tree; exec preserves it, and no-new-privileges prevents ordinary exec privilege gains. Existing separate processes are unaffected. Use standard os/exec, synchronously on the locked goroutine when inheritance depends on that thread. There is no raw fork wrapper or child-start hook in this package.
Use errors.Is(err, os.ErrInvalid) to identify package validation errors. Kernel EPERM, EACCES, EINVAL, ENOSYS, resource errors, and policy-denied probes remain distinguishable with errors.Is/errors.As. Use errors.As to obtain a SynchronizationError and its refusing TID. The package never retries a failed irreversible operation or weakens the requested policy.
See design decisions and verification.