T09 · Insecure Skill Coding Practices
- Location
scripts/farm_task_manager.py:39- Finding
Insufficient path validation permits file overwrite outside the intended workspace
- Content
View full analysis
bool: """Validate a file path is safe for writing. Blocks system paths and sensitive dotfiles. Allows workspace and home directories. """ path = Path(filepath).expanduser().resolve() # Allow workspace and home allowed_paths = [ WORKSPACE, Path.home(), ] # Block system paths blocked_paths = [ Path("/etc"), Path("/usr"), Path("/var"), Path("/root"), Path("/bin"), Path("/sbin"), Path("/boot"), Path("/lib"), Path("/opt"), ] # Block sensitive dotfiles sensitive_patterns = [ ".ssh", ".bashrc", ".zshrc", ".bash_profile", ".zprofile", ".bash_history", ".zsh_history", ".aws", ".env", ".secret", ".token", ".key", ] # Check if path is allowed is_allowed = any(str(path).startswith(str(allowed)) for allowed in allowed_paths) # Check if path is blocked is_blocked = any(str(path).startswith(str(blocked)) for blocked in blocked_paths) # Check for sensitive dotfiles in path has_sensitive = any(f"/{s}/" in str(path) or f"/{s}" in str(path) for s in sensitive_patterns) return is_allowed and not is_blocked and not has_sensitive ``` The validated path is subsequently opened in truncating write mode: ```python if not is_safe_path(args.file): print(f"Error: Unsafe path {args.file}") return try: args.file.parent.mkdir(parents=True, exist_ok=True) if format_type == "json": with open(args.file, 'w') as f: json.dump(tasks, f, indent=2) ``` # ...[truncated 3146 chars]- Remediation
View remediation
bool: export_root = EXPORT_DIR.resolve() candidate = Path(filepath).expanduser().resolve(strict=False) try: candidate.relative_to(export_root) except ValueError: return False return candidate != export_root ``` On supported Python versions, `candidate.is_relative_to(export_root)` may be used instead. 3. Do not rely on a sensitive-file denylist as the primary authorization control. Use a narrowly scoped allowlist root. 4. Avoid silently truncating existing files. Use exclusive creation mode (`x`) by default, or require an explicit overwrite option and confirmation. 5. Mitigate validation-to-open race conditions and symlink attacks. Where practical, open files relative to a trusted directory descriptor and use platform protections such as `O_NOFOLLOW`. 6. Write to a temporary file inside the approved export directory, flush and synchronize it, and atomically replace the final destination only after all validation succeeds. 7. Add regression tests covering: - Paths within the dedicated export directory. - `..` traversal attempts. - Prefix-collision paths such as `/home/user-other/file`. - Unapproved home files such as `~/.profile`. - Existing-file overwrite attempts. - Symlinks pointing outside the approved export directory. ]]>
