mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-12-04 13:43:55 +08:00
Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b53eccd8d1 | ||
|
|
fd9e601026 | ||
|
|
df5e047b60 | ||
|
|
49b9421ed8 | ||
|
|
3286e2009c |
@@ -6,6 +6,8 @@ All notable changes to this project are documented in this file. The format is b
|
||||
|
||||
### Security
|
||||
|
||||
- **`GET /api/traffic` no longer returns the global proxy password.** With traffic capture off, its `proxy` field was the saved global egress proxy URL with its `user:pass` in clear, although `GET /api/settings` masks the same setting, and the dashboard requests it on every load. The field now shows `__masked__` when a global proxy is set (sending it back to `PUT /api/settings` keeps the stored proxy, as before), and still shows the local recording proxy address with capture on. Proxy validation errors returned by `PUT /api/settings` no longer quote the submitted address.
|
||||
- **A custom HTTP tool's own proxy goes through the target gate.** With the gate on, only the tool URL was checked: the proxy in the tool's `proxy` field was dialled without any check, so a tool whose target was approved could send its request to any host and port, loopback and private addresses included, through a proxy nobody approved. With the gate on, the proxy's host and port are now a target like the URL, as a proxy named on a Bash command line is: the call waits for an approval or is refused, the approval request shows the proxy without its credentials, and the connection to the proxy goes through the gate's dialer. That connection is checked and dialled as a direct hop: the approval pins the addresses it resolved rather than the name alone, so a proxy name that later answers another address is refused instead of being dialled unpinned. The recording and global proxies (`use_recording_proxy`) are unchanged. `ARTEX_SANDBOX=required` is unchanged: the sandbox egress policy already checks the proxy connection. With the gate off (no task scope, a task with the gate off, or the custom tool test endpoint) the proxy is not checked, as before, and neither is the tool URL, which can already name a loopback or private address in that mode. Behaviour change: with the gate on, a tool that uses its own proxy now raises an approval request for the proxy host and port (or is refused when none is granted) until the proxy is approved for the task.
|
||||
- **Text deny and ask rules see a Bash command as the shell decodes it.** Regex and string intercept rules on `tool_input` were matched on the raw text, but Bash removes quotes and backslashes and decodes `$'...'` before it runs a command, so `r\m -rf ./x`, `r''m -rf`, `"r"m -rf`, `/bin/r\m -rf`, `rm -r''f`, `rm -R -$'f'` or a backslash-newline inside a word ran `rm -rf` while the built-in recursive-force-delete rule did not match; so did `rm -rf ./x` on the line after another command, since the input encodes the newline as `\n` and its `n` hid the word boundary. A deny or ask rule on a Bash call now also meets the command decoded with the word decoder argv rules use: the simple commands joined by `; `, every word with its quotes, backslash escapes and line continuations removed, a word with an expansion kept as written. This covers every built-in regex rule and operator deny and ask rules; allow rules are still matched on the text as written only. The word decoder now also decodes ANSI-C strings (`$'r\x6d'`), so argv deny and ask rules meet `$'nmap'` and `bash -c $'nmap x'` too.
|
||||
- **`fuzzy_ip` asset rules and the URL host check match every spelling of an IP address.** `fuzzy_ip` compared the raw strings, so a block rule `::1` let `insert_assets` register `0:0:0:0:0:0:0:1` or `::0001`, and a rule written expanded missed the compressed form. The rule is now also matched against the canonical form of each address (zeros compressed, lower case, IPv4-mapped addresses unmapped, zone dropped), and a pattern that is a whole address is canonicalized too; a partial pattern such as `10.0.` keeps its substring meaning. `cidr` rules now match a zone-qualified address (`fe80::1%eth0`), and a zone-qualified IPv6 URL host (`http://[fe80::1%25eth0]/`) is classified as an IP instead of a domain, so `exact_ip`, `fuzzy_ip` and `cidr` rules see it, in `insert_assets` and for stored assets.
|
||||
- **The always-allow denylist refuses `sqlmap`, `sqlite3` and `nmap`.** An argv allow rule covers every flag, and each of these programs has a flag or script hook that runs code chosen by the caller: `sqlmap --eval`, `sqlite3 .shell` and `nmap --script` with a Lua NSE file. After an operator clicked "always allow" on a harmless call, later calls of the same program matched the rule and skipped the fallback judge, so those flags ran arbitrary code. The three names join the code-owned denylist; `sqlite3` is stored as `sqlite` because `argvProgramName` strips the version suffix, and `sqlmap.py`/`sqlmapapi.py` reduce to their bare names through the same extension stripping. Allow rules already stored for these programs stop matching because the denylist is checked again at match time: their calls go back to the judge or to an ask rule, and the rows stay in the rules table.
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
package intercept
|
||||
|
||||
import "context"
|
||||
|
||||
// directHopKey marks a check or a connection the platform opens itself to a
|
||||
// named hop. A custom HTTP tool's own proxy is such a hop: the tool dials the
|
||||
// proxy directly, and the proxy, not ARTEX, connects to the target. Pins for it
|
||||
// bind the addresses the decision compared, never the name alone.
|
||||
type directHopKey struct{}
|
||||
|
||||
// WithDirectHop marks ctx as a direct connection to the hop being checked or
|
||||
// dialled: the target gate does not treat its pins as name-only.
|
||||
func WithDirectHop(ctx context.Context) context.Context {
|
||||
return context.WithValue(ctx, directHopKey{}, true)
|
||||
}
|
||||
|
||||
// DirectHop reports whether ctx was marked by WithDirectHop.
|
||||
func DirectHop(ctx context.Context) bool {
|
||||
v, _ := ctx.Value(directHopKey{}).(bool)
|
||||
return v
|
||||
}
|
||||
@@ -58,6 +58,17 @@ func PinnedDialer(toolName string, scoped bool) func(ctx context.Context, networ
|
||||
}
|
||||
}
|
||||
|
||||
// PinnedDialerDirect is PinnedDialer for a connection ARTEX opens itself to a
|
||||
// named hop, such as a custom HTTP tool's own proxy. The hop is not behind the
|
||||
// proxy: the dial is checked and opened on the addresses the decision compared,
|
||||
// so a pin for its name cannot be satisfied by a name that later rebinds.
|
||||
func PinnedDialerDirect(toolName string) func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
dial := PinnedDialer(toolName, true)
|
||||
return func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
return dial(WithDirectHop(ctx), network, addr)
|
||||
}
|
||||
}
|
||||
|
||||
// GateOn reports whether ctx carries a target scope whose gate is on.
|
||||
func GateOn(ctx context.Context) bool {
|
||||
_, on := renderedScope(ctx)
|
||||
|
||||
+15
-10
@@ -233,8 +233,11 @@ func (c *targetCheck) run(targets []Target) ([]TargetRequest, TargetResult) {
|
||||
// Behind a proxy the proxy chooses the address it connects to, so every pin
|
||||
// is name-only for this call, whatever the pin row says: the proxy can be
|
||||
// turned on after a pin was approved. The recording proxy, the global egress
|
||||
// proxy and a custom tool's own proxy all count.
|
||||
nameOnly := (proxied != nil && proxied()) || (toolProxy != nil && toolProxy(c.tool))
|
||||
// proxy and a custom tool's own proxy all count. A direct hop (WithDirectHop)
|
||||
// is not behind them: the tool dials it itself, so its pins bind the
|
||||
// addresses the decision compared.
|
||||
direct := DirectHop(c.ctx)
|
||||
nameOnly := !direct && ((proxied != nil && proxied()) || (toolProxy != nil && toolProxy(c.tool)))
|
||||
|
||||
var unpinned []TargetRequest
|
||||
var uses []func()
|
||||
@@ -280,7 +283,7 @@ func (c *targetCheck) run(targets []Target) ([]TargetRequest, TargetResult) {
|
||||
if err != nil {
|
||||
return c.block(TargetGateUnavailable, "gate_unavailable", ct, "the pins could not be read: "+err.Error())
|
||||
}
|
||||
pin := coveringPin(pins, ct.ips, nameOnly)
|
||||
pin := coveringPin(pins, ct.ips, nameOnly, direct)
|
||||
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
|
||||
@@ -291,11 +294,11 @@ func (c *targetCheck) run(targets []Target) ([]TargetRequest, TargetResult) {
|
||||
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()))
|
||||
}
|
||||
pin = coveringPin(pins, ct.ips, nameOnly)
|
||||
pin = coveringPin(pins, ct.ips, nameOnly, direct)
|
||||
}
|
||||
if pin != nil {
|
||||
ct.cover = coverPin
|
||||
if nameOnly || pin.NameOnlyEffective {
|
||||
if nameOnly || (pin.NameOnlyEffective && !direct) {
|
||||
ct.cover = coverNameOnly
|
||||
}
|
||||
uses = append(uses, func() { c.pinUsed(ct, pin, nameOnly) })
|
||||
@@ -396,7 +399,7 @@ func (c *targetCheck) pinUsed(ct *checkedTarget, pin *db.TargetPin, nameOnly boo
|
||||
return
|
||||
}
|
||||
t := ct.audit("pin_match")
|
||||
t.PinID, t.PinVersion, t.PinnedIPs, t.NameOnlyEffective = pin.ID, pin.Version, pin.PinnedIPs, pin.NameOnlyEffective || nameOnly
|
||||
t.PinID, t.PinVersion, t.PinnedIPs, t.NameOnlyEffective = pin.ID, pin.Version, pin.PinnedIPs, nameOnly || (pin.NameOnlyEffective && !DirectHop(c.ctx))
|
||||
c.log("allowed", fmt.Sprintf("Target %s is covered by pin v%d of %s.", ct.Target, pin.Version, c.scope.scopeName()), "", t)
|
||||
}
|
||||
|
||||
@@ -529,11 +532,13 @@ func exemptionHolds(ct *checkedTarget) bool {
|
||||
}
|
||||
|
||||
// coveringPin returns the pin that covers the resolved addresses: the first
|
||||
// candidate that is name-only, or that holds every address. The address sets
|
||||
// of two pins are never merged.
|
||||
func coveringPin(pins []*db.TargetPin, resolved []string, nameOnly bool) *db.TargetPin {
|
||||
// candidate that is name-only, or that holds every address. A direct hop does
|
||||
// not accept a name-only pin on its name alone: the connection is opened to the
|
||||
// addresses the decision compared, so such a pin covers only when it holds them
|
||||
// too. The address sets of two pins are never merged.
|
||||
func coveringPin(pins []*db.TargetPin, resolved []string, nameOnly, direct bool) *db.TargetPin {
|
||||
for _, p := range pins {
|
||||
if nameOnly || p.NameOnlyEffective || subset(resolved, p.PinnedIPs) {
|
||||
if nameOnly || (!direct && p.NameOnlyEffective) || subset(resolved, p.PinnedIPs) {
|
||||
return p
|
||||
}
|
||||
}
|
||||
|
||||
@@ -295,8 +295,10 @@ func (i *Interceptor) openTargetRequest(ctx context.Context, ref db.TargetScopeR
|
||||
proxied := i.upstreamProxy
|
||||
i.mu.RUnlock()
|
||||
// Behind the upstream proxy the proxy chooses the address: the approval is
|
||||
// for the name, and the pin created from this row says so.
|
||||
nameOnly := proxied != nil && proxied()
|
||||
// for the name, and the pin created from this row says so. A direct hop is
|
||||
// not behind it: the tool dials it itself, so the approval and its pin bind
|
||||
// the addresses a human reads.
|
||||
nameOnly := !DirectHop(ctx) && proxied != nil && proxied()
|
||||
|
||||
dec := Decision{Action: "ask"}
|
||||
if ask != nil {
|
||||
|
||||
+56
-1
@@ -741,6 +741,20 @@ func (s *Server) runHTTPTool(ctx context.Context, key string, execRaw json.RawMe
|
||||
if res := intercept.GateRenderedURL(ctx, key, rawURL); res.Code != "" {
|
||||
return actool.Errorf(guard.TargetBlockMessage(res)), nil
|
||||
}
|
||||
// The tool's own proxy is a connection the panel opens too: with the gate
|
||||
// on it is a target, as a proxy named on a Bash command line is, and the
|
||||
// dial is checked again (httpToolTransport). Gate off, it is not checked,
|
||||
// like the tool URL itself, which may name a loopback or private address
|
||||
// in that mode. In required mode the sandbox policy checks the proxy dial.
|
||||
if sbPolicy == nil {
|
||||
if proxy := s.toolOwnProxy(spec); proxy != "" {
|
||||
// The proxy is a direct hop: ARTEX dials it itself, so its pin binds
|
||||
// the addresses the approval resolved, not the name alone.
|
||||
if res := intercept.GateRenderedURL(intercept.WithDirectHop(ctx), key, gateProxyURL(proxy)); res.Code != "" {
|
||||
return actool.Errorf(guard.TargetBlockMessage(res)), nil
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := intercept.CheckStatefulTool(ctx, key, nil, rawURL, method); err != nil {
|
||||
return actool.Errorf(err.Error()), nil
|
||||
}
|
||||
@@ -949,9 +963,16 @@ func sandboxHTTPTransport(tr *http.Transport, policy *sandbox.EgressPolicy) *htt
|
||||
// httpToolTransport is the transport of one http tool call, or nil
|
||||
// (http.DefaultTransport). A call through a proxy keeps httpProxyTransport: it
|
||||
// dials the proxy, which makes the connection to the target. A direct call in
|
||||
// a gated scope connects through the pinned dialer, to addresses a pin covers.
|
||||
// a gated scope connects through the pinned dialer, to addresses a pin covers;
|
||||
// so does the tool's own proxy outside required mode.
|
||||
func (s *Server) httpToolTransport(ctx context.Context, key string, spec httpExec) *http.Transport {
|
||||
if tr := s.httpProxyTransport(spec); tr != nil {
|
||||
if intercept.GateOn(ctx) && !agent.SandboxRequired() && s.toolOwnProxy(spec) != "" {
|
||||
// The proxy hop is direct: the dial resolves and pins its addresses,
|
||||
// so a proxy name that later answers another address is refused.
|
||||
tr.DialContext = intercept.PinnedDialerDirect(key)
|
||||
tr.DisableKeepAlives = true
|
||||
}
|
||||
return tr
|
||||
}
|
||||
if !intercept.GateOn(ctx) {
|
||||
@@ -1004,6 +1025,40 @@ func (s *Server) httpProxyTransport(spec httpExec) *http.Transport {
|
||||
return tr
|
||||
}
|
||||
|
||||
// toolOwnProxy returns the proxy URL of the tool's own exec.proxy when the call
|
||||
// goes through it, "" when the call is direct or goes through the recording or
|
||||
// global proxy, endpoints the gate exempts as configured (see
|
||||
// httpProxyTransport).
|
||||
func (s *Server) toolOwnProxy(spec httpExec) string {
|
||||
if spec.UseRecordingProxy {
|
||||
if tr := s.m.Traffic(); tr != nil && s.m.TrafficEnabled() {
|
||||
return ""
|
||||
}
|
||||
if proxyURLString(s.m.GlobalProxy()) != "" {
|
||||
return ""
|
||||
}
|
||||
}
|
||||
proxy := proxyURLString(spec.Proxy)
|
||||
if _, err := url.Parse(proxy); err != nil {
|
||||
return "" // httpProxyTransport goes direct
|
||||
}
|
||||
return proxy
|
||||
}
|
||||
|
||||
// gateProxyURL is a tool proxy as the gate reads it: without credentials,
|
||||
// since the gate records the URL it checks, and with the port net/http dials
|
||||
// for a socks5 proxy that names none. "" (no host) fails closed in the gate.
|
||||
func gateProxyURL(proxy string) string {
|
||||
u, err := url.Parse(proxyWithoutCredentials(proxy))
|
||||
if err != nil || u.Host == "" {
|
||||
return ""
|
||||
}
|
||||
if s := strings.ToLower(u.Scheme); (s == "socks5" || s == "socks5h") && u.Port() == "" {
|
||||
u.Host = strings.TrimSuffix(u.Host, ":") + ":1080" // u.Host keeps IPv6 brackets
|
||||
}
|
||||
return u.String()
|
||||
}
|
||||
|
||||
// proxyURLString returns a proxy address as a URL: a bare host:port gets
|
||||
// "http://", an address that already has a scheme (as ProxyAddr returns it) is
|
||||
// kept as is.
|
||||
|
||||
@@ -118,10 +118,12 @@ func TestCustomHTTPDirectDialPinned(t *testing.T) {
|
||||
// With the gate off (and without a scope) the call keeps http.DefaultTransport:
|
||||
// no transport is built. A spec with a proxy keeps its proxy transport, without
|
||||
// a dialer. Gate on and direct: a transport with the pinned dialer, no
|
||||
// environment proxy, keep-alive off.
|
||||
// environment proxy, keep-alive off. Gate on, the tool's own proxy is dialled
|
||||
// through the pinned dialer too.
|
||||
func TestCustomHTTPGateOffTransportUnchanged(t *testing.T) {
|
||||
s := &Server{}
|
||||
direct := httpExec{URL: "http://api.example.com/"}
|
||||
proxied := httpExec{URL: direct.URL, Proxy: "http://127.0.0.1:1"}
|
||||
scope := func(on bool) context.Context {
|
||||
return intercept.WithTargetScope(context.Background(), intercept.TargetScope{TaskID: "7", Enabled: func() bool { return on }})
|
||||
}
|
||||
@@ -129,9 +131,12 @@ func TestCustomHTTPGateOffTransportUnchanged(t *testing.T) {
|
||||
if tr := s.httpToolTransport(ctx, "probe", direct); tr != nil {
|
||||
t.Fatalf("%s: transport %+v, want nil (http.DefaultTransport)", name, tr)
|
||||
}
|
||||
if tr := s.httpToolTransport(ctx, "probe", proxied); tr == nil || tr.Proxy == nil || tr.DialContext != nil || tr.DisableKeepAlives {
|
||||
t.Fatalf("%s, operator proxy: transport %+v, want the proxy transport without a dialer", name, tr)
|
||||
}
|
||||
}
|
||||
if tr := s.httpToolTransport(scope(true), "probe", httpExec{URL: direct.URL, Proxy: "http://127.0.0.1:1"}); tr == nil || tr.Proxy == nil || tr.DialContext != nil {
|
||||
t.Fatalf("operator proxy: transport %+v, want the proxy transport without a dialer", tr)
|
||||
if tr := s.httpToolTransport(scope(true), "probe", proxied); tr == nil || tr.Proxy == nil || tr.DialContext == nil || !tr.DisableKeepAlives {
|
||||
t.Fatalf("gated operator proxy: transport %+v, want the proxy transport with the pinned dialer", tr)
|
||||
}
|
||||
if tr := s.httpToolTransport(scope(true), "probe", direct); tr == nil || tr.Proxy != nil || tr.DialContext == nil || !tr.DisableKeepAlives {
|
||||
t.Fatalf("gated direct call: transport %+v", tr)
|
||||
@@ -239,13 +244,13 @@ func TestCustomToolTestEndpointDialUngated(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// Documents a known limit: a custom http tool that goes through a proxy is not
|
||||
// bound to pins. The pinned dialer covers direct connections only; through a
|
||||
// proxy the connection to the target is the proxy's, and the proxy here
|
||||
// connects to a peer nobody pinned. Step 2.2 binds the recording proxy (and
|
||||
// flips its half of this test); an operator-written proxy stays unbound
|
||||
// (OPEN-6).
|
||||
func TestBypass_CustomHTTPProxyPeerNotPinned(t *testing.T) {
|
||||
// A custom http tool that goes through a proxy: the target pin is name-only,
|
||||
// since the proxy makes the connection to the target, and the proxy here
|
||||
// connects to a peer nobody pinned. The tool's own proxy is a gate target
|
||||
// (formerly the known limit OPEN-6): the call waits for its approval, then the
|
||||
// proxy is dialled through the pinned dialer. The recording and global proxies
|
||||
// are not checked here and are dialled as before.
|
||||
func TestCustomHTTPOwnProxyGated(t *testing.T) {
|
||||
g := newGateServer(t)
|
||||
on := true
|
||||
task := g.newTask(t, db.TaskCreateOptions{TargetGate: &on})
|
||||
@@ -270,28 +275,43 @@ func TestBypass_CustomHTTPProxyPeerNotPinned(t *testing.T) {
|
||||
direct := g.s.buildCustomTool(&db.Tool{Key: "probe_bypass", Kind: "http", Exec: execJSON(t, map[string]any{"url": url})})
|
||||
approveTarget(t, g, task, direct, func() (string, bool) { return callTool(t, direct, gatedCtx(task, 0), `{}`, nil) }, key)
|
||||
|
||||
// The tool's own proxy: refused until its host:port is approved, then
|
||||
// dialled through the pinned dialer, at the pinned proxy address only.
|
||||
proxyKey := strings.TrimPrefix(proxy.URL, "http://")
|
||||
dialer.route(proxyKey, proxy.Listener.Addr().String())
|
||||
ownProxy := g.s.buildCustomTool(&db.Tool{Key: "probe_bypass", Kind: "http", Exec: execJSON(t, map[string]any{"url": url, "proxy": proxy.URL})})
|
||||
callOwn := func() (string, bool) { return callTool(t, ownProxy, gatedCtx(task, 0), `{}`, nil) }
|
||||
approveTarget(t, g, task, ownProxy, callOwn, proxyKey)
|
||||
if hits.Load() != 0 || len(dialer.calls()) != 0 {
|
||||
t.Fatalf("the proxy was dialled before its approval: hits=%d dialled %v", hits.Load(), dialer.calls())
|
||||
}
|
||||
if out, isErr := callOwn(); isErr || !strings.Contains(out, "probe-reached") || hits.Load() != 1 {
|
||||
t.Fatalf("operator proxy after the approval: error=%v out=%q hits=%d", isErr, out, hits.Load())
|
||||
}
|
||||
if got := dialer.calls(); !slices.Equal(got, []string{proxyKey}) {
|
||||
t.Fatalf("dialled %v, want the pinned proxy only; the pinned address 203.0.113.7 is never dialled through a proxy", got)
|
||||
}
|
||||
|
||||
// use_recording_proxy through the global proxy: not checked here, as before.
|
||||
// The global proxy carries a scheme, as in production (ProxyAddr returns it
|
||||
// as is with capture off); httpProxyTransport must not write a second one.
|
||||
global := httptest.NewServer(proxy.Config.Handler)
|
||||
t.Cleanup(global.Close)
|
||||
g.m.mu.Lock()
|
||||
g.m.globalProxy = proxy.URL
|
||||
g.m.globalProxy = global.URL
|
||||
g.m.mu.Unlock()
|
||||
t.Cleanup(func() {
|
||||
g.m.mu.Lock()
|
||||
g.m.globalProxy = ""
|
||||
g.m.mu.Unlock()
|
||||
})
|
||||
for name, exec := range map[string]map[string]any{
|
||||
"operator proxy": {"url": url, "proxy": proxy.URL},
|
||||
"use_recording_proxy": {"url": url, "use_recording_proxy": true},
|
||||
} {
|
||||
before := hits.Load()
|
||||
tool := g.s.buildCustomTool(&db.Tool{Key: "probe_bypass", Kind: "http", Exec: execJSON(t, exec)})
|
||||
if out, isErr := callTool(t, tool, gatedCtx(task, 0), `{}`, nil); isErr || !strings.Contains(out, "probe-reached") || hits.Load() != before+1 {
|
||||
t.Fatalf("%s: error=%v out=%q", name, isErr, out)
|
||||
}
|
||||
before, dialled := hits.Load(), len(dialer.calls())
|
||||
tool := g.s.buildCustomTool(&db.Tool{Key: "probe_bypass", Kind: "http", Exec: execJSON(t, map[string]any{"url": url, "use_recording_proxy": true})})
|
||||
if out, isErr := callTool(t, tool, gatedCtx(task, 0), `{}`, nil); isErr || !strings.Contains(out, "probe-reached") || hits.Load() != before+1 {
|
||||
t.Fatalf("use_recording_proxy: error=%v out=%q", isErr, out)
|
||||
}
|
||||
if got := dialer.calls(); len(got) != 0 {
|
||||
t.Fatalf("dialled %v; the pinned address 203.0.113.7 is never dialled through a proxy", got)
|
||||
if got := dialer.calls(); len(got) != dialled {
|
||||
t.Fatalf("dialled %v; the global proxy is not dialled through the gate", got[dialled:])
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Autumn-27/artex/agent"
|
||||
"github.com/Autumn-27/artex/db"
|
||||
)
|
||||
|
||||
// Gate on: the tool's own proxy is a target. An approved target URL does not
|
||||
// let the call reach an unapproved proxy: the proxy is not dialled and a
|
||||
// request opens on its host:port, recorded without the proxy credentials.
|
||||
func TestCustomHTTPGatedOwnProxyNotDialed(t *testing.T) {
|
||||
g := newGateServer(t)
|
||||
on := true
|
||||
task := g.newTask(t, db.TaskCreateOptions{TargetGate: &on})
|
||||
_, targetHits, host, port := countingServer(t)
|
||||
_, proxyHits, _, proxyPort := countingServer(t)
|
||||
targetURL := "http://" + host + ":" + port + "/"
|
||||
direct := g.s.buildCustomTool(&db.Tool{Key: "probe_own_proxy", Kind: "http", Exec: execJSON(t, map[string]any{"url": targetURL})})
|
||||
approveTarget(t, g, task, direct, func() (string, bool) { return callTool(t, direct, gatedCtx(task, 0), `{}`, nil) }, host+":"+port)
|
||||
if out, isErr := callTool(t, direct, gatedCtx(task, 0), `{}`, nil); isErr || targetHits.Load() != 1 {
|
||||
t.Fatalf("approved direct call: error=%v out=%q", isErr, out)
|
||||
}
|
||||
|
||||
proxyKey := "127.0.0.1:" + proxyPort
|
||||
tool := g.s.buildCustomTool(&db.Tool{Key: "probe_own_proxy", Kind: "http",
|
||||
Exec: execJSON(t, map[string]any{"url": targetURL, "proxy": "http://user:pw-secret@" + proxyKey})})
|
||||
out, isErr := callTool(t, tool, gatedCtx(task, 0), `{}`, nil)
|
||||
if !isErr || !strings.Contains(out, "TARGET_APPROVAL_PENDING") || !strings.Contains(out, proxyKey) {
|
||||
t.Fatalf("unapproved proxy: error=%v out=%q", isErr, out)
|
||||
}
|
||||
if n := proxyHits.Load(); n != 0 {
|
||||
t.Fatalf("unapproved proxy received %d request(s)", n)
|
||||
}
|
||||
if n := targetHits.Load(); n != 1 {
|
||||
t.Fatalf("target received %d request(s), want only the direct one", n)
|
||||
}
|
||||
_, toolName, input, ok := openTargetRequest(t, g.m.pg, task.ID, proxyKey)
|
||||
if !ok || toolName != "probe_own_proxy" || strings.Contains(input, "pw-secret") || strings.Contains(input, "user") {
|
||||
t.Fatalf("request on the proxy: ok=%v tool=%q input=%s", ok, toolName, input)
|
||||
}
|
||||
}
|
||||
|
||||
// A saved tool's own proxy is a direct hop: the approval pins the addresses it
|
||||
// resolved, and a proxy name that later answers another address is refused
|
||||
// instead of being dialled unpinned (DNS rebinding). The tool is saved so the
|
||||
// manager knows it uses a proxy, as in production.
|
||||
func TestCustomHTTPOwnProxyHostnameRebindingRefused(t *testing.T) {
|
||||
g := newGateServer(t)
|
||||
on := true
|
||||
task := g.newTask(t, db.TaskCreateOptions{TargetGate: &on})
|
||||
_, targetHits, host, port := countingServer(t)
|
||||
proxy, proxyHits, _, _ := countingServer(t)
|
||||
targetKey := host + ":" + port
|
||||
proxyKey := "proxy.example.com:3128"
|
||||
res := &countingResolver{answers: map[string][]string{"proxy.example.com": {"203.0.113.7"}}}
|
||||
g.m.interceptor.SetResolver(res)
|
||||
dialer := newRouteDialer(g)
|
||||
dialer.route("203.0.113.7:3128", proxy.Listener.Addr().String())
|
||||
tool := &db.Tool{Key: "probe_rebind_proxy", Kind: "http", Description: "probe",
|
||||
Exec: execJSON(t, map[string]any{"url": "http://" + targetKey + "/", "proxy": "http://" + proxyKey})}
|
||||
if err := g.m.pg.CreateCustomTool(tool); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = g.m.pg.DeleteCustomTool(tool.Key) })
|
||||
built := g.s.buildCustomTool(tool)
|
||||
call := func() (string, bool) { return callTool(t, built, gatedCtx(task, 0), `{}`, nil) }
|
||||
|
||||
approveTarget(t, g, task, built, call, targetKey)
|
||||
approveTarget(t, g, task, built, call, proxyKey)
|
||||
if out, isErr := call(); isErr || !strings.Contains(out, "probe-reached") || proxyHits.Load() != 1 {
|
||||
t.Fatalf("approved proxy: error=%v out=%q hits=%d", isErr, out, proxyHits.Load())
|
||||
}
|
||||
pins, err := g.m.pg.ActiveTargetPins(taskRef(t, task), "proxy.example.com", 3128)
|
||||
if err != nil || len(pins) != 1 || pins[0].NameOnlyEffective ||
|
||||
len(pins[0].PinnedIPs) != 1 || pins[0].PinnedIPs[0] != "203.0.113.7" {
|
||||
t.Fatalf("proxy pin: %+v, %v", pins, err)
|
||||
}
|
||||
|
||||
res.set("proxy.example.com", "203.0.113.9")
|
||||
beforeTarget, beforeProxy, beforeCalls := targetHits.Load(), proxyHits.Load(), len(dialer.calls())
|
||||
out, isErr := call()
|
||||
if !isErr || !strings.Contains(out, "TARGET_APPROVAL_PENDING") || !strings.Contains(out, proxyKey) {
|
||||
t.Fatalf("rebound proxy: error=%v out=%q", isErr, out)
|
||||
}
|
||||
if proxyHits.Load() != beforeProxy || targetHits.Load() != beforeTarget {
|
||||
t.Fatalf("rebound proxy was reached: proxy=%d target=%d",
|
||||
proxyHits.Load()-beforeProxy, targetHits.Load()-beforeTarget)
|
||||
}
|
||||
if got := len(dialer.calls()); got != beforeCalls {
|
||||
t.Fatalf("dialled %v after the rebind", dialer.calls()[beforeCalls:])
|
||||
}
|
||||
}
|
||||
|
||||
// Gate off (sandbox off): the proxy is not checked, as on c03939c1. The tool
|
||||
// URL itself is not checked in that mode either.
|
||||
func TestCustomHTTPOwnProxyGateOffUnchanged(t *testing.T) {
|
||||
g := newGateServer(t)
|
||||
off := false
|
||||
task := g.newTask(t, db.TaskCreateOptions{TargetGate: &off})
|
||||
_, hits, host, port := countingServer(t)
|
||||
tool := g.s.buildCustomTool(&db.Tool{Key: "probe_gate_off", Kind: "http",
|
||||
Exec: execJSON(t, map[string]any{"url": "http://api.example.com/", "proxy": "http://" + host + ":" + port})})
|
||||
if out, isErr := callTool(t, tool, gatedCtx(task, 0), `{}`, nil); isErr || !strings.Contains(out, "probe-reached") || hits.Load() != 1 {
|
||||
t.Fatalf("gate off, loopback proxy: error=%v out=%q hits=%d", isErr, out, hits.Load())
|
||||
}
|
||||
}
|
||||
|
||||
// ARTEX_SANDBOX=required with the gate on: the proxy is checked by the sandbox
|
||||
// egress policy only, as on c03939c1. A proxy inside the sandbox scope and
|
||||
// never approved in the gate is dialled, and no gate request opens on it.
|
||||
func TestSandboxHTTPToolGatedProxyUnchanged(t *testing.T) {
|
||||
g := newGateServer(t)
|
||||
on := true
|
||||
task := g.newTask(t, db.TaskCreateOptions{TargetGate: &on})
|
||||
target, targetHits := canaryServer(t, "127.0.0.1", nil)
|
||||
proxy, proxyHits := canaryServer(t, "127.0.0.2", nil)
|
||||
targetKey := strings.TrimPrefix(target.URL, "http://")
|
||||
proxyKey := strings.TrimPrefix(proxy.URL, "http://")
|
||||
sandboxRequired(t)
|
||||
call := func(exec map[string]any) (string, bool) {
|
||||
tool := g.s.buildCustomTool(&db.Tool{Key: "probe_sb_proxy", Kind: "http", Exec: execJSON(t, exec)})
|
||||
ctx := agent.WithSandboxRunInfo(gatedCtx(task, 0), agent.SandboxRunInfo{
|
||||
TaskID: task.ID, ScopeCIDRs: []string{"127.0.0.1/32", "127.0.0.2/32"},
|
||||
})
|
||||
return callTool(t, tool, ctx, `{}`, nil)
|
||||
}
|
||||
direct := map[string]any{"method": "GET", "url": target.URL + "/"}
|
||||
directTool := g.s.buildCustomTool(&db.Tool{Key: "probe_sb_proxy", Kind: "http", Exec: execJSON(t, direct)})
|
||||
approveTarget(t, g, task, directTool, func() (string, bool) { return call(direct) }, targetKey)
|
||||
before := targetHits.Load()
|
||||
out, isErr := call(map[string]any{"method": "GET", "url": target.URL + "/", "proxy": proxy.URL})
|
||||
if isErr || !strings.Contains(out, "CANARY_BODY") || proxyHits.Load() != 1 || targetHits.Load() != before {
|
||||
t.Fatalf("required mode, in-scope proxy: error=%v out=%q proxy hits=%d", isErr, out, proxyHits.Load())
|
||||
}
|
||||
if _, _, _, ok := openTargetRequest(t, g.m.pg, task.ID, proxyKey); ok {
|
||||
t.Fatal("required mode opened a gate request on the proxy")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package server
|
||||
|
||||
import "testing"
|
||||
|
||||
// The gate reads a tool proxy without its credentials, with the port a socks5
|
||||
// proxy without one is dialled on.
|
||||
func TestGateProxyURL(t *testing.T) {
|
||||
for in, want := range map[string]string{
|
||||
"http://user:pw@10.0.0.5:8080": "http://10.0.0.5:8080",
|
||||
"socks5://user:pw@10.0.0.5": "socks5://10.0.0.5:1080",
|
||||
"socks5h://[::1]": "socks5h://[::1]:1080",
|
||||
"socks5://10.0.0.5:9050": "socks5://10.0.0.5:9050",
|
||||
"https://proxy.example": "https://proxy.example",
|
||||
"http://": "",
|
||||
} {
|
||||
if got := gateProxyURL(in); got != want {
|
||||
t.Fatalf("gateProxyURL(%q) = %q, want %q", in, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
+10
-2
@@ -3764,9 +3764,17 @@ func (s *Server) getTraffic(w http.ResponseWriter, r *http.Request) {
|
||||
pq.MatchNone = q.Get("company") != "" && len(hosts) == 0 // a company owning no host matches nothing
|
||||
ex, matched, _ := tr.Page(pq, page, size)
|
||||
count, _ := tr.Count() // global total, for the stat card
|
||||
enabled := s.m.TrafficEnabled()
|
||||
// The proxy agents use: the local recording proxy with capture on, else
|
||||
// the global egress proxy, which may carry user:pass and is masked as in
|
||||
// GET /api/settings.
|
||||
proxy := maskedSecret(s.m.GlobalProxy())
|
||||
if enabled {
|
||||
proxy = tr.ProxyAddr()
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{
|
||||
"enabled": s.m.TrafficEnabled(), // reflect the capture toggle
|
||||
"proxy": s.m.ProxyAddr(),
|
||||
"enabled": enabled, // reflect the capture toggle
|
||||
"proxy": proxy,
|
||||
"count": count, // total recorded (unfiltered)
|
||||
"total": matched, // rows matching the current filter (for pagination)
|
||||
"page": page,
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Autumn-27/artex/traffic"
|
||||
)
|
||||
|
||||
// GET /api/traffic names the proxy agents use. With capture off that is the
|
||||
// global egress proxy, which may carry user:pass: it is masked as in
|
||||
// GET /api/settings. With capture on it is the local recording proxy, shown
|
||||
// as is.
|
||||
func TestGetTrafficMasksGlobalProxy(t *testing.T) {
|
||||
tr, err := traffic.Open(t.TempDir(), ":0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { tr.Close() })
|
||||
get := func(m *Manager) string {
|
||||
t.Helper()
|
||||
w := httptest.NewRecorder()
|
||||
(&Server{m: m}).getTraffic(w, httptest.NewRequest(http.MethodGet, "/api/traffic", nil))
|
||||
if w.Code != http.StatusOK || strings.Contains(w.Body.String(), "gp-secret") {
|
||||
t.Fatalf("GET /api/traffic: HTTP %d or the proxy password returned in clear: %s", w.Code, w.Body.String())
|
||||
}
|
||||
var body struct {
|
||||
Proxy string `json:"proxy"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return body.Proxy
|
||||
}
|
||||
const gp = "http://user:gp-secret@lab-proxy:8080"
|
||||
if got := get(&Manager{traffic: tr, globalProxy: gp}); got != "__masked__" {
|
||||
t.Fatalf("capture off: proxy = %q, want __masked__", got)
|
||||
}
|
||||
if got := get(&Manager{traffic: tr}); got != "" {
|
||||
t.Fatalf("capture off, no global proxy: proxy = %q, want empty", got)
|
||||
}
|
||||
if got := get(&Manager{traffic: tr, globalProxy: gp, trafficOn: true}); got != tr.ProxyAddr() {
|
||||
t.Fatalf("capture on: proxy = %q, want the recording proxy %q", got, tr.ProxyAddr())
|
||||
}
|
||||
}
|
||||
|
||||
// The proxy value GET /api/traffic returns, sent back to PUT /api/settings,
|
||||
// keeps the stored global proxy; a refused proxy does not echo its password.
|
||||
func TestTrafficProxyRoundTripKeepsGlobalProxy(t *testing.T) {
|
||||
s, _, request := trafficEvidenceServer(t)
|
||||
pg := s.m.PG()
|
||||
t.Cleanup(func() { pg.Exec(`DELETE FROM settings WHERE key IN ('global_proxy','traffic_capture')`) })
|
||||
const gp = "http://user:gp-secret@lab-proxy:8080"
|
||||
if w := request("PUT", "/api/settings", `{"global_proxy":"`+gp+`","traffic_capture":false}`); w.Code != 200 {
|
||||
t.Fatalf("PUT /api/settings: HTTP %d %s", w.Code, w.Body.String())
|
||||
}
|
||||
w := request("GET", "/api/traffic", "")
|
||||
if w.Code != 200 || strings.Contains(w.Body.String(), "gp-secret") {
|
||||
t.Fatalf("GET /api/traffic: HTTP %d or the proxy password returned in clear: %s", w.Code, w.Body.String())
|
||||
}
|
||||
var got struct {
|
||||
Proxy string `json:"proxy"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w := request("PUT", "/api/settings", `{"global_proxy":"`+got.Proxy+`"}`); w.Code != 200 {
|
||||
t.Fatalf("PUT /api/settings with the value read back: HTTP %d %s", w.Code, w.Body.String())
|
||||
}
|
||||
if v, _, err := pg.GetSetting("global_proxy"); err != nil || v != gp || s.m.GlobalProxy() != gp {
|
||||
t.Fatalf("stored global proxy after the round trip = %q / %q (%v), want it unchanged", v, s.m.GlobalProxy(), err)
|
||||
}
|
||||
for _, bad := range []string{"http://user:gp-secret@", "user:gp-secret@lab-proxy:8080", "http://user:gp-secret@lab proxy:8080", "ftp://user:gp-secret@lab-proxy:21"} {
|
||||
w := request("PUT", "/api/settings", `{"global_proxy":"`+bad+`"}`)
|
||||
if w.Code != 400 || strings.Contains(w.Body.String(), "gp-secret") || strings.Contains(w.Body.String(), "user") {
|
||||
t.Fatalf("PUT /api/settings %q: HTTP %d %s, want a 400 that does not quote the address", bad, w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
if v, _, _ := pg.GetSetting("global_proxy"); v != gp {
|
||||
t.Fatalf("a refused proxy replaced the stored one: %q", v)
|
||||
}
|
||||
}
|
||||
+24
-1
@@ -1,6 +1,9 @@
|
||||
package traffic
|
||||
|
||||
import "testing"
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestValidateProxyURL(t *testing.T) {
|
||||
ok := []string{
|
||||
@@ -27,6 +30,26 @@ func TestValidateProxyURL(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// Validation errors reach the PUT /api/settings response and logs: they never
|
||||
// quote the address, which may carry a password.
|
||||
func TestValidateProxyURLErrorsOmitAddress(t *testing.T) {
|
||||
for _, raw := range []string{
|
||||
"http://user:pw-secret@", // no host
|
||||
"user:pw-secret@proxy.example:3128", // no scheme, parsed as scheme "user"
|
||||
"http://user:pw-secret@bad host:3128", // url.Parse error, which quotes its input
|
||||
"ftp://user:pw-secret@proxy.example:21", // unsupported scheme
|
||||
"//user:pw-secret@proxy.example:3128", // no scheme
|
||||
} {
|
||||
_, err := ValidateProxyURL(raw)
|
||||
if err == nil {
|
||||
t.Fatalf("ValidateProxyURL(%q) expected error", raw)
|
||||
}
|
||||
if strings.Contains(err.Error(), "pw-secret") || strings.Contains(err.Error(), "user") {
|
||||
t.Fatalf("ValidateProxyURL(%q) error quotes the address: %v", raw, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetUpstreamProxyStoreClear(t *testing.T) {
|
||||
tr := &Traffic{}
|
||||
if got := tr.upstream.Load(); got != nil {
|
||||
|
||||
+6
-4
@@ -563,21 +563,23 @@ func (t *Traffic) RewriteRules() *rewrite.Set { return t.rewriteRules.Load() }
|
||||
// ValidateProxyURL parses and checks a proxy URL (http/https/socks5, optional
|
||||
// user:pass), returning the parsed URL. Exposed so callers can validate a global
|
||||
// proxy before persisting it even when the traffic proxy itself is disabled.
|
||||
// Errors never quote the address (nor the url.Parse error, which does): it may
|
||||
// carry a password, and callers return them to the client.
|
||||
func ValidateProxyURL(raw string) (*url.URL, error) {
|
||||
raw = strings.TrimSpace(raw)
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse proxy address %q: %w", raw, err)
|
||||
return nil, errors.New("proxy address is not a valid URL")
|
||||
}
|
||||
switch u.Scheme {
|
||||
case "http", "https", "socks5":
|
||||
case "":
|
||||
return nil, fmt.Errorf("proxy %q is missing a scheme (use http://, https://, or socks5://)", raw)
|
||||
return nil, errors.New("proxy address is missing a scheme (use http://, https://, or socks5://)")
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported proxy scheme %q (use http, https, or socks5)", u.Scheme)
|
||||
return nil, errors.New("unsupported proxy scheme (use http, https, or socks5)")
|
||||
}
|
||||
if u.Host == "" {
|
||||
return nil, fmt.Errorf("proxy %q is missing a host", raw)
|
||||
return nil, errors.New("proxy address is missing a host")
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user