Files
Pulse/internal/agentexec/policy.go
rcourtman c48c46a67d Check arguments of auto-approved commands in the default policy
The default command policy approves a list of inspection programs
without a human. Those rules match the start of the command, so the
same programs also ran their other forms without approval: ip and
ifconfig changes, find -delete/-exec/-fprint, du --files0-from,
file -f/-m/-d, sar -o, ss -K, journalctl --vacuum-*/--cursor-file,
ps environments and similar.

After a pattern matches, autoApprovedArgsSafe now splits the command
into shell words after quote removal (refusing anything the shell would
expand) and, for find, du, file, last, blkid, ss, lsof, journalctl,
systemctl, apt-cache, sar, ps, ip, ifconfig, dpkg, pvesh and podman,
refuses options that change the host, write files or read another
file's contents. ip, ifconfig, dpkg and podman use allowlists; the rest
deny the risky options, including getopt_long abbreviations and short
option clusters. Programs that read meaning from the number of operands
refuse unquoted globs. Several patterns are anchored, and service
status takes a plain service name.

Commands without an approval or the Trusted flag also no longer inherit
variables that change how sh, grep, ps, blkid or apt-cache read the
command line (BASH_FUNC_*, BASH_ENV, ENV, SHELLOPTS, BASHOPTS, PS4,
GREP_OPTIONS, PS_FORMAT, PS_PERSONALITY, CMD_ENV, BLKID_FILE,
BLKID_CONF, APT_CONFIG).

Display forms Patrol and operators use keep running without approval;
the tests list both sides. The agent environment test used ps e as its
auto-approved read, which is now refused, so it prints the environment
the shell received through a swapped executable instead. The
agent-lifecycle contract records the rule.
2026-11-14 00:36:37 +00:00

587 lines
17 KiB
Go

