security

package
v0.1.4 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2026 License: AGPL-3.0 Imports: 17 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.

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; 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

This section is empty.

Variables

View Source
var ErrSandboxUnavailable = errors.New("security: sandbox backend unavailable")

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), "" elsewhere or when the tool is absent — in which case a non-off mode is a no-op and callers should surface that rather than pretend isolation exists.

func CheckEndpointHost added in v0.1.1

func CheckEndpointHost(host string, allowPrivate bool) error

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

func CheckModelEndpoint(rawurl string, allowPlaintext bool) error

CheckModelEndpoint is the one call the model paths make: pin the guard to this endpoint's own host and honour the model's plaintext opt-in. 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 EndpointHost

func EndpointHost(rawurl string) string

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

func MetadataHost(host string) bool

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

func PrivateHost(host string) bool

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 ProxyTargetMetadata added in v0.1.4

func ProxyTargetMetadata(rawurl string) bool

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

func Redact(s string) string

Redact scrubs the two secret shapes that can appear in adapter output: a credential-named KEY=value / key: value pair, and a Bearer token. It is a heuristic safety net, not a parser — the real guarantee is that secrets are injected via env and never persisted, so this only defends against a misbehaving adapter echoing them back into a result or log.

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 NewAudit

func NewAudit(db *sql.DB) *Audit

NewAudit wraps a DB.

func (*Audit) Entries

func (a *Audit) Entries(ctx context.Context) ([]AuditRow, error)

Entries returns all audit rows, oldest first.

func (*Audit) Record

func (a *Audit) Record(ctx context.Context, e Entry) error

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

func (a *Audit) VerifyChain(ctx context.Context) error

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.

const (
	ModeOff      Mode = "off"
	ModeStandard Mode = "standard"
	ModeStrict   Mode = "strict"
)

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

func DefaultPolicy(workDir string) Policy

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 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 stays the historical shape: environment filtering and cwd only, no OS boundary — the child can still read and write any path its uid can, starting with $HOME (deliberately forwarded because agent CLIs keep credentials and config there). ApplyPolicy layers the real confinement on top: a deny-default sandbox-exec profile on macOS or a bubblewrap bind-mount jail on Linux, driven by Policy (see policy.go). What both share: 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 NewSandbox

func NewSandbox(dir string) *Sandbox

NewSandbox builds a sandbox rooted at dir.

func (*Sandbox) Apply

func (s *Sandbox) Apply(cmd *exec.Cmd, extra ...string) error

Apply configures cmd with the sandboxed working directory and environment.

func (*Sandbox) ApplyPolicy added in v0.0.10

func (s *Sandbox) ApplyPolicy(cmd *exec.Cmd, p Policy, extra ...string) error

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.

It returns an error for a strict policy on a host with no backend: that mode exists to deny reads of credential paths, and running the child anyway would leave the operator believing in a boundary that is not there. Standard mode keeps running (bubblewrap is a separate package on most Linux distributions) and reports the same missing backend as a failure in doctor.

func (*Sandbox) Env

func (s *Sandbox) Env(extra ...string) []string

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.

Jump to

Keyboard shortcuts

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