Skip to content

feat: allow overriding default exclude-ports in CLI#7324

Open
chovanecadam wants to merge 1 commit intoprojectdiscovery:devfrom
chovanecadam:cli-reserved-ports
Open

feat: allow overriding default exclude-ports in CLI#7324
chovanecadam wants to merge 1 commit intoprojectdiscovery:devfrom
chovanecadam:cli-reserved-ports

Conversation

@chovanecadam
Copy link
Copy Markdown

@chovanecadam chovanecadam commented Apr 2, 2026

Proposed changes

Fixes: #7323

This MR adds a CLI option to overwrite the default excluded-ports array for the whole scan.

Proof

make build

go test ./pkg/protocols/common/contextargs/...
# ok  	github.com/projectdiscovery/nuclei/v3/pkg/protocols/common/contextargs	0.011s

./bin/nuclei --help|grep rport
#    -rport, -reserved-ports string[]      list of reserved ports that network templates should avoid

Default behavior unchanged.

./bin/nuclei -verbose -t network/cves/2001/CVE-2001-1473.yaml -target TARGET:80
# [WRN] [CVE-2001-1473] Could not make network request for (147.251.125.30:22) : could not connect to server: cause="context cancelled before establishing connection" address=147.251.125.30:22 chain="context deadline exceeded"

We can specify array of excluded ports in CLI. Networking templates now can scan SSH running on port 80.

./nuclei -rport 0 -verbose -t network/cves/2001/CVE-2001-1473.yaml -target 147.251.125.30:80

Checklist

  • Pull request is created against the dev branch
  • All checks passed (lint, unit/integration/regression tests etc.) with my changes
  • I have added tests that prove my fix is effective or that my feature works
  • I have added necessary documentation (if appropriate)

Summary by CodeRabbit

  • New Features

    • Added -reserved-ports (short -rport) CLI flag enabling users to specify a comma-separated list of ports that network templates should avoid during execution
    • CLI-specified reserved ports take precedence over template-level port exclusions and default reserved ports
  • Tests

    • Added comprehensive test suite covering port exclusion behavior and precedence scenarios

@auto-assign auto-assign bot requested a review from dogancanbakir April 2, 2026 10:02
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Apr 2, 2026

Walkthrough

Added a new CLI flag -reserved-ports (short -rport) to accept a comma-separated list of ports that network templates should avoid. The reserved ports parameter is now threaded through the Options struct and passed to the UseNetworkPort function, which implements a three-tier precedence: CLI-provided ports override template exclusions, which override default reserved ports.

Changes

Cohort / File(s) Summary
CLI Flag Configuration
cmd/nuclei/main.go
Added -reserved-ports (-rport) CLI flag wired to options.ReservedPorts as a string slice.
Core Port Selection Logic
pkg/protocols/common/contextargs/contextargs.go, pkg/protocols/common/contextargs/contextargs_test.go
Updated UseNetworkPort signature to accept templateExcludePorts (string) and cliExcludePorts ([]string). Renamed reservedPorts to defaultReservedPorts. Implemented precedence logic: CLI ports override template ports, which override defaults. Added comprehensive test suite covering default behavior, template overrides, and CLI precedence.
Protocol Integration
pkg/protocols/javascript/js.go, pkg/protocols/network/request.go
Updated method calls to UseNetworkPort to pass request.options.Options.ReservedPorts as the CLI exclude ports parameter in both JavaScript template execution and network request handling.
Options Struct
pkg/types/types.go
Added ReservedPorts field to types.Options struct and ensured it is copied in the Copy() method.

Sequence Diagram

