Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .clang-format
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
BasedOnStyle: LLVM
Language: C
ColumnLimit: 100
IndentWidth: 2
ContinuationIndentWidth: 4
SortIncludes: false
InsertBraces: true
AllowShortIfStatementsOnASingleLine: Never
AllowShortLoopsOnASingleLine: false
AllowShortBlocksOnASingleLine: Never
30 changes: 29 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,39 @@ All notable changes to this project will be documented in this file.

## Unreleased

## [0.3] - 2026-06-17

### Added

- Add top-level `Landlock.capture` and `Landlock.capture!`, direct Landlock/`exec` capture APIs with stdout/stderr capture, stdin, wall-clock timeout with process-group cleanup, output byte limits, `rlimits:`, controlled environments, `chdir:`, TCP/scoped Landlock rules, `allow_all_known:`, and optional `seccomp_deny_network:`.
- Expose `Landlock.seccomp_deny_network!` from the native extension so capture children can install the same deny-network seccomp filter used by the helper binary.

### Changed

- Remove the legacy `Landlock::SafeExec` Ruby facade. Use `Landlock.capture`/`capture!` with argv arrays for captured subprocesses and `Landlock.exec`/`spawn` for non-capturing subprocesses.
- `Landlock.exec`, `Landlock.spawn`, and `Landlock.capture` now use the packaged native `landlock-safe-exec` helper when available, passing sandbox policy as helper arguments to avoid forking a large Ruby process for child setup and falling back to the Ruby fork runner if the helper argv exceeds `ARG_MAX`.
- Split subprocess running internals into `Landlock::Runner::Native` and `Landlock::Runner::Fork` backends, with shared validation, process I/O, rlimit, environment, and policy helpers.
- Normalize subprocess `env:` keys and values in Ruby before spawning and keep environment values out of native-helper argv.
- Require non-empty `Landlock.exec`/`spawn` policies instead of launching an unsandboxed command when no Landlock rules are provided.

### Fixed

- Treat timeouts as failures for `capture!` even when a command handles termination and exits with an otherwise successful status.
- Bound post-timeout pipe draining so escaped descendants that keep stdout/stderr open cannot hang capture past the requested timeout.
- Harden `landlock-safe-exec` by closing inherited file descriptors, applying rlimits after sandbox setup, matching Ruby `write:` rights, tightening CLI parsing, and making the shared seccomp network-deny filter reject x32 syscall-number bypasses.
- Validate `Landlock.capture` filesystem policy paths before forking so missing paths raise `ArgumentError`.
- Reject empty `Landlock.capture` policies unless another restriction such as seccomp or rlimits is provided.
- Filter directory-only custom path-rule rights for file paths in `Landlock.restrict!`, matching helper behavior.

### Documentation

- Document `Landlock.capture`, its result/error types, capture options, and subprocess sandboxing guidance.

### [0.2.1] - 2026-06-16

- Build `landlock-safe-exec` without Ruby extension `$(LIBS)` to avoid unnecessary runtime library dependencies and improve SafeExec helper startup time.

### [0.2] - 2026-04-30
## [0.2] - 2026-04-30

- Add `Landlock::SafeExec.capture`, backed by a compiled `landlock-safe-exec` helper, for subprocess capture with Landlock, optional seccomp network denial, resource limits, exact environment handling, stdin, timeout handling, process-group cleanup, result metadata, and output limits.
- Share native Landlock syscall/constant definitions between the Ruby extension and helper binary.
Expand Down
83 changes: 40 additions & 43 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ See [CHANGELOG.md](CHANGELOG.md) for release notes.

## Safe subprocess execution

Pass commands as an argument array. `Landlock.exec` and `Landlock.spawn` do not invoke a shell implicitly; use an explicit shell in the array if that is really required. Both helpers accept `env:` and `unsetenv_others:` and pass them through to `Kernel.exec` so subprocesses can run with a controlled environment.
Pass commands as an argument array. `Landlock.exec` and `Landlock.spawn` do not invoke a shell implicitly; use an explicit shell in the array if that is really required. Both helpers require a non-empty Landlock policy, accept `env:`/`unsetenv_others:` for controlled environments, and use the packaged native helper when available so the long-lived child is not a forked Ruby process.

Allow Ruby to execute and read its runtime, but only allow outbound TCP connections to port 443:

