Skip to content

fix(scan): handles nil (*ListenHandler).IPConn#1466

Merged
Mzack9999 merged 1 commit intodevfrom
dwisiswant0/fix/scan/handles-nil-ListenHandler-net-IPConn
May 5, 2025
Merged

fix(scan): handles nil (*ListenHandler).IPConn#1466
Mzack9999 merged 1 commit intodevfrom
dwisiswant0/fix/scan/handles-nil-ListenHandler-net-IPConn

Conversation

@dwisiswant0
Copy link
Copy Markdown
Member

@dwisiswant0 dwisiswant0 commented May 5, 2025

Closes #1422

Test:

sudo $(which go) test -v -timeout 30s -run ^TestConcurrentSYNScans$ ./pkg/runner/

Summary by CodeRabbit

  • Tests

    • Added a new test to verify concurrent SYN scans across multiple targets, ensuring reliable operation under parallel execution.
  • Bug Fixes

    • Improved robustness by preventing network operations on uninitialized connections, reducing potential errors during scanning.
  • Refactor

    • Simplified and clarified the retry logic for sending packets, making the process more reliable and maintainable.

Signed-off-by: Dwi Siswanto <git@dw1.io>
@dwisiswant0 dwisiswant0 requested a review from Mzack9999 May 5, 2025 05:26
@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented May 5, 2025

Walkthrough

The changes introduce a new concurrent SYN scan test in the runner's test suite and refactor the network packet sending logic in the Unix scanner implementation. The test function, TestConcurrentSYNScans, launches multiple goroutines to perform SYN scans on different targets, ensuring proper error handling and resource management. In the scanner implementation, nil checks are added before sending packets to avoid nil pointer dereferences, and the retry logic for sending packets is refactored from a goto-based approach to a more idiomatic loop structure.

Changes

File(s) Change Summary
pkg/runner/runner_test.go Added TestConcurrentSYNScans for concurrent SYN scan testing with multiple goroutines and improved error handling.
pkg/scan/scan_unix.go Added nil checks for network connections before sending packets; refactored retry logic in packet sending functions.

Assessment against linked issues

Objective Addressed Explanation
Prevent nil pointer dereference in concurrent scanning (connections checked before send) (#1422)
Refactor retry logic to avoid goto and improve clarity (#1422)
Add test coverage for concurrent scanning scenarios (#1422)

Poem

A bunny with code on its mind,
Fixed nils that were tricky to find.
With loops in the place of a goto disgrace,
And tests that all run intertwined.
No more panics or tears,
Just robust code—cheers!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Copy Markdown

@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: 0

🧹 Nitpick comments (6)
pkg/scan/scan_unix.go (3)

253-257: Consider deduplicating repetitive connection-nil checks

Introducing the early‐exit nil checks for TcpConn4, UdpConn4, TcpConn6, and UdpConn6 is a solid safety guard against dereferencing a nil *IPConn.
However, the pattern is now duplicated four times. Extracting a tiny helper such as

func checkConn(conn net.PacketConn, proto, ip string, port int) bool {
	if conn == nil {
		gologger.Debug().Msgf("%s connection is nil, cannot send packet to %s:%d\n",
			proto, ip, port)
		return false
	}
	return true
}

and using it like

if !checkConn(listenHandler.TcpConn4, "TcpConn4", ip, p.Port) {
	return
}

would reduce boilerplate, make future maintenance easier, and keep the senders symmetric.

Also applies to: 298-302, 359-363, 404-408


480-503: Add an explicit nil guard for the supplied conn and streamline error return

sendWithConn now retries in a loop—good move! Two small nits:

  1. If a caller accidentally passes nil you’ll get a panic on WriteTo. A cheap guard prevents that.
  2. After the retry loop exits err is guaranteed to be non-nil; the subsequent if err != nil is therefore redundant.
func sendWithConn(destIP string, conn net.PacketConn, l ...gopacket.SerializableLayer) error {
-	var err error
+	if conn == nil {
+		return fmt.Errorf("cannot send packet to %s: nil PacketConn", destIP)
+	}
+	var err error-	for retries := 0; retries < maxRetries; retries++ {
+	for retries := 0; retries < maxRetries; retries++ {
 		_, err = conn.WriteTo(data, addr)
 		if err == nil {
 			return nil
 		}
 		time.Sleep(time.Duration(sendDelayMsec) * time.Millisecond)
 	}
-	if err != nil {
-		return fmt.Errorf("could not send packet to %s: %s", destIP, err)
-	}
-	return nil
+	return fmt.Errorf("could not send packet to %s after %d retries: %w",
+		destIP, maxRetries, err)
 }

This both avoids a potential panic path and simplifies the tail logic.


506-534: sendWithHandler shares retry logic with sendWithConn – factor out common code

The retry block here is identical to the one in sendWithConn. Extracting a small reusable helper such as

func retrySend(max int, delay time.Duration, send func() error) error {
	for i := 0; i < max; i++ {
		if err := send(); err == nil {
			return nil
		}
		time.Sleep(delay)
	}
	return fmt.Errorf("exceeded %d retries", max)
}

would DRY up both functions and ensure future tweaks (back-off strategy, metrics, etc.) are applied consistently.

pkg/runner/runner_test.go (3)

880-884: Root-required test will be skipped in most CI environments

The os.Geteuid() != 0 guard is practical for local runs, but it means the new concurrency stress-test won’t execute in typical CI pipelines (which run unprivileged).
Consider one of:

  • Adding a build tag (e.g., //go:build privileged) so regular go test ./... doesn’t report a large chunk of skipped tests, or
  • Falling back to a mocked scanner when not root, so the concurrency logic is still exercised.

This will preserve coverage without needing root everywhere.


889-897: Channel capacity might dead-lock if more than one error per goroutine is sent

errChan is buffered with numGoroutines, under the assumption that each goroutine emits at most one error. While currently true, a future change (e.g., logging both runner creation and enumeration errors) would block the goroutine and stall the test.

Two defensive tweaks:

-errChan := make(chan error, numGoroutines)
+errChan := make(chan error, numGoroutines*2) // allow >1 error per goroutine

or send with a non-blocking select:

select {
case errChan <- err:
default:
    t.Log("error dropped:", err)
}

Either avoids accidental deadlocks down the road.


927-931: Minor: context timeout may be tight on slower systems

The test times out after 20 s irrespective of CPU count or network conditions. In resource-constrained CI this could yield spurious failures.
Consider making the timeout proportional to numGoroutines (or an env override) to keep the test robust:

-timeout := 20 * time.Second
+timeout := time.Duration(numGoroutines*15) * time.Second // ≈15 s per worker
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7cce01e and 49fc1fd.

📒 Files selected for processing (2)
  • pkg/runner/runner_test.go (2 hunks)
  • pkg/scan/scan_unix.go (5 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (7)
  • GitHub Check: build-windows
  • GitHub Check: release-test-mac
  • GitHub Check: build-linux
  • GitHub Check: Functional Test (ubuntu-latest)
  • GitHub Check: build-mac
  • GitHub Check: release-test-linux
  • GitHub Check: Analyze (go)

@Mzack9999 Mzack9999 merged commit d53dbe3 into dev May 5, 2025
13 checks passed
@Mzack9999 Mzack9999 deleted the dwisiswant0/fix/scan/handles-nil-ListenHandler-net-IPConn branch May 5, 2025 16:35
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.

Nil pointer error after concurrent scanning with goroutines

2 participants