Skip to content

fix(subscraping): cap untrusted source response bodies with a size limit - #1809

Merged
Mzack9999 merged 2 commits into
projectdiscovery:devfrom
adamsjack711-ux:security/cap-response-body-size
Aug 10, 2026
Merged

Mzack9999 merged 2 commits into
projectdiscovery:devfrom
adamsjack711-ux:security/cap-response-body-size

Conversation

@adamsjack711-ux

@adamsjack711-ux adamsjack711-ux commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Passive-source HTTP responses were read with unbounded io.ReadAll(resp.Body) (and json.Decoder / bufio.Scanner) across the source implementations. A malicious, compromised, or MITM'd upstream API returning a very large body can drive the process to OOM — the client timeout bounds time, not size (and NewSession sets InsecureSkipVerify: true).

This caps response bodies centrally at the session layer so every source inherits the limit regardless of how it reads the body.

Changes

  • pkg/subscraping/agent.go: added maxResponseBodySize = 50 * 1024 * 1024 (50MB) and a LimitResponseBody helper that wraps resp.Body in an io.LimitReader while preserving Close. Applied in the shared httpRequestWrapper (covers Get / SimpleGet / Post / SimplePost / HTTPRequest).
  • pkg/subscraping/sources/threatcrowd/threatcrowd.go: applied the same helper to its raw session.Client.Do call, which bypasses the wrapper.
  • pkg/subscraping/agent_test.go: unit tests for the cap (oversized body truncated, small body untouched, nil-safe, Close propagation).

50MB is generous enough that legitimate large subdomain lists are unaffected. No timeout, concurrency, or source logic changed.

Testing

go build ./... and go test ./pkg/... pass.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added an optional maximum response-size limit for passive HTTP enumeration.
    • Added --response-size-read / -rsr configuration, with unlimited reading by default.
    • Invalid negative size limits are rejected.
    • Response bodies remain safely closable when limits are applied.
  • Bug Fixes

    • Prevented oversized or continuously streamed responses from consuming excessive resources.
    • Applied response-size protection to ThreatCrowd data retrieval.
  • Documentation

    • Documented the new response-size setting and command-line options.
  • Tests

    • Added coverage for capped, uncapped, small, nil, and streamed responses.

Passive sources read third-party (and, since TLS verification is skipped,
potentially MITM'd) HTTP response bodies with unbounded io.ReadAll /
json.Decoder / bufio.Scanner. The client Timeout bounds time, not size, so a
malicious or compromised upstream could stream an effectively unbounded body
and OOM the process.

Cap the body centrally at the session layer (httpRequestWrapper) so every
source inherits the limit regardless of how it consumes the body. The
threatcrowd source issues a raw session.Client.Do, bypassing the wrapper, so it
opts in explicitly via the exported LimitResponseBody helper. The wrapper
preserves the original body's Close, so no body/connection leak.

50MB cap is generous enough that legitimate large subdomain lists are
unaffected.

Co-Authored-By: Claude Fable 5 <[email protected]>

Signed-off-by: Jack Adams-Lovell <[email protected]>
@coderabbitai

coderabbitai Bot commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 7b9c69dc-8ff5-4f57-be8a-476cb796223d

📥 Commits

Reviewing files that changed from the base of the PR and between b3d955c and 7946c6e.

📒 Files selected for processing (9)
  • README.md
  • pkg/passive/passive.go
  • pkg/runner/enumerate.go
  • pkg/runner/options.go
  • pkg/runner/validate.go
  • pkg/subscraping/agent.go
  • pkg/subscraping/agent_test.go
  • pkg/subscraping/sources/threatcrowd/threatcrowd.go
  • pkg/subscraping/types.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • pkg/subscraping/sources/threatcrowd/threatcrowd.go

Walkthrough

Adds configurable response-body size limits for passive HTTP sources. The limit flows from runner options into sessions and applies to shared requests and the ThreatCrowd direct request path. Tests cover capped, unlimited, nil, and close-propagation behavior.

Changes

Response body limits

Layer / File(s) Summary
Limit configuration and session propagation
pkg/runner/..., pkg/passive/passive.go, pkg/subscraping/types.go, README.md
Adds the --response-size-read/-rsr option, validates nonnegative values, documents the setting, and passes it into passive enumeration sessions.
Response body limit contract
pkg/subscraping/agent.go, pkg/subscraping/agent_test.go
Adds LimitResponseBody with unlimited and nil-safe behavior. The wrapper preserves close propagation and caps oversized reads.
HTTP response enforcement
pkg/subscraping/agent.go, pkg/subscraping/agent_test.go, pkg/subscraping/sources/threatcrowd/threatcrowd.go
Applies the limit before response processing in shared requests and the ThreatCrowd direct path. Integration tests verify capped and unlimited responses.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Suggested reviewers: mzack9999

Poem

A rabbit bounds the bytes that flow,
With closures safe from start to slow.
Shared requests hop within the line,
ThreatCrowd follows the same design.
“Read safely!” says the rabbit fine.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: limiting untrusted passive-source response bodies to reduce resource risks.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
pkg/subscraping/agent.go (1)

30-53: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Consider surfacing when truncation actually happened.

io.LimitReader truncates silently — callers get exactly maxResponseBodySize bytes and an io.EOF, with no way to tell "response was small" from "response got cut off at the cap." For any source whose body-consumption path doesn't strictly validate format (e.g., line-based scanners), a truncated response could yield partial results with no error. Worth considering a small wrapper that flags/logs when the cap was actually hit (e.g., track bytes read and compare to the limit, or peek one extra byte), so operators can distinguish "legit small body" from "cap enforced against an oversized/malicious response."

♻️ Illustrative direction (not a full fix)
 type limitedResponseBody struct {
-	io.Reader // io.LimitReader over the original body
+	*io.LimitedReader // exposes N (remaining bytes) so callers can detect truncation
 	io.Closer // the original body's Close
 }

 func LimitResponseBody(response *http.Response) {
 	if response == nil || response.Body == nil {
 		return
 	}
+	lr := &io.LimitedReader{R: response.Body, N: maxResponseBodySize}
 	response.Body = &limitedResponseBody{
-		Reader: io.LimitReader(response.Body, maxResponseBodySize),
+		LimitedReader: lr,
 		Closer: response.Body,
 	}
 }

Callers/other helpers could then check lr.N == 0 after reading to know the cap was hit and log a warning.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pkg/subscraping/agent.go` around lines 30 - 53, Update limitedResponseBody
and LimitResponseBody to detect whether reads consume the full
maxResponseBodySize and whether an additional byte exists, exposing that
truncation state to callers after consumption. Preserve the existing reader and
Close behavior while ensuring small responses are not marked truncated and
capped oversized responses can be distinguished and logged by their callers.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@pkg/subscraping/agent_test.go`:
- Around line 93-94: Update the request setup in the test to use
http.NewRequestWithContext instead of http.NewRequest, supplying an appropriate
context and preserving the existing GET method, server URL, and error assertion;
add the context import required by this change.

---

Nitpick comments:
In `@pkg/subscraping/agent.go`:
- Around line 30-53: Update limitedResponseBody and LimitResponseBody to detect
whether reads consume the full maxResponseBodySize and whether an additional
byte exists, exposing that truncation state to callers after consumption.
Preserve the existing reader and Close behavior while ensuring small responses
are not marked truncated and capped oversized responses can be distinguished and
logged by their callers.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 39717648-4017-4403-9017-a7e4ecaa7009

📥 Commits

Reviewing files that changed from the base of the PR and between d0ea102 and b3d955c.

📒 Files selected for processing (3)
  • pkg/subscraping/agent.go
  • pkg/subscraping/agent_test.go
  • pkg/subscraping/sources/threatcrowd/threatcrowd.go

Comment thread pkg/subscraping/agent_test.go Resolved
@dogancanbakir
dogancanbakir requested a review from Mzack9999 August 5, 2026 15:16
@Mzack9999

Copy link
Copy Markdown
Member

Thanks for the hardening PR. The central LimitReader on the session path is a clean place for this.

Before merging:

  1. Did you hit a real OOM from an oversized passive-source response (repro, source, or crash dump), or is this preventive? We only found an old large-scan memory issue (Exceptionally large scan - out of memory #41), not one tied to unbounded HTTP bodies.

  2. Default behavior: subfinder’s goal is to return as many subdomains as sources provide. A hard size cap changes that by truncating large legitimate responses. Prefer keeping current behavior as the default and making a body-size limit optional (flag / config) for operators who want the memory guard.

@Mzack9999
Mzack9999 merged commit 717f59d into projectdiscovery:dev Aug 10, 2026
9 checks passed
social4hyq pushed a commit to social4hyq/homebrew-core that referenced this pull request Sep 20, 2026
subfinder 2.16.0

Created-by: HarmonybrewBot
Commit-by: HarmonybrewBot
Merged-by: HarmonybrewBot
Description: Created by `brew bump`

---

Created with `brew bump-formula-pr`.<details>
  <summary>release notes</summary>
  <pre><!-- Release notes generated using configuration in .github/release.yml at main -->

## What's Changed

* feat(sources): honor -max-results across paginating sources by @Gerijacki in projectdiscovery/subfinder#1810
* fix(extractor): match the target domain literally and reject partial hosts by @Gerijacki in projectdiscovery/subfinder#1811
* fix(subscraping): cap untrusted source response bodies with a size limit by @adamsjack711-ux in projectdiscovery/subfinder#1809
* fix(subscraping): use DialContext instead of the deprecated Dial by @jonaslejon in projectdiscovery/subfinder#1835
* feat: add scanmalware passive source by @jonaslejon in projectdiscovery/subfinder#1834
* fix(crtsh): set statement_timeout via SQL query to avoid PgBouncer handshake rejection (#1828) by @gcoinstash-cmd in projectdiscovery/subfinder#1832

## New Contributors
* @J12934 made their first contribution in projectdiscovery/subfinder#1823
* @adamsjack711-ux made their first contribution in projectdiscovery/subfinder#1809
* @gcoinstash-cmd made their first contribution in projectdiscovery/subfinder#1832

**Full Changelog**: https://github.com/projectdiscovery/subfinder/compare/v2.15.0...v2.16.0</pre>
  <p>View the full release notes at <a href="https://github.com/projectdiscovery/subfinder/releases/tag/v2.16.0">https://github.com/projectdiscovery/subfinder/releases/tag/v2.16.0</a>.</p>
</details>
<hr>

See merge request: Harmonybrew/homebrew-core!17505
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants