ai_data_scientist / shared /security.py
VAH6002's picture
Upload 264 files
56c063a verified
Raw History Blame Contribute Delete
23.3 kB
"""
Security utilities for the MCP AI Data Scientist system.
Provides file upload validation, SQL injection prevention, and security monitoring.
"""
import hashlib
import os
import re
import time
from typing import Dict, List, Optional, Set, Tuple
from pathlib import Path
import logging
from dataclasses import dataclass
from datetime import datetime, timedelta
import json
import asyncio
from collections import defaultdict, deque
# Try to import python-magic, fall back to basic MIME detection
try:
import magic
MAGIC_AVAILABLE = True
except ImportError:
MAGIC_AVAILABLE = False
logging.warning("python-magic not available - using basic MIME type detection")
# Configure logging
logger = logging.getLogger(__name__)
@dataclass
class SecurityEvent:
"""Represents a security event for audit logging."""
timestamp: datetime
event_type: str
user_id: str
ip_address: str
details: Dict
severity: str # LOW, MEDIUM, HIGH, CRITICAL
@dataclass
class FileValidationResult:
"""Result of file security validation."""
is_valid: bool
file_type: str
size_bytes: int
hash_sha256: str
threats_detected: List[str]
warnings: List[str]
class FileSecurityValidator:
"""Validates uploaded files for security threats and compliance."""
# Allowed file types for data analysis
ALLOWED_MIME_TYPES = {
'text/csv',
'application/vnd.ms-excel',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/json',
'text/plain',
'application/x-parquet'
}
# Maximum file size (100MB)
MAX_FILE_SIZE = 100 * 1024 * 1024
# Dangerous file extensions
DANGEROUS_EXTENSIONS = {
'.exe', '.bat', '.cmd', '.com', '.pif', '.scr', '.vbs', '.js',
'.jar', '.app', '.deb', '.pkg', '.dmg', '.sh', '.ps1'
}
# Suspicious patterns in file content
SUSPICIOUS_PATTERNS = [
rb'<script[^>]*>', # JavaScript
rb'javascript:', # JavaScript protocol
rb'vbscript:', # VBScript protocol
rb'data:text/html', # Data URI with HTML
rb'<?php', # PHP code
rb'<%', # ASP/JSP code
rb'exec\s*\(', # Code execution
rb'eval\s*\(', # Code evaluation
rb'system\s*\(', # System calls
]
def __init__(self):
if MAGIC_AVAILABLE:
try:
self.magic_mime = magic.Magic(mime=True)
except Exception as e:
logging.warning(f"Failed to initialize python-magic: {e}")
self.magic_mime = None
else:
self.magic_mime = None
async def validate_file(self, file_content: bytes, filename: str, user_id: str) -> FileValidationResult:
"""
Comprehensive file validation including type checking, size limits, and threat scanning.
"""
threats = []
warnings = []
# Basic file info
file_size = len(file_content)
file_hash = hashlib.sha256(file_content).hexdigest()
# Check file size
if file_size > self.MAX_FILE_SIZE:
threats.append(f"File size {file_size} exceeds maximum allowed size {self.MAX_FILE_SIZE}")
if file_size == 0:
threats.append("Empty file not allowed")
# Check file extension
file_ext = Path(filename).suffix.lower()
if file_ext in self.DANGEROUS_EXTENSIONS:
threats.append(f"Dangerous file extension: {file_ext}")
# Detect MIME type
try:
if self.magic_mime:
detected_mime = self.magic_mime.from_buffer(file_content)
else:
# Fallback MIME type detection based on file extension
detected_mime = self._detect_mime_type_fallback(filename, file_content)
except Exception as e:
threats.append(f"Could not determine file type: {str(e)}")
detected_mime = "unknown"
# Validate MIME type
if detected_mime not in self.ALLOWED_MIME_TYPES:
threats.append(f"File type not allowed: {detected_mime}")
# Scan for suspicious patterns
for pattern in self.SUSPICIOUS_PATTERNS:
if re.search(pattern, file_content, re.IGNORECASE):
threats.append(f"Suspicious content pattern detected")
break
# Check for embedded executables (PE header)
if file_content.startswith(b'MZ'):
threats.append("Embedded executable detected")
# Check for ZIP bombs (nested archives)
if detected_mime in ['application/zip', 'application/x-rar']:
warnings.append("Archive files require additional validation")
# Validate CSV structure if it's a CSV file
if detected_mime == 'text/csv' or file_ext == '.csv':
csv_threats = await self._validate_csv_content(file_content)
threats.extend(csv_threats)
is_valid = len(threats) == 0
return FileValidationResult(
is_valid=is_valid,
file_type=detected_mime,
size_bytes=file_size,
hash_sha256=file_hash,
threats_detected=threats,
warnings=warnings
)
def _detect_mime_type_fallback(self, filename: str, content: bytes) -> str:
"""Fallback MIME type detection based on file extension and content."""
file_ext = Path(filename).suffix.lower()
# Basic MIME type mapping
mime_map = {
'.csv': 'text/csv',
'.txt': 'text/plain',
'.json': 'application/json',
'.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'.xls': 'application/vnd.ms-excel',
'.parquet': 'application/x-parquet'
}
# Check file extension first
if file_ext in mime_map:
return mime_map[file_ext]
# Basic content-based detection
if content.startswith(b'PK'): # ZIP-based formats (Excel, etc.)
if file_ext in ['.xlsx', '.xlsm']:
return 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
return 'application/zip'
if content.startswith(b'{"') or content.startswith(b'[{'): # JSON
return 'application/json'
# Try to decode as text
try:
content.decode('utf-8')
if ',' in content.decode('utf-8')[:1000]: # Likely CSV
return 'text/csv'
return 'text/plain'
except UnicodeDecodeError:
pass
return 'application/octet-stream'
async def _validate_csv_content(self, content: bytes) -> List[str]:
"""Validate CSV file content for security issues."""
threats = []
try:
# Decode content
text_content = content.decode('utf-8', errors='ignore')
# Check for formula injection
formula_patterns = [r'^=', r'^@', r'^\+', r'^\-']
lines = text_content.split('\n')[:100] # Check first 100 lines
for line_num, line in enumerate(lines, 1):
cells = line.split(',')
for cell_num, cell in enumerate(cells):
cell = cell.strip().strip('"\'')
for pattern in formula_patterns:
if re.match(pattern, cell):
threats.append(f"Potential formula injection at line {line_num}, cell {cell_num}")
# Check for excessively long lines (potential DoS)
max_line_length = 10000
for line_num, line in enumerate(lines, 1):
if len(line) > max_line_length:
threats.append(f"Excessively long line at {line_num} (potential DoS)")
except Exception as e:
threats.append(f"CSV validation error: {str(e)}")
return threats
class SQLInjectionPrevention:
"""Prevents SQL injection attacks through input validation and sanitization."""
# Common SQL injection patterns
SQL_INJECTION_PATTERNS = [
r"(\b(SELECT|INSERT|UPDATE|DELETE|DROP|CREATE|ALTER|EXEC|UNION)\b)",
r"(--|#|/\*|\*/)",
r"(\b(OR|AND)\s+\d+\s*=\s*\d+)",
r"(\b(OR|AND)\s+['\"]?\w+['\"]?\s*=\s*['\"]?\w+['\"]?)",
r"(;\s*(SELECT|INSERT|UPDATE|DELETE|DROP|CREATE|ALTER|EXEC))",
r"(\bUNION\s+(ALL\s+)?SELECT)",
r"(\b(INFORMATION_SCHEMA|SYSOBJECTS|SYSCOLUMNS)\b)",
r"(xp_cmdshell|sp_executesql)",
r"(\b(CAST|CONVERT|CHAR|ASCII)\s*\()",
]
@classmethod
def validate_input(cls, input_value: str, field_name: str = "input") -> Tuple[bool, List[str]]:
"""
Validate input for SQL injection attempts.
Returns (is_safe, list_of_threats)
"""
if not isinstance(input_value, str):
return True, []
threats = []
# Check against known patterns
for pattern in cls.SQL_INJECTION_PATTERNS:
if re.search(pattern, input_value, re.IGNORECASE):
threats.append(f"Potential SQL injection in {field_name}: pattern '{pattern}' detected")
# Check for excessive length (potential buffer overflow)
if len(input_value) > 10000:
threats.append(f"Input too long in {field_name}: {len(input_value)} characters")
# Check for null bytes
if '\x00' in input_value:
threats.append(f"Null byte detected in {field_name}")
return len(threats) == 0, threats
@classmethod
def sanitize_input(cls, input_value: str) -> str:
"""Sanitize input by removing dangerous characters."""
if not isinstance(input_value, str):
return str(input_value)
# Remove null bytes
sanitized = input_value.replace('\x00', '')
# Remove SQL comments
sanitized = re.sub(r'--.*$', '', sanitized, flags=re.MULTILINE)
sanitized = re.sub(r'/\*.*?\*/', '', sanitized, flags=re.DOTALL)
# Limit length
if len(sanitized) > 1000:
sanitized = sanitized[:1000]
return sanitized.strip()
class RateLimiter:
"""Implements rate limiting and DDoS protection."""
def __init__(self):
self.requests = defaultdict(deque) # IP -> deque of timestamps
self.blocked_ips = {} # IP -> block_until_timestamp
# Rate limiting configuration
self.limits = {
'per_minute': 60, # 60 requests per minute
'per_hour': 1000, # 1000 requests per hour
'per_day': 10000 # 10000 requests per day
}
# Block duration for violations (in seconds)
self.block_durations = {
'minor': 300, # 5 minutes
'major': 3600, # 1 hour
'severe': 86400 # 24 hours
}
def is_allowed(self, ip_address: str, endpoint: str = "default") -> Tuple[bool, str]:
"""
Check if request from IP is allowed based on rate limits.
Returns (is_allowed, reason_if_blocked)
"""
current_time = time.time()
# Check if IP is currently blocked
if ip_address in self.blocked_ips:
if current_time < self.blocked_ips[ip_address]:
remaining = int(self.blocked_ips[ip_address] - current_time)
return False, f"IP blocked for {remaining} more seconds"
else:
# Block expired, remove it
del self.blocked_ips[ip_address]
# Clean old requests
self._clean_old_requests(ip_address, current_time)
# Add current request
self.requests[ip_address].append(current_time)
# Check rate limits
violation = self._check_rate_limits(ip_address, current_time)
if violation:
# Block the IP
block_duration = self.block_durations[violation['severity']]
self.blocked_ips[ip_address] = current_time + block_duration
return False, f"Rate limit exceeded: {violation['reason']}"
return True, ""
def _clean_old_requests(self, ip_address: str, current_time: float):
"""Remove requests older than 24 hours."""
cutoff_time = current_time - 86400 # 24 hours
while (self.requests[ip_address] and
self.requests[ip_address][0] < cutoff_time):
self.requests[ip_address].popleft()
def _check_rate_limits(self, ip_address: str, current_time: float) -> Optional[Dict]:
"""Check if any rate limits are violated."""
requests = self.requests[ip_address]
# Check per-minute limit
minute_ago = current_time - 60
minute_requests = sum(1 for req_time in requests if req_time > minute_ago)
if minute_requests > self.limits['per_minute']:
return {
'severity': 'minor',
'reason': f'Too many requests per minute: {minute_requests}/{self.limits["per_minute"]}'
}
# Check per-hour limit
hour_ago = current_time - 3600
hour_requests = sum(1 for req_time in requests if req_time > hour_ago)
if hour_requests > self.limits['per_hour']:
return {
'severity': 'major',
'reason': f'Too many requests per hour: {hour_requests}/{self.limits["per_hour"]}'
}
# Check per-day limit
day_ago = current_time - 86400
day_requests = sum(1 for req_time in requests if req_time > day_ago)
if day_requests > self.limits['per_day']:
return {
'severity': 'severe',
'reason': f'Too many requests per day: {day_requests}/{self.limits["per_day"]}'
}
return None
class SecureFileStorage:
"""Manages secure file storage with access controls."""
def __init__(self, base_path: str = "uploads"):
self.base_path = Path(base_path)
self.base_path.mkdir(exist_ok=True)
# Set restrictive permissions
os.chmod(self.base_path, 0o750)
def get_user_directory(self, user_id: str) -> Path:
"""Get user-specific directory with proper isolation."""
# Sanitize user_id to prevent directory traversal
safe_user_id = re.sub(r'[^a-zA-Z0-9_-]', '', user_id)
if not safe_user_id or safe_user_id != user_id:
raise ValueError(f"Invalid user_id: {user_id}")
user_dir = self.base_path / safe_user_id
user_dir.mkdir(exist_ok=True)
# Set user-only permissions
os.chmod(user_dir, 0o700)
return user_dir
def store_file(self, user_id: str, filename: str, content: bytes) -> str:
"""Store file securely with user isolation."""
# Validate filename
safe_filename = self._sanitize_filename(filename)
user_dir = self.get_user_directory(user_id)
file_path = user_dir / safe_filename
# Prevent overwriting existing files
counter = 1
original_path = file_path
while file_path.exists():
stem = original_path.stem
suffix = original_path.suffix
file_path = user_dir / f"{stem}_{counter}{suffix}"
counter += 1
# Write file with restrictive permissions
with open(file_path, 'wb') as f:
f.write(content)
os.chmod(file_path, 0o600) # Owner read/write only
return str(file_path.relative_to(self.base_path))
def get_file(self, user_id: str, file_path: str) -> bytes:
"""Retrieve file with access control validation."""
# Validate that file belongs to user
full_path = self.base_path / file_path
user_dir = self.get_user_directory(user_id)
# Ensure file is within user directory
try:
full_path.resolve().relative_to(user_dir.resolve())
except ValueError:
raise PermissionError(f"Access denied to file: {file_path}")
if not full_path.exists():
raise FileNotFoundError(f"File not found: {file_path}")
with open(full_path, 'rb') as f:
return f.read()
def delete_file(self, user_id: str, file_path: str) -> bool:
"""Delete file with access control validation."""
full_path = self.base_path / file_path
user_dir = self.get_user_directory(user_id)
# Ensure file is within user directory
try:
full_path.resolve().relative_to(user_dir.resolve())
except ValueError:
raise PermissionError(f"Access denied to file: {file_path}")
if full_path.exists():
full_path.unlink()
return True
return False
def _sanitize_filename(self, filename: str) -> str:
"""Sanitize filename to prevent directory traversal and other attacks."""
# Remove path separators and dangerous characters
safe_name = re.sub(r'[<>:"/\\|?*\x00-\x1f]', '', filename)
# Remove leading/trailing dots and spaces
safe_name = safe_name.strip('. ')
# Prevent reserved names on Windows
reserved_names = {
'CON', 'PRN', 'AUX', 'NUL', 'COM1', 'COM2', 'COM3', 'COM4',
'COM5', 'COM6', 'COM7', 'COM8', 'COM9', 'LPT1', 'LPT2',
'LPT3', 'LPT4', 'LPT5', 'LPT6', 'LPT7', 'LPT8', 'LPT9'
}
name_without_ext = Path(safe_name).stem.upper()
if name_without_ext in reserved_names:
safe_name = f"file_{safe_name}"
# Ensure filename is not empty
if not safe_name:
safe_name = "unnamed_file"
# Limit length
if len(safe_name) > 255:
name_part = safe_name[:200]
ext_part = Path(safe_name).suffix[-50:] if Path(safe_name).suffix else ""
safe_name = name_part + ext_part
return safe_name
class SecurityAuditLogger:
"""Logs security events for monitoring and compliance."""
def __init__(self, log_file: str = "logs/security_audit.log"):
self.log_file = Path(log_file)
self.log_file.parent.mkdir(exist_ok=True)
# Configure security logger
self.logger = logging.getLogger('security_audit')
self.logger.setLevel(logging.INFO)
# Create file handler
handler = logging.FileHandler(self.log_file)
formatter = logging.Formatter(
'%(asctime)s - %(levelname)s - %(message)s'
)
handler.setFormatter(formatter)
self.logger.addHandler(handler)
def log_event(self, event: SecurityEvent):
"""Log a security event."""
event_data = {
'timestamp': event.timestamp.isoformat(),
'event_type': event.event_type,
'user_id': event.user_id,
'ip_address': event.ip_address,
'severity': event.severity,
'details': event.details
}
log_message = json.dumps(event_data)
if event.severity in ['HIGH', 'CRITICAL']:
self.logger.error(log_message)
elif event.severity == 'MEDIUM':
self.logger.warning(log_message)
else:
self.logger.info(log_message)
def log_authentication_event(self, user_id: str, ip_address: str,
success: bool, details: Dict = None):
"""Log authentication events."""
event = SecurityEvent(
timestamp=datetime.utcnow(),
event_type='authentication',
user_id=user_id,
ip_address=ip_address,
severity='MEDIUM' if not success else 'LOW',
details={
'success': success,
'additional_details': details or {}
}
)
self.log_event(event)
def log_file_upload_event(self, user_id: str, ip_address: str,
filename: str, validation_result: FileValidationResult):
"""Log file upload security events."""
severity = 'HIGH' if validation_result.threats_detected else 'LOW'
event = SecurityEvent(
timestamp=datetime.utcnow(),
event_type='file_upload',
user_id=user_id,
ip_address=ip_address,
severity=severity,
details={
'filename': filename,
'file_size': validation_result.size_bytes,
'file_type': validation_result.file_type,
'file_hash': validation_result.hash_sha256,
'threats_detected': validation_result.threats_detected,
'warnings': validation_result.warnings
}
)
self.log_event(event)
def log_rate_limit_violation(self, ip_address: str, endpoint: str, reason: str):
"""Log rate limiting violations."""
event = SecurityEvent(
timestamp=datetime.utcnow(),
event_type='rate_limit_violation',
user_id='unknown',
ip_address=ip_address,
severity='MEDIUM',
details={
'endpoint': endpoint,
'reason': reason
}
)
self.log_event(event)
def log_sql_injection_attempt(self, user_id: str, ip_address: str,
field_name: str, threats: List[str]):
"""Log SQL injection attempts."""
event = SecurityEvent(
timestamp=datetime.utcnow(),
event_type='sql_injection_attempt',
user_id=user_id,
ip_address=ip_address,
severity='HIGH',
details={
'field_name': field_name,
'threats_detected': threats
}
)
self.log_event(event)
# Global instances
file_validator = FileSecurityValidator()
sql_prevention = SQLInjectionPrevention()
rate_limiter = RateLimiter()
secure_storage = SecureFileStorage()
audit_logger = SecurityAuditLogger()