T09 · Insecure Skill Coding Practices
- Location
scripts/state_manager.py:24- Finding
Path Traversal Enables Arbitrary JSON File Read and Overwrite
- Content
View full analysis
str: return os.path.join(STATE_DIR, f"{project}.json") ``` The resulting path is used directly by the state creation, loading, and saving operations: ```python def create(project: str, title: str): """Create a new session state.""" _ensure_state_dir() path = _state_path(project) if os.path.exists(path): print(f"[brain] Session already exists for '{project}'. Use 'update' to modify.") return _load(project) state = { "session_id": f"sess_{datetime.now(timezone.utc).strftime('%Y%m%d_%H%M%S')}", "project": project, "title": title, "created_at": _now(), "updated_at": _now(), "tasks": [], "subagents": { "active": 0, "completed": 0, "failed": 0 }, "knowledge": { "wiki_initialized": False, "wiki_root": None, "last_ingest": None }, "log": [] } with open(path, "w") as f: json.dump(state, f, indent=2) print(f"[brain] Session created: {project} — {title}") return state ``` ```python def _load(project: str) -> dict | None: path = _state_path(project) if not os.path.exists(path): print(f"[brain] No session found for '{project}'.") return None with open(path) as f: return json.load(f) def _save(project: str, state: dict): _ensure_state_dir() state["updated_at"] = _now() with open(_state_path(project), "w") as f: json.dump(state, f, indent=2) print(f"[brain] State saved: {project}") ``` ### Technical Analysis The `project` argument is controlled through command-line operations and is interpolated directly into a filesystem ...[truncated 2031 chars]- Remediation
View remediation
str: if not PROJECT_PATTERN.fullmatch(project): raise ValueError("Invalid project identifier") return project ``` 2. Resolve the final path and verify that it remains inside the state directory: ```python STATE_ROOT = Path(STATE_DIR).resolve() def _state_path(project: str) -> Path: validate_project(project) candidate = (STATE_ROOT / f"{project}.json").resolve() if candidate.parent != STATE_ROOT: raise ValueError("State path escapes the state directory") return candidate ``` 3. Reject absolute paths, path separators, `..`, null bytes, and platform-specific alternate separators before filesystem access. 4. Prevent symbolic-link attacks by checking that existing files are regular files and opening them with `O_NOFOLLOW` where supported. 5. Write state atomically to a securely created temporary file in `STATE_DIR`, apply restrictive permissions such as `0600`, call `fsync()`, and replace the destination with `os.replace()`. 6. Add tests covering absolute paths, nested traversal, encoded or alternate separators, symlink targets, and race conditions. ]]>
