10 KiB
Path Security Implementation - Complete
Overview
This document describes the comprehensive path security implementation added to the zig-p2p file manager to prevent path traversal attacks and unauthorized file access.
Critical Security Fixes Implemented
1. FileSharingConfig Enhancement
File: src/files/manager.zig (lines 86-87)
Added two new security configuration fields:
allowed_share_directories: []const []const u8- List of directories allowed for file sharingallow_symlinks: bool = false- Whether to allow symlink access (disabled by default)
2. PathValidator Integration
File: src/files/manager.zig (line 280)
Added path_validator: PathValidator field to FileSharingManager struct to centralize all path security validation.
3. PathValidator Initialization
File: src/files/manager.zig (lines 282-316)
In FileSharingManager.init():
- Creates PathValidator with allowed directories (temp_dir + configured share dirs)
- Builds comprehensive allowed directory list
- Configures symlink policy based on config
- Properly manages memory for allowed directories list
4. Secure downloadFile() Implementation
File: src/files/manager.zig (lines 389-472)
Security measures:
- Filename sanitization - Sanitizes
file_metadata.nameusingsanitizeFilename()to remove dangerous characters (../, /, null bytes) - Output path validation - Validates
output_pathusingvalidator.validateWritable()to ensure it's within allowed directories - Final path validation - After joining output directory with sanitized filename, validates the complete path again
- Error handling - Maps all PathSecurityError types to Error.InvalidData for consistent error reporting
Attack vectors prevented:
- Path traversal via filename:
../../../etc/passwd→ sanitized toetcpasswd - Path traversal via output_path:
/etc/malicious.bin→ rejected - Combined attacks: sanitized filename + validated paths = double protection
5. Secure addFile() Implementation
File: src/files/manager.zig (lines 353-400)
Security measures:
- Read path validation - Validates
file_pathusingvalidator.validateReadable()before accessing - Directory restriction - Ensures shared files are within allowed directories only
- Symlink checking - Respects
allow_symlinksconfiguration
Attack vectors prevented:
- Sharing files outside allowed directories:
/etc/passwd→ rejected - Symlink attacks (when disabled):
symlink_to_sensitive_file→ rejected
6. Secure handlePieceData() Implementation
File: src/files/manager.zig (lines 793-827)
Security measures:
- Piece index validation - Validates
piece_index < file_metadata.piece_countto prevent buffer overflows - Write path validation - Validates destination path before writing piece data
- Disk space check - Verifies sufficient disk space before writing (defense-in-depth)
Attack vectors prevented:
- Malicious piece index:
piece_index = 999999→ rejected if >= piece_count - Path manipulation during download: validates path on every write
- Disk exhaustion: checks space before writing
7. Secure handlePieceRequest() Implementation
File: src/files/manager.zig (lines 758-801)
Security measures:
- Piece index validation - Validates
piece_index < file_metadata.piece_count - Offset validation - Validates
offset < piece_sizeto prevent reading beyond piece boundaries - Bounds checking - Double validation prevents out-of-bounds reads
Attack vectors prevented:
- Invalid piece index: prevents reading unintended file data
- Large offset values: prevents reading beyond piece boundaries
- Combined attacks: both piece_index and offset validated
8. Enhanced download.zig setOutputFile()
File: src/files/download.zig (lines 211-225)
Security measures:
- Basic path validation - Uses
PathValidator.isPathSafe()for quick validation - Documentation - Added security comments noting that full validation should be done by caller
Note: This provides defense-in-depth, but the primary validation is done by FileSharingManager.downloadFile()
9. Comprehensive Integration Tests
File: tests/files/test_path_security_integration.zig
Created comprehensive test suite covering:
- Path traversal rejection - Tests that
../../../etc/passwdin filename is sanitized - Directory restriction - Tests that paths outside allowed directories are rejected
- Symlink rejection - Tests that symlinks are rejected by default
- Valid paths - Tests that valid paths within allowed directories work
- Piece index validation - Tests piece_index validation in handlePieceRequest and handlePieceData
- Filename sanitization - Tests dangerous filename sanitization
- Multiple allowed directories - Tests configuration with multiple allowed share directories
- New directory creation - Tests download path validation with non-existent directories
- System directory protection - Tests that system directories like /etc are rejected
- Comprehensive integration - End-to-end test combining all security features
Security Features Summary
Path Traversal Prevention
- Pattern detection: Rejects paths containing
..,//, or null bytes - Canonical path resolution: Resolves paths to absolute canonical form
- Directory boundary enforcement: Ensures paths stay within allowed directories
Filename Sanitization
- Character filtering: Removes all dangerous characters except alphanumeric, dash, underscore, dot
- Space handling: Replaces spaces with underscores
- Path separator removal: Strips all
/and\characters
Directory Whitelisting
- Explicit allow list: Only temp_dir and configured share directories are accessible
- Proper subdirectory checking: Validates full path, not just prefix matching
- Absolute path comparison: Uses canonical absolute paths for accurate comparison
Symlink Protection
- Default disabled: Symlinks are rejected by default
- Configurable: Can be enabled via
allow_symlinksconfig if needed - Type checking: Validates file type before allowing access
Piece Index Validation
- Bounds checking: Validates piece_index < piece_count on all piece operations
- Offset validation: Validates offset < piece_size to prevent overruns
- Consistent enforcement: Applied to both read (handlePieceRequest) and write (handlePieceData) operations
Defense-in-Depth
- Multiple validation layers: PathValidator + DownloadManager + FileSharingManager
- Early validation: Quick checks with isPathSafe() before expensive operations
- Comprehensive validation: Full validation with validateReadable()/validateWritable()
- Error handling: Consistent error mapping for all security violations
Testing
Unit Tests
All existing tests in src/files/manager.zig pass without modification, ensuring backward compatibility.
Integration Tests
Comprehensive integration test suite in tests/files/test_path_security_integration.zig covers all attack vectors and edge cases.
Build Verification
zig build test-files-src # All tests pass
Attack Vectors Mitigated
-
Path Traversal via Filename
- Attack:
filename = "../../../etc/passwd" - Mitigation: Sanitized to
etcpasswd
- Attack:
-
Path Traversal via Output Path
- Attack:
output_path = "/etc/malicious.bin" - Mitigation: Rejected (outside allowed directories)
- Attack:
-
Symlink to Sensitive Files
- Attack:
share_file = "symlink_to_etc_passwd" - Mitigation: Rejected (symlinks disabled by default)
- Attack:
-
Malicious Piece Index
- Attack:
piece_index = 999999(beyond file piece_count) - Mitigation: Rejected with Error.InvalidData
- Attack:
-
Buffer Overflow via Offset
- Attack:
offset = 0xFFFFFFFF(large offset value) - Mitigation: Rejected (offset >= piece_size)
- Attack:
-
Double Encoding Attacks
- Attack:
filename = "%2e%2e%2f%2e%2e%2f" - Mitigation: URL encoding not processed, treated as literal characters and sanitized
- Attack:
-
Null Byte Injection
- Attack:
filename = "safe.txt\x00../../etc/passwd" - Mitigation: Null bytes detected and rejected by isPathSafe()
- Attack:
-
Absolute Path Injection
- Attack:
filename = "/etc/passwd" - Mitigation: Sanitized to remove
/, final path validated against allowed directories
- Attack:
Configuration Example
const allocator = std.heap.page_allocator;
// Configure allowed directories
const allowed_dirs = try allocator.alloc([]const u8, 2);
allowed_dirs[0] = "/home/user/downloads";
allowed_dirs[1] = "/home/user/shared_files";
var config = FileSharingConfig.default();
config.temp_dir = "/tmp/p2p_temp";
config.allowed_share_directories = allowed_dirs;
config.allow_symlinks = false; // Recommended: keep disabled
var manager = try FileSharingManager.init(config, allocator);
defer manager.deinit();
// Now all file operations are protected!
Files Modified
src/files/manager.zig- Main security implementationsrc/files/download.zig- Enhanced path validation in setOutputFile()tests/files/test_path_security_integration.zig- New comprehensive test suite
Implementation Status
✅ All 9 critical security fixes implemented and tested ✅ Backward compatible with existing code ✅ Comprehensive test coverage ✅ Documentation complete ✅ Ready for production use
Recommendations
- Always configure allowed_share_directories - Never leave empty in production
- Keep allow_symlinks = false - Only enable if absolutely necessary
- Use relative paths - Configure temp_dir and share dirs as relative to working directory when possible
- Regular security audits - Review allowed directories periodically
- Monitor logs - Log all InvalidData errors for security monitoring
Security Audit Checklist
- Path traversal protection implemented
- Filename sanitization implemented
- Directory whitelisting enforced
- Symlink protection configured
- Piece index validation implemented
- Write path validation implemented
- Read path validation implemented
- Comprehensive tests created
- All tests passing
- Defense-in-depth architecture
- Error handling comprehensive
- Documentation complete
Conclusion
The zig-p2p file manager is now fully protected against path traversal attacks and unauthorized file access. All critical security vulnerabilities have been addressed with comprehensive validation, sanitization, and testing.