rshell

package module
v0.0.0-...-22e76aa Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 23, 2026 License: Apache-2.0 Imports: 0 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

rshell

rshell

License

A default-deny shell interpreter for Go, built for AI agents that need a bounded Bash/POSIX-like command surface.

rshell is maintained in the Datadog Agent repository as an independently importable Go module. Agent releases tag it as pkg/rshell/v0.X.Y for Agent 7.X.Y; other projects can also pin an Agent commit before a tagged release. Agent builds use the source in this checkout.

The initial import is from DataDog/rshell commit df8b6056.

[!IMPORTANT] The CLI is a development and local-validation tool, not a production security boundary. Production integrations should embed the Go package and explicitly configure commands, paths, environment, timeouts, and execution mode.

Install

go get github.com/DataDog/datadog-agent/pkg/rshell/interp

For the optional development CLI, run from an Agent checkout:

bazel run //pkg/rshell/cmd/rshell -- --allowed-commands rshell:echo -c 'echo hello'

Quick start

A minimal embedded runner (imports omitted):

func runScript(ctx context.Context) error {
	program, err := interp.ParseScript(`echo "hello from rshell"`, "")
	if err != nil {
		return err
	}

	runner, err := interp.New(
		interp.StdIO(nil, os.Stdout, os.Stderr),
		interp.AllowedCommands([]string{"rshell:echo"}),
		interp.MaxExecutionTime(5*time.Second),
	)
	if err != nil {
		return err
	}
	defer runner.Close()

	return runner.Run(ctx, program)
}

See the interp package API for runner options and lifecycle details.

The same command through the development CLI:

rshell --allowed-commands rshell:echo --timeout 5s -c 'echo "hello from rshell"'

Check a script without executing it

For checks against the local execution host, call runner.Check(ctx, script) on a runner configured with the same options you would use for execution. Integrations that decode a protobuf request can pass its script and effective policies through the existing runner options. For grants intended for another host, use CheckRemote below: constructing a runner opens local sandbox roots.

runner, err := interp.New(
	interp.AllowedCommands([]string{"rshell:cat", "rshell:grep"}),
	interp.AllowedPaths([]string{"/var/log:ro"}),
)
if err != nil {
	return err
}
defer runner.Close()

report, err := runner.Check(ctx, `cat /var/log/app.log | grep ERROR`)
if err != nil {
	return err // cancellation, timeout, or invalid runner
}
// report.Allowed: all command sites passed the static authorization check.
// report.Commands: per-command allowed/status, source line/column, and issues.
// report.Issues: script-wide parse errors or unsupported shell features.
// report.Warnings: configuration warnings, including skipped AllowedPaths.

The JSON-compatible report distinguishes allowed, denied, and indeterminate. Both the report and each command have an Allowed boolean, which is true only for allowed. Issues have stable codes such as command_not_allowed, unknown_command, path_not_allowed, remediation_required, and requires_execution; path issues include the requested path. A denial takes precedence over an indeterminate check.

Checking uses the shell parser, builtin flag parser, current runner environment and directory, and the configured command, path, mode, elevation, and systemd policies. It never executes commands or substitutions, consumes stdin, writes redirects, or calls elevation/systemd backends. It may inspect sandboxed filesystem metadata. The runner's state and output streams are unchanged.

This is a conservative authorization preview. Every syntactic branch is checked, even one that might not run, and loops are inspected once. Simple assignments and environment values are resolved. Globs, command substitutions, paths after cd, and operations whose operands depend on file contents can be indeterminate; see the coverage details. An allowed report does not promise an exit code of zero, file existence, valid embedded programs, sufficient OS privileges, or termination. Always execute through Run, which enforces policy again against the state at execution time.

Preview authorization for a remote host
func CheckRemote(ctx context.Context, script string, policy interp.RemotePolicy) (*interp.CheckResult, error)

Call interp.CheckRemote after your application authenticates the caller, resolves the target, authorizes persisted policies, and computes effective grants. It shares the local checker's parsing, syntax and flag validation, command traversal, policies, limits, and complete CheckResult envelope. It does not construct a runner, read the embedding application's filesystem or environment, look up its working directory, consume streams, or invoke systemd/elevation backends. Remote grant roots need not exist locally.

