Spaces:
Paused
Paused
File size: 23,258 Bytes
56c063a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 | """
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() |