T09 · Insecure Skill Coding Practices
- Location
scripts/batch_rename.py:28- Finding
Path Traversal in Batch Rename Destination
- Content
View full analysis
Vulnerability Details
File Location:
scripts/batch_rename.py, lines 28–47
Vulnerability Type: Unvalidated destination path / path traversal
Risk Level: HighVulnerable Code
python if regex: try: new_name = re.sub(pattern, replacement, old_name) except re.error as e: print(f"[ERROR] Regular expression error: {e}") continue else: new_name = old_name.replace(pattern, replacement) if new_name == old_name: skipped.append(old_name) continue new_path = f.parent / new_name if preview: print(f" Preview: {old_name} → {new_name}") else: if new_path.exists(): print(f"[SKIP] Destination already exists: {new_name}") skipped.append(old_name) continue f.rename(new_path)Technical Analysis
The replacement value is controlled through command-line arguments and is used to construct
new_pathwithout ensuring that the resulting value is a simple filename. A replacement can contain parent-directory components such as../, directory separators, or an absolute path.With
pathlib, joining a parent path with an absolute second operand produces the absolute path itself. Relative traversal components can similarly resolve outsidef.parent. When execution mode is enabled,f.rename(new_path)therefore permits moving a selected source file outside the directory the user intended to process.The existing destination check prevents replacement of an existing target in this function, but it does not stop relocation to a new attacker-selected path.
Attack Path
- An attacker or untrusted automation configuration supplies a crafted replacement containing
../components or an absolute path. - A user or agent invokes the
replacecommand with--execute. - The script derives
new_namefrom the untrusted replacement. f.parent / new_nameresolves outside the selected directory.- `f. ...[truncated 581 chars]
- An attacker or untrusted automation configuration supplies a crafted replacement containing
- Remediation
View remediation
Remediation Suggestions
Treat the generated value strictly as a filename rather than a path:
- Reject absolute paths.
- Reject
/,\, empty names,.and... - Verify that
Path(new_name).name == new_name. - Resolve the destination and confirm that its parent is exactly the resolved source directory.
- Refuse execution if containment validation fails.
- Consider a restrictive allowlist for characters permitted in generated filenames.
- Add tests covering absolute paths, nested paths,
../traversal, Windows drive paths, UNC paths, and mixed separators.
Example containment validation:
python candidate = Path(new_name) if candidate.is_absolute() or candidate.name != new_name or new_name in {".", ".."}: raise ValueError("Replacement must produce a plain filename") parent = f.parent.resolve() new_path = (parent / new_name).resolve() if new_path.parent != parent: raise ValueError("Destination escapes the source directory")
