T09 · Insecure Skill Coding Practices
- Location
scripts/data_manager.py:76- Finding
Path Traversal Enables Arbitrary JSON File Read and Write
- Content
View full analysis
Vulnerability Details
File Location:
scripts/data_manager.py, lines 76-108
Vulnerability Type: Path traversal and insufficient path validation
Risk Level: HighVulnerable Code
python def _get_record_path(self, date: str) -> Path: """Get the record file path for a specified date.""" return self.records_dir / f"{date}.json" def save_daily_record(self, date: str, record: Dict) -> bool: """Save a daily record.""" try: record_path = self._get_record_path(date) with open(record_path, 'w', encoding='utf-8') as f: json.dump(record, f, ensure_ascii=False, indent=2) return True except Exception as e: print(f"Failed to save record: {e}") return False def save_user_record(self, record: Dict) -> bool: """Save a user record using its date or the current date.""" date = record.get('date', datetime.now().strftime('%Y-%m-%d')) return self.save_daily_record(date, record) def get_daily_record(self, date: str) -> Optional[Dict]: """Get a record for a specified date.""" record_path = self._get_record_path(date) if record_path.exists(): with open(record_path, 'r', encoding='utf-8') as f: return json.load(f) return NoneTechnical Analysis
The
dateparameter is treated as a trusted filename component even though it can be supplied by a caller throughsave_daily_record(),get_daily_record(), or thedatefield accepted bysave_user_record().Appending
.jsondoes not prevent traversal. A value containing parent-directory components, such as../../target, produces a path equivalent to:text data/daily_records/../../target.jsonThe implementation does not:
- Strictly parse the value as a
YYYY-MM-DDdate. - Reject path separators or
..components. - Resolve the constructed path to its canonical location.
- Verify that the resolved path remains within
data/daily_records.
Consequently, the affected read m ...[truncated 1774 chars]
- Strictly parse the value as a
- Remediation
View remediation
Remediation Suggestions
-
Strictly validate and canonicalize all date inputs:
python def _validate_date(self, date: str) -> str: parsed = datetime.strptime(date, "%Y-%m-%d") canonical = parsed.strftime("%Y-%m-%d") if canonical != date: raise ValueError("Invalid date format") return canonical -
Resolve the final path and verify containment within the records directory:
python def _get_record_path(self, date: str) -> Path: safe_date = self._validate_date(date) base = self.records_dir.resolve() candidate = (base / f"{safe_date}.json").resolve() if candidate.parent != base: raise ValueError("Record path escapes the records directory") return candidate -
Explicitly reject path separators, null bytes, and traversal components before constructing a path.
-
Apply the same validated helper to both read and write operations so that security checks cannot diverge.
-
Use atomic writes to reduce corruption risk:
- Create a temporary file inside
records_dir. - Flush and synchronize it.
- Replace the destination atomically.
- Create a temporary file inside
-
Set restrictive directory and file permissions appropriate for sensitive health data.
-
Add negative security tests covering values such as:
text ../profile ../../target /absolute/path ..\target 2026-05-15/../../target -
Confirm that invalid dates and all paths outside
daily_recordsare rejected before any filesystem access occurs.
-