package agentexec
import (
"encoding/json"
"fmt"
"regexp"
"slices"
"strings"
"sync"
"time"
"github.com/rs/zerolog/log"
)
// DefaultVerifyWindow is the default duration the verifier substrate waits
// for a postcondition to settle after a write capability has been dispatched.
// Two minutes is enough for restart-class operations on a healthy host while
// staying short enough that an operator watching a run does not feel stalled.
const DefaultVerifyWindow = 2 * time.Minute
// MaxVerifyWindow is the hard upper bound for the verify window. A larger
// value would let an agent (or a misconfigured policy) pin the audit record
// in "executing" for too long while polling for a postcondition. Fifteen
// minutes covers slow rollouts (kubectl rollout, big VM boot) without
// leaving the action dangling indefinitely.
const MaxVerifyWindow = 15 * time.Minute
// CommandPolicy defines what commands are allowed, blocked, or require approval
type CommandPolicy struct {
// AutoApprove patterns - commands matching these are automatically allowed
AutoApprove []string `json:"auto_approve"`
// RequireApproval patterns - commands matching these need user approval
RequireApproval []string `json:"require_approval"`
// Blocked patterns - commands matching these are never allowed
Blocked []string `json:"blocked"`
// VerifyWindow is the maximum wall-clock duration the verifier substrate
// waits for a postcondition to settle after a write capability has been
// dispatched. Zero / negative values are coerced to DefaultVerifyWindow
// by NormalizeVerifyWindow; values above MaxVerifyWindow are clamped.
VerifyWindow time.Duration `json:"verify_window"`
// allowLogReads approves cat, head, tail and grep whose every file
// operand is under /var/log (see isAutoApprovedLogRead).
allowLogReads bool
// checkArgs refuses, for programs an auto-approve pattern names, the
// arguments that change the system or read or write other files (see
// autoApprovedArgsSafe).
checkArgs bool
// compiled regex patterns
autoApproveRe []*regexp.Regexp
requireApprovalRe []*regexp.Regexp
blockedRe []*regexp.Regexp
}
// NormalizeVerifyWindow returns the bounded verify window for a policy:
// values <= 0 fall back to DefaultVerifyWindow, values above MaxVerifyWindow
// are clamped to MaxVerifyWindow. Returned value is always within
// [DefaultVerifyWindow, MaxVerifyWindow] except where the operator
// explicitly picked something in (0, DefaultVerifyWindow]; we keep
// operator-chosen small windows rather than silently widening them.
func NormalizeVerifyWindow(d time.Duration) time.Duration {
if d <= 0 {
return DefaultVerifyWindow
}
if d > MaxVerifyWindow {
return MaxVerifyWindow
}
return d
}
// Normalize applies the verifier-substrate floor to the policy in place:
// VerifyWindow is bounded to [(0,], MaxVerifyWindow] with the documented
// default. Other policy fields are left alone; pattern compilation lives
// in compile().
func (p *CommandPolicy) Normalize() {
if p == nil {
return
}
p.VerifyWindow = NormalizeVerifyWindow(p.VerifyWindow)
}
// policyJSON is the wire-format shadow of CommandPolicy used to serialize
// VerifyWindow as a Go duration string (e.g. "2m0s") rather than the raw
// nanosecond integer time.Duration would otherwise produce. The other
// pattern slices are passed through unchanged.
type policyJSON struct {
AutoApprove []string `json:"auto_approve"`
RequireApproval []string `json:"require_approval"`
Blocked []string `json:"blocked"`
VerifyWindow string `json:"verify_window"`
}
// MarshalJSON emits the policy with VerifyWindow as a Go duration string so
// the operator-facing config remains human-readable.
func (p *CommandPolicy) MarshalJSON() ([]byte, error) {
if p == nil {
return []byte("null"), nil
}
window := NormalizeVerifyWindow(p.VerifyWindow)
return json.Marshal(policyJSON{
AutoApprove: p.AutoApprove,
RequireApproval: p.RequireApproval,
Blocked: p.Blocked,
VerifyWindow: window.String(),
})
}
// UnmarshalJSON parses the wire-format policy and applies NormalizeVerifyWindow
// so deserialized values always satisfy the configured bounds.
func (p *CommandPolicy) UnmarshalJSON(data []byte) error {
var shadow policyJSON
if err := json.Unmarshal(data, &shadow); err != nil {
return err
}
p.AutoApprove = shadow.AutoApprove
p.RequireApproval = shadow.RequireApproval
p.Blocked = shadow.Blocked
if shadow.VerifyWindow == "" {
p.VerifyWindow = DefaultVerifyWindow
} else {
d, err := time.ParseDuration(shadow.VerifyWindow)
if err != nil {
return fmt.Errorf("parse verify_window %q: %w", shadow.VerifyWindow, err)
}
p.VerifyWindow = NormalizeVerifyWindow(d)
}
return nil
}
// defaultPolicyTemplate compiles the default patterns once. Compiled regexps are
// safe for concurrent use and CommandPolicy only ever replaces its compiled
// slices, so every default policy can share them. A private copy costs about
// 230 KiB and 1.4 ms, and each organization's AI service holds a policy.
var defaultPolicyTemplate = sync.OnceValue(buildDefaultPolicy)
// DefaultPolicy returns a sensible default command policy. The exported pattern
// lists are the caller's own copy.
func DefaultPolicy() *CommandPolicy {
template := defaultPolicyTemplate()
return &CommandPolicy{
AutoApprove: slices.Clone(template.AutoApprove),
RequireApproval: slices.Clone(template.RequireApproval),
Blocked: slices.Clone(template.Blocked),
VerifyWindow: template.VerifyWindow,
allowLogReads: template.allowLogReads,
checkArgs: template.checkArgs,
autoApproveRe: template.autoApproveRe,
requireApprovalRe: template.requireApprovalRe,
blockedRe: template.blockedRe,
}
}
func buildDefaultPolicy() *CommandPolicy {
p := &CommandPolicy{
VerifyWindow: DefaultVerifyWindow,
allowLogReads: true,
checkArgs: true,
AutoApprove: []string{
// System inspection
`^ps(\s|$)`,
`^top\s+-bn`,
`^df(\s|$)`,
`^free(\s|$)`,
`^uptime$`,
`^hostname$`,
`^uname(\s|$)`,
`^cat\s+/proc/(cpuinfo|meminfo|loadavg|uptime|version|diskstats|mdstat|swaps|mounts|filesystems|partitions)$`,
`^cat\s+/proc/net/(dev|route|tcp|tcp6|udp|udp6|unix)$`,
`^cat\s+/etc/os-release$`,
`^lsof(\s|$)`,
`^netstat(\s|$)`,
`^ss(\s|$)`,
// ip and ifconfig: display forms only (see ipArgsSafe and
// ifconfigArgsSafe).
`^ip\s+(addr|address|route|link)(\s|$)`,
`^ifconfig(\s|$)`,
`^ping\s+-c\s*1\s+-w\s*1\s+([0-9]{1,3}\.){3}[0-9]{1,3}$`,
`^ping\s+-c\s*1\s+-w\s*1\s+[0-9a-f:]+$`,
`^w$`,
`^who$`,
`^last(\s|$)`,
// Log reading (read-only). cat, head, tail and grep of files
// under /var/log are approved by isAutoApprovedLogRead, which
// checks every operand rather than matching a prefix.
`^journalctl\s`,
// Service status (read-only)
`^systemctl\s+status\s`,
`^systemctl\s+is-active\s`,
`^systemctl\s+is-enabled\s`,
`^systemctl\s+list-units`,
`^service\s+[a-z0-9][a-z0-9@._-]*\s+status$`,
// Docker inspection (read-only)
`^docker\s+ps(\s|$)`,
`^docker\s+logs\s`,
`^docker\s+inspect\s`,
`^docker\s+stats\s+--no-stream(\s|$)`,
`^docker\s+top\s`,
`^docker\s+images(\s|$)`,
`^docker\s+network\s+ls(\s|$)`,
`^docker\s+volume\s+ls(\s|$)`,
`^podman\s+ps(\s|$)`,
`^podman\s+logs\s`,
`^podman\s+inspect\s`,
`^podman\s+stats\s+--no-stream(\s|$)`,
`^podman\s+top\s`,
`^podman\s+images(\s|$)`,
`^podman\s+network\s+ls(\s|$)`,
`^podman\s+volume\s+ls(\s|$)`,
// Proxmox inspection (read-only)
`^pct\s+list`,
`^pct\s+config\s`,
`^pct\s+status\s`,
`^qm\s+list`,
`^qm\s+config\s`,
`^qm\s+status\s`,
`^pvesh\s+get\s`,
// Disk/storage info. du, file, find, blkid, sar and the other
// programs autoApprovedArgsSafe names also have their arguments
// checked.
`^lsblk(\s|$)`,
`^blkid(\s|$)`,
`^fdisk\s+-l`,
`^du(\s|$)`,
`^ls(\s|$)`,
`^stat(\s|$)`,
`^file(\s|$)`,
`^find\s+/.*-size`, // Find large files
`^find\s+/.*-mtime`, // Find by modification time
`^find\s+/.*-type`, // Find by type
// Memory inspection
`^vmstat(\s|$)`,
`^sar\s`,
`^iostat(\s|$)`,
`^mpstat(\s|$)`,
// Docker inspection (read-only)
`^docker\s+system\s+df(\s|$)`,
`^podman\s+system\s+df(\s|$)`,
// APT inspection (read-only)
`^apt\s+list`,
`^apt-cache\s`,
`^dpkg\s+-l`,
`^dpkg\s+--list`,
},
RequireApproval: []string{
// Service control
`^systemctl\s+(restart|stop|start|reload)\s`,
`^service\s+\S+\s+(restart|stop|start|reload)`,
// Docker control
`^docker\s+(restart|stop|start|kill)\s`,
`^docker\s+exec\s`,
`^docker\s+rm\s`,
`^podman\s+(restart|stop|start|kill)\s`,
`^podman\s+exec\s`,
`^podman\s+rm\s`,
// Process control
`^kill\s`,
`^pkill\s`,
`^killall\s`,
// Package management
`^apt\s`,
`^apt-get\s`,
`^yum\s`,
`^dnf\s`,
`^pacman\s`,
// Proxmox control
`^pct\s+(start|stop|shutdown|reboot|resize|set)\s`,
`^qm\s+(start|stop|shutdown|reboot|reset|resize|set)\s`,
// journalctl maintenance (modifies logs / persistent state)
`^journalctl\s+--vacuum`,
`^journalctl\s+--rotate`,
// Temp file cleanup (safe with approval)
`^rm\s+(-rf?|-fr?)\s+/var/tmp/`,
`^rm\s+(-rf?|-fr?)\s+/tmp/`,
// Find commands that can execute actions or delete files
`^find\s+.+\s-(exec|execdir|ok|okdir|delete)\b`,
},
Blocked: []string{
// Destructive filesystem operations - block root and critical paths
// Note: /var/tmp and /tmp cleanup is allowed with approval (see RequireApproval)
`rm\s+-rf\s+/$`, // rm -rf / (root)
`rm\s+-rf\s+/\*`, // rm -rf /* (root wildcard)
`rm\s+-rf\s+/home($|\s|/)`, // rm -rf /home
`rm\s+-rf\s+/etc($|\s|/)`, // rm -rf /etc
`rm\s+-rf\s+/usr($|\s|/)`, // rm -rf /usr
`rm\s+-rf\s+/var/lib($|\s|/)`, // rm -rf /var/lib
`rm\s+-rf\s+/boot($|\s|/)`, // rm -rf /boot
`rm\s+-rf\s+/root($|\s|/)`, // rm -rf /root (root home)
`rm\s+-rf\s+/bin($|\s|/)`, // rm -rf /bin
`rm\s+-rf\s+/sbin($|\s|/)`, // rm -rf /sbin
`rm\s+-rf\s+/lib($|\s|/)`, // rm -rf /lib
`rm\s+-rf\s+/opt($|\s|/)`, // rm -rf /opt
`rm\s+--no-preserve-root`,
`mkfs`,
`dd\s+.*of=/dev/`,
`>\s*/dev/sd`,
`>\s*/dev/nvme`,
// System destruction (host-level commands only)
// Note: qm/pct reboot/shutdown are allowed with approval (see RequireApproval)
`^shutdown(\s|$)`,
`^reboot(\s|$)`,
`^init\s+0`,
`^poweroff(\s|$)`,
`^halt(\s|$)`,
// Dangerous permissions
`chmod\s+777`,
`chmod\s+-R\s+777`,
`chown\s+-R\s+.*:.*\s+/`,
// Remote code execution
`curl.*\|\s*(ba)?sh`,
`wget.*\|\s*(ba)?sh`,
`bash\s+-c\s+.*curl`,
`bash\s+-c\s+.*wget`,
// Crypto mining indicators
`xmrig`,
`minerd`,
`cpuminer`,
// Fork bomb patterns
`:\(\)\s*{\s*:\s*\|\s*:`,
// Clear system logs
`>\s*/var/log/`,
`truncate.*--size.*0.*/var/log/`,
// Sensitive procfs reads can expose credentials or kernel memory.
`^cat\s+/proc/(kcore|kallsyms|keys|timer_list|sched_debug)(\s|$)`,
`^cat\s+/proc/(self|[0-9]+)/(environ|mem)(\s|$)`,
`^cat\s+/proc/(self|[0-9]+)/(fd|fdinfo|root)(/|\s|$)`,
},
}
p.compile()
p.Normalize()
return p
}
func (p *CommandPolicy) compile() {
p.autoApproveRe = compilePatterns(p.AutoApprove)
p.requireApprovalRe = compilePatterns(p.RequireApproval)
p.blockedRe = compilePatterns(p.Blocked)
}
func compilePatterns(patterns []string) []*regexp.Regexp {
result := make([]*regexp.Regexp, 0, len(patterns))
for _, pattern := range patterns {
re, err := regexp.Compile(pattern)
if err != nil {
log.Warn().Err(err).Str("pattern", pattern).Msg("Skipping invalid command policy regex")
continue
}
result = append(result, re)
}
return result
}
// PolicyDecision represents the policy decision for a command
type PolicyDecision string
const (
PolicyAllow PolicyDecision = "allow"
PolicyRequireApproval PolicyDecision = "require_approval"
PolicyBlock PolicyDecision = "block"
)
// Evaluate checks a command against the policy
func (p *CommandPolicy) Evaluate(command string) PolicyDecision {
command = strings.TrimSpace(command)
// Options can differ only by case (grep -F and -f, ss -K and -k), so the
// log read and argument checks work on the original text.
argvCommand := command
command = strings.ToLower(command)
policyCommand := command
blockedCandidates := []string{command}
// Normalize simple sudo prefix so policy applies consistently.
// For sudo invocations with flags, keep policyCommand conservative, but still
// inspect the extracted underlying command against blocked patterns.
if strings.HasPrefix(command, "sudo ") {
if sudoCommand, hasFlags, ok := extractSudoCommand(command); ok {
blockedCandidates = append(blockedCandidates, sudoCommand)
if !hasFlags {
policyCommand = sudoCommand
}
}
argvCommand = stripPlainSudo(argvCommand)
}
// Check blocked first (highest priority)
for _, candidate := range blockedCandidates {
for _, re := range p.blockedRe {
if re.MatchString(candidate) {
return PolicyBlock
}
}
}
// Compound shell commands are never auto-approved.
if containsShellControlOperators(policyCommand) {
return PolicyRequireApproval
}
// Check require approval
for _, re := range p.requireApprovalRe {
if re.MatchString(policyCommand) {
return PolicyRequireApproval
}
}
// Check auto-approve
if p.allowLogReads && isAutoApprovedLogRead(argvCommand) {
return PolicyAllow
}
for _, re := range p.autoApproveRe {
if re.MatchString(policyCommand) {
if p.checkArgs && !autoApprovedArgsSafe(policyProgram(policyCommand), argvCommand) {
return PolicyRequireApproval
}
return PolicyAllow
}
}
// Default: require approval for unknown commands
return PolicyRequireApproval
}
// IsBlocked returns true if a command is blocked
func (p *CommandPolicy) IsBlocked(command string) bool {
return p.Evaluate(command) == PolicyBlock
}
// NeedsApproval returns true if a command needs user approval
func (p *CommandPolicy) NeedsApproval(command string) bool {
return p.Evaluate(command) == PolicyRequireApproval
}
// IsAutoApproved returns true if a command can run without approval
func (p *CommandPolicy) IsAutoApproved(command string) bool {
return p.Evaluate(command) == PolicyAllow
}
// policyProgram returns the first word of the policy's lower-case view of a
// command.
func policyProgram(command string) string {
fields := strings.Fields(command)
if len(fields) == 0 {
return ""
}
return fields[0]
}
func containsShellControlOperators(command string) bool {
if strings.Contains(command, "\n") || strings.Contains(command, "\r") {
return true
}
// A single & runs the command before it in the background and starts
// another, so it separates commands as much as ; does.
for _, marker := range []string{";", "&", "|", "`", "$(", ">", "<"} {
if strings.Contains(command, marker) {
return true
}
}
return false
}
// stripPlainSudo removes a leading "sudo " that carries no options, keeping
// the rest of the text exactly as the shell will see it. Anything else
// returns "" so no log read check applies.
func stripPlainSudo(command string) string {
if !strings.HasPrefix(command, "sudo ") {
return ""
}
rest := strings.TrimLeft(command[len("sudo"):], " ")
if rest == "" || rest[0] == '-' {
return ""
}
return rest
}
func extractSudoCommand(command string) (string, bool, bool) {
parts := strings.Fields(command)
if len(parts) < 2 || parts[0] != "sudo" {
return "", false, false
}
i := 1
hasFlags := false
expectValue := false
for i < len(parts) {
token := parts[i]
if expectValue {
expectValue = false
i++
continue
}
if token == "--" {
hasFlags = true
i++
break
}
if strings.HasPrefix(token, "--") {
hasFlags = true
if !strings.Contains(token, "=") && sudoLongOptionNeedsValue(token) {
expectValue = true
}
i++
continue
}
if strings.HasPrefix(token, "-") && token != "-" {
hasFlags = true
if sudoShortOptionNeedsValue(token) {
expectValue = true
}
i++
continue
}
break
}
if i >= len(parts) {
return "", hasFlags, false
}
return strings.Join(parts[i:], " "), hasFlags, true
}
func sudoLongOptionNeedsValue(token string) bool {
switch token {
case "--user", "--group", "--host", "--prompt", "--chdir", "--close-from", "--command-timeout", "--role", "--type":
return true
default:
return false
}
}
func sudoShortOptionNeedsValue(token string) bool {
switch token {
case "-u", "-g", "-h", "-p", "-C", "-T", "-r", "-t", "-R", "-D":
return true
}
if len(token) <= 2 || !strings.HasPrefix(token, "-") || strings.HasPrefix(token, "--") {
return false
}
switch token[1] {
case 'u', 'g', 'h', 'p', 'C', 'T', 'r', 't', 'R', 'D':
// Attached value form (e.g. -uroot) already carries its value.
return false
default:
return false
}
}