T09 · Insecure Skill Coding Practices
- Location
scripts/design_pipeline.py:354- Finding
Predictable Temporary File Names Permit Unintended File Overwrite and Deletion
- Content
View full analysis
Vulnerability Details
File Location:
scripts/design_pipeline.py:215,scripts/design_pipeline.py:272, andscripts/design_pipeline.py:354-372
Vulnerability Type: Predictable and unsafe temporary-file handling
Risk Level: MediumVulnerable Code
python def автоулучшение(путь, детали, итерация=1): """ Автоматическое улучшение на основе слабых метрик. Возвращает путь к улучшенному файлу. """ print(f"\n Итерация улучшения #{итерация}") tmp = путь.replace(".png", f"_improved_{итерация}.png")python # Промежуточный файл tmp_output = output.replace(".png", "_draft.png")python # Сохраняем финальный результат from PIL import Image as PILImage final = PILImage.open(текущий) output_dir = os.path.dirname(output) if output_dir: os.makedirs(output_dir, exist_ok=True) final.save(output, "PNG", quality=95) # Очистка промежуточных файлов for f in [tmp_output] + [ output.replace(".png", f"_improved_{i}.png") for i in range(1, макс_итераций + 1) ]: if f != output and os.path.exists(f): try: os.remove(f) except Exception: passTechnical Analysis
The pipeline constructs temporary file names deterministically by applying string replacement to the caller-controlled
outputpath. It does not use exclusive temporary-file creation, verify whether a derived path existed before the current run, or maintain an authoritative list of files created by the current invocation.For example, an output path named
report.pngproduces predictable sibling paths such as:report_draft.pngreport_improved_1.pngreport_improved_2.pngreport_improved_3.png
If any of those files already exist, image-generation or improvement operations can overwrite them. The cleanup loop subsequently deletes every matching predictable path that exists, regardless of whether the current p ...[truncated 1766 chars]
- Remediation
View remediation
Remediation Suggestions
- Use
tempfile.TemporaryDirectory()to place all intermediate files in a unique, isolated directory created for the current invocation. - Alternatively, use
tempfile.NamedTemporaryFile()ortempfile.mkstemp()with exclusive creation rather than deriving temporary paths from the final output name. - Maintain an explicit collection of temporary paths successfully created by the current process. Cleanup must operate only on that collection.
- Never delete a path merely because it matches a predictable naming pattern.
- Construct paths with
pathlib.Pathand inspect suffixes with.suffixor generate names with.with_name()instead of using unrestricted string replacement. - Write the final image to a unique temporary file in the destination directory and publish it with
os.replace()only after successful generation. This provides atomic finalization while avoiding partially written output. - Reject or explicitly confirm overwriting when the requested final output already exists.
- Replace broad exception suppression with specific exception handling and visible error reporting or logging.
- Where symlink-based attacks are relevant, validate that output and temporary paths are regular files under an approved directory and use secure open semantics supported by the target platform.
A safer structure is:
python from pathlib import Path from tempfile import TemporaryDirectory import os destination = Path(output).resolve() destination.parent.mkdir(parents=True, exist_ok=True) with TemporaryDirectory( prefix=".design-pipeline-", dir=destination.parent, ) as temp_directory: temp_root = Path(temp_directory) draft_path = temp_root / "draft.png" improved_paths = [ temp_root / f"improved_{index}.png" for index in range(1, max_iterations + 1) ] # Generate and process only within temp_root. # After successful completion: ...[truncated 141 chars]- Use
