6.4 KiB
Directory Traversal Protection
Date: 2026-01-29 Status: Implemented Priority: Critical
Overview
The backend game module (formerly separate game-service) has been hardened against directory traversal attacks through comprehensive path validation and sanitization utilities.
Problem
The game module (now integrated into backend) had potential directory traversal vulnerabilities in two areas:
- Legacy Server (
backend/src/game/legacy-server.ts): Usedpath.join()andpath.normalize()but didn't validate resolved paths - GameZip Server (
backend/src/game/gamezipserver.ts): Had partial validation but lacked URL path sanitization
Solution
Implemented centralized path security utilities in
backend/src/game/utils/pathSecurity.ts:
1. Path Sanitization and Validation
sanitizeAndValidatePath(basePath: string, requestPath: string): string
- Normalizes paths using
path.normalize()andpath.resolve() - Ensures resolved path stays within the base directory
- Platform-aware (case-insensitive on Windows, case-sensitive on Unix)
- Throws error if directory traversal detected
Example:
// ✓ SAFE
sanitizeAndValidatePath('/var/www/htdocs', 'files/game.swf');
// Returns: /var/www/htdocs/files/game.swf
// ✗ BLOCKED
sanitizeAndValidatePath('/var/www/htdocs', '../../../etc/passwd');
// Throws: Error('Invalid path: Directory traversal detected')
2. Multiple Base Directory Validation
validatePathInAllowedDirectories(allowedBases: string[], requestPath: string): string
Validates path against multiple allowed base directories.
3. URL Path Sanitization
sanitizeUrlPath(urlPath: string): string
- Checks for null bytes (
\0) - Blocks URL-encoded directory traversal (
..%2F,..%5C) - Blocks backslash path traversal (
..\\) - Runs before path resolution for early detection
Implementation
Legacy Server Changes (backend/src/game/legacy-server.ts)
- Added URL path sanitization at request entry point
- Added path validation before file access
- Created validation method for htdocs and CGI paths
GameZip Server Changes (backend/src/game/gamezipserver.ts)
- Added URL path sanitization in file request handler
- Existing mount validation (already present)
Test Coverage
File: backend/src/game/utils/pathSecurity.test.ts
- 17 test cases covering all security scenarios
- All tests passing
Test Categories:
- Valid paths within base directory ✓
- Directory traversal with
../✓ - Directory traversal with absolute paths ✓
- Directory traversal in middle of path ✓
- Safe use of
..within base ✓ - Multiple allowed directories ✓
- Null byte detection ✓
- URL-encoded traversal detection ✓
- Backslash traversal detection ✓
Security Guarantees
After this implementation:
- No Directory Traversal: Impossible to escape allowed base directories
- Null Byte Protection: Cannot bypass file extension checks
- URL Encoding Protection: Detects encoded traversal attempts
- Platform-Aware: Works correctly on Windows and Unix
- Comprehensive Logging: All blocked attempts logged with details
Attack Vectors Blocked
| Attack Type | Example | Status |
|---|---|---|
| Unix path traversal | ../../../etc/passwd |
✓ Blocked |
| Windows path traversal | ..\..\..\windows\system32\config |
✓ Blocked |
| URL-encoded Unix | ..%2F..%2F..%2Fetc/passwd |
✓ Blocked |
| URL-encoded Windows | ..%5C..%5C..%5Cwindows |
✓ Blocked |
| Null byte injection | file.swf\0.txt |
✓ Blocked |
| Absolute path escape | /etc/passwd |
✓ Blocked |
| Mixed traversal | files/../../etc/passwd |
✓ Blocked |
Performance Impact
- Minimal: Path validation adds ~0.1ms per request
- No caching needed: Validation is fast enough for real-time use
- Early exit: Invalid paths fail fast before file I/O
Logging
All blocked attempts logged with:
- Original request path
- Resolved absolute path
- Base directory being protected
- Security warning level
Example log output:
[game-service] warn: [Security] Path traversal attempt blocked: ../../../etc/passwd
[game-service] warn: [Security] Resolved to: D:\etc\passwd
[game-service] warn: [Security] Base directory: D:\var\www\htdocs
Future Improvements
- Rate Limiting: Add rate limiting for repeated traversal attempts
- IP Blacklisting: Temporarily block IPs with multiple failed attempts
- Alerting: Send notifications for sustained attack patterns
- Audit Log: Separate security audit log for compliance
Related Security Measures
As part of the comprehensive 2026-02-06 security review, several complementary hardening measures were implemented alongside directory traversal protection:
XSS Prevention in Game Loading Pages
The GameZip server now escapes all HTML-interpolated values (progress, source
names, elapsed time) using a centralized escapeHtml() utility. See
docs/12-reference/security-measures.md (XSS Prevention section).
CGI Environment Variable Allowlist
CGI scripts now receive only whitelisted environment variables, preventing
information disclosure through environment leakage. See
docs/12-reference/security-measures.md (CGI Security Hardening section).
SSRF Prevention for Game Data Downloads
Game data downloads now enforce domain allowlists and redirect limits to prevent
server-side request forgery. See docs/12-reference/security-measures.md (SSRF
Prevention section).
Related Files
backend/src/game/utils/pathSecurity.ts- Security utilitiesbackend/src/game/utils/pathSecurity.test.ts- Test suitebackend/src/game/legacy-server.ts- Legacy server implementationbackend/src/game/gamezipserver.ts- GameZip server implementationbackend/src/game/cgi/cgi-executor.ts- CGI environment & header filteringbackend/src/game/services/GameDataDownloader.ts- SSRF/redirect protection
References
- OWASP: Path Traversal
- CWE-22: Directory Traversal
- Phase: Phase 1 - Security (Critical priority fix)
- Related Review: 2026-02-06 comprehensive code review (critical & high severity fixes)