sequenceDiagram
    actor User as User/CLI
    participant CLI as CLI Flag Parser
    participant Opts as Options
    participant Tmpl as Template Executor
    participant NetPort as UseNetworkPort

    User->>CLI: -reserved-ports "22,25,..."
    CLI->>Opts: Set ReservedPorts (string slice)
    Tmpl->>Tmpl: Load template with excludePorts
    Tmpl->>NetPort: executeWithResults(port,<br/>templateExcludePorts,<br/>cliExcludePorts)
    NetPort->>NetPort: Precedence Check
    alt CLI ports available
        NetPort->>NetPort: Use cliExcludePorts
    else Template ports specified
        NetPort->>NetPort: Use templateExcludePorts
    else
        NetPort->>NetPort: Use defaultReservedPorts
    end
    NetPort-->>Tmpl: Updated context with final port
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Poem

🐰 Reserved ports now bend to CLI's will,
A three-tier dance of exclusion skill,
No more hiding services in the mist,
CLI claims first—templates won't resist,
Network paths clearer, bugs now dismissed! 🌟

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title clearly describes the main change: adding a CLI flag to override the default exclude-ports, which aligns with the changeset that adds -rport/-reserved-ports flag to allow users to control reserved ports.
Linked Issues check ✅ Passed The PR implementation fully addresses issue #7323 by adding a CLI flag to override default reserved ports, enabling users to scan services on HTTP ports by specifying custom port exclusions.
Out of Scope Changes check ✅ Passed All changes are directly scoped to implementing the reserved-ports CLI flag feature: CLI flag wiring, function signature updates to pass reserved ports through the call chain, and test coverage for the new functionality.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ 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 and usage tips.

@neo-by-projectdiscovery-dev
Copy link
Copy Markdown

neo-by-projectdiscovery-dev bot commented Apr 2, 2026

Neo - PR Security Review

No security issues found

Comment @pdneo help for available commands. · Open in Neo

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

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)
cmd/nuclei/main.go (1)

376-376: Clarify that -reserved-ports overrides defaults.

The flag wiring is good; consider tightening the help text so users understand this list replaces default exclusions rather than extending them.

✏️ Suggested wording
-flagSet.StringSliceVarP(&options.ReservedPorts, "reserved-ports", "rport", nil, "list of reserved ports that network templates should avoid", goflags.CommaSeparatedStringSliceOptions),
+flagSet.StringSliceVarP(&options.ReservedPorts, "reserved-ports", "rport", nil, "comma-separated ports overriding default excluded ports for network templates (example: -rport 0)", goflags.CommaSeparatedStringSliceOptions),
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@cmd/nuclei/main.go` at line 376, Update the flag help string for
flagSet.StringSliceVarP so it clearly states that the "reserved-ports" (alias
"rport") value replaces the built-in default exclusion list rather than
appending to it; specifically modify the usage text passed to
flagSet.StringSliceVarP (associated with options.ReservedPorts and the
"reserved-ports"/"rport" flag) to say something like "list of reserved ports
that network templates should avoid — this replaces the default exclusion list"
(or equivalent concise wording).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@pkg/protocols/common/contextargs/contextargs.go`:
- Around line 116-121: Normalize excluded-port tokens before using them: when
building ignorePorts from templateExcludePorts or cliExcludePorts ensure each
token is trimmed (use strings.TrimSpace on each Split token) and then
deduplicated (sliceutil.Dedupe). Update the block that sets ignorePorts
(variables templateExcludePorts, cliExcludePorts, and ignorePorts in
contextargs.go) to map TrimSpace over tokens coming from
strings.Split(templateExcludePorts, ",") and to trim any entries in
cliExcludePorts as well so comparisons later will match whitespace-padded
inputs.

---

Nitpick comments:
In `@cmd/nuclei/main.go`:
- Line 376: Update the flag help string for flagSet.StringSliceVarP so it
clearly states that the "reserved-ports" (alias "rport") value replaces the
built-in default exclusion list rather than appending to it; specifically modify
the usage text passed to flagSet.StringSliceVarP (associated with
options.ReservedPorts and the "reserved-ports"/"rport" flag) to say something
like "list of reserved ports that network templates should avoid — this replaces
the default exclusion list" (or equivalent concise wording).
🪄 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: ca4ff839-f1ca-40fa-91b8-159725b35b5e

📥 Commits

Reviewing files that changed from the base of the PR and between c6fb1ae and 76e6ad7.

📒 Files selected for processing (6)
  • cmd/nuclei/main.go
  • pkg/protocols/common/contextargs/contextargs.go
  • pkg/protocols/common/contextargs/contextargs_test.go
  • pkg/protocols/javascript/js.go
  • pkg/protocols/network/request.go
  • pkg/types/types.go

Comment on lines +116 to 121
if len(cliExcludePorts) > 0 {
ignorePorts = cliExcludePorts
} else if templateExcludePorts != "" {
// TODO: add support for service names like http,https,ssh etc once https://github.com/projectdiscovery/netdb is ready
ignorePorts = sliceutil.Dedupe(strings.Split(excludePorts, ","))
ignorePorts = sliceutil.Dedupe(strings.Split(templateExcludePorts, ","))
}
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.

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Inspect UseNetworkPort parsing:"
rg -n -C3 'UseNetworkPort|templateExcludePorts|cliExcludePorts|strings.Split|TrimSpace' pkg/protocols/common/contextargs/contextargs.go

echo
echo "Inspect TestUseNetworkPort cases:"
rg -n 'templateExcl|cliReserved|name:' pkg/protocols/common/contextargs/contextargs_test.go

Repository: projectdiscovery/nuclei

Length of output: 1835


🏁 Script executed:

rg -n "normalizePorts|TrimSpace" pkg/protocols/common/contextargs/ --type go

Repository: projectdiscovery/nuclei

Length of output: 49


🏁 Script executed:

# Check if sliceutil or other utility packages have port normalization
rg -n "TrimSpace|Dedupe" pkg/utils/ --type go -A 2 | head -30

Repository: projectdiscovery/nuclei

Length of output: 174


🏁 Script executed:

# Check if there are other port-related parsing that might have similar issues
rg -n "strings\.Split.*port|excludePort" pkg/protocols/ --type go | head -20

Repository: projectdiscovery/nuclei

Length of output: 152


🏁 Script executed:

# Check the javascript/js.go port parsing more thoroughly
rg -n -B5 -A10 'strings\.Split.*portStr' pkg/protocols/javascript/js.go

Repository: projectdiscovery/nuclei

Length of output: 520


🏁 Script executed:

# Find where ignorePorts is actually used for comparison
rg -n -A15 'ignorePorts :=' pkg/protocols/common/contextargs/contextargs.go | head -40

Repository: projectdiscovery/nuclei

Length of output: 636


🏁 Script executed:

# Check sliceutil.Dedupe to understand what it does
fd -t f "sliceutil" --exec cat {} \; 2>/dev/null | head -100

Repository: projectdiscovery/nuclei

Length of output: 49


🏁 Script executed:

# Find sliceutil package/file
fd -t f -i sliceutil

Repository: projectdiscovery/nuclei

Length of output: 49


🏁 Script executed:

# Check how ignorePorts is used after assignment (the actual comparison)
rg -n -A30 'if port ==' pkg/protocols/common/contextargs/contextargs.go | head -50

Repository: projectdiscovery/nuclei

Length of output: 908


🏁 Script executed:

# Find stringsutil.EqualFoldAny implementation to confirm comparison behavior
fd -t f stringsutil || rg -n "func EqualFoldAny" --type go

Repository: projectdiscovery/nuclei

Length of output: 49


🏁 Script executed:

# Get the full context of how ports flow through the system
rg -n "defaultReservedPorts" pkg/protocols/common/contextargs/contextargs.go -B 2 -A 2

Repository: projectdiscovery/nuclei

Length of output: 556


🏁 Script executed:

# Search more broadly for EqualFoldAny and stringsutil
rg -n "EqualFoldAny" --type go | head -20

