ab ovo
This commit is contained in:
245
architecture/SECURITY_IMPLEMENTATION.md
Normal file
245
architecture/SECURITY_IMPLEMENTATION.md
Normal file
@@ -0,0 +1,245 @@
|
||||
# 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 sharing
|
||||
- `allow_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:**
|
||||
1. **Filename sanitization** - Sanitizes `file_metadata.name` using `sanitizeFilename()` to remove dangerous characters (../, /, null bytes)
|
||||
2. **Output path validation** - Validates `output_path` using `validator.validateWritable()` to ensure it's within allowed directories
|
||||
3. **Final path validation** - After joining output directory with sanitized filename, validates the complete path again
|
||||
4. **Error handling** - Maps all PathSecurityError types to Error.InvalidData for consistent error reporting
|
||||
|
||||
**Attack vectors prevented:**
|
||||
- Path traversal via filename: `../../../etc/passwd` → sanitized to `etcpasswd`
|
||||
- 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:**
|
||||
1. **Read path validation** - Validates `file_path` using `validator.validateReadable()` before accessing
|
||||
2. **Directory restriction** - Ensures shared files are within allowed directories only
|
||||
3. **Symlink checking** - Respects `allow_symlinks` configuration
|
||||
|
||||
**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:**
|
||||
1. **Piece index validation** - Validates `piece_index < file_metadata.piece_count` to prevent buffer overflows
|
||||
2. **Write path validation** - Validates destination path before writing piece data
|
||||
3. **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:**
|
||||
1. **Piece index validation** - Validates `piece_index < file_metadata.piece_count`
|
||||
2. **Offset validation** - Validates `offset < piece_size` to prevent reading beyond piece boundaries
|
||||
3. **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:**
|
||||
1. **Basic path validation** - Uses `PathValidator.isPathSafe()` for quick validation
|
||||
2. **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:
|
||||
1. **Path traversal rejection** - Tests that `../../../etc/passwd` in filename is sanitized
|
||||
2. **Directory restriction** - Tests that paths outside allowed directories are rejected
|
||||
3. **Symlink rejection** - Tests that symlinks are rejected by default
|
||||
4. **Valid paths** - Tests that valid paths within allowed directories work
|
||||
5. **Piece index validation** - Tests piece_index validation in handlePieceRequest and handlePieceData
|
||||
6. **Filename sanitization** - Tests dangerous filename sanitization
|
||||
7. **Multiple allowed directories** - Tests configuration with multiple allowed share directories
|
||||
8. **New directory creation** - Tests download path validation with non-existent directories
|
||||
9. **System directory protection** - Tests that system directories like /etc are rejected
|
||||
10. **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_symlinks` config 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
|
||||
```bash
|
||||
zig build test-files-src # All tests pass
|
||||
```
|
||||
|
||||
## Attack Vectors Mitigated
|
||||
|
||||
1. **Path Traversal via Filename**
|
||||
- Attack: `filename = "../../../etc/passwd"`
|
||||
- Mitigation: Sanitized to `etcpasswd`
|
||||
|
||||
2. **Path Traversal via Output Path**
|
||||
- Attack: `output_path = "/etc/malicious.bin"`
|
||||
- Mitigation: Rejected (outside allowed directories)
|
||||
|
||||
3. **Symlink to Sensitive Files**
|
||||
- Attack: `share_file = "symlink_to_etc_passwd"`
|
||||
- Mitigation: Rejected (symlinks disabled by default)
|
||||
|
||||
4. **Malicious Piece Index**
|
||||
- Attack: `piece_index = 999999` (beyond file piece_count)
|
||||
- Mitigation: Rejected with Error.InvalidData
|
||||
|
||||
5. **Buffer Overflow via Offset**
|
||||
- Attack: `offset = 0xFFFFFFFF` (large offset value)
|
||||
- Mitigation: Rejected (offset >= piece_size)
|
||||
|
||||
6. **Double Encoding Attacks**
|
||||
- Attack: `filename = "%2e%2e%2f%2e%2e%2f"`
|
||||
- Mitigation: URL encoding not processed, treated as literal characters and sanitized
|
||||
|
||||
7. **Null Byte Injection**
|
||||
- Attack: `filename = "safe.txt\x00../../etc/passwd"`
|
||||
- Mitigation: Null bytes detected and rejected by isPathSafe()
|
||||
|
||||
8. **Absolute Path Injection**
|
||||
- Attack: `filename = "/etc/passwd"`
|
||||
- Mitigation: Sanitized to remove `/`, final path validated against allowed directories
|
||||
|
||||
## Configuration Example
|
||||
|
||||
```zig
|
||||
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
|
||||
|
||||
1. `src/files/manager.zig` - Main security implementation
|
||||
2. `src/files/download.zig` - Enhanced path validation in setOutputFile()
|
||||
3. `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
|
||||
|
||||
1. **Always configure allowed_share_directories** - Never leave empty in production
|
||||
2. **Keep allow_symlinks = false** - Only enable if absolutely necessary
|
||||
3. **Use relative paths** - Configure temp_dir and share dirs as relative to working directory when possible
|
||||
4. **Regular security audits** - Review allowed directories periodically
|
||||
5. **Monitor logs** - Log all InvalidData errors for security monitoring
|
||||
|
||||
## Security Audit Checklist
|
||||
|
||||
- [x] Path traversal protection implemented
|
||||
- [x] Filename sanitization implemented
|
||||
- [x] Directory whitelisting enforced
|
||||
- [x] Symlink protection configured
|
||||
- [x] Piece index validation implemented
|
||||
- [x] Write path validation implemented
|
||||
- [x] Read path validation implemented
|
||||
- [x] Comprehensive tests created
|
||||
- [x] All tests passing
|
||||
- [x] Defense-in-depth architecture
|
||||
- [x] Error handling comprehensive
|
||||
- [x] 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.
|
||||
Reference in New Issue
Block a user