Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Alive Proxy into Options #5903

Merged
merged 2 commits into from
Dec 12, 2024
Merged

Add Alive Proxy into Options #5903

merged 2 commits into from
Dec 12, 2024

Conversation

ShubhamRasal
Copy link
Contributor

@ShubhamRasal ShubhamRasal commented Dec 12, 2024

This PR addresses an issue where concurrent requests in a single Nuclei instance shared the same proxy due to global variable usage. By moving proxy configurations to individual request options, we enable isolated and parallel request handling, improving flexibility and reliability in SDK mode operations.

Proposed changes

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

    • Introduced new proxy configuration options: AliveHttpProxy and AliveSocksProxy.
  • Bug Fixes

    • Enhanced error handling and logging for proxy-related functionalities.
  • Refactor

    • Updated proxy handling across multiple components to utilize new configuration options instead of global variables.
  • Chores

    • Removed deprecated proxy-related constants and variables from the codebase.

- Provides ability to pass diff proxy in single nuclei instance using sdk
@auto-assign auto-assign bot requested a review from dogancanbakir December 12, 2024 03:27
Copy link

coderabbitai bot commented Dec 12, 2024

Walkthrough

The changes in this pull request involve a refactoring of proxy handling within the application. A new constant HTTP_PROXY_ENV is introduced, and existing references to proxy URLs are replaced with options that allow for more flexible configurations. The Options struct is updated to include AliveHttpProxy and AliveSocksProxy, facilitating the management of proxy settings across various components. Additionally, several files have been modified to utilize these new options in their respective functions, enhancing the clarity and functionality of proxy configurations.

Changes

File Path Change Summary
internal/runner/proxy.go Added constant HTTP_PROXY_ENV, modified loadProxyServers to use the new constant and update options for proxy URLs.
internal/runner/runner.go Updated New function to use options.AliveHttpProxy and options.AliveSocksProxy for HTTP client initialization.
lib/sdk_private.go Modified init function to check e.opts.AliveHttpProxy and e.opts.AliveSocksProxy for HTTP client initialization.
pkg/protocols/common/protocolstate/state.go Changed Init function to use options.AliveSocksProxy for proxy URL parsing.
pkg/protocols/headless/engine/engine.go Updated New function to replace types.ProxyURL with options.AliveHttpProxy for Chrome launcher configuration.
pkg/protocols/headless/engine/http_client.go Modified newHttpClient to use options.AliveHttpProxy and options.AliveSocksProxy for proxy settings.
pkg/protocols/http/httpclientpool/clientpool.go Updated GetRawHTTP and Get functions to use options.Options.AliveHttpProxy and options.Options.AliveSocksProxy.
pkg/reporting/trackers/github/github.go Replaced global types.ProxyURL with custom HTTP client handling in New function. Removed related import.
pkg/reporting/trackers/gitlab/gitlab.go Simplified error handling in CreateIssue method by removing unused variable resp.
pkg/reporting/trackers/linear/linear.go Modified New function to handle custom HttpClient option.
pkg/types/proxy.go Deleted file containing declarations for HTTP_PROXY_ENV, ProxyURL, and ProxySocksURL.
pkg/types/types.go Added fields AliveHttpProxy and AliveSocksProxy to Options struct.

Poem

In the burrow where changes bloom,
Proxies dance, dispelling gloom.
Options new, like springtime's cheer,
Alive and vibrant, drawing near.
With hops and skips, we celebrate,
A flexible world, oh, isn't it great? 🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 8b05d5c and 8db1c2e.

📒 Files selected for processing (1)
  • pkg/reporting/trackers/github/github.go (1 hunks)
🔇 Additional comments (1)
pkg/reporting/trackers/github/github.go (1)

65-68: ⚠️ Potential issue

Complete the type assertion safety checks.

While the safety check for tc.Transport has been added, there's still an unsafe type assertion for options.HttpClient.HTTPClient.Transport that could panic.

Apply this diff to add complete safety checks:

 if options.HttpClient != nil && options.HttpClient.HTTPClient != nil {
     if tcTransport, ok := tc.Transport.(*http.Transport); ok {
-        tcTransport.Proxy = options.HttpClient.HTTPClient.Transport.(*http.Transport).Proxy
+        if clientTransport, ok := options.HttpClient.HTTPClient.Transport.(*http.Transport); ok {
+            tcTransport.Proxy = clientTransport.Proxy
+        }
     }
 }

🪧 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.

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. (Experiment)
  • @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.

@ShubhamRasal ShubhamRasal linked an issue Dec 12, 2024 that may be closed by this pull request
1 task
@ShubhamRasal ShubhamRasal self-assigned this Dec 12, 2024
Copy link

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

🧹 Outside diff range and nitpick comments (4)
pkg/protocols/headless/engine/http_client.go (1)

Line range hint 64-68: Fix error variable shadowing in SOCKS proxy error handling

There's a potential bug where the wrong error is being returned in the SOCKS proxy error handling.

Apply this fix:

 socksURL, proxyErr := url.Parse(options.AliveSocksProxy)
 if proxyErr != nil {
-    return nil, err
+    return nil, proxyErr
 }
pkg/types/types.go (2)

97-98: Consider renaming field to follow Go naming convention for HTTP

The field name AliveHttpProxy should be AliveHTTPProxy to follow Go's naming convention where HTTP should be capitalized.

-	AliveHttpProxy string
+	AliveHTTPProxy string

97-100: Improve field documentation

The current comments could be more descriptive about the purpose and usage of these fields.

-	// AliveProxy is the alive proxy to use
-	AliveHttpProxy string
-	// AliveSocksProxy is the alive socks proxy to use
-	AliveSocksProxy string
+	// AliveHTTPProxy specifies the HTTP proxy URL to be used for individual requests
+	// This allows for isolated proxy configurations in concurrent scenarios
+	AliveHTTPProxy string
+	// AliveSocksProxy specifies the SOCKS proxy URL to be used for individual requests
+	// This allows for isolated proxy configurations in concurrent scenarios
+	AliveSocksProxy string
internal/runner/runner.go (1)

185-185: Improve condition readability

The condition structure could be clearer by grouping the proxy checks.

-	if options.ProxyInternal && options.AliveHttpProxy != "" || options.AliveSocksProxy != "" {
+	if options.ProxyInternal && (options.AliveHttpProxy != "" || options.AliveSocksProxy != "") {
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between c731126 and 8b05d5c.

📒 Files selected for processing (12)
  • internal/runner/proxy.go (2 hunks)
  • internal/runner/runner.go (1 hunks)
  • lib/sdk_private.go (1 hunks)
  • pkg/protocols/common/protocolstate/state.go (1 hunks)
  • pkg/protocols/headless/engine/engine.go (1 hunks)
  • pkg/protocols/headless/engine/http_client.go (1 hunks)
  • pkg/protocols/http/httpclientpool/clientpool.go (2 hunks)
  • pkg/reporting/trackers/github/github.go (1 hunks)
  • pkg/reporting/trackers/gitlab/gitlab.go (1 hunks)
  • pkg/reporting/trackers/linear/linear.go (1 hunks)
  • pkg/types/proxy.go (0 hunks)
  • pkg/types/types.go (1 hunks)
💤 Files with no reviewable changes (1)
  • pkg/types/proxy.go
🔇 Additional comments (9)
internal/runner/proxy.go (2)

17-19: LGTM: Good package encapsulation

Moving the HTTP_PROXY_ENV constant into the runner package improves encapsulation and reduces dependencies on the types package.


59-62: LGTM: Improved proxy configuration handling

The change from global variables to options-based configuration improves thread safety for concurrent requests. This aligns well with the PR's objective of fixing concurrent request issues.

pkg/protocols/headless/engine/http_client.go (1)

59-62: LGTM: Thread-safe proxy configuration

The change to use options-scoped proxy configuration improves thread safety and aligns with the PR's objective.

pkg/protocols/headless/engine/engine.go (1)

76-77: LGTM: Proper integration with Chrome launcher

The change correctly integrates the new proxy configuration with the Chrome launcher while maintaining thread safety.

pkg/reporting/trackers/gitlab/gitlab.go (1)

104-109: LGTM! Improved error handling.

The error handling has been simplified by removing the unused response variable while maintaining the same functionality.

pkg/protocols/common/protocolstate/state.go (1)

112-113: LGTM! Verify proxy initialization.

The change from global ProxySocksURL to options.AliveSocksProxy improves concurrent request handling by isolating proxy configurations. This aligns with the PR objective of preventing shared proxy issues.

✅ Verification successful

Let me verify the initialization by checking where the AliveSocksProxy is set in the codebase.


Let me check how the proxy is being initialized by looking at the proxy setup code.


Let me try a different approach to check the proxy initialization code.


Based on the code analysis, I can now provide the final response:

LGTM! Proxy initialization is properly handled.

The AliveSocksProxy is correctly initialized in the loadProxyServers function, which:

  1. Validates the proxy URL before assignment
  2. Only sets AliveSocksProxy for SOCKS5 scheme
  3. Verifies proxy availability using GetAnyAliveProxy
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify that AliveSocksProxy is properly initialized before use
rg -A 2 "AliveSocksProxy.*=.*" 

Length of output: 1833


Script:

#!/bin/bash
# Check for AliveSocksProxy struct field definition
ast-grep --pattern 'type $_ struct {
  $$$
  AliveSocksProxy $_
  $$$
}'

# Check for any direct assignments to AliveSocksProxy
rg "\.AliveSocksProxy\s*=" -A 2

Length of output: 28038


Script:

#!/bin/bash
# Check the proxy initialization code
rg -A 10 "func.*proxy" internal/runner/proxy.go

Length of output: 49


Script:

#!/bin/bash
# Check the proxy setup code in the runner package
rg -A 10 "parseProxyURL|configureProxy" internal/runner/

# Also check for any proxy-related function
rg -A 10 "proxy" internal/runner/proxy.go

Length of output: 1562

pkg/reporting/trackers/linear/linear.go (1)

63-65: LGTM! Custom HTTP client transport is correctly handled.

The implementation properly reuses the transport from the provided HttpClient, maintaining connection settings and proxy configurations.

pkg/protocols/http/httpclientpool/clientpool.go (1)

160-163: LGTM! Proxy configuration priority is correctly implemented.

The implementation properly prioritizes HTTP proxy over SOCKS proxy and maintains the FastDialer fallback.

internal/runner/runner.go (1)

Line range hint 97-100: Verify consistent proxy field usage across codebase

Let's verify that all references to the new proxy fields are consistent across the codebase.

✅ Verification successful

Based on the search results, I can now generate the final response:

Proxy configuration usage is consistent across codebase

The proxy field references are consistently used throughout the codebase:

  • Defined in pkg/types/types.go
  • Properly set in internal/runner/proxy.go
  • Correctly utilized in HTTP client configurations in pkg/protocols/http/httpclientpool/clientpool.go
  • Properly implemented in headless engine in pkg/protocols/headless/engine/
  • Correctly handled in protocol state management in pkg/protocols/common/protocolstate/state.go

The remaining ProxyURL references are standard Go HTTP client function calls, not related to the configuration fields.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for all occurrences of AliveHttpProxy and AliveSocksProxy
echo "Searching for proxy field references..."
rg "AliveHttpProxy|AliveSocksProxy" --type go

# Search for any remaining global proxy URL references that should be migrated
echo "Searching for potential remaining global proxy references..."
rg "ProxyURL|ProxySocksURL" --type go

Length of output: 2561

pkg/reporting/trackers/github/github.go Outdated Show resolved Hide resolved
@@ -120,7 +120,7 @@ func (e *NucleiEngine) init(ctx context.Context) error {
_ = protocolinit.Init(e.opts)
})

