Skip to content

Conversation

@dwisiswant0
Copy link
Member

@dwisiswant0 dwisiswant0 commented Oct 21, 2024

Proposed changes

Fix #5742

TODO:

  • Add note in docs.

How has been this tested?

  • code-template-1
id: code-template-1

info:
  name: uname
  author: dwisiswant0
  severity: info
  description: uname
  tags: code,test

code:
  - pre-condition: '!IsWindows()'
    engine:
      - sh
      - bash
    source: uname -a

    matchers:
      - type: word
        words:
          - Linux
          - Darwin
        condition: or
  • code-template-2
id: code-template-2

info:
  name: uname
  author: dwisiswant0
  severity: info
  description: uname
  tags: code,test

self-contained: true

code:
  - pre-condition: '!IsWindows()'
    engine:
      - sh
      - bash
    source: uname -a

    matchers:
      - type: word
        words:
          - Linux
          - Darwin
        condition: or
  • code-template-with-http-1
id: code-template-with-http-1

info:
  name: uname
  author: dwisiswant0
  severity: info
  description: uname
  tags: code,test

code:
  - pre-condition: '!IsWindows()'
    engine:
      - sh
      - bash
    source: uname -a

    matchers:
      - type: word
        words:
          - Linux
          - Darwin
        condition: or

http:
  - method: GET
    path:
      - "{{BaseURL}}/"
    matchers:
      - type: status
        status:
          - 200

Validate:

$ go run cmd/nuclei/main.go -silent -validate -code -t code-template-with-http-1.yaml && echo "OK"
OK
$ go run cmd/nuclei/main.go -silent -validate -code -t code-template-1.yaml && echo "OK"
[FTL] Could not validate templates: errors occurred during template validation
exit status 1
$ go run cmd/nuclei/main.go -silent -validate -code -t code-template-2.yaml && echo "OK"
OK

Test:

$ go test -v -race -run "^TestCodeProtocol$" ./pkg/protocols/code/...
=== RUN   TestCodeProtocol
--- PASS: TestCodeProtocol (0.06s)
PASS
ok  	github.com/projectdiscovery/nuclei/v3/pkg/protocols/code	1.299s

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 support for marking code protocol requests as self-contained, improving handling of single and multi-protocol templates.
  • Bug Fixes
    • Enhanced validation to ensure single code protocol requests are self-contained, preventing misconfiguration.
  • Tests
    • Updated tests to reflect the new self-contained requirement for code protocol requests.

Copy link
Member

@tarunKoyalwar tarunKoyalwar left a comment

Choose a reason for hiding this comment

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

while this is one way to achieve , just confirming if we want to head in this direction cc: @ehsandeep @Mzack9999

i remember that one usecase was that , code protocol can be used to run other exploits that can't be necessarily run with javascript or http

  • some exploit in python which uses structs and stuff and would be difficult to achieve it in go
  • other such remote exploits that have poc's but can't be run with go but still require input

^ both of these require passing http url as input ( i remember there was one such template as well ).

If we still want to keep these usecases it might be just enough to print a forced warning like we do when we run code protocol without -code flag

@dwisiswant0
Copy link
Member Author

while this is one way to achieve , just confirming if we want to head in this direction cc: @ehsandeep @Mzack9999

i remember that one usecase was that , code protocol can be used to run other exploits that can't be necessarily run with javascript or http

  • some exploit in python which uses structs and stuff and would be difficult to achieve it in go
  • other such remote exploits that have poc's but can't be run with go but still require input

^ both of these require passing http url as input ( i remember there was one such template as well ).

If we still want to keep these usecases it might be just enough to print a forced warning like we do when we run code protocol without -code flag

To your concern:

This should be a bug, and we should drop a note in docs that: code-protocol-based templates are self-contained, unless they include other protocols in the template.

Also, the CVE-2024-22120 template should be rewritten to an HTTP-protocol-based template. I don't see any need to do it with the code-protocol-based template (it's just too raw & improper or over-engineered). Ref: https://support.zabbix.com/browse/ZBX-24505.

CC: @projectdiscovery/template.

Originally posted by @dwisiswant0 in #5742

IMO, I think code-protocol-based templates should be used for the pre-exploitation stage (like building) or other generative steps. After that, they could switch to other protocols for the actual exploit stage, matching whatever protocol is used on the target.

To make this even more effective, we could aim to support similar caps to Python like struct or pwntools lib - and if we can integrate this into the DSL engine, we could achieve continuous generation and handling within that env.

@github-actions
Copy link

This pull request has been automatically marked as stale due to inactivity. It will be closed in 7 days if no further activity occurs. Please update if you wish to keep it open.

@github-actions github-actions bot added the Status: Stale This issue/PR has been inactive for a while and may be closed soon if no further activity occ label Jul 20, 2025
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 20, 2025

Walkthrough

A new SelfContained boolean field was added to the code protocol's Request struct, with related validation in the Compile method to ensure it is set for single protocol requests. Template parsing logic was updated to flag code requests as self-contained and to better handle multi-protocol templates, including a utility method to detect multiple protocols.

Changes

File(s) Change Summary
pkg/protocols/code/code.go Added SelfContained field to Request; updated struct comment; enforced validation in Compile method.
pkg/protocols/code/code_test.go Updated test to set SelfContained: true in code protocol request initialization.
pkg/templates/compile.go Enhanced self-contained flag handling for code requests; improved multi-protocol template processing logic.
pkg/templates/templates.go Added hasMultipleProtocols method to Template to detect presence of multiple protocol request types.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant TemplateParser
    participant CodeRequest

    User->>TemplateParser: Parse template
    TemplateParser->>CodeRequest: Initialize Request
    TemplateParser->>CodeRequest: Set SelfContained flag (if applicable)
    TemplateParser->>TemplateParser: Check for multiple protocols
    CodeRequest->>CodeRequest: Compile
    CodeRequest-->>TemplateParser: Validate SelfContained if single protocol
    TemplateParser-->>User: Return parsed/validated template or error
Loading

Poem

A field named SelfContained hops in,
Ensuring code requests now begin
With clarity, not silent woe—
Templates checked before they go!
Multi-protocols, we now detect,
So rabbits code with more respect.
🐇✨


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2039b5c and afaa176.

