Documentation
¶
Overview ¶
Package security implements the execution-side hardening of design doc §16 and plan P3-29..P3-32: a reduced subprocess environment, network egress validation, secret scrubbing, a high-risk audit trail, and — when sandbox.mode is configured — OS-level confinement for every spawned subprocess (seatbelt on macOS, bubblewrap on Linux, AppContainer plus a write-restricted token on Windows; see policy.go and the platform sandbox_* files). Everything here is deterministic — the "adversarial model review" layers (design §14.2 Layer 2/3) are a later, model-dependent phase.
Index ¶
- Constants
- Variables
- func Backend() string
- func CheckEndpointHost(host string, allowPrivate bool) error
- func CheckModelEndpoint(rawurl string, allowPlaintext bool) error
- func CheckModelEndpointPinned(rawurl string, allowPlaintext bool, allowedHosts []string) error
- func EndpointHost(rawurl string) string
- func GuardedDialContext(d *net.Dialer) func(ctx context.Context, network, address string) (net.Conn, error)
- func MetadataHost(host string) bool
- func PrivateHost(host string) bool
- func ProxyForRequest(req *http.Request) (*url.URL, error)
- func ProxyTargetMetadata(rawurl string) bool
- func Redact(s string) string
- func RedactJSON(raw []byte) []byte
- func SetBasePolicy(p Policy)
- func SystemSecretPaths() []string
- type Audit
- type AuditRow
- type Entry
- type Mode
- type NetworkGuard
- type Policy
- type ProxyDrop
- type Sandbox
Constants ¶
const KeepProxyEnv = "OPENPANDA_KEEP_PROXY"
KeepProxyEnv is the escape hatch for the rare operator whose local proxy is intentionally down at start (started later, or a tunnel brought up after the node). It disables the drop entirely rather than whitelisting one variable, so the behaviour is a single, obvious switch.
const ModelAllowedHostsEnv = "OPENPANDA_MODEL_ALLOWED_HOSTS"
ModelAllowedHostsEnv is an out-of-band host allowlist for model endpoints, as a comma-separated list of hostnames (host:port is accepted too). It is read from the process environment — a different trust source from the agent-writable config file that supplies base_url — so an operator can pin which hosts a model endpoint is allowed to name. When it is unset the legacy self-pinned behaviour applies and no existing deployment changes.
Variables ¶
ErrSandboxUnavailable reports a policy that asks for OS confinement the host cannot provide.
Functions ¶
func Backend ¶ added in v0.0.10
func Backend() string
Backend names the OS confinement the platform implements: "seatbelt" on macOS (sandbox-exec), "bwrap" on Linux (bubblewrap), "appcontainer" on Windows, and "" on unsupported platforms or when the tool is absent. Standard and strict refuse subprocess launches when it is empty; callers report that condition instead of implying isolation.
func CheckEndpointHost ¶ added in v0.1.1
CheckEndpointHost validates the host of an endpoint a request asked the daemon to dial. Metadata addresses are refused outright: no legitimate model or push service lives there, and reaching one turns the daemon into a credential proxy.
allowPrivate keeps RFC1918 and loopback addressable — that is what makes a self-hosted model on the LAN or on this machine configurable at all.
func CheckModelEndpoint ¶ added in v0.1.4
CheckModelEndpoint is the one call the model paths make. It honours the model's plaintext opt-in and, when ModelAllowedHostsEnv is set, an operator-supplied allowlist; otherwise it pins the guard to this endpoint's own host as before. A model that never opted in keeps the https rule, so the waiver has to be asked for in the model's own config rather than inferred from the URL.
func CheckModelEndpointPinned ¶ added in v0.1.6
CheckModelEndpointPinned validates rawurl against an explicit allowlist. Deriving the pin from the URL being checked proves nothing about the URL, so a non-empty list replaces that self-pin; an empty list falls back to it for compatibility. The https rule (and the per-model plaintext opt-in) is enforced in both cases.
func EndpointHost ¶
EndpointHost returns the lowercased host (host:port) of a URL, or "" when the URL cannot be parsed or has no host. Callers use it to pin the guard to the configured model endpoint so the allowlist is never empty in production.
func GuardedDialContext ¶ added in v0.1.1
func GuardedDialContext(d *net.Dialer) func(ctx context.Context, network, address string) (net.Conn, error)
GuardedDialContext wraps a dialer so no connection is ever made to a cloud metadata address. The host checks above see the name as written; this one sees the address actually dialed, which closes DNS rebinding (a public name whose answer is 169.254.169.254) and a redirect to such an address.
Private and loopback addresses stay dialable on purpose: a self-hosted model or push service on the LAN is a normal deployment, and the metadata range is the one that hands out the host's own credentials.
func MetadataHost ¶ added in v0.1.1
MetadataHost reports whether host names an address a cloud instance uses to hand out its own credentials — the 169.254.169.254 (AWS, Azure, GCP, DigitalOcean, OpenStack) and 100.100.100.200 (Alibaba Cloud) metadata services, plus the whole link-local range they live in.
It matters because the panel takes an endpoint URL from an HTTP request body and then dials it from the host. A caller who holds the panel token can point a model endpoint at the metadata service and read the answer back through the console's own "test this model" round trip: a token leak becomes a cloud-credential leak, with the daemon as the confused deputy.
Link-local covers fe80::/10 as well, where the same trick works over IPv6.
func PrivateHost ¶ added in v0.1.1
PrivateHost reports whether host resolves to an address inside the host's own network: RFC1918 space, carrier-grade NAT, and IPv6 unique local addresses. A browser push endpoint or a model endpoint should normally name a public service, so a request that names a private address is either a mistake or a probe — but note that a *model* endpoint on the LAN (a self-hosted Ollama, a vLLM box) is a legitimate use, which is why this is separate from MetadataHost.
func ProxyForRequest ¶ added in v0.1.7
ProxyForRequest is the http.Transport.Proxy hook every model client should use. It resolves the proxy from the environment exactly like net/http would, then refuses a **loopback** proxy that has stopped listening, falling back to a direct connection.
Start-time sanitising covers a proxy that is already dead when panda launches. This covers the rest of the process lifetime, which is the case that actually bites: panda is started from a shell that owns a working local proxy (a desktop tunnel, or a sandbox sidecar), the session ends or the tunnel restarts on a new port, and the exported address outlives the listener. The entry model would then fail every call with "proxyconnect … connection refused" until someone restarted the process — and no configuration change inside the running console could help, because net/http had already cached the value. Returning nil here turns that failure into a direct connection, and the cache re-probes so a restored tunnel is picked up again.
A non-loopback proxy is returned untouched: it is reached over the network, where a refused probe says nothing dependable.
func ProxyTargetMetadata ¶ added in v0.1.4
ProxyTargetMetadata reports whether rawurl names a cloud metadata service that an egress proxy would resolve outside this process. GuardedDialContext only sees the proxy address on such a connection, so the target has to be resolved and judged here, before the request carries a credential into the proxy. A name the local resolver cannot answer is allowed through: a proxy-only split-DNS deployment still has to work.
func Redact ¶
Redact scrubs credential assignments, bearer tokens, recognizable provider keys and PEM private keys from diagnostic text.
func RedactJSON ¶ added in v0.1.7
RedactJSON preserves number precision and only re-encodes records that contain secrets.
func SetBasePolicy ¶ added in v0.0.10
func SetBasePolicy(p Policy)
SetBasePolicy installs the deployer-level sandbox settings every ApplyPolicy call starts from. Called once during daemon wiring.
func SystemSecretPaths ¶ added in v0.0.10
func SystemSecretPaths() []string
SystemSecretPaths lists the home-relative locations where this platform family keeps reusable credentials. ModeStrict denies subprocesses read and write access to them; the list errs toward the well-known names rather than completeness.
Types ¶
type Audit ¶
type Audit struct {
// contains filtered or unexported fields
}
Audit appends high-risk operation records to the audit_log table. Callers pass a DB whose schema includes audit_log (see storage.Migrate).
Entries can carry the node's Ed25519 attestation (P2-9): the signature covers the entry's chain hash, so a row cannot be rewritten and re-hashed by a DB writer who lacks the private key. Signing is installed with SetSigner; a key-less Audit records the historical unsigned shape.
func (*Audit) Record ¶
Record writes one entry, linking it to the global audit hash chain (A3). The read of the chain head and the insert must live in one transaction: two concurrent Records that each read the same head would both link to it, forking the chain and failing VerifyChain on one of them (M2). The store opens with _txlock=immediate, so BeginTx takes the write lock at once and serializes the tx bodies — the second writer's head read always sees the first writer's row.
func (*Audit) SetSigner ¶ added in v0.0.10
func (a *Audit) SetSigner(pub ed25519.PublicKey, priv ed25519.PrivateKey)
SetSigner installs the node identity used to sign recorded entries and to bind verification to this node's key. priv may be nil for callers that only verify (`panda audit verify`, the panel's integrity endpoint): with no private key nothing is signed, but signatures that do exist must be by pub.
func (*Audit) VerifyChain ¶
VerifyChain verifies the global audit hash chain. It returns nil if intact, or an error describing the first break.
The signature rules mirror TaskStore.VerifyTaskEventChain (P2-9 hardening): when the Audit knows the node's key, a signature must be BY THAT KEY (verifying against whatever key a row names would let a DB writer re-sign the chain under a keypair of their own), and once a signed row exists no later row may be unsigned (tail stripping). Pre-signing rows form a legacy unsigned prefix — there is nothing to check them against.
type AuditRow ¶
type AuditRow struct {
ID int64
TS int64
Who string
What string
Target string
Result string
Detail string
PrevHash string
// Sig/SigPub are the P2-9 attestation: the Ed25519 signature over this
// row's chain hash and the public key that produced it (both hex). Empty
// on rows recorded before entry signing or by an Audit without a key.
Sig string
SigPub string
}
AuditRow is one audit_log row.
type Entry ¶
type Entry struct {
Who string // actor node id
What string // operation, e.g. "native:tier2", "circuit:open", "agent:spawn"
Target string // task id / agent / command
Result string // "authorized" / "denied" / "ok" / "failed" / "open"
Detail string // extra context, never secrets
}
Entry is one high-risk operation record (plan P3-32). High-risk means any Tier-2 execution or denial, any circuit trip, and any adapter spawn — the operations whose "who / what / result" must be reconstructable later.
type Mode ¶ added in v0.0.10
type Mode string
Mode selects how hard ApplyPolicy confines a subprocess. ModeOff keeps the historical behavior — environment filtering and cwd only. ModeStandard adds the platform's deny-default file-write confinement plus explicit deny lists. ModeStrict additionally denies reads of credential-shaped paths so a subprocess cannot exfiltrate secrets that standard mode still lets it read.
type NetworkGuard ¶
type NetworkGuard struct {
// contains filtered or unexported fields
}
NetworkGuard validates the endpoints an agent subprocess is pointed at (plan P3-30). The deterministic MVP enforces two things at spawn time: the model endpoint is HTTPS (so the API key never travels cleartext) and it is in an explicit allowlist. Hard Linux-level egress control (netns/iptables restricting what the subprocess can reach) is a deploy concern layered on top; this guards the one host PANDA itself hands to the adapter.
func NewNetworkGuard ¶
func NewNetworkGuard(hosts ...string) *NetworkGuard
NewNetworkGuard builds a guard allowing the given hostnames (bare or host:port). Matching is case-insensitive and treats a host:port entry as allowing the bare host too — the entry is stored verbatim (so an exact host:port match still works) plus its hostname leg (so a URL that names the host without a port, or on a different one, still matches the bare-host check).
func (*NetworkGuard) CheckURL ¶
func (g *NetworkGuard) CheckURL(rawurl string) error
CheckURL validates a URL against the guard: it must be https and its host must be in the allowlist. Loopback endpoints (localhost, 127.0.0.0/8, ::1) are exempt from the https requirement (plaintext is fine for a local dev model), but are still subject to the host allowlist — so a guard pinned to a remote endpoint (D7) rejects loopback too.
type Policy ¶ added in v0.0.10
type Policy struct {
Mode Mode
// AllowNetwork gates outbound networking as a whole; endpoint-level
// filtering stays with NetworkGuard.
AllowNetwork bool
// WorkDir is the subprocess's cwd and is always writable. Empty means
// "wherever the daemon would run it" — resolved to the daemon cwd.
WorkDir string
// WritablePaths get write access beyond WorkDir. Absolute paths are used
// as-is; relative paths and "~/…" resolve against the user's home —
// that convention lets config files and credential manifests name
// "~/.claude" without knowing the account name. Entries are directories:
// a missing one is created as a directory before bind-mounting.
WritablePaths []string
// WritableFiles are the file-shaped siblings of WritablePaths — the bare
// credential files that sit at $HOME root (".claude.json") rather than in
// a directory of their own. Splitting them out is what lets a missing
// entry be created with the right inode type: a dotfile basename is not
// a file signature (".claude" is a directory), and a guessed-wrong create
// both mounts the wrong thing and leaves a junk file on the host that
// blocks the real directory forever.
WritableFiles []string
// DenyReadPaths lose both read and write access under ModeStrict (and
// keep write-denied only under ModeStandard — reading is the baseline
// there). Home-relative spelling follows WritablePaths.
DenyReadPaths []string
// DenyWritePaths lose write access under every mode. The node's own
// state (database, memory, config) lands here so a subprocess cannot
// corrupt bookkeeping the drift detector relies on.
DenyWritePaths []string
}
Policy is the resolved confinement for one subprocess launch. The base policy (SetBasePolicy) carries the deployer's choices; per-callsite code derives the final policy from it (adapter credential dirs, extra deny lists).
func BasePolicy ¶ added in v0.0.10
func BasePolicy() Policy
BasePolicy returns a copy of the configured base policy.
func DefaultPolicy ¶ added in v0.0.10
DefaultPolicy derives the launch policy for a subprocess whose working directory is workDir — the shape every caller shares before adding its own writable/deny entries.
type ProxyDrop ¶ added in v0.1.7
type ProxyDrop struct {
// Key is the environment variable that was unset.
Key string
// Addr is the loopback host:port the value pointed at.
Addr string
// Err is the failed dial, kept for the log line and for tests.
Err error
}
ProxyDrop records one proxy variable that named a dead local port and was removed from the process environment.
func SanitizeLocalProxyEnv ¶ added in v0.1.7
func SanitizeLocalProxyEnv() []ProxyDrop
SanitizeLocalProxyEnv removes proxy variables that point at a loopback address nothing is listening on, and reports what it removed.
The failure this prevents: a long-lived process started from a shell that exports a loopback proxy — a desktop VPN client, a container helper, a sandbox sidecar — keeps that value for its entire lifetime. When the client restarts on a new port (or the sandbox session ends), every outbound request dies in the proxy handshake with "connection refused" against an address that no longer exists, and no amount of configuration editing inside the running process helps: net/http caches the proxy for the process lifetime.
Only loopback proxies are probed. A remote proxy host is reached over the network, so a failed TCP connect says nothing dependable about it (a corporate proxy can sit behind a firewall that refuses raw probes while still serving CONNECT), and dropping a working proxy would break egress. A loopback listener, by contrast, either accepts the connection or the client is not running — there is no ambiguous middle state.
The caller runs this once, before any HTTP client is built, so the decision also reaches children spawned afterwards: panda's daemon mode re-execs itself, and exec.Command inherits the sanitized environment.
type Sandbox ¶
type Sandbox struct {
// contains filtered or unexported fields
}
Sandbox sets an adapter subprocess's working directory and replaces its inherited environment with a fixed allow-list (plan P3-29).
Apply uses the process-wide policy; ApplyPolicy accepts an explicit one. ModeOff only filters the environment and sets cwd — the child can still read and write any path its uid can, including $HOME (deliberately forwarded because agent CLIs keep credentials and config there). Standard and strict add a deny-default sandbox-exec profile on macOS or a bubblewrap bind-mount jail on Linux, or AppContainer/token restrictions on Windows, driven by Policy (see policy.go). The child starts in the task directory instead of wherever the daemon happens to run, and it does not inherit the parent's arbitrary environment, so an unrelated secret in the daemon's env does not silently reach a third-party agent CLI.
func (*Sandbox) Apply ¶
Apply configures cmd with the working directory, filtered environment and process-wide OS confinement policy.
func (*Sandbox) ApplyPolicy ¶ added in v0.0.10
ApplyPolicy is Apply plus the OS confinement layer: it installs the environment and cwd first, then wraps the command under the platform's sandbox mechanism when the policy's mode asks for one. With ModeOff it degenerates to the plain Apply behavior.
Both standard and strict return an error on a host with no backend: the requested OS boundary must exist before the child may start. ModeOff is the explicit choice to run with environment filtering and cwd only.
func (*Sandbox) Env ¶
Env returns the subprocess environment: a fixed allow-list of the variables an adapter needs to function at all, plus any explicitly injected entries (e.g. model credentials). Everything else in the parent's environment is dropped. HOME is forwarded on purpose — agent CLIs read their own config and auth from it — so this is an environment filter, not a home-directory boundary.
Unset variables are omitted rather than forwarded empty: exporting HOME="" to a child is not the same as leaving it unset, and several CLIs treat the empty value as a configured-but-broken home and fail instead of falling back.