Expand Down Expand Up @@ -66,23 +66,17 @@ Landlock.exec(
)
```

## SafeExec helper
## Capturing subprocess output

`Landlock::SafeExec.capture` runs a command through the compiled `landlock-safe-exec` helper. The helper applies Landlock rules, resource limits, and an optional seccomp network-deny filter in the execing process before replacing itself with the target command. This keeps the privileged setup out of Ruby/FFI and avoids running Ruby code in a post-fork child. Use `capture!` when unsuccessful exit statuses should raise.

For example, inspect an uploaded video with `ffprobe` while only allowing reads from the upload and system runtime paths, denying network access, and bounding CPU/output:
`Landlock.capture` is the stdout/stderr-capturing sibling of `Landlock.exec`: it launches a child process, applies Landlock rules, resource limits, and the optional seccomp network-deny filter before the target command starts, then execs that command directly. When the packaged `landlock-safe-exec` helper is available, `exec`, `spawn`, and `capture` all spawn that small native helper with policy arguments so the parent does not need to fork a bloated Ruby process; they fall back to the Ruby fork path when the helper cannot be used or when an unusually large helper argv would exceed the platform `ARG_MAX`. Environment changes are applied by Ruby when spawning the helper rather than encoded in helper argv. Use `capture!` when unsuccessful exit statuses should raise.

```ruby
result = Landlock::SafeExec.capture(
"ffprobe",
"-v", "error",
"-show_format",
"-show_streams",
"-of", "json",
upload_path,
read: [upload_path, *Landlock::SafeExec.default_read_paths],
execute: Landlock::SafeExec.default_execute_paths,
result = Landlock.capture(
["ffprobe", "-v", "error", "-show_format", "-of", "json", upload_path],
read: [upload_path, "/usr", "/lib", "/lib64", "/etc"].select { |path| File.exist?(path) },
execute: ["/usr", "/lib", "/lib64"].select { |path| File.exist?(path) },
env: { "PATH" => ENV.fetch("PATH", "") },
unsetenv_others: true,
rlimits: {
cpu_seconds: 5,
memory_bytes: 512 * 1024 * 1024,
Expand All @@ -98,45 +92,46 @@ result = Landlock::SafeExec.capture(
metadata = JSON.parse(result.stdout) if result.success?
```

Pass `stdin:` when a tool should read from standard input instead of a file:
`Landlock.capture` takes the command as a single argv array, like `Landlock.exec`. It returns a `Landlock::CaptureResult` with `stdout`, `stderr`, `status`, `success?`, `timed_out?`, and `output_truncated?`, including for unsuccessful exit statuses. It also supports array destructuring:

```ruby
stdout, stderr, status = Landlock::SafeExec.capture(
"tr", "a-z", "A-Z",
stdin: "hello",
env: { "PATH" => ENV.fetch("PATH", "") }
stdout, stderr, status = Landlock.capture(
["tool", "arg"],
read: ["/usr", "/lib", "/lib64", "/etc"].select { |path| File.exist?(path) },
execute: ["/usr", "/lib", "/lib64"].select { |path| File.exist?(path) }
)
```

`capture` returns a `Landlock::SafeExec::Result` with `stdout`, `stderr`, `status`, `success?`, `timed_out?`, and `output_truncated?`, including for unsuccessful exit statuses. It also supports array destructuring:
`Landlock.capture!` has the same return shape for successful commands, but raises `Landlock::CommandError` for unsuccessful statuses. The error also exposes `stdout`, `stderr`, `status`, and `result`.

`Landlock.capture` requires an actual restriction: provide Landlock rules, `seccomp_deny_network: true`, or `rlimits:`. This avoids accidentally running a command completely unsandboxed when a dynamically built policy is empty. It also requires Linux Landlock support and raises `Landlock::UnsupportedError` when unavailable; it does not fall back to running the command unsandboxed.

Pass `stdin:` when a tool should read from standard input instead of a file:

```ruby
stdout, stderr, status = Landlock::SafeExec.capture("tool", "arg")
stdout, stderr, status = Landlock.capture(
["tr", "a-z", "A-Z"],
stdin: "hello",
rlimits: { open_files: 64 }
)
```

`capture!` has the same return shape for successful commands, but raises `Landlock::SafeExec::CommandError` for unsuccessful statuses. The error also exposes `stdout`, `stderr`, `status`, and `result`.

SafeExec options:
Capture options:

- `read:`, `write:`, `execute:` — filesystem allowlists. Explicit paths must exist; missing paths raise `ArgumentError` instead of being silently ignored.
- `connect_tcp:` — allowed outbound TCP ports. If omitted on Landlock ABI v4+, SafeExec denies outbound TCP by installing a dummy allow rule for port `0`. Pass `connect_tcp: []` to leave outbound TCP unrestricted.
- `bind_tcp:` — allowed TCP bind ports. Binding is unrestricted unless this is provided.
- `paths:` — exact path rules with explicit Landlock rights, e.g. `{ path:, rights: %i[read_file] }`.
- `connect_tcp:` and `bind_tcp:` — allowed TCP ports. TCP access is unrestricted unless a network rule is provided.
- `scope:` — Landlock ABI v6+ scopes such as `:signal` and `:abstract_unix_socket`.
- `seccomp_deny_network:` — additionally deny common Linux network syscalls with seccomp. This is Linux-specific and intended as defense in depth.
- `rlimits:` — resource limits. Supported keys are `:cpu_seconds`, `:memory_bytes`, `:file_size_bytes`, `:open_files`, and `:processes`. Values must be non-negative integers.
- `timeout:` — wall-clock timeout in seconds. On timeout SafeExec terminates the process group and returns/raises with `result.timed_out?` true.
- `max_output_bytes:` — combined stdout+stderr byte limit. With `truncate_output: false`, exceeding the limit raises. With `truncate_output: true`, output is truncated and `result.output_truncated?` is true.
- `timeout:` — wall-clock timeout in seconds. On timeout capture terminates the process group and returns/raises with `result.timed_out?` true.
- `max_output_bytes:` — combined stdout+stderr byte limit. With `truncate_output: false`, exceeding the limit raises `Landlock::CommandError` with the partial output captured before termination. With `truncate_output: true`, output is truncated and `result.output_truncated?` is true.
- `stdin:` — string or IO-like object to write to the child process stdin.
- `chdir:` — working directory for the child.
- `env:` — exact child environment by default.
- `inherit_env:` — when true, inherit the parent environment and apply `env:` as overrides.
- `success_status_codes:` — status codes considered successful by `capture!`; defaults to `[0]`.
- `allow_all_known:` — when filesystem rules are present, handle all Landlock filesystem rights known to the running ABI so unlisted filesystem access is denied. Defaults to `true`.

SafeExec uses an exact environment by default: `env:` is the full environment passed to the child, not additions to the parent environment. Use `inherit_env: true` when a command really needs the parent environment plus the supplied `env:` overrides.

Use `Landlock::SafeExec.supported?` (or `sandboxing?`) to check whether the Linux helper and Landlock are available. When this is false, SafeExec still runs commands in pass-through mode but does not enforce Landlock/seccomp sandbox options.

On non-Linux platforms, or when the compiled helper is unavailable, SafeExec runs as a pass-through compatibility wrapper. Process-management features such as capture, timeout, environment handling, `chdir:`, output limits, `stdin:`, and supported `rlimits:` still apply, but Landlock and seccomp options (`read:`, `write:`, `execute:`, `connect_tcp:`, `bind_tcp:`, `seccomp_deny_network:`) are ignored and a warning is emitted. This makes cross-platform integration easier while keeping the security guarantees explicit: sandboxing is Linux-only.
- `env:` — environment entries for the child.
- `unsetenv_others:` — clear the parent environment before applying `env:`.
- `success_status_codes:` and `failure_message:` — `capture!` failure handling options.
- `allow_all_known:` — when filesystem rules are present, handle all Landlock filesystem rights known to the running ABI so unlisted filesystem access is denied.

## Restrict current process

Expand Down Expand Up @@ -204,12 +199,14 @@ Treat small positive or negative deltas as noise and benchmark on the kernel, fi

Landlock is not a complete container. It restricts selected kernel-mediated actions for the current thread and its future descendants, but it does not create namespaces, hide process IDs, virtualize the filesystem, or isolate the process from every kernel interface. For serious untrusted execution, combine Landlock with a controlled environment, resource limits, seccomp, and process isolation appropriate to your threat model.

`Landlock.restrict!` only installs a Landlock ruleset. It does not close already-open file descriptors, impose resource limits, clean the environment, or kill subprocess trees. `Landlock::SafeExec` adds practical subprocess hardening around this — exact environment by default, `close_others`, optional `rlimits:`, optional `seccomp_deny_network:`, output limits, timeout handling, and process-group termination — but it is still not a VM/container boundary.
`Landlock.restrict!` only installs a Landlock ruleset. It does not close already-open file descriptors, impose resource limits, clean the environment, or kill subprocess trees. The subprocess helpers add practical hardening around this: `exec`/`spawn` add controlled environments and `close_others`, while `capture` also adds optional `rlimits:`, optional `seccomp_deny_network:`, output limits, timeout handling, and process-group termination. This is still not a VM/container boundary. By default, subprocess helpers close inherited file descriptors numbered 3 and higher before installing the sandbox; pass `close_others: false` only when the child intentionally needs inherited descriptors. Direct `landlock-safe-exec` use also closes inherited descriptors by default.

When the native helper is used, sandbox policy details such as allowed paths, TCP ports, scopes, rights, and rlimits are passed as helper argv. They may be visible to same-user processes through tools such as `ps` or `/proc/<pid>/cmdline` until the helper execs the target command. Environment values passed with `env:` are not encoded in helper argv, but do not put secrets in policy path names or other policy arguments.

If `Landlock.exec` or `Landlock.spawn` child setup fails before `exec`, the child prints a diagnostic and exits 127. `landlock-safe-exec` setup/argument failures exit 126. These codes can collide with commands that legitimately exit with the same status, so inspect stderr when debugging failures.
If `Landlock.exec`, `Landlock.spawn`, or `Landlock.capture` child setup fails before `exec`, the child prints a diagnostic and exits 127. `landlock-safe-exec` setup/argument failures exit 126. These codes can collide with commands that legitimately exit with the same status, so inspect stderr when debugging failures.

Path rules follow the kernel's normal path resolution when the rule is installed. Because paths are opened without `O_NOFOLLOW`, a symlink rule applies to the symlink target's inode, not to the symlink path itself. SafeExec validates explicit `read:`, `write:`, and `execute:` paths before launching so typos fail closed instead of silently weakening a policy.
Path rules follow the kernel's normal path resolution when the rule is installed. Because paths are opened without `O_NOFOLLOW`, a symlink rule applies to the symlink target's inode, not to the symlink path itself. Capture APIs validate explicit `read:`, `write:`, and `execute:` paths before launching so typos fail closed instead of silently weakening a policy.

Landlock only restricts access rights included in a ruleset's handled set: omitted categories remain allowed. Use `allow_all_known: true` when you want unlisted filesystem actions denied. SafeExec defaults `allow_all_known:` to true when filesystem rules are provided. Landlock TCP rules do not cover UDP or pathname Unix-domain sockets; ABI v6+ scopes can restrict signals and abstract Unix-domain sockets. SafeExec's `seccomp_deny_network:` is Linux-specific defense in depth for common network syscalls, not a general-purpose seccomp policy language.
Landlock only restricts access rights included in a ruleset's handled set: omitted categories remain allowed. Use `allow_all_known: true` when you want unlisted filesystem actions denied. Landlock TCP rules do not cover UDP or pathname Unix-domain sockets; ABI v6+ scopes can restrict signals and abstract Unix-domain sockets. `seccomp_deny_network:` is Linux-specific defense in depth for common network syscalls, not a general-purpose seccomp policy language.

`Landlock.restrict!` applies to the calling thread and its future children; already-running sibling threads are not retroactively sandboxed. Prefer `Landlock::SafeExec`, `Landlock.exec`, or `Landlock.spawn` for subprocess sandboxing from a larger Ruby application.
`Landlock.restrict!` applies to the calling thread and its future children; already-running sibling threads are not retroactively sandboxed. Prefer `Landlock.capture`, `Landlock.exec`, or `Landlock.spawn` for subprocess sandboxing from a larger Ruby application.
26 changes: 22 additions & 4 deletions Rakefile
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
require "bundler"
require "rake/testtask"
require "rake/extensiontask"
require "shellwords"

begin
Bundler.setup :default, :development
Expand All @@ -13,16 +14,33 @@ rescue Bundler::BundlerError => error
exit error.status_code
end

Rake::ExtensionTask.new("landlock") do |ext|
ext.lib_dir = "lib/landlock"
end
Rake::ExtensionTask.new("landlock") { |ext| ext.lib_dir = "lib/landlock" }

Rake::TestTask.new do |t|
t.libs << "test"
t.libs << "lib"
t.pattern = "test/**/*_test.rb"
end

formattable_ruby_files = FileList["Gemfile", "Rakefile", "*.gemspec", "{lib,test,benchmark}/**/*.rb"].to_a.freeze
formattable_c_files = FileList["ext/**/*.{c,h}"].to_a.freeze
stree_print_width = 120
clang_format = ENV.fetch("CLANG_FORMAT", "clang-format")

namespace :format do
desc "Check Ruby/C formatting"
task :check do
sh "bundle exec stree check --print-width=#{stree_print_width} #{formattable_ruby_files.map(&:shellescape).join(" ")}"
sh "#{clang_format.shellescape} --dry-run --Werror #{formattable_c_files.map(&:shellescape).join(" ")}"
end
end

desc "Format Ruby/C files"
task :format do
sh "bundle exec stree write --print-width=#{stree_print_width} #{formattable_ruby_files.map(&:shellescape).join(" ")}"
sh "#{clang_format.shellescape} -i #{formattable_c_files.map(&:shellescape).join(" ")}"
end

task test: :compile

namespace :bench do
Expand All @@ -35,4 +53,4 @@ end
desc "Run the Landlock overhead benchmark suite"
task bench: "bench:overhead"

task default: [:compile, :test]
task default: %i[compile test]
Loading
Loading