if e.opts.ProxyInternal && types.ProxyURL != "" || types.ProxySocksURL != "" {
if e.opts.ProxyInternal && e.opts.AliveHttpProxy != "" || e.opts.AliveSocksProxy != "" {
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix the logical operator in proxy condition.

The condition combines multiple checks with incorrect operator precedence which could lead to unintended behavior.

Apply this diff to fix the condition:

-if e.opts.ProxyInternal && e.opts.AliveHttpProxy != "" || e.opts.AliveSocksProxy != "" {
+if e.opts.ProxyInternal && (e.opts.AliveHttpProxy != "" || e.opts.AliveSocksProxy != "") {
📝 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 e.opts.ProxyInternal && e.opts.AliveHttpProxy != "" || e.opts.AliveSocksProxy != "" {
if e.opts.ProxyInternal && (e.opts.AliveHttpProxy != "" || e.opts.AliveSocksProxy != "") {

@@ -182,7 +182,7 @@ func New(options *types.Options) (*Runner, error) {
runner.catalog = disk.NewCatalog(config.DefaultConfig.TemplatesDirectory)

var httpclient *retryablehttp.Client
if options.ProxyInternal && types.ProxyURL != "" || types.ProxySocksURL != "" {
if options.ProxyInternal && options.AliveHttpProxy != "" || options.AliveSocksProxy != "" {
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Update field name for consistency

Once the field name in types.go is updated to AliveHTTPProxy, this reference should be updated as well.

-	if options.ProxyInternal && options.AliveHttpProxy != "" || options.AliveSocksProxy != "" {
+	if options.ProxyInternal && options.AliveHTTPProxy != "" || options.AliveSocksProxy != "" {
📝 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 options.ProxyInternal && options.AliveHttpProxy != "" || options.AliveSocksProxy != "" {
if options.ProxyInternal && options.AliveHTTPProxy != "" || options.AliveSocksProxy != "" {

@ehsandeep ehsandeep merged commit be1f634 into dev Dec 12, 2024
12 of 15 checks passed
@ehsandeep ehsandeep deleted the pass-proxy-through-options branch December 12, 2024 22:53
@ehsandeep ehsandeep added this to the Nuclei v3.3.8 milestone Dec 12, 2024
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] Concurrent Requests Share Proxy in SDK Mode Due to Global Variable
4 participants