Skip to content
thunder-edgePublic

About

Go wrapper for nsjail sandbox

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

go-nsjail

A Go library for configuring and supervising nsjail. Module: github.com/thunder-edge/go-nsjail. Requires Go 1.22 or newer.

  • Complete generated Go types for the pinned native protobuf configuration.
  • Strict native .cfg parsing and serialization, preserving proto2 field presence.
  • Synchronous and asynchronous execution, streams, pipes, extra files and signals.
  • Context cancellation with a configurable termination grace period.
  • Typed validation/exit errors, partial output and bounded stderr diagnostics.
  • Docker stages to compile nsjail, run it and test this library on Linux.

Execution requires Linux and an installed nsjail executable. Configuration helpers work on other platforms; executing commands there returns ErrUnsupportedPlatform. This library invokes the nsjail binary without CGO or an implicit shell.

Quick start

package main

import (
    "context"
    "log"
    "os"
    "time"

    nsjail "github.com/thunder-edge/go-nsjail"
    "github.com/thunder-edge/go-nsjail/config"
    "google.golang.org/protobuf/proto"
)

func main() {
    client, err := nsjail.New("") // Resolve nsjail in PATH, or supply an explicit path.
    if err != nil { log.Fatal(err) }

    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()
    cmd := client.Command(ctx, "/bin/echo", "hello")
    cmd.Config = &config.NsJailConfig{
        Mode: config.Mode_ONCE.Enum(),
        TimeLimit: proto.Uint32(3),
        CloneNewnet: proto.Bool(true),
    }
    cmd.Args = []string{"--chroot", "/"}
    cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr
    result, err := cmd.Run()
    if err != nil { log.Fatal(err) }
    log.Printf("exit=%d duration=%s", result.ExitCode, result.Duration)
}

Mounting / is a minimal demonstration, not a filesystem access policy for untrusted code. Choose mounts, ID mappings, resource limits, capabilities and seccomp policy for your workload. The library preserves upstream defaults and never weakens isolation to recover from an error.

Native configuration

cfg, err := config.Load("jail.cfg")
// Alternatively: config.Parse(data), config.Marshal(cfg), config.Validate(cfg).
// Handle err before using cfg.
cmd := client.Command(ctx, "/bin/echo", "hello")
cmd.Config = cfg

Or set cmd.ConfigFile = "jail.cfg". Choose one source. Relative ConfigFile paths are resolved against cmd.Dir when set. The source file is never overwritten. Start makes a validated snapshot in a private temporary directory (0700), writes its configuration with mode 0600, and removes it after failed Start or Wait. Relative paths inside the configuration retain nsjail semantics and are resolved in the nsjail process's working directory.

Use pointer fields (proto.Bool(false), proto.Uint32(0), etc.) to distinguish explicit values from omitted defaults. Comments and source formatting are not retained by a round trip. All native fields, including nested networking rules, are in config.proto. Kernel support, policy compilation and mount permissions are checked by nsjail at runtime.

cmd.Args accepts the complete pinned CLI, with strict option names and explicit values. Native options precede --; the payload follows it. Long-option abbreviations are rejected. Use Config/ConfigFile instead of --config; daemonization is rejected so Wait can retain ownership. Explicit payload argv overrides exec_bin from the config; explicit CLI options such as --exec_file still follow upstream override semantics.

Process lifecycle

Method Behavior
Run() Start and Wait; returns *Result and error
Start() / Wait() Asynchronous launch followed by required cleanup/reaping
Output() Capture stdout; preserve at most 32 KiB of stderr in ExitError
CombinedOutput() Capture stdout and stderr together
StdinPipe() Write input; close to send EOF
StdoutPipe() / StderrPipe() Read concurrently with execution, before Wait
Signal(s) / Kill() Signal the private process group; still call Wait

A Client is safe for concurrent command creation. Each Cmd is single-use. Configure it before Start, and do not mutate its inputs concurrently with Start. Signal/Kill may run concurrently with Wait; concurrent or repeated Wait is rejected. Start only confirms process creation, not successful isolation or listener readiness.

Stdin, Stdout and Stderr accept io.Reader/io.Writer. Nil streams act like /dev/null. Output methods reject conflicting output writers or pipes. Capture keeps output in memory; use streams for long-running or noisy workloads. The library does not interrupt an arbitrary caller-provided reader/writer that blocks forever. Close or otherwise unblock those yourself. Close pipe handles if you abandon a command before Start.

Dir and Env configure the outer nsjail process. The jailed environment is controlled by native envar and keep_env. ExtraFiles[i] becomes outer fd 3+i; include it in PassFd to retain it in the payload. Caller-owned files remain open after Wait.

Cancellation sends SIGTERM to the private process group, then SIGKILL after GracePeriod (default 2 seconds; zero means immediate kill). Context errors are available with errors.Is. nsjail normally terminates its jailed children when its supervisor receives SIGTERM. An enabled PID namespace also prevents descendants from outliving its namespace init. If you disable that namespace and let processes escape the group, the wrapper cannot promise complete descendant cleanup. Kill is immediate; forward_signals controls nsjail's behavior.

Errors and modes

Use errors.Is(err, nsjail.ErrInvalidConfig) and errors.As(err, &validationError) for input errors. Missing binaries/start failures preserve their underlying exec/os errors. ExitError exposes Result, a wrapped *exec.ExitError and captured diagnostic stderr. Output methods return partial output on failure. A nonzero code alone cannot distinguish payload failure from sandbox setup failure. A native time_limit expiry is an nsjail exit, not necessarily a Go context.DeadlineExceeded.

Mode Result describes
ONCE A single supervised execution
RERUN The repeating supervisor, not each payload run
LISTEN The TCP supervisor, not each connection
EXECVE The subprocess replaced by the payload; never the Go application

For LISTEN, set Mode_LISTEN, Port and Bindhost, call Start, and poll the listening socket with a bounded timeout before treating the service as ready. See the runnable listener example. Native resource/time-limit semantics differ in EXECVE because there is no supervisor; use a context to bound the outer process lifetime.

Build nsjail with Docker

No C/C++ toolchain is needed on the host:

docker build --target nsjail-runtime -t go-nsjail:runtime .
docker run --rm go-nsjail:runtime --help

The nsjail-build stage installs Debian build dependencies, checks out f100fd917c6d3ed0fd15d868528b735cb5fb1a1a, initializes its Kafel submodule, and runs make. The nsjail-runtime stage includes the binary, its shared libraries, revision metadata and upstream licenses. NSJAIL_REVISION may be overridden with another full SHA for development; doing so does not update the Go schema automatically. Source revision pinning does not imply bit-for-bit images: Debian package repositories and base tags may change.

The Docker image is an independent Linux environment; building it does not install nsjail on a macOS/Windows host. Run the Go application and nsjail in the same Linux environment. For an application image, build from the runtime target and copy in your compiled Go binary, then override ENTRYPOINT with your application.

Development and integration

make fmt
make fmt-check
make lint
make test
make build
make docker-test

The Docker test target runs the real nsjail under Linux in a disposable privileged container with no host volumes and --cgroupns=private. Its entry script delegates memory, CPU and PID controllers within that container's cgroup namespace. Privilege is needed here for nested namespaces/mounts; the image build itself requires none. Review and restrict runtime capabilities for your own deployment. The test suite does not silently skip failed isolation checks.

The EXECVE integration case explicitly disables the user namespace because this runner cannot install GID mappings after direct unshare. It retains the other namespaces and runs with an explicit non-root payload UID. This is test configuration, never an automatic library fallback. Other integration modes keep the user namespace enabled.

make generate requires Python 3, protoc 29.3 and Go; it installs protoc-gen-go v1.34.2 into .tools/, regenerates protobuf types, the descriptor fixture and the CLI table. Imported sources and attribution are documented in third_party/nsjail/README.md. Do not edit generated files by hand. Update revision, schema, CLI fixture and Docker together.

Validation status

Validated with Go 1.22.5 on macOS arm64 and Go 1.26.8/1.27.1 on Linux arm64, including the race detector and real nsjail integration. Go builds pass for Linux amd64/arm64 and Windows amd64. The nsjail Docker build and unit tests also pass for emulated AMD64. Full AMD64 integration still requires a native runner: the local emulator rejects PR_SET_SECCOMP, also when nsjail is invoked directly without this library. The test is not skipped; the GitHub Actions integration job is configured for native AMD64.

License

Apache-2.0. See LICENSE and third-party attribution.

About

Go wrapper for nsjail sandbox

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages