Secure Implementation
Comprehensive File Upload Security Framework
Secure Implementation Strategy
graph TD
A[File Upload Request] --> B[Client-Side Validation]
B --> C[Server-Side Validation]
C --> D[File Type Checking]
D --> E[File Size Verification]
E --> F[Sanitize Filename]
F --> G[Generate Unique Filename]
G --> H[Store in Secure Location]
H --> I[Set Strict Permissions]
Validation Techniques
Multi-Layer Validation Approach
Validation Layer |
Security Mechanism |
Client-Side |
Initial Basic Checks |
Server-Side |
Comprehensive Validation |
File System |
Strict Permission Controls |
Secure Python Implementation
import os
import magic
from werkzeug.utils import secure_filename
class FileUploadHandler:
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'pdf'}
MAX_FILE_SIZE = 5 * 1024 * 1024 ## 5MB
@staticmethod
def validate_file(file_stream):
## Check file size
file_stream.seek(0, os.SEEK_END)
file_size = file_stream.tell()
file_stream.seek(0)
if file_size > FileUploadHandler.MAX_FILE_SIZE:
raise ValueError("File too large")
## Check file type using magic
file_type = magic.from_buffer(file_stream.read(2048), mime=True)
file_stream.seek(0)
allowed_mime_types = {
'image/jpeg',
'image/png',
'application/pdf'
}
if file_type not in allowed_mime_types:
raise ValueError("Invalid file type")
@staticmethod
def secure_filename(filename):
## Sanitize filename
sanitized_name = secure_filename(filename)
## Generate unique filename
unique_filename = f"{uuid.uuid4()}_{sanitized_name}"
return unique_filename
@staticmethod
def save_file(file_stream, upload_directory):
## Validate file
FileUploadHandler.validate_file(file_stream)
## Generate secure filename
filename = FileUploadHandler.secure_filename(file_stream.filename)
## Full file path
file_path = os.path.join(upload_directory, filename)
## Save file with restricted permissions
with open(file_path, 'wb') as f:
f.write(file_stream.read())
## Set secure file permissions
os.chmod(file_path, 0o640)
Bash File Permission Hardening
#!/bin/bash
## Secure upload directory
UPLOAD_DIR="/var/www/uploads"
## Create directory with restricted permissions
mkdir -p "$UPLOAD_DIR"
chown www-data:www-data "$UPLOAD_DIR"
chmod 750 "$UPLOAD_DIR"
## Set default ACL for new files
setfacl -d -m u::rw,g::r,o::- "$UPLOAD_DIR"
Advanced Security Considerations
File Storage Strategies
- Store uploaded files outside web root
- Use separate storage volumes
- Implement access logging
Recommended Permissions
- Web server user: Read/Write
- Group: Read-only
- Others: No access
LabEx Security Recommendations
At LabEx, we emphasize a holistic approach to file upload security, combining multiple validation layers and strict access controls.
Key Implementation Principles
- Never trust user input
- Validate at multiple layers
- Use secure libraries
- Implement strict permission models
- Log and monitor file upload activities