Compare commits

..
Author SHA1 Message Date
BaaRai 0c756a033e fix(enrich): let a stored exemption on any port of a name approve its lookup
LookupAllowed checks the name with port 0, and nameApproved looks the
stored exemption up by exact host and port. The exemption list refuses
port 0 (SetExemptions takes 1 to 65535), so no stored exemption could
ever match: the branch that let a stored exemption on the name approve
the lookup was dead, while the comment, the commit that added it and the
CHANGELOG said it worked.

A stored exemption on the name, on any of its ports, now approves the
lookup, as an active pin on any port of the name already does. An
operator exemption on host:port already lets the gate resolve and dial
the name for a call to that port in any task, so refusing the bare DNS
lookup protected nothing. The exemptions are also indexed by host, and
only the exact normalised name matches: an exemption on example.com:443
approves neither sub.example.com nor example.com.evil. Block rules are
still checked first and win, a derived exemption still approves no
lookup, and the exemption is read when the lookup runs, so one removed
after the lookup was queued stops it. The gate's rule for a connection
is unchanged: it still needs the exemption on its exact host and port.

Refs #1025
2026-12-06 22:49:30 +01:00
BaaRai bebb620b3a fix(enrich): resolve an inserted domain only when its scope approves it
insert_assets queued a DNS lookup for every domain asset it wrote, and the
enrichment engine ran it from the panel with dnsx without any context: the
target gate and the task egress scope never saw it. The labels of any name
no asset block rule matched reached the name server of its domain, and
revoking a pin or a grant did not stop a lookup already queued.

ResolveDomain now takes the context of the call, as ProbeSite does, and the
worker decides when the job runs, not when it is queued. The decision is the
one the target gate takes before it resolves a name, now shared by both
(nameApproved): under a gated scope the name must be covered by an active pin
of the scope on any port of it, a stored exemption on it or an
operator-approved egress grant, and no asset block rule may match it. A job
without a context or without a target scope resolves nothing, as a probe
without one dials nothing, and a gated scope without its gate is refused.
While ARTEX_SANDBOX is required, a name outside the task's sandbox egress
scope is refused too, checked on the name before any lookup, as the sandbox
client of the probe does. With the gate off the lookup runs as before. A
refused lookup opens no approval request.

Refs #1025
2026-12-06 22:23:06 +01:00
14 changed files with 637 additions and 23 deletions
+1
View File
@@ -6,6 +6,7 @@ All notable changes to this project are documented in this file. The format is b
### Security
- **Asset enrichment no longer resolves a domain that nothing approved.** Every domain asset `insert_assets` wrote was queued for a DNS lookup that the enrichment engine ran from the panel with its own resolver, outside the target gate and the task egress scope: the labels of any name no asset block rule matched reached the name server of its domain (`exfil.never-approved.example`), and revoking a pin or a scope did not stop a lookup already queued. The lookup now carries the target scope of the call that wrote the asset and is decided when it runs, not when it is queued, with the rule the target gate applies before it resolves a name: under a gated scope a name is looked up only when an active pin of the scope on any port of it, a stored exemption on any port of it or an operator-approved egress grant covers it and no asset block rule matches it; a lookup without a target scope resolves nothing, as a probe without one dials nothing; and while `ARTEX_SANDBOX=required` a name outside the task's sandbox egress scope is not looked up either. A refused lookup opens no approval request and is only logged. With the gate off the lookup runs as before, and an approved name writes the same records with the same cooldown.
- **Six built-in deny rules catch more spellings of the same destructive action.** The curl / wget DELETE rule now takes `curl --request=DELETE` as well as `--request DELETE`, and `-X DELETE` at the end of a short option cluster (`curl -sX DELETE`, `-fsSLX DELETE`, `-sXDELETE`), while a lowercase `-x`, the proxy option that the rule used to catch in `curl -x delete-proxy:8080`, no longer matches; "Kill all processes" takes the signal as `-KILL`, `-SIGKILL`, `-s KILL`, `-n 9` or `--signal KILL` (or 9 or SIGKILL in each form) before `-1`, with an optional `--`; "Flush firewall rules" takes options such as `-t nat`, `--table=nat` or `-w 5` before `-F` / `--flush`; the disk overwrite redirect in "Destructive system commands" covers `/dev/nvme`, `/dev/vd`, `/dev/xvd`, `/dev/hd` and `/dev/mmcblk` next to `/dev/sd`, and now matches `cat /dev/zero > /dev/sda` with a space before the device, which it never did because the redirect sat behind a leading `\b`, and the same rule now matches the fork bomb `:(){ :|:& };:`, which sat behind it too; and the Python DELETE rule takes `request("DELETE", ...)` on any receiver (`requests`, `httpx`, a session or client, `http.client`); and the JS/generic method rule takes a double-quoted verb, which reaches it JSON-escaped (`method="DELETE"`, `requests.request(method="DELETE")`, `"method": "DELETE"`). `kill -9 -10`, `pkill`, `iptables -L | grep -F x`, `2>/dev/null` and redirects to devices that are not disks stay allowed. The seed literals are widened for fresh installs, and a v6 seed (`intercept_default_rules_v6`) rewrites the six rows of an existing database in place when they still carry the old seed text, so a rule the operator edited is left alone, a disabled rule stays disabled and a deleted rule is not recreated. Still open: URL-encoded verbs, JSON-escaped or otherwise encoded command text (`\u003e`, base64), non-shell interpreters and scripts written then run, `tee /dev/sdX` and other writers that are not a redirect, `kill -TERM -1`, `killall -KILL`, and `ip6tables`, `iptables-nft` and `iptables-legacy` flushes.
- **The egress proxy judges a NAT64 address by the IPv4 address it embeds.** A NAT64 gateway connects `64:ff9b::a.b.c.d` to `a.b.c.d`, and the Docker backend gives the proxy no never-list, so a task scope covering `64:ff9b::/96` (for example `::/0`) let the proxy dial the NAT64 form of loopback, the private ranges, CGNAT and the metadata addresses; this needs IPv6 on the egress network and a NAT64 gateway that translates such addresses. No scope now opens an address in `64:ff9b::/96` whose IPv4 address is in the never-list or default-denied (`0.0.0.0/8`, private, loopback, CGNAT, link-local, metadata, multicast, reserved), not even a scope naming the NAT64 address itself or an IPv4 scope opening the IPv4 range, as the Kubernetes backend's never-list already does. Public addresses in the prefix stay reachable when the scope allows them. The panel's URL checks use the same policy. The local-use prefix `64:ff9b:1::/48` and operator-chosen NAT64 prefixes are not covered: the operator's setup decides where the IPv4 bits sit.
- **On the Docker backend no task scope opens loopback, link-local, the listed metadata addresses, the Docker networks or the host's bridge addresses.** The runner gave the Docker egress proxy no never-list, so a scope covering them (`0.0.0.0/0`, a private range that holds `egress-net` such as `172.16.0.0/12`, or `::/0` with IPv6 on `egress-net`) let the proxy dial `169.254.169.254`, `168.63.129.16`, `100.100.100.200`, its own loopback, the `egress-net` addresses of the other tasks' proxies and the host's bridge gateways. The runner now passes `ARTEX_NEVER_CIDRS`: the list the Kubernetes backend uses, built by the same code, plus the subnets of `egress-net` and of the task network and the gateway of every bridge network, read when the proxy is created. If the networks cannot be read, no proxy runs. At start-up the runner removes the proxies it finds, and each task gets a new one at its next command. Update the `artex-egress-proxy` image together with the runner (`update.sh` does): an older image ignores `ARTEX_NEVER_CIDRS`. The host's other addresses stay reachable when a scope covers them.
+86
View File
@@ -0,0 +1,86 @@
package agent
import (
"context"
"net"
"strings"
"sync"
"testing"
"time"
"github.com/Autumn-27/artex/enrich"
"github.com/Autumn-27/artex/intercept"
"github.com/miekg/dns"
)
// lookupCounter is a local DNS server that counts the queries per name and
// answers none, so that the engine writes nothing (no asset store here).
type lookupCounter struct {
mu sync.Mutex
seen map[string]int
}
func (c *lookupCounter) queries(name string) int {
c.mu.Lock()
defer c.mu.Unlock()
return c.seen[name]
}
func (c *lookupCounter) waitFor(t *testing.T, name string) {
t.Helper()
deadline := time.Now().Add(15 * time.Second)
for c.queries(name) == 0 {
if time.Now().After(deadline) {
t.Fatalf("the resolver never received a query for %s", name)
}
time.Sleep(5 * time.Millisecond)
}
}
// realEnrichEngine is the enrichment engine of a worker run, with one worker,
// resolving through a local counting DNS server.
func realEnrichEngine(t *testing.T) (*enrich.Engine, *lookupCounter) {
t.Helper()
pc, err := net.ListenPacket("udp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
c := &lookupCounter{seen: map[string]int{}}
srv := &dns.Server{PacketConn: pc, Handler: dns.HandlerFunc(func(w dns.ResponseWriter, r *dns.Msg) {
m := new(dns.Msg)
m.SetReply(r)
if len(r.Question) > 0 {
c.mu.Lock()
c.seen[strings.TrimSuffix(strings.ToLower(r.Question[0].Name), ".")]++
c.mu.Unlock()
}
_ = w.WriteMsg(m)
})}
go func() { _ = srv.ActivateAndServe() }()
t.Cleanup(func() { _ = srv.Shutdown() })
t.Setenv("ARTEX_DNS_RESOLVERS", pc.LocalAddr().String())
e := enrich.New(nil, nil, 1)
t.Cleanup(e.Close)
return e, c
}
// The insert_assets probe of the issue, through triggerEnrichment and the real
// engine: a subdomain written by a call whose context carries no target scope
// is not looked up, while one written under a scope whose gate is off still is.
// The second lookup runs after the first on the single worker, so once it
// reached the resolver the first one was decided.
func TestInsertAssetsUnscopedDomainQueriesNoResolver(t *testing.T) {
e, dnsSrv := realEnrichEngine(t)
ts := NewToolSet(nil, "worker")
ts.SetEnrich(e)
ts.triggerEnrichment(context.Background(), "subdomain", 7, assetInputItem{Type: "subdomain", Domain: "exfil.never-approved.example"})
gateOff := intercept.WithTargetScope(context.Background(), intercept.TargetScope{TaskID: "7"})
ts.triggerEnrichment(gateOff, "subdomain", 8, assetInputItem{Type: "subdomain", Domain: "gate-off.example"})
dnsSrv.waitFor(t, "gate-off.example")
if n := dnsSrv.queries("exfil.never-approved.example"); n != 0 {
t.Fatalf("%d resolver queries for exfil.never-approved.example, inserted without a target scope; want none", n)
}
}
+11 -4
View File
@@ -9,13 +9,15 @@ import (
// Before insert_assets called the engine, the ToolSet field was assigned but
// never read, so no asset was ever resolved or probed (see triggerEnrichment).
type fakeEnrich struct {
resolved []string
probed []string
probeCtx []context.Context
resolved []string
resolveCtx []context.Context
probed []string
probeCtx []context.Context
}
func (f *fakeEnrich) ResolveDomain(id int64, host string) {
func (f *fakeEnrich) ResolveDomain(ctx context.Context, id int64, host string) {
f.resolved = append(f.resolved, host)
f.resolveCtx = append(f.resolveCtx, ctx)
}
func (f *fakeEnrich) ProbeSite(ctx context.Context, id int64, url string) {
@@ -58,6 +60,11 @@ func TestInsertAssetsTriggersEnrichment(t *testing.T) {
if len(enr.resolved) != 1 || enr.resolved[0] != tc.wantDomain {
t.Fatalf("resolved %v, want [%s]", enr.resolved, tc.wantDomain)
}
// The lookup keeps the caller's context too: the engine decides
// on the target scope it carries whether the name may be resolved.
if len(enr.resolveCtx) != 1 || enr.resolveCtx[0] != ctx {
t.Fatalf("lookup did not receive the caller context")
}
} else if len(enr.resolved) != 0 {
t.Fatalf("resolved %v, want no DNS job", enr.resolved)
}
+1 -1
View File
@@ -239,7 +239,7 @@ func (t *ToolSet) SetNotifyFinding(fn func(int64, string)) { t.notifyFinding = f
// EnrichTrigger is the enrichment engine seen from the tool layer (see package
// enrich). Kept as an interface here to avoid coupling agent → enrich.
type EnrichTrigger interface {
ResolveDomain(id int64, host string)
ResolveDomain(ctx context.Context, id int64, host string)
ProbeSite(ctx context.Context, id int64, url string)
}
+5 -3
View File
@@ -139,8 +139,10 @@ func insertAssetsRuleLoadFailure(err error) (actool.Result, bool) {
// service has nothing to resolve or probe on its own.
//
// The trigger is best-effort by design: the engine dedups by cooldown, drops the
// job when its queue is full, resolves DNS ungated and gates the HTTP probe on
// the target scope carried by ctx (a probe without a scope dials nothing). A nil
// job when its queue is full, and gates both jobs on the target scope carried by
// ctx: a lookup without a scope resolves nothing, and under a gated scope only a
// name the scope approves when the job runs is resolved; a probe without a scope
// dials nothing. A nil
// engine — no manager, or a tool set built outside a worker run — is a no-op.
func (t *ToolSet) triggerEnrichment(ctx context.Context, typ string, id int64, item assetInputItem) {
if t.enrich == nil || id <= 0 {
@@ -149,7 +151,7 @@ func (t *ToolSet) triggerEnrichment(ctx context.Context, typ string, id int64, i
switch typ {
case "root_domain", "subdomain":
if host := strings.TrimSpace(item.Domain); host != "" {
t.enrich.ResolveDomain(id, host)
t.enrich.ResolveDomain(ctx, id, host)
}
case "service":
// Only the HTTP branch (url set) has something to probe; a non-HTTP
+3 -2
View File
@@ -256,12 +256,13 @@ func TestCloseIdempotent(t *testing.T) {
func TestResolveDomainEnqueues(t *testing.T) {
e := &Engine{jobs: make(chan job, 8), closed: make(chan struct{})}
e.ResolveDomain(1, "example.com")
ctx := context.Background()
e.ResolveDomain(ctx, 1, "example.com")
if len(e.jobs) != 1 {
t.Error("ResolveDomain should enqueue one job")
}
j := <-e.jobs
if j.kind != jobDNS || j.id != 1 || j.arg != "example.com" {
if j.kind != jobDNS || j.id != 1 || j.arg != "example.com" || j.ctx != ctx {
t.Errorf("unexpected job: %+v", j)
}
}
+34 -6
View File
@@ -2,7 +2,8 @@
// in the asset model and auto-association design doc §5: an async worker pool that
// resolves domains (dnsx) and probes web assets (HTTP, through the recording proxy)
// and writes the results back into the asset graph — creating IP/port nodes,
// resolves/exposes edges, and filling attrs.dns / attrs.http. DNS is ungated; HTTP
// resolves/exposes edges, and filling attrs.dns / attrs.http. A domain is resolved
// only for a name the target scope of the asking call approves (lookupAllowed); HTTP
// probing is gated by RoE (§5.2).
package enrich
@@ -59,7 +60,7 @@ type job struct {
kind jobKind
id int64 // asset id (domain for DNS, site for HTTP)
arg string // host (DNS) or url (HTTP)
ctx context.Context // HTTP: carries the target scope the probe dials under
ctx context.Context // carries the target scope the lookup or the probe runs under
}
// Engine owns the resolver, the proxy-routed HTTP client, and the worker pool.
@@ -305,9 +306,13 @@ func sandboxClient(policy *sandbox.EgressPolicy) *http.Client {
}
}
// ResolveDomain enqueues a DNS resolution for a domain asset (ungated). host is the
// FQDN. No-op for an empty engine.
func (e *Engine) ResolveDomain(id int64, host string) { e.enqueue(job{jobDNS, id, host, nil}) }
// ResolveDomain enqueues a DNS resolution for a domain asset. host is the FQDN.
// ctx carries the target scope of the call that asks for the lookup: the lookup
// runs only if that scope approves host when the job runs (see lookupAllowed).
// No-op for an empty engine.
func (e *Engine) ResolveDomain(ctx context.Context, id int64, host string) {
e.enqueue(job{jobDNS, id, host, ctx})
}
// ProbeSite enqueues an HTTP probe for a web-asset (site). rawURL is the site URL.
// ctx carries the target scope of the call that asks for the probe: the probe
@@ -348,7 +353,11 @@ func (e *Engine) worker() {
}
switch j.kind {
case jobDNS:
e.doDNS(j.id, j.arg)
if err := e.lookupAllowed(j.ctx, j.arg); err != nil {
slog.Info("[enrich] DNS lookup refused", "host", j.arg, "err", err)
} else {
e.doDNS(j.id, j.arg)
}
case jobHTTP:
e.doHTTP(j.ctx, j.id, j.arg)
}
@@ -372,6 +381,25 @@ func itoa(n int64) string { return strconv.FormatInt(n, 10) }
// ---- DNS ----
// lookupAllowed decides, when a DNS job is about to run, whether the panel may
// resolve host for the call that queued it. The lookup leaves the panel through
// its resolver, so it takes the decisions an HTTP probe of the name takes: the
// target gate on the scope ctx carries (intercept.LookupAllowed: no scope
// refuses, a gated scope needs the name approved) and, while ARTEX_SANDBOX is
// required, the task's sandbox egress scope, checked on the name before
// anything is resolved.
func (e *Engine) lookupAllowed(ctx context.Context, host string) error {
if err := intercept.LookupAllowed(ctx, host); err != nil {
return err
}
if e.sandboxPolicy != nil {
if policy := e.sandboxPolicy(ctx); policy != nil && !policy.AllowsDomain(host) {
return fmt.Errorf("sandbox egress denied: domain %q is not in the task scope", host)
}
}
return nil
}
func (e *Engine) doDNS(id int64, host string) {
if e.resolv == nil {
return
+28
View File
@@ -180,3 +180,31 @@ func TestDoHTTPUsesSandboxClient(t *testing.T) {
t.Fatalf("doHTTP used the normal client %d time(s) under a sandbox policy", n)
}
}
// A DNS job takes the decisions a probe of the name takes. While the sandbox is
// required, a name outside the task's sandbox egress scope is not looked up,
// even when the target gate does not decide (gate off); without a target scope
// nothing is looked up at all.
func TestLookupAllowedFollowsSandboxScope(t *testing.T) {
policy, err := sandbox.NewEgressPolicy("7", []string{"lab.test"}, nil, nil)
if err != nil {
t.Fatal(err)
}
gateOff := intercept.WithTargetScope(context.Background(), intercept.TargetScope{TaskID: "7"})
e := &Engine{}
if err := e.lookupAllowed(gateOff, "exfil.example"); err != nil {
t.Fatalf("gate off, sandbox not required: %v, want the lookup to run", err)
}
e.SetSandboxPolicy(func(context.Context) *sandbox.EgressPolicy { return policy })
if err := e.lookupAllowed(gateOff, "api.lab.test"); err != nil {
t.Fatalf("name in the sandbox scope: %v, want the lookup to run", err)
}
if err := e.lookupAllowed(gateOff, "exfil.example"); err == nil {
t.Fatal("name outside the sandbox scope: the lookup would run")
}
for name, ctx := range map[string]context.Context{"nil context": nil, "no target scope": context.Background()} {
if err := e.lookupAllowed(ctx, "api.lab.test"); err == nil {
t.Fatalf("%s: the lookup would run", name)
}
}
}
+313
View File
@@ -0,0 +1,313 @@
package intercept_test
import (
"context"
"errors"
"net"
"strconv"
"strings"
"sync"
"testing"
"time"
"github.com/Autumn-27/artex/db"
"github.com/Autumn-27/artex/enrich"
"github.com/Autumn-27/artex/intercept"
"github.com/miekg/dns"
)
// dnsServer is the resolver of the enrich engine in these tests: a local DNS
// server that counts the queries per name and answers none, so that no lookup
// writes to the asset store (there is none here). A name in hold waits until
// its channel is closed.
type dnsServer struct {
mu sync.Mutex
seen map[string]int
hold map[string]chan struct{}
}
// startDNSServer starts the server and points the engines built after it at
// it, through ARTEX_DNS_RESOLVERS.
func startDNSServer(t *testing.T) *dnsServer {
t.Helper()
pc, err := net.ListenPacket("udp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
s := &dnsServer{seen: map[string]int{}, hold: map[string]chan struct{}{}}
srv := &dns.Server{PacketConn: pc, Handler: dns.HandlerFunc(s.serve)}
go func() { _ = srv.ActivateAndServe() }()
t.Cleanup(func() { _ = srv.Shutdown() })
t.Setenv("ARTEX_DNS_RESOLVERS", pc.LocalAddr().String())
return s
}
func (s *dnsServer) serve(w dns.ResponseWriter, r *dns.Msg) {
m := new(dns.Msg)
m.SetReply(r)
if len(r.Question) > 0 {
name := strings.TrimSuffix(strings.ToLower(r.Question[0].Name), ".")
s.mu.Lock()
s.seen[name]++
hold := s.hold[name]
s.mu.Unlock()
if hold != nil {
<-hold
}
}
_ = w.WriteMsg(m)
}
func (s *dnsServer) queries(name string) int {
s.mu.Lock()
defer s.mu.Unlock()
return s.seen[name]
}
// holdName makes the queries for name wait until the returned release is
// called. release is idempotent and also runs at the end of the test.
func (s *dnsServer) holdName(t *testing.T, name string) (release func()) {
ch := make(chan struct{})
s.mu.Lock()
s.hold[name] = ch
s.mu.Unlock()
var once sync.Once
release = func() { once.Do(func() { close(ch) }) }
t.Cleanup(release)
return release
}
func (s *dnsServer) waitFor(t *testing.T, name string) {
t.Helper()
deadline := time.Now().Add(15 * time.Second)
for s.queries(name) == 0 {
if time.Now().After(deadline) {
t.Fatalf("the resolver never received a query for %s", name)
}
time.Sleep(5 * time.Millisecond)
}
}
// gateOff is the context of a call whose scope has the target gate off: the
// gate does not decide, and the lookup runs as before the gate.
func gateOff() context.Context {
return intercept.WithTargetScope(context.Background(), intercept.TargetScope{TaskID: "7", Enabled: func() bool { return false }})
}
// resolve queues the DNS job insert_assets queues for a domain asset written by
// a call running on ctx.
func resolve(e *enrich.Engine, ctx context.Context, id int64, host string) {
e.ResolveDomain(ctx, id, host)
}
// drain waits until the single worker of e has run every job queued before:
// it queues the lookup of a name the gate does not decide and waits for its
// query.
func drain(t *testing.T, s *dnsServer, e *enrich.Engine, id int64) {
t.Helper()
name := "drain-" + strconv.FormatInt(id, 10) + ".example"
resolve(e, gateOff(), id, name)
s.waitFor(t, name)
}
func newEngine(t *testing.T) *enrich.Engine {
t.Helper()
e := enrich.New(nil, nil, 1)
t.Cleanup(e.Close)
return e
}
// insert_assets queues a DNS lookup for every domain asset it writes. Under a
// gated scope, a name nothing approved for the task (no pin, no stored
// exemption, no operator-approved egress grant) must not be looked up: the
// lookup leaves the panel through its resolver, and the labels of the name are
// a channel to the name server of its domain.
func TestEnrichDNSUnapprovedNameQueriesNoResolver(t *testing.T) {
s := startDNSServer(t)
g := intercept.NewDialGate(t)
g.Pin("app.example.com", 443, "203.0.113.7")
g.GrantDomain("lab.test")
e := newEngine(t)
resolve(e, g.Ctx(), 1, "exfil.never-approved.example")
resolve(e, g.Ctx(), 2, "exfil.lab.test.never-approved.example")
drain(t, s, e, 3)
for _, name := range []string{"exfil.never-approved.example", "exfil.lab.test.never-approved.example"} {
if n := s.queries(name); n != 0 {
t.Fatalf("%d resolver queries for %s, which nothing approved for the task; want none", n, name)
}
}
}
// A lookup without a target scope resolves nothing, as a probe without one
// dials nothing: a nil context, and a context the scope never reached.
func TestEnrichDNSWithoutTargetScopeQueriesNoResolver(t *testing.T) {
s := startDNSServer(t)
e := newEngine(t)
resolve(e, nil, 1, "nil-ctx.never-approved.example") //nolint:staticcheck // the nil context is the case
resolve(e, context.Background(), 2, "no-scope.never-approved.example")
drain(t, s, e, 3)
for _, name := range []string{"nil-ctx.never-approved.example", "no-scope.never-approved.example"} {
if n := s.queries(name); n != 0 {
t.Fatalf("%d resolver queries for %s without a target scope; want none", n, name)
}
}
}
// A name the scope approves is still resolved: a pin on any port of the name,
// a name under an operator-approved egress grant, and any name of a scope
// whose gate is off.
func TestEnrichDNSApprovedNameResolves(t *testing.T) {
s := startDNSServer(t)
g := intercept.NewDialGate(t)
g.Pin("app.example.com", 8443, "203.0.113.7")
g.GrantDomain("lab.test")
e := newEngine(t)
resolve(e, g.Ctx(), 1, "app.example.com")
resolve(e, g.Ctx(), 2, "api.lab.test")
resolve(e, gateOff(), 3, "gate-off.example")
for _, name := range []string{"app.example.com", "api.lab.test", "gate-off.example"} {
s.waitFor(t, name)
}
}
// The queue is asynchronous: the scope is checked when the lookup runs, not
// when it is queued. A lookup queued while its pin was active and run after
// the pin was revoked resolves nothing.
func TestEnrichDNSRevokedBeforeRunQueriesNoResolver(t *testing.T) {
s := startDNSServer(t)
g := intercept.NewDialGate(t)
g.Pin("busy.example.com", 443, "203.0.113.8")
g.Pin("late.example.com", 443, "203.0.113.9")
e := newEngine(t)
// The single worker is busy on a lookup the server holds, so the next
// lookup waits in the queue.
release := s.holdName(t, "busy.example.com")
resolve(e, g.Ctx(), 1, "busy.example.com")
s.waitFor(t, "busy.example.com")
resolve(e, g.Ctx(), 2, "late.example.com")
g.Revoke("late.example.com", 443)
release()
drain(t, s, e, 3)
if n := s.queries("late.example.com"); n != 0 {
t.Fatalf("%d resolver queries for late.example.com after its pin was revoked; want none", n)
}
}
// An operator exemption on host:port lets the gate resolve and dial the name
// for a call to that port in any task, so it approves the lookup of the name,
// on any of its ports, as a pin on any port does. Stored exemptions always
// carry a real port (SetExemptions refuses port 0), and the lookup has none.
func TestEnrichDNSStoredExemptionOnAnyPortResolves(t *testing.T) {
s := startDNSServer(t)
g := intercept.NewDialGate(t)
g.StoreExemptions(db.TargetExemption{Host: "pkg.example.com", Port: 443}, db.TargetExemption{Host: "alt.example.com", Port: 8443})
e := newEngine(t)
resolve(e, g.Ctx(), 1, "pkg.example.com")
resolve(e, g.Ctx(), 2, "alt.example.com")
drain(t, s, e, 3)
for _, name := range []string{"pkg.example.com", "alt.example.com"} {
if s.queries(name) == 0 {
t.Fatalf("no resolver query for %s, which a stored exemption on one of its ports approves", name)
}
}
}
// LookupAllowed matches a stored exemption on the exact normalised name, on
// any port: not a subdomain, a parent or a longer name, and a block rule on the
// name still wins. A derived exemption does not approve a lookup.
func TestLookupAllowedStoredExemptionOnAnyPort(t *testing.T) {
cases := []struct {
name string
exempt []db.TargetExemption
derived []string
blocked []string
host string
want string // error code; empty when the lookup may run
}{
{name: "exemption on the name, port 443", exempt: []db.TargetExemption{{Host: "example.com", Port: 443}}, host: "example.com"},
{name: "exemption on the name, port 8443, name written in capitals with a dot", exempt: []db.TargetExemption{{Host: "example.com", Port: 8443}}, host: "Example.COM."},
{name: "exemption on another name", exempt: []db.TargetExemption{{Host: "other.example", Port: 443}}, host: "example.com", want: "TARGET_NOT_APPROVED"},
{name: "exemption on the parent only", exempt: []db.TargetExemption{{Host: "example.com", Port: 443}}, host: "sub.example.com", want: "TARGET_NOT_APPROVED"},
{name: "exemption on a subdomain only", exempt: []db.TargetExemption{{Host: "sub.example.com", Port: 443}}, host: "example.com", want: "TARGET_NOT_APPROVED"},
{name: "exemption on a prefix of the name", exempt: []db.TargetExemption{{Host: "example.com", Port: 443}}, host: "example.com.evil", want: "TARGET_NOT_APPROVED"},
{name: "exemption on a name it ends with inside a label", exempt: []db.TargetExemption{{Host: "example.com", Port: 443}}, host: "evilexample.com", want: "TARGET_NOT_APPROVED"},
{name: "exemption and a block rule on the name", exempt: []db.TargetExemption{{Host: "example.com", Port: 443}}, blocked: []string{"example.com"}, host: "example.com", want: intercept.TargetRuleBlocked},
{name: "derived exemption on the name", derived: []string{"https://example.com"}, host: "example.com", want: "TARGET_NOT_APPROVED"},
}
for _, c := range cases {
g := intercept.NewDialGate(t)
g.StoreExemptions(c.exempt...)
if c.derived != nil {
g.Exempt(c.derived...)
}
g.BlockDomain(c.blocked...)
err := intercept.LookupAllowed(g.Ctx(), c.host)
switch {
case c.want == "" && err != nil:
t.Errorf("%s: LookupAllowed(%q) = %v, want the lookup to run", c.name, c.host, err)
case c.want != "" && (err == nil || !strings.HasPrefix(err.Error(), c.want+":")):
t.Errorf("%s: LookupAllowed(%q) = %v, want %s", c.name, c.host, err, c.want)
}
}
}
// The same rows through the enrich engine: a stored exemption on another name,
// on the parent domain only, or on the name with a block rule on it resolves
// nothing.
func TestEnrichDNSStoredExemptionOvermatchQueriesNoResolver(t *testing.T) {
s := startDNSServer(t)
g := intercept.NewDialGate(t)
g.StoreExemptions(db.TargetExemption{Host: "other.example", Port: 443}, db.TargetExemption{Host: "pkg.example.com", Port: 443},
db.TargetExemption{Host: "blocked.example.com", Port: 443})
g.BlockDomain("blocked.example.com")
e := newEngine(t)
names := []string{"unexempt.example", "sub.pkg.example.com", "pkg.example.com.evil", "blocked.example.com"}
for n, name := range names {
resolve(e, g.Ctx(), int64(n+1), name)
}
drain(t, s, e, int64(len(names)+1))
for _, name := range names {
if n := s.queries(name); n != 0 {
t.Fatalf("%d resolver queries for %s, which no stored exemption approves; want none", n, name)
}
}
}
// The exemption list refuses port 0, so no stored exemption carries the port of
// a lookup: that is why the lookup takes an exemption on any port of the name.
func TestSetExemptionsRefusesPortZero(t *testing.T) {
ic := intercept.New(nil) // refused before anything is stored
if _, _, err := ic.SetExemptions([]db.TargetExemption{{Host: "pkg.example.com", Port: 0}}, "test"); !errors.Is(err, intercept.ErrInvalidExemption) {
t.Fatalf("SetExemptions(pkg.example.com:0) = %v, want it refused", err)
}
}
// The exemption is read when the lookup runs: one removed after the lookup was
// queued and before the worker runs it resolves nothing.
func TestEnrichDNSExemptionRemovedBeforeRunQueriesNoResolver(t *testing.T) {
s := startDNSServer(t)
g := intercept.NewDialGate(t)
g.Pin("busy.example.com", 443, "203.0.113.8")
g.StoreExemptions(db.TargetExemption{Host: "late.example.com", Port: 443})
e := newEngine(t)
release := s.holdName(t, "busy.example.com")
resolve(e, g.Ctx(), 1, "busy.example.com")
s.waitFor(t, "busy.example.com")
resolve(e, g.Ctx(), 2, "late.example.com")
g.StoreExemptions()
release()
drain(t, s, e, 3)
if n := s.queries("late.example.com"); n != 0 {
t.Fatalf("%d resolver queries for late.example.com after its exemption was removed; want none", n)
}
}
+37
View File
@@ -3,6 +3,8 @@ package intercept
import (
"context"
"testing"
"github.com/Autumn-27/artex/db"
)
// DialGate exposes the pinned-dial fixture of target_dial_test.go to the tests
@@ -31,3 +33,38 @@ func (d *DialGate) Exempt(urls ...string) {
// Calls returns every address the base dialer was asked to connect to.
func (d *DialGate) Calls() []string { return d.rec.calls() }
// GrantDomain sets the operator-approved egress grants of the fixture's task to
// the given domains. Call it before any job reads them.
func (d *DialGate) GrantDomain(domains ...string) {
var grants []db.ScopeEgress
for _, v := range domains {
grants = append(grants, db.ScopeEgress{Kind: "domain", Value: v})
}
d.g.store.mu.Lock()
d.g.store.grants = grants
d.g.store.mu.Unlock()
}
// Revoke revokes the active pin of host on port, as the revoke route does.
func (d *DialGate) Revoke(host string, port int) { d.g.store.revoke(host, port) }
// StoreExemptions replaces the stored exemption list of the fixture, as
// SetExemptions stores it: exact host, normalised, and a port from 1 to 65535.
func (d *DialGate) StoreExemptions(list ...db.TargetExemption) {
d.g.store.mu.Lock()
d.g.store.exempt = list
d.g.store.mu.Unlock()
}
// BlockDomain sets the asset block rules of the fixture to one exact_domain
// rule per name.
func (d *DialGate) BlockDomain(names ...string) {
var rules []db.AssetInterceptRule
for _, n := range names {
rules = append(rules, db.AssetInterceptRule{Enabled: true, Kind: "exact_domain", Pattern: n})
}
d.g.store.mu.Lock()
d.g.store.rules = rules
d.g.store.mu.Unlock()
}
+10 -5
View File
@@ -146,11 +146,15 @@ func (i *Interceptor) SetExemptions(list []db.TargetExemption, changedBy string)
return out, digest, nil
}
// exemptions is the exemption list as one gated call sees it.
// exemptions is the exemption list as one gated call sees it. storedName holds
// the host of every stored exemption: a stored exemption on the name on any of
// its ports approves a lookup of the name (LookupAllowed), while a connection
// needs one on its exact host and port (stored).
type exemptions struct {
derived map[string]bool // db.TargetKey(host, port)
stored map[string]bool
digest string // of the stored list
derived map[string]bool // db.TargetKey(host, port)
stored map[string]bool
storedName map[string]bool // host as stored
digest string // of the stored list
}
func (i *Interceptor) loadExemptions() (exemptions, error) {
@@ -158,12 +162,13 @@ func (i *Interceptor) loadExemptions() (exemptions, error) {
if err != nil {
return exemptions{}, err
}
ex := exemptions{derived: map[string]bool{}, stored: map[string]bool{}, digest: digest}
ex := exemptions{derived: map[string]bool{}, stored: map[string]bool{}, storedName: map[string]bool{}, digest: digest}
for _, e := range i.DerivedExemptions() {
ex.derived[db.TargetKey(e.Host, e.Port)] = true
}
for _, e := range stored {
ex.stored[db.TargetKey(e.Host, e.Port)] = true
ex.storedName[e.Host] = true
}
return ex, nil
}
+16 -2
View File
@@ -197,6 +197,20 @@ func (c *targetCheck) namePinned(host string) (bool, error) {
return slices.ContainsFunc(c.pins, func(p *db.TargetPin) bool { return p.Host == host }), nil
}
// nameApproved reports whether something already approved the name of ct, so
// that it may be resolved: a stored exemption on the target, an
// operator-approved egress grant that covers it, or an active pin of the scope
// on any port of the name. The stored exemption must be on the exact host and
// port of ct; LookupAllowed, whose target has no port, also takes one on any
// port of the name. The error is a failed read of the pins.
func (c *targetCheck) nameApproved(ct *checkedTarget, ex exemptions, grants []db.ScopeEgress) (bool, error) {
pinned, err := c.namePinned(ct.Host)
if err != nil {
return false, err
}
return pinned || ex.stored[db.TargetKey(ct.Host, ct.Port)] || scopeGrantCover(grants, ct), nil
}
func (c *targetCheck) readPins() error {
if c.pinsRead {
return nil
@@ -416,11 +430,11 @@ func (c *targetCheck) run(targets []Target) ([]TargetRequest, TargetResult) {
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)
approved, err := c.nameApproved(ct, ex, grants)
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) {
if approved {
named = append(named, n)
continue
}
+88
View File
@@ -0,0 +1,88 @@
package intercept
import (
"context"
"fmt"
)
// LookupAllowed decides whether the panel may resolve host, a name it looks up
// on its own outside a tool call (the DNS lookup of asset enrichment), for the
// target scope ctx carries. A lookup leaves the panel through its resolver,
// past the sandbox egress boundary, so it follows the gate's rule for
// resolving a name (targetCheck.run): no asset block rule matches the name,
// and a stored exemption on the name on any of its ports, an operator-approved
// egress grant of the task or an active pin of the scope on any port of it
// approves it. A lookup has no port: an exemption on host:port already lets
// the gate resolve the name for a call to that port, so it approves the
// lookup on any port, as a pin does; a connection still needs the exemption
// on its exact host and port. A derived exemption does not approve a lookup.
// A name nothing approved is refused; no approval request is opened and
// nothing is logged as a gate decision.
//
// Everything is read when it is called, so a caller that queues the lookup
// decides when the lookup runs: a pin or grant revoked in between stops it.
//
// It fails closed like PinnedDialer for a scoped client: a nil context, a
// context without a target scope and a gated scope without its gate are
// refused. With the scope's gate off the gate does not decide, as for a
// connection, and the lookup may run. A host that is not a name has nothing to
// resolve and is refused under a gated scope.
func LookupAllowed(ctx context.Context, host string) error {
if ctx == nil {
return lookupRefused(TargetGateUnavailable, host, "no target scope reached the lookup")
}
scope, ok := TargetScopeFromContext(ctx)
switch {
case !ok:
return lookupRefused(TargetGateUnavailable, host, "no target scope reached the lookup")
case scope.Enabled == nil || !scope.Enabled():
return nil
case scope.Interceptor == nil:
return lookupRefused(TargetGateUnavailable, host, "the target scope carries no gate")
}
return scope.Interceptor.lookupAllowed(ctx, scope, host)
}
func (i *Interceptor) lookupAllowed(ctx context.Context, scope TargetScope, host string) error {
kind, h, ok := normalizeHost(host, false)
if !ok || kind != TargetDomain {
return lookupRefused(TargetResolveFailed, host, "it is not a name")
}
c := &targetCheck{i: i, ctx: ctx, scope: scope}
var err error
if c.ref, err = scope.ref(); err != nil {
return lookupRefused(TargetGateUnavailable, h, err.Error())
}
ct := &checkedTarget{Target: Target{Kind: kind, Host: h}}
rules, err := i.targets.BlockRules(c.ref)
if err != nil {
return lookupRefused(TargetGateUnavailable, h, "the asset rules could not be read: "+err.Error())
}
if rule, hit := blockRule(rules, ct); hit {
return lookupRefused(TargetRuleBlocked, h, "an asset rule blocks it. "+rule.Reason())
}
ex, err := i.loadExemptions()
if err != nil {
return lookupRefused(TargetGateUnavailable, h, "the exemption list could not be read: "+err.Error())
}
grants, err := i.targets.EgressGrants(c.ref)
if err != nil {
return lookupRefused(TargetGateUnavailable, h, "the egress grants could not be read: "+err.Error())
}
approved, err := c.nameApproved(ct, ex, grants)
if err != nil {
return lookupRefused(TargetGateUnavailable, h, "the pins could not be read: "+err.Error())
}
if !approved && !ex.storedName[h] {
return lookupRefused(targetNotApproved, h, "it is not approved for "+scope.scopeName())
}
return nil
}
// targetNotApproved: a name the panel would resolve on its own is not
// approved for the scope (LookupAllowed).
const targetNotApproved = "TARGET_NOT_APPROVED"
func lookupRefused(code, host, reason string) error {
return fmt.Errorf("%s: %s is not looked up: %s", code, host, reason)
}
+4
View File
@@ -241,6 +241,10 @@ func (p *EgressPolicy) domainAllowed(host string) bool {
return false
}
// AllowsDomain reports whether host matches the scope domains, the check
// ResolveAndCheck makes on a name before it resolves it. It resolves nothing.
func (p *EgressPolicy) AllowsDomain(host string) bool { return p.domainAllowed(host) }
func (p *EgressPolicy) inNever(addr netip.Addr) bool {
addr = addr.Unmap()
for _, pfx := range p.Never {