Repository: projectdiscovery/nuclei

Length of output: 2619


🏁 Script executed:

# Check all imports in the contextargs file to understand what stringsutil is used
head -20 pkg/protocols/common/contextargs/contextargs.go

Repository: projectdiscovery/nuclei

Length of output: 598


🏁 Script executed:

# Find the stringsutil package to check EqualFoldAny implementation
rg -n "package strings|func EqualFoldAny" --type go | grep -A5 "EqualFoldAny"

Repository: projectdiscovery/nuclei

Length of output: 49


🏁 Script executed:

# Check if there are integration tests or other test files that might test with whitespace
find pkg/protocols/common/contextargs -name "*test*" -type f

Repository: projectdiscovery/nuclei

Length of output: 119


🏁 Script executed:

# Examine the full test file to see all test cases
cat pkg/protocols/common/contextargs/contextargs_test.go

Repository: projectdiscovery/nuclei

Length of output: 2137


Normalize excluded port tokens before matching.

templateExcludePorts and CLI-provided cliExcludePorts are not trimmed. Inputs like "80, 443" will create tokens with leading/trailing whitespace that fail to match during port comparison, causing incorrect port-rewrite behavior.

This differs from the port parsing in pkg/protocols/javascript/js.go, which correctly applies strings.TrimSpace() to each token. Test coverage also lacks whitespace-padded port cases.

💡 Proposed fix
 func (ctx *Context) UseNetworkPort(port string, templateExcludePorts string, cliExcludePorts []string) error {
 	ignorePorts := defaultReservedPorts
 
 	if len(cliExcludePorts) > 0 {
-		ignorePorts = cliExcludePorts
+		ignorePorts = normalizePorts(cliExcludePorts)
 	} else if templateExcludePorts != "" {
 		// TODO: add support for service names like http,https,ssh etc once https://github.com/projectdiscovery/netdb is ready
-		ignorePorts = sliceutil.Dedupe(strings.Split(templateExcludePorts, ","))
+		ignorePorts = normalizePorts(strings.Split(templateExcludePorts, ","))
 	}
@@
 	return nil
 }
+
+func normalizePorts(ports []string) []string {
+	normalized := make([]string, 0, len(ports))
+	for _, p := range ports {
+		p = strings.TrimSpace(p)
+		if p != "" {
+			normalized = append(normalized, p)
+		}
+	}
+	return sliceutil.Dedupe(normalized)
+}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if len(cliExcludePorts) > 0 {
ignorePorts = cliExcludePorts
} else if templateExcludePorts != "" {
// TODO: add support for service names like http,https,ssh etc once https://github.com/projectdiscovery/netdb is ready
ignorePorts = sliceutil.Dedupe(strings.Split(excludePorts, ","))
ignorePorts = sliceutil.Dedupe(strings.Split(templateExcludePorts, ","))
}
if len(cliExcludePorts) > 0 {
ignorePorts = normalizePorts(cliExcludePorts)
} else if templateExcludePorts != "" {
// TODO: add support for service names like http,https,ssh etc once https://github.com/projectdiscovery/netdb is ready
ignorePorts = normalizePorts(strings.Split(templateExcludePorts, ","))
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/protocols/common/contextargs/contextargs.go` around lines 116 - 121,
Normalize excluded-port tokens before using them: when building ignorePorts from
templateExcludePorts or cliExcludePorts ensure each token is trimmed (use
strings.TrimSpace on each Split token) and then deduplicated (sliceutil.Dedupe).
Update the block that sets ignorePorts (variables templateExcludePorts,
cliExcludePorts, and ignorePorts in contextargs.go) to map TrimSpace over tokens
coming from strings.Split(templateExcludePorts, ",") and to trim any entries in
cliExcludePorts as well so comparisons later will match whitespace-padded
inputs.

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.

[BUG] networking services on HTTP ports are never scanned

1 participant