Skip to content

Smaller performance costs: cap walk, wordlist copies, serial AXFR, -dL, MCP queue #365

Closed

Description

@TMHSDigital

Summary

Costs that matter only for large inputs or long-running servers. Each item states the size at which it shows.

1. Budget cap in a scan with a visited set walks and builds every unscheduled candidate

  • Where: internal/scan/dispatcher.go:221-252, internal/scan/dispatcher.go:376-380, internal/scan/dispatcher.go:320-327
  • What happens: When -max-queries or -max-duration stops admission and d.visited != nil (see the finding above), stopAdmitting loops over every remaining (expansion, entry) pair and concatenates a name for each one: for _, e := range d.frontier[d.head:] { for i := e.next; i < d.n; i++ { entry := d.cfg.Entries[i]; name := entry + "." + e.parent; ... d.visited[key] ...; if d.cfg.scope.excluded(name) {...} } } (dispatcher.go:228-246). Each found parent queues d.remaining += d.n candidates (dispatcher.go:379-380), so the walk is O(queued parents x wordlist length). It runs on the dispatcher goroutine, which meanwhile does not drain completed or answer cancellation.
  • Impact: This only applies to recursive scans with a visited set, which the finding above shows is the norm when passive sources are on. At the cap, a 100k-entry list with 200 queued parents makes 20M iterations: about 2 s of CPU and about 0.8 GB of short-lived strings. A 1M-entry list makes 200M iterations: about 20 s and about 8 GB of garbage. The scan stalls at the very point the user's budget said it should stop, and the -max-duration deadline overruns by that amount. The figures are estimates (about 100 ns and about 40 B per iteration), not measured.
  • To see it: Static. Use -recursive -max-queries 100000 -w <100k-line list containing one dotted line> against a target where many depth-1 names resolve (for example a lab zone with a * record under found names disabled). Time from the cap notice to EventDone.
  • Suggested fix: (1) Skip building name when d.cfg.scope.empty(): depth-1 keys are the entry itself. (2) For depth > 1, build the key in one reused []byte and look it up with d.visited[string(buf)], which Go does without allocating. (3) Better: count the duplicates per expansion without walking. Only multi-label entries can collide, so iterate just those (a small list) per queued expansion and count the matches, then skip left - dupes in O(1), as countUnbuilt already does for exclusions.

2. Merging passive-source names copies the whole wordlist slice once per target

  • Where: internal/passive/passive.go:95-98, internal/wordlist/reader.go:274-282, internal/candidates/candidates.go:64-72, internal/cli/session.go:676-684
  • What happens: Prepared.For returns the shared entries with capacity equal to their length: return p.entries[:len(p.entries):len(p.entries)], ... ("appending to it copies", reader.go:272-281). passive.Merge then does return append(entries, added...), added (passive.go:98). So the first source that adds even one name reallocates and copies the full slice of string headers (16 bytes per entry), and Go's growth for large slices rounds the new capacity up by about 1.25x. Prepared keeps the original slice for the next -dL target (reader.go:150-152), so both copies are live at once during the scan.
  • Impact: About 20 extra bytes per wordlist entry for each target scanned with -sources/-ct/-axfr: about 40 MB on a 2M-line list and about 100 MB on a 5M-line list. That is on the order of a quarter of the 98 MB per 1M candidates measured by BenchmarkRun1M. The cost is small next to DNS time, but it works against the per-entry memory work of Large wordlists peak at ~150 B/entry: raw lines, visited map, per-source sets #248, which cut entry counts to 4 bytes.
  • To see it: Static. Use -w <5M-line list> -sources ct <target> and compare peak RSS with the same run without -sources.
  • Suggested fix: Keep the source names apart from the wordlist slice. Have scan.Config take a second Extra []string that the dispatcher indexes after Entries (resume positions stay len(Entries)+i), or have candidates.Set hold base, extra and expose an accessor. The engine then never needs one contiguous copy.

