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

fix recursive struct validation during JSON marshaling #5883

Merged
merged 1 commit into from
Dec 19, 2024

Conversation

dogancanbakir
Copy link
Member

@dogancanbakir dogancanbakir commented Dec 4, 2024

Proposed changes

Closes #5882

example.go :

package main

import (
	"context"
	"fmt"

	nuclei "github.com/projectdiscovery/nuclei/v3/lib"
)

func main() {
	ne, err := nuclei.NewNucleiEngineCtx(context.Background())
	if err != nil {
		panic(err)
	}

	b, _ := ne.GetTemplates()[0].MarshalJSON()
	fmt.Println(string(b))
}
$ go run .
{"id":"azure-takeover-detection","info":{"name":"Microsoft Azure Takeover Detection","author":["pdteam"],"tags":["dns","takeover","azure"],"description":"Microsoft Azure is vulnerable to subdomain takeover attacks. Subdomain takeovers are a common, high-severity threat for organizations that regularly create and delete many resources. A subdomain takeover can occur when a D\u003e","reference":["https://godiego.co/posts/STO/","https://docs.microsoft.com/en-us/azure/security/fundamentals/subdomain-takeover","https://cystack.net/research/subdomain-takeover-chapter-two-azure-services/"],"severity":"high","metadata":{"max-request":1},"classification":{"cve-id":null,"cwe-id":["cwe-404"],"cvss-metrics":"CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:C/C:L/I:L/A:N","cvss-score":7.2}},"dns":[{"matchers":[{"type":"word","part":"body","words":["NXDOMAIN"]},{"type":"dsl","dsl":["contains(cname, \"azure-api.net\")","contains(cname, \"azure-mobile.net\")","contains(cname, \"azurecontainer.io\")","contains(cname, \"azurecr.io\")","contains(cname, \"azuredatalakestore.net\")","contains(cname, \"azureedge.net\")","contains(cname, \"azurefd.net\")","contains(cname, \"azurehdinsight.net\")","contains(cname, \"azurewebsites.net\")","contains(cname, \"azurewebsites.windows.net\")","contains(cname, \"blob.core.windows.net\")","contains(cname, \"cloudapp.azure.com\")","contains(cname, \"cloudapp.net\")","contains(cname, \"database.windows.net\")","contains(cname, \"redis.cache.windows.net\")","contains(cname, \"search.windows.net\")","contains(cname, \"servicebus.windows.net\")","contains(cname, \"trafficmanager.net\")","contains(cname, \"visualstudio.com\")"]}],"extractors":[{"type":"dsl","dsl":["cname"]}],"matchers-condition":"and","name":"{{FQDN}}","type":"A","retries":3,"attack":"","recursion":true}],"signature":"","variables":{}}

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

    • Improved JSON serialization and deserialization for templates, enhancing data handling.
    • Ensured unique request ID assignment for multiple requests across various protocols.
  • Bug Fixes

    • Resolved issues with infinite recursion during JSON marshaling.

@dogancanbakir dogancanbakir self-assigned this Dec 4, 2024
@auto-assign auto-assign bot requested a review from dwisiswant0 December 4, 2024 06:05
Copy link

coderabbitai bot commented Dec 4, 2024

Walkthrough

The changes in this pull request focus on enhancing the JSON marshaling and unmarshaling processes for the Template struct in pkg/templates/templates.go. The MarshalJSON and UnmarshalJSON methods have been updated to use type aliases to prevent recursion during JSON operations. Additionally, the validateAllRequestIDs method has been modified to ensure unique request ID assignment across multiple protocols. These updates aim to resolve the stack overflow issue encountered during JSON marshaling.

Changes

Files Change Summary
pkg/templates/templates.go Updated MarshalJSON and UnmarshalJSON methods to use type aliases to avoid recursion. Modified validateAllRequestIDs method for unique request ID assignment.

Assessment against linked issues

Objective Addressed Explanation
Resolve stack overflow during JSON marshaling (#[5882])

🐰 In the meadow where templates play,
A rabbit found a brand new way.
With aliases in hand, no more stack woes,
JSON marshaling now smoothly flows!
Unique IDs for requests, oh what a delight,
Hopping through code, everything feels right! 🌼


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

@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

🧹 Outside diff range and nitpick comments (3)
pkg/templates/templates.go (3)

524-527: Consider validating the template before marshaling.

Currently, validation occurs after marshaling. It's generally better to validate the template before attempting to marshal it. This ensures that only valid data is marshaled, and any validation errors are caught early.

Apply this diff to perform validation prior to marshaling:

 func (template *Template) MarshalJSON() ([]byte, error) {
+    errValidate := validate.New().Struct(template)
+    if errValidate != nil {
+        return nil, errValidate
+    }
     type TemplateAlias Template // avoid recursion
     out, marshalErr := json.Marshal((*TemplateAlias)(template))
-    errValidate := validate.New().Struct(template)
     return out, marshalErr
 }

Line range hint 536-538: Use consistent type alias naming in UnmarshalJSON.

In UnmarshalJSON, consider renaming the type alias from Alias to TemplateAlias for consistency with MarshalJSON. This improves code readability and maintains a consistent coding style.

Apply this diff to rename the type alias:

 func (template *Template) UnmarshalJSON(data []byte) error {
-    type Alias Template
-    alias := &Alias{}
+    type TemplateAlias Template
+    alias := &TemplateAlias{}
     err := json.Unmarshal(data, alias)
     if err != nil {
         return err

Line range hint 549-551: Error message clarity in UnmarshalJSON.

The error message when failing to unmarshal a multi-protocol template includes the template ID. Ensure that template.ID is correctly populated at this point; otherwise, the error message may be less informative.

If template.ID might not be set before this point, consider including more context or verifying that the ID is available.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 2549592 and 3bd20de.

📒 Files selected for processing (1)
  • pkg/templates/templates.go (1 hunks)
🔇 Additional comments (2)
pkg/templates/templates.go (2)

524-525: Properly prevent recursion in MarshalJSON using a type alias.

The introduction of TemplateAlias as a type alias for Template effectively prevents infinite recursion during JSON marshaling. This is a correct implementation to avoid stack overflow errors when the struct implements MarshalJSON.


Line range hint 542-555: Verify the handling of multiple requests during unmarshaling.

When checking for multiple requests, the code unmarshals the JSON data into a tempMap to preserve the order of protocols and requests. Ensure that this approach correctly handles all possible cases and does not introduce any unintended side effects.

To verify, consider running tests with templates that have multiple requests of various protocols and confirm that the order is preserved and no data is lost or corrupted.

@ehsandeep ehsandeep merged commit 358249b into dev Dec 19, 2024
20 checks passed
@ehsandeep ehsandeep deleted the fix_inf_recursion branch December 19, 2024 15:06
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] ... json marshal template panic stack overflow
3 participants