Coverage for /Users/les/Projects/crackerjack/crackerjack/services/input_validator.py: 0%
193 statements
« prev ^ index » next coverage.py v7.10.6, created at 2025-09-03 15:39 -0700
« prev ^ index » next coverage.py v7.10.6, created at 2025-09-03 15:39 -0700
1"""
2Comprehensive input validation framework for security hardening.
4This module provides defense-in-depth input validation to prevent:
5- Command injection attacks (CWE-77)
6- Path traversal attacks (CWE-22)
7- SQL injection (CWE-89)
8- JSON injection (CWE-91)
9- DoS via malformed input (CWE-400)
10- Code injection (CWE-94)
11"""
13import json
14import re
15import typing as t
16from functools import wraps
17from pathlib import Path
19from pydantic import BaseModel, Field
21from ..errors import ErrorCode, ExecutionError
22from .security_logger import (
23 SecurityEventLevel,
24 get_security_logger,
25)
28class ValidationConfig(BaseModel):
29 """Configuration for input validation rules."""
31 # String limits
32 MAX_STRING_LENGTH: int = Field(default=10000, ge=1)
33 MAX_PROJECT_NAME_LENGTH: int = Field(default=255, ge=1)
34 MAX_JOB_ID_LENGTH: int = Field(default=128, ge=1)
35 MAX_COMMAND_LENGTH: int = Field(default=1000, ge=1)
37 # JSON limits
38 MAX_JSON_SIZE: int = Field(default=1024 * 1024, ge=1) # 1MB
39 MAX_JSON_DEPTH: int = Field(default=10, ge=1)
41 # Rate limiting
42 MAX_VALIDATION_FAILURES_PER_MINUTE: int = Field(default=10, ge=1)
44 # Pattern validation
45 ALLOW_SHELL_METACHARACTERS: bool = Field(default=False)
46 STRICT_ALPHANUMERIC_MODE: bool = Field(default=False)
49class ValidationResult(BaseModel):
50 """Result of input validation."""
52 valid: bool
53 sanitized_value: t.Any = None
54 error_message: str = ""
55 security_level: SecurityEventLevel = SecurityEventLevel.LOW
56 validation_type: str = ""
59class InputSanitizer:
60 """Provides secure input sanitization utilities."""
62 # Shell metacharacters that could enable command injection
63 SHELL_METACHARACTERS = {
64 ";",
65 "&",
66 "|",
67 "`",
68 "$",
69 "(",
70 ")",
71 "<",
72 ">",
73 "\n",
74 "\r",
75 "\\",
76 '"',
77 "'",
78 "*",
79 "?",
80 "[",
81 "]",
82 "{",
83 "}",
84 "~",
85 "^",
86 }
88 # Dangerous path components
89 DANGEROUS_PATH_COMPONENTS = {
90 "..",
91 ".",
92 "~",
93 "$",
94 "`",
95 ";",
96 "&",
97 "|",
98 "<",
99 ">",
100 "CON",
101 "PRN",
102 "AUX",
103 "NUL",
104 "COM1",
105 "COM2",
106 "COM3",
107 "COM4",
108 "COM5",
109 "COM6",
110 "COM7",
111 "COM8",
112 "COM9",
113 "LPT1",
114 "LPT2",
115 "LPT3",
116 "LPT4",
117 "LPT5",
118 "LPT6",
119 "LPT7",
120 "LPT8",
121 "LPT9",
122 }
124 # SQL injection patterns
125 SQL_INJECTION_PATTERNS = [
126 r"(\b(union|select|insert|update|delete|drop|create|alter|exec|execute)\b)",
127 r"(-{2,}|\/\*|\*\/)", # SQL comments
128 r"(\bor\b.*=.*|\band\b.*=.*)", # Boolean-based injection
129 r"(\bxp_cmdshell\b|\bsp_executesql\b)", # SQL Server specific
130 ]
132 # Code injection patterns
133 CODE_INJECTION_PATTERNS = [
134 r"(eval\s*\(|exec\s*\(|execfile\s*\()", # Python code execution
135 r"(__import__|getattr|setattr|delattr)", # Dynamic attribute access
136 r"(subprocess|os\.system|os\.popen|commands\.)", # System commands
137 r"(compile\s*\(|code\.compile)", # Code compilation
138 ]
140 @classmethod
141 def sanitize_string(
142 cls,
143 value: str,
144 max_length: int = 10000,
145 allow_shell_chars: bool = False,
146 strict_alphanumeric: bool = False,
147 ) -> ValidationResult:
148 """Sanitize string input with configurable restrictions."""
150 if not isinstance(value, str):
151 return ValidationResult(
152 valid=False,
153 error_message=f"Expected string, got {type(value).__name__}",
154 security_level=SecurityEventLevel.MEDIUM,
155 validation_type="type_check",
156 )
158 # Length validation
159 if len(value) > max_length:
160 return ValidationResult(
161 valid=False,
162 error_message=f"String too long: {len(value)} > {max_length}",
163 security_level=SecurityEventLevel.HIGH,
164 validation_type="length_check",
165 )
167 # Null byte injection check
168 if "\x00" in value:
169 return ValidationResult(
170 valid=False,
171 error_message="Null byte detected in input",
172 security_level=SecurityEventLevel.CRITICAL,
173 validation_type="null_byte_injection",
174 )
176 # Control character check
177 if any(ord(c) < 32 and c not in "\t\n\r" for c in value):
178 return ValidationResult(
179 valid=False,
180 error_message="Control characters detected in input",
181 security_level=SecurityEventLevel.HIGH,
182 validation_type="control_chars",
183 )
185 # Shell metacharacter check
186 if not allow_shell_chars:
187 found_chars = [c for c in value if c in cls.SHELL_METACHARACTERS]
188 if found_chars:
189 return ValidationResult(
190 valid=False,
191 error_message=f"Shell metacharacters detected: {found_chars}",
192 security_level=SecurityEventLevel.CRITICAL,
193 validation_type="shell_injection",
194 )
196 # Strict alphanumeric mode
197 if (
198 strict_alphanumeric
199 and not value.replace("-", "").replace("_", "").isalnum()
200 ):
201 return ValidationResult(
202 valid=False,
203 error_message="Only alphanumeric characters, hyphens, and underscores allowed",
204 security_level=SecurityEventLevel.MEDIUM,
205 validation_type="alphanumeric_only",
206 )
208 # SQL injection pattern check
209 for pattern in cls.SQL_INJECTION_PATTERNS:
210 if re.search(pattern, value, re.IGNORECASE):
211 return ValidationResult(
212 valid=False,
213 error_message="SQL injection pattern detected",
214 security_level=SecurityEventLevel.CRITICAL,
215 validation_type="sql_injection",
216 )
218 # Code injection pattern check
219 for pattern in cls.CODE_INJECTION_PATTERNS:
220 if re.search(pattern, value, re.IGNORECASE):
221 return ValidationResult(
222 valid=False,
223 error_message="Code injection pattern detected",
224 security_level=SecurityEventLevel.CRITICAL,
225 validation_type="code_injection",
226 )
228 # Basic sanitization (remove leading/trailing whitespace)
229 sanitized = value.strip()
231 return ValidationResult(
232 valid=True, sanitized_value=sanitized, validation_type="string_sanitization"
233 )
235 @classmethod
236 def sanitize_json(
237 cls, value: str, max_size: int = 1024 * 1024, max_depth: int = 10
238 ) -> ValidationResult:
239 """Sanitize JSON input with size and depth limits."""
241 if len(value) > max_size:
242 return ValidationResult(
243 valid=False,
244 error_message=f"JSON too large: {len(value)} > {max_size} bytes",
245 security_level=SecurityEventLevel.HIGH,
246 validation_type="json_size",
247 )
249 try:
250 # Parse JSON to validate structure
251 parsed = json.loads(value)
253 # Check nesting depth
254 def check_depth(obj: t.Any, current_depth: int = 0) -> int:
255 if current_depth > max_depth:
256 return current_depth
258 if isinstance(obj, dict):
259 return (
260 max(check_depth(v, current_depth + 1) for v in obj.values())
261 if obj
262 else current_depth
263 )
264 elif isinstance(obj, list):
265 return (
266 max(check_depth(item, current_depth + 1) for item in obj)
267 if obj
268 else current_depth
269 )
270 else:
271 return current_depth
273 actual_depth = check_depth(parsed)
274 if actual_depth > max_depth:
275 return ValidationResult(
276 valid=False,
277 error_message=f"JSON nesting too deep: {actual_depth} > {max_depth}",
278 security_level=SecurityEventLevel.HIGH,
279 validation_type="json_depth",
280 )
282 return ValidationResult(
283 valid=True, sanitized_value=parsed, validation_type="json_parsing"
284 )
286 except json.JSONDecodeError as e:
287 return ValidationResult(
288 valid=False,
289 error_message=f"Invalid JSON: {e}",
290 security_level=SecurityEventLevel.MEDIUM,
291 validation_type="json_syntax",
292 )
294 @classmethod
295 def sanitize_path(
296 cls,
297 value: str | Path,
298 base_directory: Path | None = None,
299 allow_absolute: bool = False,
300 ) -> ValidationResult:
301 """Sanitize file path with traversal protection."""
303 try:
304 path = Path(value)
306 # Resolve to absolute path to eliminate .. components
307 resolved = path.resolve()
309 # Check for dangerous components
310 for part in resolved.parts:
311 if part.upper() in cls.DANGEROUS_PATH_COMPONENTS:
312 return ValidationResult(
313 valid=False,
314 error_message=f"Dangerous path component: {part}",
315 security_level=SecurityEventLevel.CRITICAL,
316 validation_type="path_traversal",
317 )
319 # Check base directory constraint
320 if base_directory:
321 base_resolved = base_directory.resolve()
322 try:
323 resolved.relative_to(base_resolved)
324 except ValueError:
325 return ValidationResult(
326 valid=False,
327 error_message=f"Path outside base directory: {resolved}",
328 security_level=SecurityEventLevel.CRITICAL,
329 validation_type="directory_escape",
330 )
332 # Check absolute path restrictions
333 if not allow_absolute and resolved.is_absolute() and base_directory:
334 return ValidationResult(
335 valid=False,
336 error_message="Absolute paths not allowed",
337 security_level=SecurityEventLevel.HIGH,
338 validation_type="absolute_path",
339 )
341 return ValidationResult(
342 valid=True,
343 sanitized_value=resolved,
344 validation_type="path_sanitization",
345 )
347 except (OSError, ValueError) as e:
348 return ValidationResult(
349 valid=False,
350 error_message=f"Invalid path: {e}",
351 security_level=SecurityEventLevel.HIGH,
352 validation_type="path_syntax",
353 )
356class SecureInputValidator:
357 """Main input validation class with security logging."""
359 def __init__(self, config: ValidationConfig | None = None):
360 self.config = config or ValidationConfig()
361 self.logger = get_security_logger()
362 self.sanitizer = InputSanitizer()
363 self._failure_counts: dict[str, int] = {}
365 def validate_project_name(self, name: str) -> ValidationResult:
366 """Validate project name with security constraints."""
368 result = self.sanitizer.sanitize_string(
369 name,
370 max_length=self.config.MAX_PROJECT_NAME_LENGTH,
371 allow_shell_chars=False,
372 strict_alphanumeric=True,
373 )
375 if not result.valid:
376 self._log_validation_failure(
377 "project_name", name, result.error_message, result.security_level
378 )
380 return result
382 def validate_job_id(self, job_id: str) -> ValidationResult:
383 """Validate job ID with strict alphanumeric constraints."""
385 # Job IDs must be alphanumeric with hyphens only
386 if not re.match(r"^[a-zA-Z0-9\-_]+$", job_id):
387 result = ValidationResult(
388 valid=False,
389 error_message="Job ID must be alphanumeric with hyphens/underscores only",
390 security_level=SecurityEventLevel.HIGH,
391 validation_type="job_id_format",
392 )
393 self._log_validation_failure(
394 "job_id", job_id, result.error_message, result.security_level
395 )
396 return result
398 result = self.sanitizer.sanitize_string(
399 job_id,
400 max_length=self.config.MAX_JOB_ID_LENGTH,
401 allow_shell_chars=False,
402 strict_alphanumeric=True,
403 )
405 if not result.valid:
406 self._log_validation_failure(
407 "job_id", job_id, result.error_message, result.security_level
408 )
410 return result
412 def validate_command_args(self, args: str | list) -> ValidationResult:
413 """Validate command arguments to prevent injection."""
415 if isinstance(args, str):
416 result = self.sanitizer.sanitize_string(
417 args,
418 max_length=self.config.MAX_COMMAND_LENGTH,
419 allow_shell_chars=self.config.ALLOW_SHELL_METACHARACTERS,
420 )
421 elif isinstance(args, list):
422 # Validate each argument in the list
423 sanitized_args = []
424 for arg in args:
425 if not isinstance(arg, str):
426 result = ValidationResult(
427 valid=False,
428 error_message=f"Command argument must be string, got {type(arg).__name__}",
429 security_level=SecurityEventLevel.HIGH,
430 validation_type="command_arg_type",
431 )
432 break
434 arg_result = self.sanitizer.sanitize_string(
435 arg,
436 max_length=self.config.MAX_COMMAND_LENGTH,
437 allow_shell_chars=self.config.ALLOW_SHELL_METACHARACTERS,
438 )
440 if not arg_result.valid:
441 result = arg_result
442 break
444 sanitized_args.append(arg_result.sanitized_value)
445 else:
446 result = ValidationResult(
447 valid=True,
448 sanitized_value=sanitized_args,
449 validation_type="command_args_list",
450 )
451 else:
452 result = ValidationResult(
453 valid=False,
454 error_message=f"Command args must be string or list, got {type(args).__name__}",
455 security_level=SecurityEventLevel.HIGH,
456 validation_type="command_args_type",
457 )
459 if not result.valid:
460 self._log_validation_failure(
461 "command_args", str(args), result.error_message, result.security_level
462 )
464 return result
466 def validate_json_payload(self, payload: str) -> ValidationResult:
467 """Validate JSON payload with size and structure limits."""
469 result = self.sanitizer.sanitize_json(
470 payload,
471 max_size=self.config.MAX_JSON_SIZE,
472 max_depth=self.config.MAX_JSON_DEPTH,
473 )
475 if not result.valid:
476 self._log_validation_failure(
477 "json_payload",
478 payload[:100] + "...",
479 result.error_message,
480 result.security_level,
481 )
483 return result
485 def validate_file_path(
486 self,
487 path: str | Path,
488 base_directory: Path | None = None,
489 allow_absolute: bool = False,
490 ) -> ValidationResult:
491 """Validate file path with traversal protection."""
493 result = self.sanitizer.sanitize_path(path, base_directory, allow_absolute)
495 if not result.valid:
496 self._log_validation_failure(
497 "file_path", str(path), result.error_message, result.security_level
498 )
500 return result
502 def validate_environment_var(self, name: str, value: str) -> ValidationResult:
503 """Validate environment variable name and value."""
505 # Environment variable names must be valid identifiers
506 if not re.match(r"^[A-Z_][A-Z0-9_]*$", name):
507 result = ValidationResult(
508 valid=False,
509 error_message="Invalid environment variable name format",
510 security_level=SecurityEventLevel.MEDIUM,
511 validation_type="env_var_name",
512 )
513 self._log_validation_failure(
514 "env_var_name", name, result.error_message, result.security_level
515 )
516 return result
518 # Validate environment variable value
519 result = self.sanitizer.sanitize_string(
520 value, max_length=self.config.MAX_STRING_LENGTH, allow_shell_chars=False
521 )
523 if not result.valid:
524 self._log_validation_failure(
525 "env_var_value",
526 f"{name}={value}",
527 result.error_message,
528 result.security_level,
529 )
531 return result
533 def _log_validation_failure(
534 self,
535 validation_type: str,
536 input_value: str,
537 reason: str,
538 level: SecurityEventLevel,
539 ) -> None:
540 """Log validation failure with rate limiting."""
542 self.logger.log_validation_failed(
543 validation_type=validation_type,
544 file_path=input_value, # Reusing file_path field for input value
545 reason=reason,
546 )
548 # Track failure counts for rate limiting
549 self._failure_counts[validation_type] = (
550 self._failure_counts.get(validation_type, 0) + 1
551 )
554def validation_required(
555 *,
556 validate_args: bool = True,
557 validate_kwargs: bool = True,
558 config: ValidationConfig | None = None,
559):
560 """Decorator to add automatic input validation to functions."""
562 def decorator(func):
563 @wraps(func)
564 def wrapper(*args, **kwargs):
565 validator = SecureInputValidator(config)
567 # Validate string arguments
568 if validate_args:
569 for i, arg in enumerate(args):
570 if isinstance(arg, str):
571 result = validator.sanitizer.sanitize_string(arg)
572 if not result.valid:
573 raise ExecutionError(
574 message=f"Validation failed for argument {i}: {result.error_message}",
575 error_code=ErrorCode.VALIDATION_ERROR,
576 )
578 # Validate keyword arguments
579 if validate_kwargs:
580 for key, value in kwargs.items():
581 if isinstance(value, str):
582 result = validator.sanitizer.sanitize_string(value)
583 if not result.valid:
584 raise ExecutionError(
585 message=f"Validation failed for parameter {key}: {result.error_message}",
586 error_code=ErrorCode.VALIDATION_ERROR,
587 )
589 return func(*args, **kwargs)
591 return wrapper
593 return decorator
596def get_input_validator(
597 config: ValidationConfig | None = None,
598) -> SecureInputValidator:
599 """Get configured input validator instance."""
600 return SecureInputValidator(config)
603# Convenience validation functions
604def validate_and_sanitize_string(value: str, **kwargs) -> str:
605 """Validate and return sanitized string, raising on failure."""
606 validator = SecureInputValidator()
607 result = validator.sanitizer.sanitize_string(value, **kwargs)
609 if not result.valid:
610 raise ExecutionError(
611 message=f"String validation failed: {result.error_message}",
612 error_code=ErrorCode.VALIDATION_ERROR,
613 )
615 return result.sanitized_value
618def validate_and_sanitize_path(value: str | Path, **kwargs) -> Path:
619 """Validate and return sanitized path, raising on failure."""
620 validator = SecureInputValidator()
621 result = validator.sanitize_path(value, **kwargs)
623 if not result.valid:
624 raise ExecutionError(
625 message=f"Path validation failed: {result.error_message}",
626 error_code=ErrorCode.VALIDATION_ERROR,
627 )
629 return result.sanitized_value
632def validate_and_parse_json(value: str, **kwargs) -> t.Any:
633 """Validate and return parsed JSON, raising on failure."""
634 validator = SecureInputValidator()
635 result = validator.sanitizer.sanitize_json(value, **kwargs)
637 if not result.valid:
638 raise ExecutionError(
639 message=f"JSON validation failed: {result.error_message}",
640 error_code=ErrorCode.VALIDATION_ERROR,
641 )
643 return result.sanitized_value