T09 · Insecure Skill Coding Practices
- Location
scripts/lyrics_creator.py:276- Finding
Path Traversal Allows File Writes Outside the Intended Song Directory
- Content
View full analysis
Path: file = DATA_DIR / f"{title}.txt" content = f"# {title}\n# 風格:{genre} | BPM:{bpm}\n# 建立:{datetime.now().strftime('%Y-%m-%d')}\n\n{lyrics}" file.write_text(content, encoding="utf-8") return file ``` ### Technical Analysis The `title` parameter is supplied through the command line and incorporated directly into the destination path without filename sanitization or containment validation. A title containing parent-directory components such as `../`, directory separators, or an absolute path can cause the resulting destination to fall outside the documented `~/.karaoke-companion/songs/` directory. Python's `pathlib` also discards the preceding base path when the appended path is absolute. Consequently, an absolute title can directly select another writable location, subject to the automatically appended `.txt` suffix. The function then calls `Path.write_text()`, which truncates and overwrites an existing destination by default. The code does not verify the resolved path, restrict the title to a filename, or request confirmation before overwriting an existing file. ### Attack Path 1. An attacker, untrusted caller, or injected command invokes the `save` operation with a crafted title. 2. The title contains traversal components or an absolute path, for example: ```bash python3 scripts/lyrics_creator.py save /tmp/attacker-controlled \ --lyrics "controlled content" ``` 3. `save_song()` evaluates the destination as `/tmp/attacker-controlled.txt` rather than a file under `DATA_DIR`. 4. `write_text()` creates that file or overwrites it if it already exists and is writable. 5. A traversal title can similarly target other existing directori ...[truncated 985 chars]- Remediation
View remediation
Path: safe_title = re.sub(r"[^A-Za-z0-9 _.-]", "_", title).strip(" .") if not safe_title or safe_title in {".", ".."}: raise ValueError("Invalid song title") base = DATA_DIR.resolve() destination = (base / f"{safe_title}.txt").resolve() if destination.parent != base: raise ValueError("Destination must remain inside the song directory") content = ( f"# {title}\n" f"# Genre: {genre} | BPM: {bpm}\n" f"# Created: {datetime.now().strftime('%Y-%m-%d')}\n\n" f"{lyrics}" ) with destination.open("x", encoding="utf-8") as output: output.write(content) return destination ``` If legitimate overwriting is required, expose it through an explicit option and still enforce resolved-path containment. ]]>