3. Zone transfer tries every name-server address serially with a 10 s floor each

  • Where: internal/axfr/axfr.go:107-147, internal/axfr/axfr.go:19-23, internal/dns/axfr.go:38-51
  • What happens: transferTimeout := max(MinTimeout, o.Timeout) with MinTimeout = 10 * time.Second (axfr.go:21, 107). The loop for _, ns := range servers { ... for _, addr := range addrs { ... got, err := dns.Transfer(ctx, net.JoinHostPort(addr, o.Port), target, transferTimeout) ... (axfr.go:108-131) runs one server address at a time, up to MaxServers (8) x AddrsPerServer (2). Each Transfer dials TCP under that 10 s context (dns/axfr.go:40-43), so a server whose TCP/53 is silently dropped by a firewall costs the full 10 s. A refusing server answers at once. The two addresses per server are tried in turn after a timeout, but after a success the loop breaks (axfr.go:145).
  • Impact: -axfr runs before the scan for each target (session.go:686-690). A target whose 8 name servers silently drop TCP/53 delays the scan by up to 16 x 10 s = 160 s, plus the A/AAAA lookups. With -dL the delay repeats for every such target. Running the servers concurrently would bound it near one timeout (about 10-20 s). This needs a firewall that drops rather than rejects TCP/53, which is common for self-hosted BIND/NSD but not for the large managed DNS providers, hence medium confidence that the case matters in practice.
  • To see it: Static. Point -axfr (via its test port hook) at 8 NS names whose addresses are unroutable or blackholed (for example in 192.0.2.0/24) and time axfr.Try.
  • Suggested fix: Run the per-server attempts concurrently (one goroutine per name server, at most MaxServers), keeping the existing per-server address order and the break on success, and merge names, Allowed, Tried and Queries under a mutex. Probe the denial once, before the loop, using the first resolved address.

4. -dL runs wait for each target's passive sources and zone transfer before its scan, serially

  • Where: internal/cli/session.go:626-630, internal/cli/session.go:676-695, internal/cli/session.go:718, internal/cli/ct.go:36-67, internal/cli/axfr.go:43, internal/ct/ct.go:59-63, internal/passive/wayback.go:55-59
  • What happens: scanAll scans targets one after another (session.go:626-630). Inside scanOneTarget, the passive lookups (passiveNames, which ends in wg.Wait(), ct.go:67) and then the -axfr zone transfer (zoneTransfer -> axfr.Try, axfr.go:43) both run to completion before s.mainPass starts (session.go:678-694, 718). Nothing is fetched ahead, so while target i is scanned no HTTP or AXFR work runs for target i+1, and while target i+1's crt.sh request runs no DNS work runs. Within a target, the sources and the zone transfer also run one after the other (session.go:678 then 689), although they are independent and both only add names to cands. Each source lookup may take up to 60 s by default (ct.go:59-63, wayback.go:55-59, plus retryhttp back-off), and crt.sh answers for popular domains often take tens of seconds.
    sourceInfo := passiveNames(ctx, s.in.sources, target, saved, out, s.a.sourceURLs) // blocks on wg.Wait
    ...
    axfrInfo = zoneTransfer(ctx, s.f, s.a.transferPort(), target, saved, out)       // then blocks again
    ...
    res := s.mainPass(ctx, pass, mainSaved)                                         // only now the scan
  • Impact: subenum -dL scope.txt -ct (or -sources ct,wayback -axfr) on a bug-bounty scope list: wall clock is the sum over targets of fetch time + AXFR time + scan time. With the bundled 5000-word list and default unlimited rate a target's scan takes seconds, so the serial fetch can be most of the run; e.g. 200 targets x ~20 s of crt.sh = over an hour in which the resolver sits idle. Overlapping hides min(fetch, scan) per target and running sources and AXFR together hides min(sources, axfr). Estimate from the timeouts and code structure, not measured (no live sources allowed in this audit).
  • To see it: Hermetic shape: run -dL with two or more targets and -sources ct pointed at a local HTTP stub that sleeps 10 s per request (tests already inject sourceURLs), with -simulate-zone/lab DNS; total time grows by ~10 s per target with the DNS side idle during each sleep.
  • Suggested fix: Start the next target's passiveNames (and its zoneTransfer) in a goroutine when the current target's main pass starts, with a lookahead of one so crt.sh still sees one request at a time; buffer that lookup's Info/Warning lines and print them when the target starts. Within a target, run passiveNames and zoneTransfer concurrently and cands.Add in the existing order (sources, then axfr) after both return. Resume semantics are unchanged as long as a prefetched lookup for a target that never started is not saved (savedSources(..., scanned=false) already leaves it out, resume.go:485-499).

5. MCP server queues unlimited tool calls, each holding its arguments (up to 16 MB) in memory

  • Where: internal/mcp/mcp.go:30, internal/mcp/mcp.go:138-173, internal/mcp/mcp.go:244-256, internal/mcp/mcp.go:312-339
  • What happens: The reader goroutine reads lines without back-pressure (mcp.go:141-157) and the main loop hands each to dispatch (mcp.go:172), which starts a goroutine per request at once (ss.wg.Go, mcp.go:247). Tool calls then serialise on the one-slot ss.calls semaphore (mcp.go:333-338), so every call behind a running one waits as a parked goroutine. Each keeps its req alive; json.Unmarshal copies Params into the json.RawMessage (mcp.go:221), and a line may be up to maxMessage = 16 << 20 bytes (mcp.go:30). There is no cap on queued calls.
    ss.wg.Go(func() {               // one goroutine per request, no limit
    ...
    result, rerr := ss.handle(ctx, req)   // tools/call -> blocks on ss.calls
  • Impact: An agent that pipelines requests, such as many diff calls carrying whole results files while a scan or lab_scan holds the slot for up to -max-duration (2 min by default), makes the server hold about 16 MB per queued call: 100 queued calls is about 1.6 GB resident until they drain. The client is the operator's own agent, so this is a memory-growth and robustness cost, not a remote attack. The figure is computed from the code, not measured.
  • To see it: Start subenum mcp. Send a tools/call for lab_scan with scenario: lab5-... (slow timeouts) to occupy the slot. Without waiting, send N tools/call diff requests whose previous argument is about 15 MB. The process RSS grows by about 15 MB per request until the lab scan ends.
  • Suggested fix: Bound the work in flight. Either make dispatch acquire a counting semaphore of, say, 8 pending requests before wg.Go, so the reader stops reading and stdio applies back-pressure, or reject tools/call with an InvalidRequest "too many pending calls" error when the queue is full. Keep ping and notifications/cancelled outside the limit so cancellation still works.

Acceptance criteria

  • Budget cap in a scan with a visited set walks and builds every unscheduled candidate
  • Merging passive-source names copies the whole wordlist slice once per target
  • Zone transfer tries every name-server address serially with a 10 s floor each
  • -dL runs wait for each target's passive sources and zone transfer before its scan, serially
  • MCP server queues unlimited tool calls, each holding its arguments (up to 16 MB) in memory

Getting started

  • Relevant files: internal/scan/dispatcher.go, internal/passive/passive.go, internal/wordlist/reader.go, internal/candidates/candidates.go, internal/cli/session.go, internal/axfr/axfr.go
  • How to run tests: go test ./... (tests must stay hermetic: use -simulate, a lab zone or internal/dnstest, never a live domain)
  • Related docs: docs/DEVELOPER_GUIDE.md, docs/ARCHITECTURE.md

Filed by repo-audit/full-audit at 0f3b0b6. Severity: low. Effort: M. audit-key: performance|internal/scan/dispatcher.go|small-costs

Activity

  1. added
    help wanted
    performance
    severity: low
    on Nov 16, 2026
  2. TMHSDigital commented on Nov 17, 2026

    @TMHSDigital
    OwnerAuthor

    Partial fix in 3cc069c: items 1, 3 and 5 are done; 2 and 4 remain.

    1. Budget cap walk (fixed). With a multi-label entry and no -exclude, a cap now walks only the entries that are a multi-label entry or a label prefix of one (the only ones that can begin a repeated name) and counts the rest in O(1) per queued expansion. BenchmarkCapRecursiveDotted (100k entries + one dotted, 200 found parents): 2.2 s / 483 MB / 20.1M allocs per op before, 1.9 ms / 0.16 MB / 443 allocs after. TestCapCountsRepeatsWithoutWalking checks that admitted + skipped equals the uncapped scan's candidates at every cap point, and that 500k capped candidates make under 5000 allocations (510k before). With -exclude and multi-label entries the walk is still needed, as countUnbuilt cannot place multi-label entries under a pattern (#361).

    3. Serial AXFR (fixed). Name servers are asked concurrently, each server's addresses still in order with the break on success; messages are buffered and printed in server order. The denial probe is still sent to the first address that answers, before the transfers. TestTryAsksNameServersAtOnce (8 local servers whose transfers stall 2 s): 16.9 s with 1 transfer in flight before, 0.02 s with all 8 in flight after.

    5. MCP queue (fixed). A session holds at most 8 tools/call requests, running or waiting; the next gets an invalid-request error "too many tool calls pending". ping and notifications/cancelled are not counted. Retained queued calls go from unbounded to at most 8 (about 128 MB worst case at the 16 MB line limit). TestPendingToolCallsAreBounded hangs without the bound and passes with it.

    Not done:

    • 2. Passive merge copies the wordlist slice: still valid (passive.Merge appends to the capacity-capped slice from Prepared.For). Avoiding the copy means a second Extra entries slice threaded through scan.Config, the dispatcher, resume positions and pkg/subenum. That is a wider engine change than this bundle, for about 20 B per entry.
    • 4. -dL prefetch / sources and AXFR in parallel: still valid. It changes when each target's source and AXFR messages print, and how a prefetched lookup for a target that never starts interacts with resume. That needs its own design and tests.

    Verified with the full gate (gofmt, go vet, golangci-lint v2.15.0, go test ./...), and each new test was checked to fail without its fix.

  3. TMHSDigital commented on Nov 19, 2026

    @TMHSDigital
    OwnerAuthor

    Partial fix in 100b959, for item 4's in-target half.

    Done:

    • 4a. Sources and zone transfer in parallel. A target's -axfr transfer now runs in a goroutine while its passive sources are asked. The transfer's lines are held and printed after the sources' lines, and its names are added after theirs, so the messages, the candidate order and the resume positions are unchanged. TestE2EZoneTransferOverlapsSources uses a CT stub that answers only once the transfer has been asked for. It takes 3.03 s and fails without the change, and 0.02 s with it.

    Still open:

    • 4b. Fetch ahead across -dL targets. This means starting target i+1's sources while target i scans. Prefetched lines have to be held per target, and a prefetched lookup for a target that never starts must stay out of the resume state.
    • 2. Passive merge copies the wordlist slice. This needs an Extra entries slice threaded through scan.Config, the dispatcher, the resume positions and pkg/subenum.

    Verified with go test ./..., -race on the AXFR and overlap tests, and golangci-lint v2.15.0.

  4. TMHSDigital commented on Nov 21, 2026

    @TMHSDigital
    OwnerAuthor

    The rest of this is fixed in 2dcd905 (item 4b) and 5974093 (item 2). All five items are now done.

    4b. Fetch ahead across -dL targets (2dcd905). Once a target's own source lookups and zone transfer (or NSEC walk) finish, the next target's start in a goroutine while the current target scans. Only one target is fetched ahead, so crt.sh still gets one request at a time. The prefetched lookup's Warning/Note and zone-transfer lines are held and printed when that target starts, under its own === [i/n] header, so the output order doesn't change. A prefetched result is only used by its own target. If that target never starts (interrupt, resolver abort), nothing reaches s.results, so the resume state leaves it out and the resumed run asks the source again. The prefetch context is cancelled and waited on when the target loop ends. The zone lookup runs through the same zoneTransfer path, so -nsec-walk and the parent NS lookup work the same way in the prefetch.

    • TestE2EFetchesNextTargetAhead: two -dL targets. The first target's www lookup is answered only after the second target's CT request has arrived. It takes 0.02 s with the change. Without it, it fails after 3.03 s ("asked only after the first target's scan"). The test also checks that the CT stub never had more than one request at a time, and that the second target's source line prints after its header.
    • TestE2EResumeLeavesOutLookupFetchedAhead: an interrupt during the first target's scan, after the second target's lookup was fetched ahead. The state has no CT names for the second target, nothing about it was printed, and -resume fetches it again and finds its name.

    2. Source names no longer copy the wordlist (5974093). candidates.Set keeps added names (sources, -axfr, -nsec-walk, -srv) in a separate list (Set.Lists). The scan takes that list as the new scan.Config.Extra, and the dispatcher indexes it after Entries (resume positions stay len(Entries)+i). Pending roots, the recursion ceiling and the budget-cap counts (including countUnbuiltRepeats) all use the combined view. Without -recursive-w, a recursive scan still tries Extra under each name it finds. The -permute and -ptr passes check their candidates against both lists. passive.Merge now only returns the new names and doesn't write to either list. pkg/subenum's public API is unchanged: run passes the two lists through internally.

    • TestAddDoesNotCopyEntries: 1M entries with no spare capacity (the way Prepared.For hands them out), plus one new source name. With the old append it allocated 20,014,176 bytes. Now it allocates under 1 MB, and Lists returns the caller's own slice.
    • TestExtraIsIndexedAfterEntries: for flat and recursive scans, splitting the list into Entries + Extra gives the same names and stats as one joined list. That holds for a resume position inside Extra and for a cap with multi-label entries in Extra. The test fails if the engine ignores Extra.

    Verified with the full gate: gofmt, go vet, golangci-lint v2.15.0, go test -shuffle=on ./..., go mod tidy -diff. I also ran -race on the scan, candidates, pkg/subenum and related cli tests. CI is green on both commits.

    Left as is: the TUI still joins the two lists (Set.Entries) for its single scan. It has no per-target shared wordlist, so the copy there happens once per scan, not once per -dL target.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    help wantedperformanceseverity: low

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions