Skip to content

Conversation

kn1g78
Copy link

@kn1g78 kn1g78 commented Aug 8, 2025

This error always occurs when a new version of nuclei is initialized or when updating a template.

[INF] Your current nuclei-templates  are outdated. Latest is v10.2.6
[ERR] Could not find template 'C:\Users\admin\nuclei-templates': no templates found in path C:\Users\admin\nuclei-templates
[WRN] Found 24 template[s] loaded with deprecated paths, update before v3 for continued support.
[INF] Current nuclei version: v3.4.7 (latest)
[INF] Current nuclei-templates version:  (outdated)
[WRN] Scan results upload to cloud is disabled.
[INF] Scan completed in 0s. No results found.
[FTL] Could not run nuclei: no templates provided for scan

In fact, the C:\Users\admin\nuclei-templates directory is empty.
My modification solves the following issues:

  1. Empty directory issue: Fixed the issue of creating an empty nuclei-templates folder with the .nuclei.exe -update-templates command
  2. Windows Path Compatibility: Improved path handling on Windows systems
  3. Auto-initialize: Ensure that .nuclei.exe automatically downloads templates on the first run

Summary by CodeRabbit

  • Bug Fixes
    • Improved file path validation to enhance security and prevent local file inclusion vulnerabilities.
    • Ensured directories are created as needed before writing files, reducing errors when saving to new locations.

@auto-assign auto-assign bot requested a review from dogancanbakir August 8, 2025 14:26
Copy link
Contributor

coderabbitai bot commented Aug 8, 2025

Walkthrough

The update strengthens file path validation in the template installer by replacing a basic prefix check with a relative path computation to prevent directory traversal vulnerabilities. Additionally, the code now ensures that target directories exist before writing files, reducing the risk of file write errors due to missing directories.

Changes

Cohort / File(s) Change Summary
Template File Path Validation and Directory Handling
pkg/installer/template.go
Enhanced file path validation using filepath.Rel to prevent LFI vulnerabilities; ensured target directories are created before writing files.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~7 minutes

Poem

A rabbit hopped through code so neat,
Guarding paths from sly deceit.
No files stray where they shouldn't go,
Directories made, all in a row.
With every hop, security grows—
Safe and sound, the template flows! 🐇✨

Note

🔌 MCP (Model Context Protocol) integration is now available in Early Access!

Pro users can now connect to remote MCP servers under the Integrations page to get reviews and chat conversations that understand additional development context.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 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.
  • 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.

Support

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

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 generate unit tests to generate unit tests for 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
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 comments (1)
pkg/installer/template.go (1)

221-226: Critical: LFI guard is bypassed for root-level/absolute entries (uri without '/').

When strings.Index(uri, "/") == -1, the function returns early with filepath.Join(templateDir, uri) and never runs the filepath.Rel containment check. Join returns a clean path and will discard the base for absolute uris (e.g., "/etc/passwd" or "C:\Windows..."), allowing writes outside templateDir.

Fix by unifying path derivation and always applying the Rel-based containment check.

Proposed refactor (outside the changed hunk) to eliminate the early return and consistently run the guard:

// getAbsoluteFilePath returns an absolute path where a file should be written based on given uri(i.e., files in zip)
// if a returned path is empty, it means that file should not be written and skipped
func (t *TemplateManager) getAbsoluteFilePath(templateDir, uri string, f fs.FileInfo) string {
	// overwrite .nuclei-ignore every time nuclei-templates are downloaded
	if f.Name() == config.NucleiIgnoreFileName {
		return config.DefaultConfig.GetIgnoreFilePath()
	}
	// skip all meta files
	if !strings.EqualFold(f.Name(), config.NewTemplateAdditionsFileName) {
		if strings.TrimSpace(f.Name()) == "" || strings.HasPrefix(f.Name(), ".") || strings.EqualFold(f.Name(), "README.md") {
			return ""
		}
	}

	// Extract relative part from "projectdiscovery-nuclei-templates-<hash>[/...]"
	index := strings.Index(uri, "/")
	var relPath string
	if index == -1 {
		// No directory component in zip entry; still proceed with containment checks
		gologger.Warning().Msgf("failed to get directory name from uri: %s", uri)
		relPath = uri
	} else {
		rootDirectory := uri[:index+1] // includes separator
		relPath = strings.TrimPrefix(uri, rootDirectory)
	}

	// if it is a github meta directory skip it
	if stringsutil.HasPrefixAny(relPath, ".github", ".git") {
		return ""
	}

	newPath := filepath.Clean(filepath.Join(templateDir, relPath))

	// Robust containment check
	relPathToTemplateDir, err := filepath.Rel(templateDir, newPath)
	if err != nil {
		return ""
	}
	if relPathToTemplateDir == ".." || strings.HasPrefix(relPathToTemplateDir, ".."+string(os.PathSeparator)) {
		// we don't allow LFI
		return ""
	}

	if newPath == templateDir || newPath == templateDir+string(os.PathSeparator) {
		// skip writing the folder itself since it already exists
		return ""
	}

	if relPath != "" && f.IsDir() {
		// if uri is a directory, create it
		if err := fileutil.CreateFolder(newPath); err != nil {
			gologger.Warning().Msgf("uri %v: got %s while installing templates", uri, err)
		}
		return ""
	}
	return newPath
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8ef3662 and c0d213a.

📒 Files selected for processing (1)
  • pkg/installer/template.go (2 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-07-16T21:27:14.937Z
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.

Applied to files:

  • pkg/installer/template.go
🔇 Additional comments (1)
pkg/installer/template.go (1)

282-287: Solid fix: ensure parent directories exist before file writes.

This addresses cases where archive entries are streamed before their directory entries (common on Windows), preventing empty-tree installs.

Comment on lines +238 to 241
// Use filepath.Rel for more robust path comparison
relPathToTemplateDir, err := filepath.Rel(templateDir, newPath)
if err != nil || strings.HasPrefix(relPathToTemplateDir, "..") {
// we don't allow LFI
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Good hardening; make the '..' check segment-aware to avoid false positives.

Using filepath.Rel is the right fix. Replace the plain prefix check with a segment-aware one so names like "..." don’t get incorrectly rejected.

-	relPathToTemplateDir, err := filepath.Rel(templateDir, newPath)
-	if err != nil || strings.HasPrefix(relPathToTemplateDir, "..") {
+	relPathToTemplateDir, err := filepath.Rel(templateDir, newPath)
+	if err != nil {
+		return ""
+	}
+	// Disallow any path that escapes templateDir (first segment is "..")
+	if relPathToTemplateDir == ".." || strings.HasPrefix(relPathToTemplateDir, ".."+string(os.PathSeparator)) {
 		// we don't allow LFI
 		return ""
 	}
🤖 Prompt for AI Agents
In pkg/installer/template.go around lines 238 to 241, the current check for
directory traversal uses strings.HasPrefix to detect ".." which can cause false
positives with names like "...". Replace this with a segment-aware check by
splitting relPathToTemplateDir using filepath separators and verifying if any
segment equals "..". This ensures only actual directory traversal attempts are
blocked without rejecting valid paths.

@dwisiswant0
Copy link
Member

how has this been tested? and why is the current template version empty (seems like an edge case)?

@kn1g78
Copy link
Author

kn1g78 commented Aug 16, 2025

how has this been tested? and why is the current template version empty (seems like an edge case)?

I always experience this in my daily use, but I don't know the exact cause, and I've seen it in many Issues.

@Mzack9999 Mzack9999 self-requested a review September 12, 2025 15:20
Copy link
Member

@Mzack9999 Mzack9999 left a comment

Choose a reason for hiding this comment

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

I guess it would be enough in the function FreshInstallIfNotExists() to check not only if the folder exist but if it's empty. What do you think?

@kn1g78
Copy link
Author

kn1g78 commented Sep 26, 2025

I guess it would be enough in the function to check not only if the folder exist but if it's empty. What do you think?FreshInstallIfNotExists()

I think it's okay.

@dogancanbakir dogancanbakir removed their request for review October 7, 2025 12:49
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.

3 participants