mirror of
https://github.com/safedep/pmg.git
synced 2026-08-03 07:24:09 +02:00
* feat(sandbox): introduce presets - additive workload allowance bundles Presets are named, additive-only bundles of sandbox allowances for a specific workload (git hooks tooling, Astro/Vite/Next.js dev servers). They solve the per-workload tuning friction from #384 without weakening the default posture: no built-in profile references a preset, presets cannot carry deny rules or profile booleans (strict YAML decoding), and mandatory denies still win everywhere except the existing exact-match suppression. - Preset schema with metadata (author, labels) and schema_version gating - Registry over ordered sources (embedded builtin, user dir); builtin wins name collisions; source abstraction is the extension point for a future hosted registry and SafeDep cloud sync - Official presets: git, astro, vite, nextjs (with threat notes) - Overlay/runtime integration: pmg sandbox allow preset=<name> and --sandbox-allow preset=<name>, stored by reference, resolved at apply time, missing presets warn (fail closed) instead of aborting - Profile integration: presets: [...] list resolved after inherits - CLI: pmg sandbox preset list (metadata filters, --json), show (prints YAML with threat notes), lint - Docs: user guide (docs/sandbox-presets.md) and design spec Closes #384 Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PETCfE4crLcmodosz12qRn * fix(sandbox): address review findings on presets - Presets never modify deny lists: a profile authored deny now survives a preset allowing the same path (deny-beats-allow keeps it enforced). Regression test added. - Profile inspection commands (show, diff, lint) construct the profile registry with the user-aware preset registry so they agree with runtime resolution of custom profiles referencing user presets. - Handle stderr write error when warning about unresolvable presets. - Compute preset show underline from the uncolored header. - Use path.Join for embed.FS reads (slash-separated on all platforms). - Clarify in docs that lint-staged/astro are examples of preset workloads. - Drop the design spec from the PR per review. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PETCfE4crLcmodosz12qRn * fix(sandbox): harden preset precedence against authored denies Addresses external security review findings on the preset mechanism: - Bubblewrap: a mandatory write-denied path listed in allow_read lost its protection when a later writable parent bind covered it (bwrap last mount wins) - exactly the git preset shape (allow_read .git/config + allow_write .git/**). The mandatory deny now re-binds the path read-only after all writable mounts instead of being skipped. Regression test asserts mount ordering. Landlock and Seatbelt were unaffected (tests added for the same policy shape on Landlock). - Environment: ScrubEnv is allow-wins, so a preset environment allowance could override a profile-authored deny. Preset env allowances overlapping an authored deny pattern are now dropped at application time (conservative bidirectional glob overlap, fail closed). Surviving entries still opt out of built-in credential scrubbing as intended. - Network: removed allow_outbound from the preset schema. Both platform translators are all-or-nothing for outbound (one allow rule means blanket network access), so a preset outbound entry would silently change network posture far beyond what its YAML conveys. Strict decoding rejects the key. - Added a dual-path expansion equivalence test (profile presets: field vs overlay/--sandbox-allow) and documented the precedence guarantees in docs/sandbox-presets.md. Explicit --sandbox-allow and pmg sandbox allow overrides keep their existing semantics. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PETCfE4crLcmodosz12qRn * docs(sandbox): document env and preset allowances in allow command and overlay docs pmg sandbox allow help, the --sandbox-allow flag usage, and the project overlay docs enumerated only read/write/exec/net types. Add env and preset to all of them, with an overlay example for persisting an env allowance and a note on why env entries are not auto-promoted by --last. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PETCfE4crLcmodosz12qRn * chore(sandbox): trim preset code comments to corner cases and minimal godocs Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PETCfE4crLcmodosz12qRn * fix(sandbox): exact glob intersection for preset env deny overlap The bidirectional literal-text heuristic missed overlapping globs with different literal structure: preset allow AWS_*_KEY and authored deny AWS_SECRET_* both match AWS_SECRET_ACCESS_KEY but neither pattern matches the other's text, so the allowance merged and allow-wins scrubbing exposed the variable. EnvPatternsOverlap now computes exact intersection non-emptiness for the name glob dialect (case-insensitive, '*' any sequence, '?' single char) via memoized DP. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PETCfE4crLcmodosz12qRn * fix(sandbox): preset env allowances are exact names, not globs Glob-vs-glob intersection is a losing game: every dialect extension (character classes today) silently reopens the deny-bypass hole. Restricting preset environment allowances to literal variable names makes the authored-deny precedence check exact by construction: each deny pattern is evaluated against the concrete name with the same matcher ScrubEnv uses at runtime, so the decision cannot diverge from enforcement regardless of deny dialect. Removes the glob intersection machinery. Profile and --sandbox-allow env globs are unaffected. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PETCfE4crLcmodosz12qRn * fix(sandbox): reject mandatory-deny targets in preset paths Preset validation relied on IsSensitiveProjectTarget, which covers fewer files than util.DANGEROUS_FILES. A preset naming .git-credentials, .pgpass, .docker/config.json or .config/gh exactly would exact-match suppress the mandatory deny; .git/config in allow_write would suppress the write protection. Preset paths are now checked against DANGEROUS_FILES (single source of truth), .git/hooks is rejected in any direction, and .git/config is rejected for write/exec while read stays allowed for git repo discovery. Docs state the two deliberate opt-outs precisely. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PETCfE4crLcmodosz12qRn * feat(sandbox): preset init and edit commands for community authoring pmg sandbox preset init scaffolds a valid user preset (metadata flags, threat-note template, starter rule) and refuses built-in names since builtins win resolution. pmg sandbox preset edit opens the file via the shared editor package and validates the result, warning when a user preset is shadowed by a built-in. Docs lead with the scaffolded flow and spell out builtin-vs-community provenance in preset list. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PETCfE4crLcmodosz12qRn * refactor(sandbox): move mandatory-target matching into util Preset path validation re-encoded knowledge util already owns: the dangerous-files comparison and hardcoded .git/config and .git/hooks strings. util now exports GitConfigPath, GitHooksPath (also used by GetMandatoryDenyPatterns), PathCoveredBy and DangerousFileMatch, and preset validation consumes them so the mandatory deny policy has a single definition. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PETCfE4crLcmodosz12qRn --------- Co-authored-by: Claude <noreply@anthropic.com>
216 lines
8.6 KiB
Go
216 lines
8.6 KiB
Go
package sandbox
|
|
|
|
import (
|
|
"fmt"
|
|
"strings"
|
|
|
|
"github.com/safedep/dry/utils"
|
|
)
|
|
|
|
// SandboxPolicy represents a parsed and validated sandbox policy that defines
|
|
// filesystem, network, and process execution restrictions for package managers.
|
|
// Policy violations will block execution. Policy supports inheritance from parent policies.
|
|
type SandboxPolicy struct {
|
|
// These fields are not affected by inheritance and are set from the child policy.
|
|
Name string `yaml:"name" json:"name"`
|
|
Description string `yaml:"description" json:"description"`
|
|
Inherits string `yaml:"inherits,omitempty" json:"inherits,omitempty"`
|
|
PackageManagers []string `yaml:"package_managers" json:"package_managers"`
|
|
|
|
// Presets are expanded by the registry after inheritance resolution.
|
|
// Names are kept post-expansion for provenance display.
|
|
Presets []string `yaml:"presets,omitempty" json:"presets,omitempty"`
|
|
|
|
// These fields are affected by inheritance and are merged with the parent policy.
|
|
// Any new values added here should be handled in the MergeWithParent method.
|
|
Filesystem FilesystemPolicy `yaml:"filesystem" json:"filesystem"`
|
|
Network NetworkPolicy `yaml:"network" json:"network"`
|
|
Process ProcessPolicy `yaml:"process" json:"process"`
|
|
Environment EnvironmentPolicy `yaml:"environment" json:"environment"`
|
|
|
|
// The boolean fields are pointers to allow for nil values so that the YAML parser
|
|
// can set the values from the child policy if present. We can differentiate between
|
|
// nil and false values. Any new values added here should be handled in the
|
|
// MergeWithParent method. When present in the child policy, the parent value is ignored.
|
|
// When not present in the child policy, the parent value is used.
|
|
|
|
// AllowGitConfig allows write access to .git/config file.
|
|
AllowGitConfig *bool `yaml:"allow_git_config" json:"allow_git_config"`
|
|
|
|
// AllowPTY allows pseudo-terminal (PTY) operations.
|
|
AllowPTY *bool `yaml:"allow_pty" json:"allow_pty"`
|
|
|
|
// AllowNetworkBind allows binding to localhost (127.0.0.1 / ::1) for listening.
|
|
AllowNetworkBind *bool `yaml:"allow_network_bind" json:"allow_network_bind"`
|
|
|
|
// NetworkViaProxyOnly confines all outbound network access to the PMG
|
|
// proxy. Requires the proxy flow; drivers fail closed without a running
|
|
// proxy.
|
|
NetworkViaProxyOnly *bool `yaml:"network_via_proxy_only" json:"network_via_proxy_only"`
|
|
|
|
// AllowDirectDNS re-opens direct DNS (mDNSResponder) under
|
|
// NetworkViaProxyOnly. No effect otherwise. Default false: the proxy
|
|
// resolves names and direct DNS is an exfiltration channel.
|
|
AllowDirectDNS *bool `yaml:"allow_direct_dns" json:"allow_direct_dns"`
|
|
}
|
|
|
|
// FilesystemPolicy defines allowed and denied filesystem access patterns.
|
|
// Deny rules have higher priority than allow rules.
|
|
type FilesystemPolicy struct {
|
|
AllowRead []string `yaml:"allow_read" json:"allow_read"`
|
|
AllowWrite []string `yaml:"allow_write" json:"allow_write"`
|
|
DenyRead []string `yaml:"deny_read" json:"deny_read"`
|
|
DenyWrite []string `yaml:"deny_write" json:"deny_write"`
|
|
}
|
|
|
|
// NetworkPolicy defines allowed and denied network access patterns.
|
|
// Patterns are in the format "host:port" or "*:*" for wildcards.
|
|
type NetworkPolicy struct {
|
|
AllowOutbound []string `yaml:"allow_outbound" json:"allow_outbound"`
|
|
DenyOutbound []string `yaml:"deny_outbound" json:"deny_outbound"`
|
|
AllowBind []string `yaml:"allow_bind" json:"allow_bind"`
|
|
}
|
|
|
|
// ProcessPolicy defines allowed and denied process execution patterns.
|
|
// Patterns can be specific paths or glob patterns.
|
|
type ProcessPolicy struct {
|
|
AllowExec []string `yaml:"allow_exec" json:"allow_exec"`
|
|
DenyExec []string `yaml:"deny_exec" json:"deny_exec"`
|
|
}
|
|
|
|
// EnvironmentPolicy controls which environment variables are scrubbed from the
|
|
// child process. Deny extends the built-in util.DANGEROUS_ENV_VARS list; Allow
|
|
// suppresses matching denies (allow wins). Patterns are case-insensitive name
|
|
// globs. Enforcement happens in sandbox/util.ScrubEnv at process spawn.
|
|
type EnvironmentPolicy struct {
|
|
Allow []string `yaml:"allow" json:"allow"`
|
|
Deny []string `yaml:"deny" json:"deny"`
|
|
}
|
|
|
|
// Validate validates the sandbox policy for correctness before inheritance resolution.
|
|
// Returns an error if the policy is invalid.
|
|
// Note: Validation for "at least one rule" check is deferred to ValidateResolved(),
|
|
// since a child policy might have no rules of its own but inherit rules from its parent.
|
|
func (p *SandboxPolicy) Validate() error {
|
|
if p.Name == "" {
|
|
return fmt.Errorf("policy name is required")
|
|
}
|
|
|
|
if len(p.PackageManagers) == 0 {
|
|
return fmt.Errorf("policy must specify at least one package manager")
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// ValidateResolved validates a policy after inheritance has been resolved.
|
|
// This is called after MergeWithParent to ensure the final policy is valid.
|
|
func (p *SandboxPolicy) ValidateResolved() error {
|
|
if err := p.Validate(); err != nil {
|
|
return err
|
|
}
|
|
|
|
// Check that at least one access rule is defined (after inheritance)
|
|
hasRules := len(p.Filesystem.AllowRead) > 0 ||
|
|
len(p.Filesystem.AllowWrite) > 0 ||
|
|
len(p.Filesystem.DenyRead) > 0 ||
|
|
len(p.Filesystem.DenyWrite) > 0 ||
|
|
len(p.Network.AllowOutbound) > 0 ||
|
|
len(p.Network.DenyOutbound) > 0 ||
|
|
len(p.Process.AllowExec) > 0 ||
|
|
len(p.Process.DenyExec) > 0 ||
|
|
len(p.Environment.Allow) > 0 ||
|
|
len(p.Environment.Deny) > 0
|
|
|
|
if !hasRules {
|
|
return fmt.Errorf("policy must define at least one access rule (after inheritance resolution)")
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// AppliesToPackageManager returns true if this policy applies to the given package manager.
|
|
func (p *SandboxPolicy) AppliesToPackageManager(pm string) bool {
|
|
pmLower := strings.ToLower(pm)
|
|
for _, supported := range p.PackageManagers {
|
|
if strings.ToLower(supported) == pmLower {
|
|
return true
|
|
}
|
|
}
|
|
|
|
return false
|
|
}
|
|
|
|
// MergeWithParent merges the child policy with its parent policy.
|
|
// Lists are unioned (additive), package_managers are replaced, booleans are overridden.
|
|
// This method modifies the receiver (child policy) in place.
|
|
func (child *SandboxPolicy) MergeWithParent(parent *SandboxPolicy) {
|
|
// Union filesystem lists
|
|
child.Filesystem.AllowRead = unionStringSlices(parent.Filesystem.AllowRead, child.Filesystem.AllowRead)
|
|
child.Filesystem.AllowWrite = unionStringSlices(parent.Filesystem.AllowWrite, child.Filesystem.AllowWrite)
|
|
child.Filesystem.DenyRead = unionStringSlices(parent.Filesystem.DenyRead, child.Filesystem.DenyRead)
|
|
child.Filesystem.DenyWrite = unionStringSlices(parent.Filesystem.DenyWrite, child.Filesystem.DenyWrite)
|
|
|
|
// Union network lists
|
|
child.Network.AllowOutbound = unionStringSlices(parent.Network.AllowOutbound, child.Network.AllowOutbound)
|
|
child.Network.DenyOutbound = unionStringSlices(parent.Network.DenyOutbound, child.Network.DenyOutbound)
|
|
child.Network.AllowBind = unionStringSlices(parent.Network.AllowBind, child.Network.AllowBind)
|
|
|
|
// Union process lists
|
|
child.Process.AllowExec = unionStringSlices(parent.Process.AllowExec, child.Process.AllowExec)
|
|
child.Process.DenyExec = unionStringSlices(parent.Process.DenyExec, child.Process.DenyExec)
|
|
|
|
// Union environment lists
|
|
child.Environment.Allow = unionStringSlices(parent.Environment.Allow, child.Environment.Allow)
|
|
child.Environment.Deny = unionStringSlices(parent.Environment.Deny, child.Environment.Deny)
|
|
|
|
// Union preset references
|
|
child.Presets = unionStringSlices(parent.Presets, child.Presets)
|
|
|
|
// Set boolean fields by duplicating the parent value if not present in the child.
|
|
if child.AllowPTY == nil {
|
|
child.AllowPTY = utils.PtrTo(utils.SafelyGetValue(parent.AllowPTY))
|
|
}
|
|
|
|
if child.AllowGitConfig == nil {
|
|
child.AllowGitConfig = utils.PtrTo(utils.SafelyGetValue(parent.AllowGitConfig))
|
|
}
|
|
|
|
if child.AllowNetworkBind == nil {
|
|
child.AllowNetworkBind = utils.PtrTo(utils.SafelyGetValue(parent.AllowNetworkBind))
|
|
}
|
|
|
|
if child.NetworkViaProxyOnly == nil {
|
|
child.NetworkViaProxyOnly = utils.PtrTo(utils.SafelyGetValue(parent.NetworkViaProxyOnly))
|
|
}
|
|
|
|
if child.AllowDirectDNS == nil {
|
|
child.AllowDirectDNS = utils.PtrTo(utils.SafelyGetValue(parent.AllowDirectDNS))
|
|
}
|
|
}
|
|
|
|
// unionStringSlices returns a new slice containing all unique elements from both slices.
|
|
// Order is preserved: parent entries first, then child entries (excluding duplicates).
|
|
func unionStringSlices(parent, child []string) []string {
|
|
seen := make(map[string]bool)
|
|
result := make([]string, 0, len(parent)+len(child))
|
|
|
|
// Add all parent entries
|
|
for _, item := range parent {
|
|
if !seen[item] {
|
|
seen[item] = true
|
|
result = append(result, item)
|
|
}
|
|
}
|
|
|
|
// Add child entries that aren't duplicates
|
|
for _, item := range child {
|
|
if !seen[item] {
|
|
seen[item] = true
|
|
result = append(result, item)
|
|
}
|
|
}
|
|
|
|
return result
|
|
}
|