mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-12-06 12:24:44 +00:00
696 lines
27 KiB
Go
696 lines
27 KiB
Go
package intercept
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"net/netip"
|
|
"slices"
|
|
"sort"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/Autumn-27/artex/db"
|
|
)
|
|
|
|
// Block codes of the gate decision. Like the codes of a target request they
|
|
// are carried in the model-facing text of the blocked call. None of them opens
|
|
// an approval request.
|
|
const (
|
|
// TargetResolveFailed: a name did not resolve, so there is no address to
|
|
// compare with a pin or to show to a human.
|
|
TargetResolveFailed = "TARGET_RESOLVE_FAILED"
|
|
// TargetRuleBlocked: an asset block rule matches a target.
|
|
TargetRuleBlocked = "TARGET_RULE_BLOCKED"
|
|
// TargetTooMany: the call names more unpinned targets than one call may request.
|
|
TargetTooMany = "TARGET_TOO_MANY"
|
|
)
|
|
|
|
// maxUnpinnedTargets is how many distinct targets without a covering pin one
|
|
// call may request approval for. Each approval is one click on one host.
|
|
const maxUnpinnedTargets = 5
|
|
|
|
// literalResolver is the resolver recorded for an IP literal or a CIDR: the
|
|
// address is what was written, nothing was resolved.
|
|
const literalResolver = "literal"
|
|
|
|
// targetStore is what the gate reads and writes. The database implements it.
|
|
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)
|
|
// TaskAllowRules identifies proxy-only allows that cannot replace a pin.
|
|
// Any enabled one keeps mandatory-sandbox calls on the normal gate path.
|
|
TaskAllowRules(scope db.TargetScopeRef) ([]db.AssetInterceptRule, error)
|
|
// ScopePins returns the active pins of the scope. The gate reads them once
|
|
// per call and picks the candidates of each target with pinsFor.
|
|
ScopePins(scope db.TargetScopeRef) ([]*db.TargetPin, error)
|
|
// 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
|
|
// gate and are not part of this set. A scope without a task has no grants.
|
|
EgressGrants(scope db.TargetScopeRef) ([]db.ScopeEgress, error)
|
|
// Exemptions returns the stored exemption list and its digest.
|
|
Exemptions() ([]db.TargetExemption, string, error)
|
|
// LogDecision records an outcome no human took.
|
|
LogDecision(db.TargetDecision) error
|
|
}
|
|
|
|
type dbTargetStore struct{ d *db.DB }
|
|
|
|
func (s dbTargetStore) BlockRules(scope db.TargetScopeRef) ([]db.AssetInterceptRule, error) {
|
|
rules, err := s.d.ListAssetInterceptRules()
|
|
if err != nil || scope.TaskID == 0 {
|
|
return rules, err
|
|
}
|
|
block, _, err := s.d.Assets().TaskInterceptRulesSplit(scope.TaskID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return append(rules, block...), nil
|
|
}
|
|
|
|
func (s dbTargetStore) TaskAllowRules(scope db.TargetScopeRef) ([]db.AssetInterceptRule, error) {
|
|
_, allow, err := s.d.Assets().TaskInterceptRulesSplit(scope.TaskID)
|
|
return allow, err
|
|
}
|
|
|
|
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) {
|
|
if scope.TaskID == 0 {
|
|
return nil, nil // a conversation scope has no task egress grants
|
|
}
|
|
return s.d.TaskEgressGrants(scope.TaskID)
|
|
}
|
|
|
|
func (s dbTargetStore) Exemptions() ([]db.TargetExemption, string, error) {
|
|
list, raw, err := s.d.TargetExemptions()
|
|
if raw == "" {
|
|
raw = "[]"
|
|
}
|
|
return list, digestInput([]byte(raw)), err
|
|
}
|
|
|
|
func (s dbTargetStore) LogDecision(r db.TargetDecision) error {
|
|
_, err := s.d.LogTargetDecision(r)
|
|
return err
|
|
}
|
|
|
|
// CheckTargets decides, for one tool call of a gated scope, whether every
|
|
// network target the call declares may be reached: extraction, asset block
|
|
// rules, exemptions, resolution and the pin lookup. It creates no approval
|
|
// request and never waits.
|
|
//
|
|
// Only a name that something already approved is resolved: a stored exemption,
|
|
// an operator-approved egress grant or a pin that names it. A lookup goes out
|
|
// through the panel's resolver, past the sandbox egress boundary, so a name
|
|
// nothing approved is never looked up: it is requested by name, and resolved
|
|
// when a human approves it (Decide).
|
|
//
|
|
// A block is reported in the result (Code, Reason and the target that caused
|
|
// it) and logged as a decided row. Otherwise the returned requests are the
|
|
// targets no pin covers, each with the addresses a human has to read (none for
|
|
// a name that was not resolved); the caller passes them to RequestTargets and
|
|
// checks again after the decisions. No request and no code means the call may
|
|
// run.
|
|
//
|
|
// With the gate off the call returns at once: nothing is extracted, resolved,
|
|
// read or written.
|
|
func (i *Interceptor) CheckTargets(ctx context.Context, scope TargetScope, toolName string, input []byte) ([]TargetRequest, TargetResult) {
|
|
if scope.Enabled == nil || !scope.Enabled() {
|
|
return nil, TargetResult{}
|
|
}
|
|
if runtimeEgressOwnsCall(ctx, toolName, input) {
|
|
if owned, res := i.runtimeEgressMayOwnCall(ctx, scope); owned || res.Code != "" {
|
|
return nil, res
|
|
}
|
|
}
|
|
declared := extractDeclared(toolName, input)
|
|
if len(declared.targets) == 0 {
|
|
return nil, TargetResult{}
|
|
}
|
|
c := &targetCheck{i: i, ctx: ctx, scope: scope, tool: toolName, input: input, urls: declared.urls}
|
|
return c.run(declared.targets)
|
|
}
|
|
|
|
// targetCheck is one run of the gate decision.
|
|
type targetCheck struct {
|
|
i *Interceptor
|
|
ctx context.Context
|
|
scope TargetScope
|
|
ref db.TargetScopeRef
|
|
tool string
|
|
input []byte
|
|
urls []string // the URLs the call declares, as written, for the URL block rules
|
|
// redirectFrom is the origin (host:port) of a redirect hop; empty for a call.
|
|
redirectFrom string
|
|
// fresh makes every lookup skip the cache: the decision of a connection
|
|
// (dialTarget) compares the answer it is about to dial.
|
|
fresh bool
|
|
// direct is set for a connection the platform opens itself (dialTarget):
|
|
// no proxy chooses its address, so no cover is name-only and the
|
|
// connection goes only to the addresses the run compared.
|
|
direct 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.
|
|
const (
|
|
coverDerived = "derived" // an exemption derived from the configuration
|
|
coverStored = "stored" // a stored exemption that holds
|
|
coverPin = "pin" // a pin that holds every resolved address
|
|
coverNameOnly = "name_only" // a pin that is name-only for this call
|
|
coverScope = "scope_grant" // an operator-approved egress grant that covers the target
|
|
)
|
|
|
|
// checkedTarget is one target of the call and what the gate learned about it.
|
|
type checkedTarget struct {
|
|
Target
|
|
ips []string // resolved addresses; the literal itself for an IP or a CIDR
|
|
resolver string
|
|
resolvedAt time.Time
|
|
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 {
|
|
return targetName(TargetRequest{Host: t.Host, Port: t.Port})
|
|
}
|
|
|
|
func (t *checkedTarget) audit(outcome string) db.InterceptTarget {
|
|
return db.InterceptTarget{Host: t.Host, Port: t.Port, Kind: t.Kind, ResolvedIPs: t.ips,
|
|
Resolver: t.resolver, ResolvedAt: t.resolvedAt, Outcome: outcome, ExemptVoid: t.exemptVoid}
|
|
}
|
|
|
|
func (c *targetCheck) run(targets []Target) ([]TargetRequest, TargetResult) {
|
|
i := c.i
|
|
var err error
|
|
if c.ref, err = c.scope.ref(); err != nil {
|
|
return nil, TargetResult{Code: TargetGateUnavailable, Host: targets[0].Host, Port: targets[0].Port, Reason: err.Error()}
|
|
}
|
|
first := &checkedTarget{Target: targets[0]}
|
|
rules, err := i.targets.BlockRules(c.ref)
|
|
if err != nil {
|
|
return c.block(TargetGateUnavailable, "gate_unavailable", first, "the asset rules could not be read: "+err.Error())
|
|
}
|
|
ex, err := i.loadExemptions()
|
|
if err != nil {
|
|
return c.block(TargetGateUnavailable, "gate_unavailable", first, "the exemption list could not be read: "+err.Error())
|
|
}
|
|
grants, err := i.targets.EgressGrants(c.ref)
|
|
if err != nil {
|
|
return c.block(TargetGateUnavailable, "gate_unavailable", first, "the egress grants could not be read: "+err.Error())
|
|
}
|
|
grantsDigest := canonicalGrantDigest(grants)
|
|
|
|
// Block rules come first, and an exempt or pinned host that matches one is
|
|
// blocked. They are matched on what the call declares before anything is
|
|
// resolved: a hit there costs no lookup, for any target of the call.
|
|
//
|
|
// URL rules (exact_url, fuzzy_url) are matched once per decision, on the
|
|
// URLs as the call writes them. That is a known limit: exact_url compares
|
|
// the string as written, so another case, encoding (%2F), a trailing slash,
|
|
// an added query or /./ does not match, and fuzzy_url is evaded by encoding
|
|
// the substring; a command can also build its URL at run time. To keep an
|
|
// agent away from a host, a domain, IP or CIDR rule is the one to write.
|
|
if rule, u, hit := db.MatchAssetInterceptRules(rules, nil, nil, c.urls); hit {
|
|
ct := &checkedTarget{Target: targets[0]}
|
|
if t, ok := NormalizeTarget(u); ok {
|
|
ct.Target = t
|
|
}
|
|
return c.block(TargetRuleBlocked, "rule_blocked", ct, fmt.Sprintf("%s is blocked by an asset rule. %s", u, rule.Reason()))
|
|
}
|
|
// Then the declared form of every target: the name as written, the IP
|
|
// literal, the range.
|
|
checked := make([]*checkedTarget, len(targets))
|
|
c.checked = checked
|
|
for n, t := range targets {
|
|
ct := &checkedTarget{Target: t}
|
|
checked[n] = ct
|
|
if t.Kind != TargetDomain {
|
|
ct.ips, ct.resolver, ct.resolvedAt = []string{t.Host}, literalResolver, time.Now().UTC()
|
|
}
|
|
if rule, hit := blockRule(rules, ct); hit {
|
|
return c.block(TargetRuleBlocked, "rule_blocked", ct, fmt.Sprintf("%s is blocked by an asset rule. %s", t, rule.Reason()))
|
|
}
|
|
}
|
|
|
|
i.mu.RLock()
|
|
proxied := i.upstreamProxy
|
|
toolProxy := i.toolProxy
|
|
i.mu.RUnlock()
|
|
// Behind a proxy the proxy chooses the address it connects to, so every pin
|
|
// is name-only for a call whose traffic goes through one: the recording
|
|
// proxy, the global egress proxy and a custom tool's own proxy all count.
|
|
// It is decided for this check only, from the path it decides, never from
|
|
// the pin row: a connection the platform opens itself (direct) is never
|
|
// name-only, whatever proxy is set and whatever state the pin was approved
|
|
// in, and a pin approved behind a proxy compares its addresses again once
|
|
// the proxy is gone.
|
|
// A direct hop (WithDirectHop, a custom tool's own proxy checked as a
|
|
// target) is not behind the proxies either: the tool dials it itself.
|
|
nameOnly := !(c.direct || DirectHop(c.ctx)) && ((proxied != nil && proxied()) || (toolProxy != nil && toolProxy(c.tool)))
|
|
|
|
// The decision on each target, in the order the call declares them. slots
|
|
// holds the request of a target that no pin covers.
|
|
slots := make([]*TargetRequest, len(checked))
|
|
var uses []func()
|
|
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) })
|
|
return TargetResult{}
|
|
}
|
|
if ex.stored[key] {
|
|
if exemptionHolds(ct) {
|
|
ct.cover = coverStored
|
|
uses = append(uses, func() { c.exemptUsed(ct, ex.digest) })
|
|
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", NameOnly: nameOnly}
|
|
return TargetResult{}
|
|
}
|
|
if ct.err != nil {
|
|
// Checked before the grants: a granted name that does not resolve
|
|
// fails closed like any other name. Nothing was resolved, so no
|
|
// address ever met the IP block rules, and an approval could pin
|
|
// nothing; passing on the grant alone would turn a lookup failure
|
|
// into a silent allow.
|
|
_, res := c.block(TargetResolveFailed, "resolve_failed", ct, c.resolveFailure(ct))
|
|
return res
|
|
}
|
|
if scopeGrantCover(grants, ct) {
|
|
// The operator already approved this address space: the grant is a
|
|
// standing decision of theirs, recorded once like a pin use, and no
|
|
// human is asked again for a target inside it.
|
|
ct.cover = coverScope
|
|
if nameOnly {
|
|
// Behind a proxy the proxy picks the address, exactly as for a
|
|
// pin: the cover is name-only for this call, and the proxy holds
|
|
// its own allowlist. A direct connection is never here.
|
|
ct.cover = coverNameOnly
|
|
}
|
|
uses = append(uses, func() { c.scopeGrantUsed(ct, grantsDigest) })
|
|
return TargetResult{}
|
|
}
|
|
pins, err := c.activePins(ct.Host, ct.Port)
|
|
if err != nil {
|
|
_, res := c.block(TargetGateUnavailable, "gate_unavailable", ct, "the pins could not be read: "+err.Error())
|
|
return res
|
|
}
|
|
pin := coveringPin(pins, ct.ips, nameOnly)
|
|
if pin == nil && ct.Kind == TargetDomain && !c.fresh {
|
|
// A request is about to be raised: the addresses a human reads and
|
|
// pins are resolved now, never taken from the cache. A fresh run
|
|
// already has them.
|
|
if c.resolve(ct, true); ct.err != nil {
|
|
_, res := c.block(TargetResolveFailed, "resolve_failed", ct, c.resolveFailure(ct))
|
|
return res
|
|
}
|
|
if rule, hit := blockRule(rules, ct); hit {
|
|
_, res := c.block(TargetRuleBlocked, "rule_blocked", ct, fmt.Sprintf("%s is blocked by an asset rule. %s", ct.Target, rule.Reason()))
|
|
return res
|
|
}
|
|
pin = coveringPin(pins, ct.ips, nameOnly)
|
|
}
|
|
if pin != nil {
|
|
ct.cover = coverPin
|
|
if nameOnly {
|
|
ct.cover = coverNameOnly
|
|
}
|
|
uses = append(uses, func() { c.pinUsed(ct, pin, nameOnly) })
|
|
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, NameOnly: nameOnly}
|
|
if len(pins) > 0 {
|
|
// The request is raised on the key of the pin that exists (the one on
|
|
// the exact port when both exist), so that an approval extends that pin.
|
|
req.Port, req.Reason, req.Pin = pins[0].Port, "new_ip", pins[0]
|
|
}
|
|
slots[n] = &req
|
|
return TargetResult{}
|
|
}
|
|
requests := func() []TargetRequest {
|
|
var out []TargetRequest
|
|
for _, r := range slots {
|
|
if r != nil && !hasRequest(out, *r) {
|
|
out = append(out, *r)
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
// First every target that needs no lookup: a derived exemption, an IP
|
|
// literal or a range, and a name that nothing approved. A name is resolved
|
|
// only when a stored exemption on the target, an operator-approved grant or
|
|
// a pin on any port of the name names it; any other name is requested by
|
|
// name and never looked up here, so an agent cannot send data to a name
|
|
// server through the labels of a name.
|
|
var named []int
|
|
for n, ct := range checked {
|
|
if ct.Kind == TargetDomain && !ex.derived[db.TargetKey(ct.Host, ct.Port)] {
|
|
pinned, err := c.namePinned(ct.Host)
|
|
if err != nil {
|
|
return c.block(TargetGateUnavailable, "gate_unavailable", ct, "the pins could not be read: "+err.Error())
|
|
}
|
|
if pinned || ex.stored[db.TargetKey(ct.Host, ct.Port)] || scopeGrantCover(grants, ct) {
|
|
named = append(named, n)
|
|
continue
|
|
}
|
|
ct.unresolved = true
|
|
}
|
|
if res := decide(n, ct); res.Code != "" {
|
|
return nil, res
|
|
}
|
|
}
|
|
// The cap applies before any lookup: a call that already names too many
|
|
// targets to request resolves nothing.
|
|
if unpinned := requests(); len(unpinned) > maxUnpinnedTargets {
|
|
return c.tooMany(unpinned)
|
|
}
|
|
// Then the names something approved are resolved, and the rules matched on
|
|
// the addresses, before any of them is decided.
|
|
for _, n := range named {
|
|
ct := checked[n]
|
|
c.resolve(ct, c.fresh)
|
|
if rule, hit := blockRule(rules, ct); hit {
|
|
return c.block(TargetRuleBlocked, "rule_blocked", ct, fmt.Sprintf("%s is blocked by an asset rule. %s", ct.Target, rule.Reason()))
|
|
}
|
|
}
|
|
for _, n := range named {
|
|
if res := decide(n, checked[n]); res.Code != "" {
|
|
return nil, res
|
|
}
|
|
}
|
|
unpinned := requests()
|
|
if len(unpinned) > maxUnpinnedTargets {
|
|
return c.tooMany(unpinned)
|
|
}
|
|
if len(unpinned) == 0 {
|
|
// The call passes: record what let it pass, once per process.
|
|
for _, use := range uses {
|
|
use()
|
|
}
|
|
}
|
|
return unpinned, TargetResult{}
|
|
}
|
|
|
|
// resolve fills the addresses of a name. fresh skips the cache.
|
|
func (c *targetCheck) resolve(ct *checkedTarget, fresh bool) {
|
|
ct.resolver = c.i.resolve.name()
|
|
res, err := c.i.resolve.lookup(c.ctx, ct.Host, fresh)
|
|
ct.ips, ct.resolvedAt, ct.err = res.ips, res.at, err
|
|
}
|
|
|
|
// tooMany blocks a call that names more targets to request than one call may.
|
|
func (c *targetCheck) tooMany(unpinned []TargetRequest) ([]TargetRequest, TargetResult) {
|
|
names := make([]string, len(unpinned))
|
|
audit := make([]db.InterceptTarget, len(unpinned))
|
|
for n, r := range unpinned {
|
|
names[n] = targetName(r)
|
|
audit[n] = db.InterceptTarget{Host: r.Host, Port: r.Port, Kind: r.Kind, ResolvedIPs: r.ResolvedIPs,
|
|
Resolver: r.Resolver, ResolvedAt: r.ResolvedAt, Reason: r.Reason, Outcome: "too_many"}
|
|
}
|
|
reason := fmt.Sprintf("this call names %d targets that are not approved (%s); at most %d are requested per call",
|
|
len(unpinned), strings.Join(names, ", "), maxUnpinnedTargets)
|
|
c.log("denied", TargetTooMany+": "+reason, "", audit...)
|
|
return nil, TargetResult{Code: TargetTooMany, Host: unpinned[0].Host, Port: unpinned[0].Port, Reason: reason}
|
|
}
|
|
|
|
func (c *targetCheck) resolveFailure(ct *checkedTarget) string {
|
|
reason := fmt.Sprintf("the platform could not resolve %s (%v)", ct.Host, ct.err)
|
|
if pins, err := c.activePins(ct.Host, ct.Port); err == nil && len(pins) > 0 {
|
|
reason += fmt.Sprintf(", so it cannot compare the address with the approved pin (v%d: %s)",
|
|
pins[0].Version, strings.Join(pins[0].PinnedIPs, ", "))
|
|
}
|
|
return reason
|
|
}
|
|
|
|
// block logs a blocked call as a decided row and returns the block.
|
|
func (c *targetCheck) block(code, outcome string, ct *checkedTarget, reason string) ([]TargetRequest, TargetResult) {
|
|
c.log("denied", code+": "+reason, "", ct.audit(outcome))
|
|
return nil, TargetResult{Code: code, Host: ct.Host, Port: ct.Port, Reason: reason}
|
|
}
|
|
|
|
// log writes one decided row of the gate. Best effort: a failed write never
|
|
// changes the outcome of the call.
|
|
func (c *targetCheck) log(status, reason, configDigest string, targets ...db.InterceptTarget) {
|
|
action := "deny"
|
|
if status == "allowed" {
|
|
action = "allow"
|
|
}
|
|
audit := auditFor(c.ctx, Decision{Action: action, Message: reason, ConfigDigest: configDigest}, c.input, status)
|
|
if status == "allowed" {
|
|
// The row records that a pin or an exemption was used, not this one call.
|
|
audit.ExecutionStatus = "unknown"
|
|
}
|
|
for n := range targets {
|
|
targets[n].RedirectFrom = c.redirectFrom
|
|
}
|
|
audit.Targets = targets
|
|
_, agentName := taskInfoFromCtx(c.ctx)
|
|
_ = c.i.targets.LogDecision(db.TargetDecision{Scope: c.ref, AgentName: agentName, ToolName: c.tool,
|
|
ToolInput: c.input, Status: status, Reason: reason, Audit: audit})
|
|
}
|
|
|
|
// exemptUsed logs the first call of this process that passes through an
|
|
// exemption, per scope, host, port and list digest.
|
|
func (c *targetCheck) exemptUsed(ct *checkedTarget, digest string) {
|
|
key := "exempt|" + c.scope.scopeName() + "|" + db.TargetKey(ct.Host, ct.Port) + "|" + digest
|
|
if _, seen := c.i.firstUse.LoadOrStore(key, true); seen {
|
|
return
|
|
}
|
|
c.log("allowed", fmt.Sprintf("Target %s is exempt from target approval for %s.", ct.Target, c.scope.scopeName()),
|
|
digest, ct.audit("exempt"))
|
|
}
|
|
|
|
// pinUsed logs the first call of this process that a pin version covers.
|
|
// nameOnly is whether a proxy made the pin name-only for this check: the row
|
|
// records the effective state of the use, not the pin's mark.
|
|
func (c *targetCheck) pinUsed(ct *checkedTarget, pin *db.TargetPin, nameOnly bool) {
|
|
if _, seen := c.i.firstUse.LoadOrStore(fmt.Sprintf("pin|%d", pin.ID), true); seen {
|
|
return
|
|
}
|
|
t := ct.audit("pin_match")
|
|
t.PinID, t.PinVersion, t.PinnedIPs, t.NameOnlyEffective = pin.ID, pin.Version, pin.PinnedIPs, nameOnly
|
|
c.log("allowed", fmt.Sprintf("Target %s is covered by pin v%d of %s.", ct.Target, pin.Version, c.scope.scopeName()), "", t)
|
|
}
|
|
|
|
// scopeGrantCover reports whether an operator-approved egress grant covers the
|
|
// target. It mirrors the sandbox proxy's allowlist rules (sandbox/policy.go)
|
|
// exactly: a domain must match a granted domain (exact or subdomain), and an
|
|
// IP literal or a range must fall inside granted CIDRs; a range target is
|
|
// covered only when the whole range sits inside one grant. Ports play no role
|
|
// in a grant, which is why a grant can never be answered by the pin lookup
|
|
// alone: pins are keyed by host and port, grants by address.
|
|
func scopeGrantCover(grants []db.ScopeEgress, ct *checkedTarget) bool {
|
|
if len(grants) == 0 {
|
|
return false
|
|
}
|
|
inCIDR := func(v string, addr netip.Addr) bool {
|
|
if pfx, err := netip.ParsePrefix(v); err == nil {
|
|
return pfx.Contains(addr)
|
|
}
|
|
if a, err := netip.ParseAddr(v); err == nil {
|
|
return a.Unmap() == addr
|
|
}
|
|
return false
|
|
}
|
|
switch ct.Kind {
|
|
case TargetDomain:
|
|
h := strings.ToLower(strings.TrimSuffix(ct.Host, "."))
|
|
if h == "" {
|
|
return false
|
|
}
|
|
for _, g := range grants {
|
|
if g.Kind == "domain" && (h == g.Value || strings.HasSuffix(h, "."+g.Value)) {
|
|
return true
|
|
}
|
|
}
|
|
case TargetCIDR:
|
|
pfx, err := netip.ParsePrefix(ct.Host)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
pfx = pfx.Masked()
|
|
for _, g := range grants {
|
|
if g.Kind != "cidr" {
|
|
continue
|
|
}
|
|
gp, err := netip.ParsePrefix(g.Value)
|
|
if err != nil {
|
|
a, aerr := netip.ParseAddr(g.Value)
|
|
if aerr != nil {
|
|
continue
|
|
}
|
|
gp = netip.PrefixFrom(a, a.BitLen())
|
|
}
|
|
gp = gp.Masked()
|
|
if gp.Bits() <= pfx.Bits() && gp.Contains(pfx.Addr().Unmap()) {
|
|
return true
|
|
}
|
|
}
|
|
default: // an IP literal; the resolver answer is not consulted, the written address is
|
|
h := strings.TrimPrefix(strings.TrimSuffix(ct.Host, "]"), "[")
|
|
addr, err := netip.ParseAddr(h)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
addr = addr.Unmap()
|
|
for _, g := range grants {
|
|
if g.Kind == "cidr" && inCIDR(g.Value, addr) {
|
|
return true
|
|
}
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// canonicalGrantDigest digests a grant set: the normalized entries sorted and
|
|
// joined, so the digest changes exactly when a use covered by the set stops
|
|
// reflecting the operator's current decision. Like an exemption list digest,
|
|
// it lets an audit dedupe key itself on the configuration that was in force.
|
|
func canonicalGrantDigest(grants []db.ScopeEgress) string {
|
|
lines := make([]string, 0, len(grants))
|
|
for _, g := range grants {
|
|
lines = append(lines, g.Kind+"|"+strings.ToLower(g.Value))
|
|
}
|
|
sort.Strings(lines)
|
|
return digestInput([]byte(strings.Join(lines, "\n")))
|
|
}
|
|
|
|
// scopeGrantUsed logs the first call of this process that an approved grant
|
|
// covers: the decision is the operator's standing grant, so it records a
|
|
// system-decided allowed row like the pin and exemption paths do. The key and
|
|
// the logged config digest carry the grant-set digest, so a use re-audits when
|
|
// the operator changes the grants.
|
|
func (c *targetCheck) scopeGrantUsed(ct *checkedTarget, digest string) {
|
|
key := "scope|" + c.scope.scopeName() + "|" + db.TargetKey(ct.Host, ct.Port) + "|" + digest
|
|
if _, seen := c.i.firstUse.LoadOrStore(key, true); seen {
|
|
return
|
|
}
|
|
c.log("allowed", fmt.Sprintf("Target %s is covered by an operator-approved egress grant for %s.", ct.Target, c.scope.scopeName()), digest, ct.audit("scope_grant"))
|
|
}
|
|
|
|
// blockRule matches the asset block rules against a target: its name, and its
|
|
// addresses. A range is matched as written and by its network address. URL
|
|
// rules are not matched here: run matches them once, on the declared URLs.
|
|
func blockRule(rules []db.AssetInterceptRule, ct *checkedTarget) (db.AssetInterceptRule, bool) {
|
|
var domains []string
|
|
ips := ct.ips
|
|
switch ct.Kind {
|
|
case TargetDomain:
|
|
domains = []string{ct.Host}
|
|
case TargetCIDR:
|
|
if p, err := netip.ParsePrefix(ct.Host); err == nil {
|
|
ips = []string{ct.Host, p.Addr().String()}
|
|
}
|
|
}
|
|
rule, _, hit := db.MatchAssetInterceptRules(rules, domains, ips, nil)
|
|
return rule, hit
|
|
}
|
|
|
|
// exemptionHolds reports whether the stored exemption on a target applies. On a
|
|
// name it is void when the name does not resolve or one of its addresses is
|
|
// private, loopback or otherwise local. An IP literal is not resolved; it holds
|
|
// unless it is an address that can never be exempt.
|
|
func exemptionHolds(ct *checkedTarget) bool {
|
|
if ct.Kind == TargetIP {
|
|
return ValidateExemptionHost(ct.Host) == nil
|
|
}
|
|
if ct.Kind != TargetDomain || ct.err != nil || len(ct.ips) == 0 {
|
|
return false
|
|
}
|
|
return !slices.ContainsFunc(ct.ips, voidsExemption)
|
|
}
|
|
|
|
// coveringPin returns the pin that covers the resolved addresses: the first
|
|
// candidate when the check is name-only, else the first that holds every
|
|
// address. The pin's name_only_effective mark plays no role: it records how
|
|
// the pin was approved, not the path of this check. The address sets of two
|
|
// pins are never merged.
|
|
func coveringPin(pins []*db.TargetPin, resolved []string, nameOnly bool) *db.TargetPin {
|
|
for _, p := range pins {
|
|
if nameOnly || subset(resolved, p.PinnedIPs) {
|
|
return p
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func hasRequest(list []TargetRequest, r TargetRequest) bool {
|
|
for _, x := range list {
|
|
if x.Host == r.Host && x.Port == r.Port {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|