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 template signing singnature issue #5869

Merged
merged 4 commits into from
Dec 2, 2024
Merged

fix template signing singnature issue #5869

merged 4 commits into from
Dec 2, 2024

Conversation

tarunKoyalwar
Copy link
Member

@tarunKoyalwar tarunKoyalwar commented Dec 1, 2024

Proposed changes

Context

  • Original cause of the issue was CRLF and LF issue between the distro , this is now handled by converting to CRLF to LF ( before verifiying) this acts as normalization for consistent content signature

New Changes

  • Added a simple utility to Sign templates ( one at a time) with verbose and drilled down logging (for debugging purpose)
./bin/template-signer -template x.yaml                                                      
[INF] Template Signer: tarun
[INF] Signature Details:
[INF] ----------------
[INF] Signature: # digest: 490a00463044022027008c7f5e693a743c1f6f227f77062858a299ab71dcc8c942b4536baeaed7310220794c85a236515e3ca2a068ec329dce951c2241ce5bf46d52d84329cdcee22ea4:73812c4e0e52692225979bd2d5f05a3c
[INF] Content Hash (SHA256): 0a9dfd57055b184bcca8ae6db5467dfbd46c6c6e60c839c44331eaeddecbb5bd
[VER] template allow-unencrypted-ftp verified by projectdiscovery/nuclei-templates : false
[VER] template allow-unencrypted-ftp verified by tarun : true
[INF] Template Verified: true
[INF] ✓ Template signed & verified successfully

Verified if there are consistency by using this utility be testing multiple conditions like adding / removing new lines , changing distro's etc

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

  • Chores
    • Updated .gitignore patterns to broaden the scope for ignoring certain files in subdirectories.
    • Removed multiple entries from the "Binaries" section, allowing specific binaries to be tracked at the root level.
  • New Features
    • Introduced a command-line tool for signing templates with specified certificates and private keys.
    • Added a new build target for the template-signer component in the Makefile.
  • Improvements
    • Enhanced logging during the template verification process for better tracking and visibility.
    • Improved content handling in the template signing process to ensure consistent formatting.

@auto-assign auto-assign bot requested a review from dwisiswant0 December 1, 2024 14:46
Copy link
Contributor

coderabbitai bot commented Dec 1, 2024

Walkthrough

The pull request involves modifications to the .gitignore file, specifically updating patterns for ignoring certain file types and altering the handling of binary files. The patterns for .DS_Store and .exe files have been changed to include subdirectories, while numerous entries in the "Binaries" section have been removed, allowing those binaries to be tracked at the root level instead of being ignored. Additionally, a new target for building a template-signer component has been added to the Makefile, along with the introduction of a command-line tool for signing templates in cmd/tools/signer/main.go. Logging enhancements have been made in pkg/templates/compile.go.

Changes

File Change Summary
.gitignore Updated patterns for ignoring .DS_Store and .exe files to **/*.DS_Store and **/*.exe. Removed multiple entries from the "Binaries" section, changing patterns from **/ to / for various binaries, indicating they will now be tracked.
Makefile Added a new target template-signer with output location ./bin/template-signer and source package cmd/tools/signer/main.go.
cmd/tools/signer/main.go Introduced a command-line tool for signing templates, implementing functions for processing and verifying templates.
pkg/templates/compile.go Enhanced logging during the template verification process, adding verbose messages for better tracking.

Assessment against linked issues

Objective Addressed Explanation
Sign should not be platform dependent and should work cross distro's (#5868) The changes do not explicitly address platform dependency issues. Further investigation is needed to confirm if the signing process resolves the reported bug.

Poem

In the land of code where rabbits play,
The .gitignore has found a new way.
With patterns updated, it hops with glee,
Tracking binaries now, oh what a spree!
No more hiding, let them shine bright,
In the burrow of code, all feels just right! 🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between b319797 and e6a0525.

📒 Files selected for processing (1)
  • pkg/templates/signer/tmpl_signer.go (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • pkg/templates/signer/tmpl_signer.go

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

🧹 Outside diff range and nitpick comments (1)
.gitignore (1)

14-30: Consider the implications of restricting binary ignores to root level

The change from **/pattern to /pattern means binaries will only be ignored in the root directory. This could lead to:

  1. Unintended tracking of binaries in subdirectories
  2. Potential repository bloat if large binaries are committed
  3. Security concerns if sensitive binaries exist in subdirectories

Consider keeping the **/ prefix for critical binaries like nuclei, debug-*, and nuclei-stats*.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 557b4fb and e319146.

📒 Files selected for processing (1)
  • .gitignore (1 hunks)
🔇 Additional comments (2)
.gitignore (2)

14-30: Verify binary locations in the codebase

Let's verify if any of these binaries exist in subdirectories that would now be tracked.

✅ Verification successful

The .gitignore entries are correctly placed and necessary

The search results show that these entries in .gitignore are for build artifacts and binaries that would be generated in the root directory:

  • Source files exist in subdirectories (e.g., cmd/docgen/docgen.go, cmd/integration-test/integration-test.go) but the .gitignore entries are for their compiled binaries in the root
  • Main entry points found in cmd/ and other directories are source files, not the compiled binaries
  • No binary files were found in subdirectories that would be incorrectly tracked
  • The patterns match the standard Go build output location, where binaries are placed in the root directory by default
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for binary files in subdirectories that would now be tracked

# Look for potential binary files in subdirectories
for pattern in bindgen debug- docgen functional-test fuzzplayground integration-test jsdocgen main memogen nuclei nuclei-stats nuclei_dev nuclei_main scan-charts scrapefunc scrapefuncs tsgen; do
  echo "Checking for '$pattern' in subdirectories:"
  fd -t f "$pattern" --min-depth 2
done

# Check if any of these are actually needed for template signing
rg -i "template.*sign.*binary" --type go -A 5

Length of output: 6462


5-6: Verify if .exe files are needed for template signing

While the **/*.DS_Store pattern is a good improvement, the **/*.exe pattern might be too restrictive if any executables are needed for template signing. Please verify if this change could impact the template signing process.

✅ Verification successful

Based on the extensive search results, I can now provide a definitive response about the .exe files and template signing concern:

The .gitignore change is safe and won't impact template signing

The template signing functionality in Nuclei is based on cryptographic signatures stored within the template files themselves, not on executable files. The signing process:

  1. Uses ECDSA signatures stored at the end of template files
  2. Is verified using public key certificates
  3. Does not rely on any .exe files for verification

The change from *.exe to **/*.exe in .gitignore is safe because:

  • Template signing is implemented through code signatures within YAML template files
  • The signing process uses cryptographic keys and certificates, not executables
  • No .exe files are required for the template signing or verification process
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if there are any .exe files in the repository that might be needed
# for template signing

# Search for references to .exe files in the codebase
rg -i "\.exe" --type go -g '!.gitignore' -A 5

# Look for any template signing related files
rg -i "template.*sign" --type go -A 5

Length of output: 70358


Script:

#!/bin/bash
# Look for template signing related files and functionality
rg -i "template.*sign|sign.*template" --type go -A 5

# Look for any signing related configuration or documentation
fd -e md -e txt "sign" -X cat {}

Length of output: 72167

Copy link
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

🧹 Outside diff range and nitpick comments (1)
cmd/tools/signer/main.go (1)

87-93: Refactor repeated code into a helper function

The code for reading the template file, extracting the signature and content, and computing the hash is repeated. Refactoring this into a helper function enhances maintainability and reduces duplication.

Proposed refactoring:

+func readTemplateSignatureAndHash(template string) (string, [32]byte, error) {
+    bin, err := os.ReadFile(template)
+    if err != nil {
+        return "", [32]byte{}, err
+    }
+    sig, content := signer.ExtractSignatureAndContent(bin)
+    content = bytes.ReplaceAll(content, []byte("\r\n"), []byte("\n"))
+    hash := sha256.Sum256(content)
+    return sig, hash, nil
+}

 // Before signing
-sig, content := signer.ExtractSignatureAndContent(bin)
-hash := sha256.Sum256(content)
+sig, hash, err := readTemplateSignatureAndHash(template)
+if err != nil {
+    gologger.Fatal().Msgf("failed to read template file %s: %s", template, err)
+}

 // After signing
-bin2, err := os.ReadFile(template)
-if err != nil {
-    gologger.Fatal().Msgf("failed to read signed template file %s: %s", template, err)
-}
-sig2, content2 := signer.ExtractSignatureAndContent(bin2)
-hash2 := sha256.Sum256(content2)
+sig2, hash2, err := readTemplateSignatureAndHash(template)
+if err != nil {
+    gologger.Fatal().Msgf("failed to read signed template file %s: %s", template, err)
+}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between e319146 and ab7ee32.

📒 Files selected for processing (3)
  • Makefile (1 hunks)
  • cmd/tools/signer/main.go (1 hunks)
  • pkg/templates/compile.go (1 hunks)
🔇 Additional comments (2)
Makefile (1)

45-48: LGTM!

The new template-signer build target is correctly defined and follows the existing pattern.

pkg/templates/compile.go (1)

454-456: LGTM!

Adding verbose logging for template verification improves traceability and debugging.

cmd/tools/signer/main.go Show resolved Hide resolved
Copy link
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: 0

🧹 Outside diff range and nitpick comments (4)
pkg/templates/signer/tmpl_signer.go (4)

20-20: Consider using yaml.v3 instead of yaml.v2

While yaml.v2 works, yaml.v3 provides better performance, security features, and handles line endings more consistently. However, this change should align with the project's overall yaml package usage.


38-48: Add error logging for YAML parsing failures

While the fallback to original content is correct, logging YAML parsing errors would help with debugging template issues.

 var normalized interface{}
 if err := yaml.Unmarshal(content, &normalized); err != nil {
+    gologger.Debug().Msgf("Failed to normalize template content: %v", err)
     return signature, content
 }
 normalizedBytes, err := yaml.Marshal(normalized)
 if err != nil {
+    gologger.Debug().Msgf("Failed to marshal normalized template content: %v", err)
     return signature, content
 }

40-40: Consider using a more specific type for YAML unmarshalling

Using interface{} for YAML unmarshalling is very broad. Consider using a more specific type that represents your template structure to catch potential issues earlier.


38-48: Add test cases for cross-platform signature verification

The changes aim to fix cross-platform signature issues. Please add test cases that verify:

  1. Templates signed on Linux work on Windows
  2. Templates signed on Windows work on Linux
  3. Templates with various line endings (CRLF, LF) are handled correctly

Would you like me to help create these test cases?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between ab7ee32 and b319797.

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

38-48: LGTM - Clean solution for cross-platform signature normalization

The YAML-based normalization approach is a robust solution for handling cross-platform line ending differences. It's more reliable than string replacement and handles edge cases well.


38-48: Verify the impact on template formatting

The YAML normalization might affect templates that rely on specific formatting or whitespace. Please ensure this change doesn't break any existing templates, especially those with:

  1. Multi-line strings
  2. Custom indentation
  3. Specific line ending requirements in payloads
✅ Verification successful

Based on the test files and implementation review, I can now provide the final response:

YAML normalization is safe for template formatting

The implementation is safe because:

  1. The normalization is only used for signature verification, not template execution
  2. The test cases demonstrate that the original content is returned if YAML parsing fails
  3. The code includes a specific comment acknowledging payload preservation: "if we use strings.ReplaceAll(content,"\r\n","\n"), it most likely will break some payload in logic"

The test suite verifies:

  • Simple templates
  • Templates with imports
  • Templates with code protocols
  • Various tampering scenarios

All while preserving the original content when YAML parsing fails, which acts as a safety mechanism for any non-standard YAML content.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for templates that might be affected by YAML normalization

# Look for templates with multi-line strings or specific formatting
rg -l '(?m)^\s*[^#\n-][^:]+:\s*\|\s*$' 

# Look for templates with potential whitespace-sensitive payloads
rg -l '(?m)^\s*payload:\s*\|\s*$'

Length of output: 2698


Script:

#!/bin/bash
# Let's check for actual template files with multi-line content and analyze their structure

# First, let's look at template files specifically
fd -e yaml -e yml . pkg/templates integration_tests/templates | xargs rg -l '(?m)^\s*[^#\n-][^:]+:\s*\|\s*$'

# Then, let's examine a few examples of templates with multi-line content to understand their structure
fd -e yaml -e yml . pkg/templates integration_tests/templates | xargs rg -A 5 '(?m)^\s*[^#\n-][^:]+:\s*\|\s*$'

# Also check for any documentation or tests mentioning template formatting requirements
rg -i "template.*format|formatting.*template" -A 3 pkg/templates

Length of output: 1887


Script:

#!/bin/bash
# Let's examine the actual implementation and usage of the YAML normalization

# Check the signer package for any tests or documentation about formatting preservation
rg -A 5 "yaml\." pkg/templates/signer/

# Look for any existing test files that verify template signing behavior
fd ".*test.*\.go" pkg/templates/signer/

# Check if there are any existing test templates used for signing verification
fd -e yaml -e yml . pkg/templates/signer/testdata

Length of output: 1220


Script:

#!/bin/bash
# Let's examine the test files to understand how YAML normalization is tested

# Check the test files content
cat pkg/templates/signer/tmpl_signer_test.go
cat pkg/templates/signer/handler_test.go

# Look for any test cases that specifically deal with formatting
rg -A 10 "TestSign|TestVerify" pkg/templates/signer/

Length of output: 5151

@tarunKoyalwar tarunKoyalwar self-assigned this Dec 1, 2024
@ehsandeep ehsandeep removed the request for review from dwisiswant0 December 2, 2024 09:01
@ehsandeep ehsandeep merged commit 16735f5 into dev Dec 2, 2024
22 checks passed
@ehsandeep ehsandeep deleted the fix-signature-issue branch December 2, 2024 09:01
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] Templates Signed in Linux not working in windows
3 participants