⛔ Files ignored due to path filters (7)
  • integration_tests/protocols/code/ps1-snippet.yaml is excluded by !**/*.yaml
  • integration_tests/protocols/code/py-env-var.yaml is excluded by !**/*.yaml
  • integration_tests/protocols/code/py-file.yaml is excluded by !**/*.yaml
  • integration_tests/protocols/code/py-interactsh.yaml is excluded by !**/*.yaml
  • integration_tests/protocols/code/py-nosig.yaml is excluded by !**/*.yaml
  • integration_tests/protocols/code/py-snippet.yaml is excluded by !**/*.yaml
  • integration_tests/protocols/code/unsigned.yaml is excluded by !**/*.yaml
📒 Files selected for processing (4)
  • pkg/protocols/code/code.go (3 hunks)
  • pkg/protocols/code/code_test.go (1 hunks)
  • pkg/templates/compile.go (3 hunks)
  • pkg/templates/templates.go (1 hunks)
🧰 Additional context used
🧠 Learnings (4)
📓 Common learnings
Learnt from: hdm
PR: projectdiscovery/nuclei#6322
File: pkg/templates/compile.go:79-81
Timestamp: 2025-07-16T21:27:14.937Z
Learning: To make the template caching mechanism in pkg/templates/compile.go production-ready, DSLs need to be updated to use runtime options instead of cached variables, rather than restoring the Compile() calls on each request.
Learnt from: hdm
PR: projectdiscovery/nuclei#6322
File: pkg/templates/compile.go:79-81
Timestamp: 2025-07-16T21:27:14.937Z
Learning: In pkg/templates/compile.go, the template caching mechanism intentionally skips calling Compile() on copied requests to achieve performance benefits. This is the intended design, not a bug. The current implementation isn't production-ready but represents the desired direction.
pkg/protocols/code/code.go (4)
Learnt from: dwisiswant0
PR: projectdiscovery/nuclei#6290
File: pkg/protocols/http/build_request.go:457-464
Timestamp: 2025-06-30T16:34:42.125Z
Learning: In the projectdiscovery/retryablehttp-go package, the Request struct embeds URL fields directly, making req.Scheme, req.Host, and other URL fields accessible directly on the Request object instead of requiring req.URL.Scheme, req.URL.Host, etc.
Learnt from: hdm
PR: projectdiscovery/nuclei#6322
File: pkg/protocols/common/protocolstate/file.go:38-55
Timestamp: 2025-07-16T21:31:43.283Z
Learning: In pkg/protocols/common/protocolstate/file.go, the inconsistent behavior between SetLfaAllowed, GetLfaAllowed, and IsLfaAllowed functions is intentional as an interim step before implementing context-specific LFA logic. The current mixed approach of global and per-instance flags is a temporary transitional state, not a design flaw.
Learnt from: hdm
PR: projectdiscovery/nuclei#6322
File: pkg/templates/compile.go:79-81
Timestamp: 2025-07-16T21:27:14.937Z
Learning: In pkg/templates/compile.go, the template caching mechanism intentionally skips calling Compile() on copied requests to achieve performance benefits. This is the intended design, not a bug. The current implementation isn't production-ready but represents the desired direction.
Learnt from: hdm
PR: projectdiscovery/nuclei#6322
File: pkg/templates/compile.go:79-81
Timestamp: 2025-07-16T21:27:14.937Z
Learning: To make the template caching mechanism in pkg/templates/compile.go production-ready, DSLs need to be updated to use runtime options instead of cached variables, rather than restoring the Compile() calls on each request.
pkg/templates/templates.go (3)
Learnt from: hdm
PR: projectdiscovery/nuclei#6322
File: pkg/templates/compile.go:79-81
Timestamp: 2025-07-16T21:27:14.937Z
Learning: To make the template caching mechanism in pkg/templates/compile.go production-ready, DSLs need to be updated to use runtime options instead of cached variables, rather than restoring the Compile() calls on each request.
Learnt from: hdm
PR: projectdiscovery/nuclei#6322
File: pkg/templates/compile.go:59-78
Timestamp: 2025-07-16T21:28:08.073Z
Learning: The shallow copy behavior (`tplCopy := *value`) in pkg/templates/compile.go is intentional design for the template caching mechanism. The partial-copy approach is part of the performance optimization strategy, not a bug requiring deep copying.
Learnt from: hdm
PR: projectdiscovery/nuclei#6322
File: pkg/templates/compile.go:79-81
Timestamp: 2025-07-16T21:27:14.937Z
Learning: In pkg/templates/compile.go, the template caching mechanism intentionally skips calling Compile() on copied requests to achieve performance benefits. This is the intended design, not a bug. The current implementation isn't production-ready but represents the desired direction.
pkg/templates/compile.go (3)
Learnt from: hdm
PR: projectdiscovery/nuclei#6322
File: pkg/templates/compile.go:79-81
Timestamp: 2025-07-16T21:27:14.937Z
Learning: In pkg/templates/compile.go, the template caching mechanism intentionally skips calling Compile() on copied requests to achieve performance benefits. This is the intended design, not a bug. The current implementation isn't production-ready but represents the desired direction.
Learnt from: hdm
PR: projectdiscovery/nuclei#6322
File: pkg/templates/compile.go:79-81
Timestamp: 2025-07-16T21:27:14.937Z
Learning: To make the template caching mechanism in pkg/templates/compile.go production-ready, DSLs need to be updated to use runtime options instead of cached variables, rather than restoring the Compile() calls on each request.
Learnt from: hdm
PR: projectdiscovery/nuclei#6322
File: pkg/templates/compile.go:59-78
Timestamp: 2025-07-16T21:28:08.073Z
Learning: The shallow copy behavior (`tplCopy := *value`) in pkg/templates/compile.go is intentional design for the template caching mechanism. The partial-copy approach is part of the performance optimization strategy, not a bug requiring deep copying.
🔇 Additional comments (8)
pkg/protocols/code/code_test.go (1)

24-24: LGTM! Test updated correctly for new validation.

The test properly sets SelfContained: true to satisfy the new requirement that single code protocol requests must be self-contained.

pkg/templates/templates.go (1)

511-543: LGTM! Efficient multi-protocol detection implementation.

The method correctly implements the early-exit optimization suggested in previous reviews. The TODO comment appropriately documents the planned future refactoring to use a more generic approach.

pkg/protocols/code/code.go (3)

50-50: Good correction of comment description.

The comment now correctly describes this as the "code protocol" instead of "SSL protocol".


73-75: LGTM! SelfContained field properly implemented.

The field is correctly added with appropriate YAML/JSON exclusion tags and clear documentation.


143-145: Validation logic correctly enforces self-contained requirement.

The validation properly checks that single code protocol requests (when !IsMultiProtocol) must have SelfContained enabled. The error message is clear and appropriately tagged.

pkg/templates/compile.go (3)

150-152: LGTM! Code requests properly included in self-contained parsing.

The addition ensures that code protocol requests are correctly marked as self-contained when the template has the SelfContained flag enabled.


184-191: Excellent integration of multi-protocol detection.

The condition now properly handles both multiple requests and multiple protocols, preserving request order and setting the IsMultiProtocol flag when appropriate. This correctly integrates with the validation logic in the code protocol.


437-437: Good positioning of self-contained request parsing.

Calling parseSelfContainedRequests() after protocol compilation ensures all requests are available for processing. The single invocation is more efficient than the previous approach.

✨ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

@github-actions github-actions bot removed the Status: Stale This issue/PR has been inactive for a while and may be closed soon if no further activity occ label Oct 26, 2025
@dogancanbakir
Copy link
Member

merge conflict

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.

[FEATURE] Add warnings for more visibility when running self-contained templates

5 participants