report, err := interp.CheckRemote(ctx, `echo checking; cat "$LOG"`, interp.RemotePolicy{
	AllowedCommands: []string{"rshell:echo", "rshell:cat"},
	AllowedPaths:    []string{"/var/log:ro"},
	Mode:            interp.ModeReadOnly,
	Env:             []string{"LOG=/var/log/app.log"},
	Dir:             "/var/log", // optional remote cwd; never inferred locally
	Timeout:         5 * time.Second,
})
if err != nil {
	return err // invalid configuration, cancellation, or timeout
}
// echo: allowed. cat: indeterminate/requires_execution, with Path=/var/log/app.log.
// Overall: Status=indeterminate, Allowed=false. Nothing executes.

RemotePolicy fields:

Field Meaning / default
AllowedCommands []string Exact rshell:<command> grants; empty denies all commands
AllowedPaths []string Absolute remote roots with optional :ro (default) or :rw; empty denies filesystem access
Mode interp.Mode Empty or ModeReadOnly blocks remediation; ModeRemediation still requires the relevant grants
AllowedSystemServices []interp.SystemServiceControlGrant Exact Service names and Actions; empty denies all service actions
ElevatableCommands []string Additional rshell:<command> grants for the sudo marker; no callback; command grants are still required
Env []string Explicit KEY=value pairs; empty by default, plus normal shell defaults
Dir string Optional absolute remote cwd; without it, relative paths and $PWD are indeterminate
Timeout time.Duration Fresh deadline per call; zero defaults to five seconds, negative is invalid; an earlier context deadline wins

Malformed configuration is an error. Path grants reserve colons for one terminal :ro/:rw suffix and Windows volume prefixes. Matching uses execution's lexical containment and most-specific access-mode rules; read-only aliases cannot widen writes. A terminal :ro/:rw is always an access mode, so a directory whose real name ends in one cannot be granted. $ALLOWED_PATHS is indeterminate when grants are configured, because the target determines which roots actually open. Use the same rshell version and platform conventions on the checking service and target; this API does not translate Windows paths or builtin availability for a different OS.

Known missing grants produce denied. A lexically permitted file operation produces indeterminate/requires_execution, because remote root existence, symlink containment, file types, hard-link restrictions, and OS access still need checking. There are no local "missing root" warnings. A denial takes precedence over uncertainty. This is an authorization preview, not an execution-success guarantee: actual execution must reauthorize against the target's current policies and filesystem using the normal runner and sandbox.

Security model

Policy is layered and default-deny:

Surface Default Explicit opt-in
Commands Denied AllowedCommands with namespaced entries such as rshell:cat
Filesystem Denied AllowedPaths roots, optionally suffixed with :ro or :rw
Environment Empty; the host environment is not inherited Env
Writes and remediation commands Disabled WithMode(ModeRemediation) plus a matching :rw path or capability grant
Systemd All units and actions denied Exact unit/action grants through AllowedSystemServices; systemctl also requires remediation mode

A terminal :ro or :rw on an AllowedPaths entry is always the access mode, never part of the directory name, on every platform: /srv/app:rw always means /srv/app, read-write. A directory whose real name ends in :ro or :rw therefore cannot be allowed. Suffix parsing never consults the filesystem, so files created by a script cannot change which roots a later runner opens or their modes. If an entry's full text, suffix included, names an existing path on Linux or macOS, the runner warns:

AllowedPaths: existing path "/srv/app:rw" is not granted; the ":rw" suffix is read as the access mode for "/srv/app" (paths ending in :ro or :rw cannot be allowed)

The warning is informational and does not fail runner construction, so a planted file cannot prevent later runs. The privileged helper's Landlock policy applies the same rule.

The Linux Private Action Runner integration adds a separate production boundary: the socket-facing privileged helper verifies the signed task, then dispatches it to a fresh one-shot worker. That worker derives Landlock rules from the verified effective path, command, and system-service policies and installs the reviewed seccomp denylist before executing the script. The signed action selects read-only or remediation mode; either action may selectively elevate explicitly authorized commands, while read-only actions receive no Landlock write rights. See Privileged helper for the lifecycle, kernel requirements, fixed builtin path grants, and syscall policy.

Only registered rshell builtins are executable through the public API; host binaries and unknown commands are rejected. Read-only mode is the default; remediation mode enables only the separately authorized write and host-remediation surfaces.

Sed selects the longest regex match at the leftmost position, including for in-place edits. Remediation-mode sed -i uses bounded, non-atomic writes with best-effort restoration. It rejects known oversized input before reading and caps each input/output buffer's capacity at 256 MiB. It reserves time within the write budget to resolve an abandoned writer; if the writer remains active, it reports an unknown outcome and skips restoration rather than racing it. Partial changes can remain; see the feature reference for timeout and recovery limits.

For simple commands, rshell expands only enough words to identify the command, then applies command, elevation, and mode policy before expanding the remaining arguments, inline assignments, or redirects. A rejected command therefore cannot trigger command substitutions or redirect side effects through its unused arguments. Once a command is authorized, redirects retain normal shell semantics: they are established before execution and remain effective even if the command later exits nonzero. Because an input redirect (< file) reads a file without invoking a command, it is authorized as an implicit cat file: it is refused unless rshell:cat is allowed (the platform's null device, /dev/null on Unix or NUL on Windows, is exempt), so allowing a stdin filter such as tr does not by itself grant file reads.

Script text is bounded before parsing: at most 5 MiB of source, and a nesting depth (parentheses, substitutions, brace groups, pipelines, logical lists, and if/while/for/case compounds) of at most 5000. Both are enforced before and during AST validation so that a deeply nested but sub-5-MiB script cannot overflow the parser's or interpreter's recursion and crash the embedding process.

Commands run by find -exec, find -execdir, and xargs may themselves run commands, up to 16 levels deep (interp.MaxNestedCommandDepth). A command past that depth is refused instead of running (with nested command depth exceeds maximum of 16 unless an earlier command or mode check refuses it first), and the builtin that tried to run it reports the failure as it would any other refused command.

Shell expansion is bounded independently of the execution timeout: a command may receive at most 16,384 expanded arguments totaling 10 MiB, and one Run may produce at most 64 MiB of expanded argument, assignment, redirect, and heredoc text across all loops, subshells, and pipeline stages. The argument cap is enforced before an unquoted variable or command substitution is field-split, not after the fields are built. Individual variable values remain capped at 1 MiB and heredocs at 10 MiB. The variables a script holds at once are capped at 1 MiB of values plus 1 MiB of names and fixed per-variable overhead (about 16k variables), shared by every concurrently running subshell and pipeline stage; a subshell that overrides or clears an inherited variable is still charged for the copy its parent holds.

Redirect targets undergo shell expansion and must resolve to exactly one field; ambiguous targets fail before the file is opened. Quoting preserves literal spaces and wildcard characters.

On Linux, ss treats absent IPv6 socket tables as empty, including for -6; other read errors still fail the command.

Some inspection builtins read fixed kernel interfaces outside AllowedPaths, and trusted systemd target paths intentionally bypass the filesystem sandbox. Their platform limits, data exposure, and authorization rules are documented in the feature reference.

Features and platforms

Allow rshell:help, then run help to distinguish commands available now, allowlisted commands that require remediation mode, and commands disabled by policy; it also always shows an Elevatable commands section listing commands that may be prefixed with sudo, or an explicit notice when none qualify. Use help <command> for command-specific details. See SHELL_FEATURES.md for the complete supported and blocked feature matrix.

The interpreter supports Linux, macOS, and Windows. Some host-inspection builtins are platform-specific; the feature reference calls those out individually.

Development

See CONTRIBUTING.md for setup, testing, and pull request guidance. Security-sensitive builtin implementation rules live in docs/RULES.md.

License

Apache License 2.0

Documentation

Overview

Package rshell contains the restricted shell module. Use interp to run scripts.

Directories

Path Synopsis
Package allowedpaths implements a filesystem sandbox that restricts access to a set of allowed directories using os.Root (Go 1.24+).
Package allowedpaths implements a filesystem sandbox that restricts access to a set of allowed directories using os.Root (Go 1.24+).
internal/fsstat
Package fsstat reads filesystem metadata for a path opened through os.Root.
Package fsstat reads filesystem metadata for a path opened through os.Root.
internal/writeopen
Package writeopen opens sandboxed files for writing.
Package writeopen opens sandboxed files for writing.
Package analysis provides a go/analysis.Analyzer that enforces symbol-level import restrictions on Go source files.
Package analysis provides a go/analysis.Analyzer that enforces symbol-level import restrictions on Go source files.
Package builtins defines restricted shell commands and their capabilities.
Package builtins defines restricted shell commands and their capabilities.
awk
Package awk implements a restricted, POSIX-oriented awk interpreter.
Package awk implements a restricted, POSIX-oriented awk interpreter.
break
Package breakcmd implements the break builtin command.
Package breakcmd implements the break builtin command.
cat
Package cat implements the cat builtin command.
Package cat implements the cat builtin command.
cd
Package cd implements the cd builtin command.
Package cd implements the cd builtin command.
continue
Package continuecmd implements the continue builtin command.
Package continuecmd implements the continue builtin command.
cut
Package cut implements the cut builtin command.
Package cut implements the cut builtin command.
df
Package df implements the df builtin command.
Package df implements the df builtin command.
du
Package du implements the du builtin command.
Package du implements the du builtin command.
echo
Package echo implements the echo builtin command.
Package echo implements the echo builtin command.
exit
Package exit implements the exit builtin command.
Package exit implements the exit builtin command.
false
Package falsecmd implements the false builtin command.
Package falsecmd implements the false builtin command.
find
Package find implements the find builtin command.
Package find implements the find builtin command.
free
Package free implements the free builtin command.
Package free implements the free builtin command.
grep
Package grep implements the grep builtin command.
Package grep implements the grep builtin command.
head
Package head implements the head builtin command.
Package head implements the head builtin command.
help
Package help implements the help builtin command.
Package help implements the help builtin command.
internal/boundedreplace
Package boundedreplace sizes the result of a string replacement before any of it is allocated.
Package boundedreplace sizes the result of a string replacement before any of it is allocated.
internal/diskstats
Package diskstats reads mounted-filesystem usage information from the kernel and presents it as a normalised cross-platform Mount struct.
Package diskstats reads mounted-filesystem usage information from the kernel and presents it as a normalised cross-platform Mount struct.
internal/flagparser
Package flagparser bridges between pflag and the GNU-getopt wording that rshell builtins are expected to match.
Package flagparser bridges between pflag and the GNU-getopt wording that rshell builtins are expected to match.
internal/loopctl
Package loopctl bounds command iteration and checks cancellation.
Package loopctl bounds command iteration and checks cancellation.
internal/meminfo
Package meminfo reads host memory and swap usage from the kernel and presents it as a normalised cross-platform Info struct.
Package meminfo reads host memory and swap usage from the kernel and presents it as a normalised cross-platform Info struct.
internal/ntfsmft
Package ntfsmft computes disk usage for a target directory on an NTFS volume by reading the raw $MFT.
Package ntfsmft computes disk usage for a target directory on an NTFS volume by reading the raw $MFT.
internal/procfd
Package procfd provides Linux open-file-descriptor enumeration for the lsof builtin.
Package procfd provides Linux open-file-descriptor enumeration for the lsof builtin.
internal/procinfo
Package procinfo provides OS-specific process information for the ps builtin.
Package procinfo provides OS-specific process information for the ps builtin.
internal/procmaps
Package procmaps reads per-process virtual memory mappings for the pmap builtin and presents them as a normalised cross-platform slice of Mapping.
Package procmaps reads per-process virtual memory mappings for the pmap builtin and presents them as a normalised cross-platform slice of Mapping.
internal/procnetroute
Package procnetroute reads the Linux IPv4 routing table from /proc/net/route.
Package procnetroute reads the Linux IPv4 routing table from /proc/net/route.
internal/procnetsocket
Package procnetsocket reads Linux socket state from /proc/net/.
Package procnetsocket reads Linux socket state from /proc/net/.
internal/procpath
Package procpath provides the single canonical default path to the Linux proc filesystem.
Package procpath provides the single canonical default path to the Linux proc filesystem.
internal/procsyskernel
Package procsyskernel reads Linux kernel information from /proc/sys/kernel/.
Package procsyskernel reads Linux kernel information from /proc/sys/kernel/.
internal/sizeparse
Package sizeparse parses coreutils-style non-negative byte sizes.
Package sizeparse parses coreutils-style non-negative byte sizes.
internal/sysinfo
Package sysinfo provides cross-platform access to system uptime and load average data.
Package sysinfo provides cross-platform access to system uptime and load average data.
internal/vmstat
Package vmstat reads virtual-memory, swap, IO-paging, and CPU pressure counters from the kernel and presents them as a normalised cross-platform Stats struct.
Package vmstat reads virtual-memory, swap, IO-paging, and CPU pressure counters from the kernel and presents them as a normalised cross-platform Stats struct.
internal/winnet
Package winnet provides socket enumeration for Windows via iphlpapi.dll.
Package winnet provides socket enumeration for Windows via iphlpapi.dll.
internal/winpoll
Package winpoll provides a non-consuming readability probe for Windows file handles.
Package winpoll provides a non-consuming readability probe for Windows file handles.
ip
Package ip implements the ip builtin command.
Package ip implements the ip builtin command.
journalctl
Package journalctl implements a bounded systemd journal query builtin.
Package journalctl implements a bounded systemd journal query builtin.
jq
Package jq implements a bounded, read-only jq subset without external code or data.
Package jq implements a bounded, read-only jq subset without external code or data.
logrotate
Package logrotate implements a remediation-mode log truncation builtin.
Package logrotate implements a remediation-mode log truncation builtin.
ls
Package ls implements the ls builtin command.
Package ls implements the ls builtin command.
lsof
Package lsof implements the lsof builtin command.
Package lsof implements the lsof builtin command.
ntfsdu
Package ntfsdu implements the Windows-only ntfs-du builtin.
Package ntfsdu implements the Windows-only ntfs-du builtin.
ping
Package ping implements the ping builtin command.
Package ping implements the ping builtin command.
pmap
Package pmap implements the pmap builtin command.
Package pmap implements the pmap builtin command.
printf
Package printf implements the printf builtin command.
Package printf implements the printf builtin command.
ps
Package ps implements the ps builtin command.
Package ps implements the ps builtin command.
pwd
Package pwd implements the pwd builtin command.
Package pwd implements the pwd builtin command.
read
Package read implements the read builtin command.
Package read implements the read builtin command.
rm
Package rm implements the rm builtin command.
Package rm implements the rm builtin command.
sed
Package sed implements the sed builtin command.
Package sed implements the sed builtin command.
sha256sum
Package sha256sum implements the sha256sum builtin command.
Package sha256sum implements the sha256sum builtin command.
sort
Package sort implements the sort builtin command.
Package sort implements the sort builtin command.
ss
Package ss implements the ss builtin command.
Package ss implements the ss builtin command.
stat
Package stat implements the stat filesystem-status builtin.
Package stat implements the stat filesystem-status builtin.
strings_cmd
Package strings_cmd implements the strings builtin command.
Package strings_cmd implements the strings builtin command.
systemctl
Package systemctl implements a capability-bounded systemd unit manager.
Package systemctl implements a capability-bounded systemd unit manager.
tail
Package tail implements the tail builtin command.
Package tail implements the tail builtin command.
tee
Package tee implements the tee builtin command.
Package tee implements the tee builtin command.
testcmd
Package testcmd implements the POSIX test and [ builtin commands.
Package testcmd implements the POSIX test and [ builtin commands.
testutil
Package testutil provides shared test helpers for builtin command tests.
Package testutil provides shared test helpers for builtin command tests.
tr
Package tr implements the tr builtin command.
Package tr implements the tr builtin command.
true
Package truecmd implements the true builtin command.
Package truecmd implements the true builtin command.
truncate
Package truncate implements the truncate builtin command.
Package truncate implements the truncate builtin command.
uname
Package uname implements the uname builtin command.
Package uname implements the uname builtin command.
uniq
Package uniq implements the uniq builtin command.
Package uniq implements the uniq builtin command.
uptime
Package uptime implements the uptime builtin command.
Package uptime implements the uptime builtin command.
vmstat
Package vmstat implements the vmstat builtin command.
Package vmstat implements the vmstat builtin command.
wc
Package wc implements the wc builtin command.
Package wc implements the wc builtin command.
xargs
Package xargs implements the xargs builtin command.
Package xargs implements the xargs builtin command.
cmd
rshell command
Package main provides the rshell development CLI.
Package main provides the rshell development CLI.
internal
interpoption
Package interpoption provides internal-only interpreter options that are not part of the public API.
Package interpoption provides internal-only interpreter options that are not part of the public API.
sandbox/landlock
Package landlock applies a process-wide Landlock filesystem policy derived from rshell AllowedPaths entries.
Package landlock applies a process-wide Landlock filesystem policy derived from rshell AllowedPaths entries.
sandbox/seccomp
Package seccomp installs the syscall restrictions used by the privileged rshell worker.
Package seccomp installs the syscall restrictions used by the privileged rshell worker.
systemd
Package systemd contains the trusted target and transport implementation used by systemd-aware builtins.
Package systemd contains the trusted target and transport implementation used by systemd-aware builtins.
version
Package version exposes the build version of rshell.
Package version exposes the build version of rshell.
Package interp implements a restricted shell interpreter designed for safe, sandboxed execution.
Package interp implements a restricted shell interpreter designed for safe, sandboxed execution.
Package privilegedhelper defines the authenticated wire protocol shared by rshell's privileged helper and the Datadog Private Action Runner.
Package privilegedhelper defines the authenticated wire protocol shared by rshell's privileged helper and the Datadog Private Action Runner.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL