T09 · Insecure Skill Coding Practices
- Location
scripts/template_manager.py:45- Finding
Template Name Path Traversal Enables Filesystem Access Outside the Template Directory
- Content
View full analysis
\n\n{body}" else: full_content = f"# SUBJECT: {subject}\n\n{body}" # Save template try: with open(template_path, 'w', encoding='utf-8') as f: f.write(full_content) ``` ```python # scripts/template_manager.py:162-179 html_path = os.path.join(TEMPLATES_DIR, f"{template_name}.html") txt_path = os.path.join(TEMPLATES_DIR, f"{template_name}.txt") template_path = None if os.path.exists(html_path): template_path = html_path elif os.path.exists(txt_path): template_path = txt_path else: print(f"⚠️ Template '{template_name}' does not exist.") return False # Delete file try: os.remove(template_path) ``` ### Technical Analysis The `template_name` value is concatenated into filesystem paths without validating its character s ...[truncated 2102 chars]- Remediation
View remediation
str: if not SAFE_TEMPLATE_NAME.fullmatch(name): raise ValueError("Invalid template name") return name ``` 2. Resolve every candidate path and verify directory containment: ```python from pathlib import Path TEMPLATE_ROOT = Path(TEMPLATES_DIR).resolve() def safe_template_path(name: str, extension: str) -> Path: validate_template_name(name) candidate = (TEMPLATE_ROOT / f"{name}{extension}").resolve() if candidate.parent != TEMPLATE_ROOT: raise ValueError("Template path escapes the template directory") return candidate ``` 3. Reject absolute paths, path separators, `..`, null bytes, and unexpected extensions. 4. Apply the same safe path-construction function consistently to load, create, overwrite, and delete operations. 5. For writes, consider atomic creation with exclusive mode when overwrite is not explicitly authorized. 6. Add tests covering `../`, absolute paths, nested traversal, symbolic links, and platform-specific separators. 7. If untrusted local users can modify the template directory, address symbolic-link traversal by opening files through a trusted directory descriptor and disabling symlink following where supported. ]]>
