Coverage for /Users/les/Projects/crackerjack/crackerjack/services/secure_path_utils.py: 0%
206 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
1import os
2import re
3import tempfile
4import typing as t
5import urllib.parse
6from pathlib import Path
8from ..errors import ErrorCode, ExecutionError
9from .security_logger import SecurityEventLevel, SecurityEventType, get_security_logger
12class SecurePathValidator:
13 """Comprehensive path security validation to prevent directory traversal attacks."""
15 MAX_FILE_SIZE = 100 * 1024 * 1024
16 MAX_PATH_LENGTH = 4096
18 # Enhanced dangerous components including encoded variations
19 DANGEROUS_COMPONENTS = {
20 "..",
21 ".",
22 "~",
23 "$",
24 "`",
25 ";",
26 "&",
27 "|",
28 "<",
29 ">",
30 "CON",
31 "PRN",
32 "AUX",
33 "NUL",
34 "COM1",
35 "COM2",
36 "COM3",
37 "COM4",
38 "COM5",
39 "COM6",
40 "COM7",
41 "COM8",
42 "COM9",
43 "LPT1",
44 "LPT2",
45 "LPT3",
46 "LPT4",
47 "LPT5",
48 "LPT6",
49 "LPT7",
50 "LPT8",
51 "LPT9",
52 }
54 # Directory traversal patterns (including encoded variations)
55 TRAVERSAL_PATTERNS = [
56 r"\.\./", # ../
57 r"\.\.\/", # ..\/
58 r"\.\.\\", # ..\
59 r"%2e%2e%2f", # URL encoded ../
60 r"%2e%2e%5c", # URL encoded ..\
61 r"%2e%2e/", # Mixed encoding
62 r"%252e%252e%252f", # Double URL encoded
63 r"\.\.%2f", # Mixed encoding
64 r"\.\.%5c", # Mixed encoding
65 r"%c0%2e%c0%2e%c0%2f", # UTF-8 overlong encoding
66 r"..%c0%af", # UTF-8 overlong encoding
67 r"..%c1%9c", # UTF-8 overlong encoding
68 ]
70 # Null byte variations
71 NULL_BYTE_PATTERNS = [
72 r"%00", # URL encoded null
73 r"\x00", # Literal null
74 r"%c0%80", # UTF-8 overlong null
75 ]
77 @classmethod
78 def validate_safe_path(
79 cls, path: str | Path, base_directory: Path | None = None
80 ) -> Path:
81 """
82 Comprehensive path validation to prevent directory traversal attacks.
84 Args:
85 path: Path to validate (string or Path object)
86 base_directory: Optional base directory to constrain path within
88 Returns:
89 Validated and normalized Path object
91 Raises:
92 ExecutionError: If path contains malicious patterns or is invalid
93 """
94 # Convert to string for pattern checking
95 path_str = str(path)
97 # Check for null bytes and dangerous patterns
98 cls._check_malicious_patterns(path_str)
100 # Convert to Path and normalize
101 try:
102 path_obj = Path(path_str)
103 normalized = cls.normalize_path(path_obj)
104 except (ValueError, OSError) as e:
105 raise ExecutionError(
106 message=f"Invalid path format: {path_str}",
107 error_code=ErrorCode.VALIDATION_ERROR,
108 ) from e
110 # Validate path length
111 if len(str(normalized)) > cls.MAX_PATH_LENGTH:
112 raise ExecutionError(
113 message=f"Path too long: {len(str(normalized))} > {cls.MAX_PATH_LENGTH}",
114 error_code=ErrorCode.VALIDATION_ERROR,
115 )
117 # Check dangerous components
118 cls._check_dangerous_components(normalized)
120 # Validate within base directory if specified
121 if base_directory:
122 if not cls.is_within_directory(normalized, base_directory):
123 raise ExecutionError(
124 message=f"Path outside allowed directory: {normalized} not within {base_directory}",
125 error_code=ErrorCode.VALIDATION_ERROR,
126 )
128 return normalized
130 @classmethod
131 def validate_file_path(
132 cls, file_path: Path, base_directory: Path | None = None
133 ) -> Path:
134 """Legacy method - redirects to validate_safe_path for consistency."""
135 return cls.validate_safe_path(file_path, base_directory)
137 @classmethod
138 def secure_path_join(cls, base: Path, *parts: str) -> Path:
139 """
140 Safe alternative to Path.joinpath() that prevents directory traversal.
142 Args:
143 base: Base directory path
144 *parts: Path components to join
146 Returns:
147 Safely joined path
149 Raises:
150 ExecutionError: If any part contains malicious patterns
151 """
152 # Validate base path
153 validated_base = cls.validate_safe_path(base)
155 # Validate each part for malicious patterns
156 for part in parts:
157 cls._check_malicious_patterns(str(part))
158 # Don't allow absolute paths or parent directory references
159 if Path(part).is_absolute():
160 raise ExecutionError(
161 message=f"Absolute path not allowed in join: {part}",
162 error_code=ErrorCode.VALIDATION_ERROR,
163 )
165 # Join paths safely
166 result = validated_base.joinpath(*parts)
168 # Ensure result is still within base directory
169 if not cls.is_within_directory(result, validated_base):
170 raise ExecutionError(
171 message=f"Joined path escapes base directory: {result} not within {validated_base}",
172 error_code=ErrorCode.VALIDATION_ERROR,
173 )
175 return result
177 @classmethod
178 def normalize_path(cls, path: Path) -> Path:
179 """
180 Canonical path resolution with security checks.
182 Args:
183 path: Path to normalize
185 Returns:
186 Normalized path with symlinks resolved
188 Raises:
189 ExecutionError: If path resolution fails or contains malicious patterns
190 """
191 try:
192 # Resolve symlinks and normalize
193 resolved = path.resolve()
195 # Additional validation after resolution
196 cls._validate_resolved_path(resolved)
198 return resolved
200 except (OSError, RuntimeError) as e:
201 raise ExecutionError(
202 message=f"Path normalization failed for {path}: {e}",
203 error_code=ErrorCode.VALIDATION_ERROR,
204 ) from e
206 @classmethod
207 def is_within_directory(cls, path: Path, directory: Path) -> bool:
208 """
209 Verify that a path is contained within a directory.
211 Args:
212 path: Path to check
213 directory: Directory that should contain the path
215 Returns:
216 True if path is within directory, False otherwise
217 """
218 try:
219 # Resolve both paths to handle symlinks
220 resolved_path = path.resolve()
221 resolved_directory = directory.resolve()
223 # Check if path is relative to directory
224 resolved_path.relative_to(resolved_directory)
225 return True
227 except (ValueError, OSError):
228 return False
230 @classmethod
231 def safe_resolve(cls, path: Path, base_directory: Path | None = None) -> Path:
232 """
233 Secure path resolution preventing symlink attacks.
235 Args:
236 path: Path to resolve
237 base_directory: Optional base directory constraint
239 Returns:
240 Safely resolved path
242 Raises:
243 ExecutionError: If resolution fails or path escapes constraints
244 """
245 # First validate the input path
246 validated_path = cls.validate_safe_path(path, base_directory)
248 # Resolve with additional symlink attack prevention
249 resolved = cls.normalize_path(validated_path)
251 # Re-validate after resolution
252 if base_directory and not cls.is_within_directory(resolved, base_directory):
253 raise ExecutionError(
254 message=f"Resolved path escapes base directory: {resolved} not within {base_directory}",
255 error_code=ErrorCode.VALIDATION_ERROR,
256 )
258 return resolved
260 @classmethod
261 def _check_malicious_patterns(cls, path_str: str) -> None:
262 """Check for directory traversal and null byte patterns."""
263 security_logger = get_security_logger()
265 # URL decode the path to catch encoded attacks
266 try:
267 decoded = urllib.parse.unquote(path_str, errors="strict")
268 except UnicodeDecodeError:
269 # If decoding fails, use original string but still check patterns
270 decoded = path_str
272 # Check both original and decoded versions
273 for check_str in [path_str, decoded]:
274 # Check for null bytes
275 for pattern in cls.NULL_BYTE_PATTERNS:
276 if re.search(pattern, check_str, re.IGNORECASE):
277 security_logger.log_security_event(
278 SecurityEventType.PATH_TRAVERSAL_ATTEMPT,
279 SecurityEventLevel.CRITICAL,
280 f"Null byte pattern detected in path: {path_str}",
281 file_path=path_str,
282 pattern_type="null_byte",
283 detected_pattern=pattern,
284 )
285 raise ExecutionError(
286 message=f"Null byte pattern detected in path: {path_str}",
287 error_code=ErrorCode.VALIDATION_ERROR,
288 )
290 # Check for directory traversal patterns
291 for pattern in cls.TRAVERSAL_PATTERNS:
292 if re.search(pattern, check_str, re.IGNORECASE):
293 security_logger.log_path_traversal_attempt(
294 attempted_path=path_str,
295 pattern_type="directory_traversal",
296 detected_pattern=pattern,
297 )
298 raise ExecutionError(
299 message=f"Directory traversal pattern detected in path: {path_str}",
300 error_code=ErrorCode.VALIDATION_ERROR,
301 )
303 @classmethod
304 def _validate_resolved_path(cls, path: Path) -> None:
305 """Additional validation for resolved paths."""
306 path_str = str(path)
308 # Check for dangerous patterns that might appear after resolution
309 if ".." in path_str or path_str.startswith("/.."):
310 raise ExecutionError(
311 message=f"Parent directory reference in resolved path: {path}",
312 error_code=ErrorCode.VALIDATION_ERROR,
313 )
315 # Check for suspicious patterns
316 suspicious_patterns = [
317 r"/tmp/.*\.\./", # Traversal in temp directories
318 r"/var/.*\.\./", # Traversal in var directories
319 r"/etc/.*\.\./", # Traversal near system files
320 ]
322 for pattern in suspicious_patterns:
323 if re.search(pattern, path_str):
324 raise ExecutionError(
325 message=f"Suspicious path pattern detected: {path}",
326 error_code=ErrorCode.VALIDATION_ERROR,
327 )
329 @classmethod
330 def _check_dangerous_components(cls, path: Path) -> None:
331 security_logger = get_security_logger()
333 for part in path.parts:
334 if part in cls.DANGEROUS_COMPONENTS:
335 security_logger.log_dangerous_path_detected(
336 path=str(path),
337 dangerous_component=part,
338 )
339 raise ExecutionError(
340 message=f"Dangerous path component detected: {part}",
341 error_code=ErrorCode.VALIDATION_ERROR,
342 )
344 @classmethod
345 def _validate_within_base_directory(cls, path: Path, base_directory: Path) -> None:
346 base_resolved = base_directory.resolve()
348 try:
349 path.relative_to(base_resolved)
350 except ValueError as e:
351 raise ExecutionError(
352 message=f"Path outside allowed directory: {path} not within {base_resolved}",
353 error_code=ErrorCode.VALIDATION_ERROR,
354 ) from e
356 @classmethod
357 def validate_file_size(cls, file_path: Path) -> None:
358 try:
359 file_size = file_path.stat().st_size
360 if file_size > cls.MAX_FILE_SIZE:
361 raise ExecutionError(
362 message=f"File too large: {file_size} bytes > {cls.MAX_FILE_SIZE} bytes limit",
363 error_code=ErrorCode.VALIDATION_ERROR,
364 )
365 except OSError as e:
366 raise ExecutionError(
367 message=f"Cannot check file size: {file_path}",
368 error_code=ErrorCode.FILE_READ_ERROR,
369 ) from e
371 @classmethod
372 def create_secure_backup_path(
373 cls, original_path: Path, base_directory: Path | None = None
374 ) -> Path:
375 validated_original = cls.validate_file_path(original_path, base_directory)
377 backup_path = validated_original.parent / f"{validated_original.name}.backup"
379 validated_backup = cls.validate_file_path(backup_path, base_directory)
381 return validated_backup
383 @classmethod
384 def create_secure_temp_file(
385 cls,
386 suffix: str = ".tmp",
387 prefix: str = "crackerjack_",
388 directory: Path | None = None,
389 purpose: str = "general",
390 ) -> t.Any:
391 """
392 Create a secure temporary file with proper permissions.
394 Args:
395 suffix: File suffix
396 prefix: File prefix
397 directory: Directory to create temp file in (validated if provided)
398 purpose: Purpose description for security logging
400 Returns:
401 Secure temporary file handle
403 Raises:
404 ExecutionError: If temp file creation fails
405 """
406 security_logger = get_security_logger()
408 # Validate directory if provided
409 if directory:
410 directory = cls.validate_safe_path(directory)
412 try:
413 temp_file = tempfile.NamedTemporaryFile(
414 mode="w+b", suffix=suffix, prefix=prefix, dir=directory, delete=False
415 )
417 # Set restrictive permissions (owner read/write only)
418 os.chmod(temp_file.name, 0o600)
420 # Log secure temp file creation
421 security_logger.log_temp_file_created(
422 temp_path=temp_file.name,
423 purpose=purpose,
424 )
426 return temp_file
428 except OSError as e:
429 raise ExecutionError(
430 message=f"Failed to create secure temporary file: {e}",
431 error_code=ErrorCode.FILE_WRITE_ERROR,
432 ) from e
435class AtomicFileOperations:
436 @staticmethod
437 def atomic_write(
438 file_path: Path, content: str | bytes, base_directory: Path | None = None
439 ) -> None:
440 security_logger = get_security_logger()
442 validated_path = SecurePathValidator.validate_safe_path(
443 file_path, base_directory
444 )
446 temp_file = None
447 try:
448 temp_file = SecurePathValidator.create_secure_temp_file(
449 prefix="atomic_write_",
450 directory=validated_path.parent,
451 purpose="atomic_file_write",
452 )
454 if isinstance(content, str):
455 temp_file.write(content.encode("utf-8"))
456 else:
457 temp_file.write(content)
459 temp_file.flush()
460 os.fsync(temp_file.fileno())
461 temp_file.close()
463 temp_path = Path(temp_file.name)
464 temp_path.replace(validated_path)
466 # Log successful atomic operation
467 security_logger.log_atomic_operation(
468 operation="write",
469 file_path=str(validated_path),
470 success=True,
471 )
473 except Exception as e:
474 if temp_file and hasattr(temp_file, "name"):
475 temp_path = Path(temp_file.name)
476 if temp_path.exists():
477 temp_path.unlink()
479 # Log failed atomic operation
480 security_logger.log_atomic_operation(
481 operation="write",
482 file_path=str(validated_path),
483 success=False,
484 error=str(e),
485 )
487 raise ExecutionError(
488 message=f"Atomic write failed for {validated_path}: {e}",
489 error_code=ErrorCode.FILE_WRITE_ERROR,
490 ) from e
492 @staticmethod
493 def atomic_backup_and_write(
494 file_path: Path, new_content: str | bytes, base_directory: Path | None = None
495 ) -> Path:
496 security_logger = get_security_logger()
498 validated_path = SecurePathValidator.validate_safe_path(
499 file_path, base_directory
500 )
502 if not validated_path.exists():
503 raise ExecutionError(
504 message=f"File does not exist: {validated_path}",
505 error_code=ErrorCode.FILE_READ_ERROR,
506 )
508 SecurePathValidator.validate_file_size(validated_path)
510 backup_path = SecurePathValidator.create_secure_backup_path(
511 validated_path, base_directory
512 )
514 try:
515 original_content = validated_path.read_bytes()
517 AtomicFileOperations.atomic_write(
518 backup_path, original_content, base_directory
519 )
521 AtomicFileOperations.atomic_write(
522 validated_path, new_content, base_directory
523 )
525 # Log successful backup creation
526 security_logger.log_backup_created(
527 original_path=str(validated_path),
528 backup_path=str(backup_path),
529 )
531 return backup_path
533 except Exception as e:
534 if backup_path.exists():
535 backup_path.unlink()
537 # Log failed backup operation
538 security_logger.log_atomic_operation(
539 operation="backup_and_write",
540 file_path=str(validated_path),
541 success=False,
542 error=str(e),
543 )
545 raise ExecutionError(
546 message=f"Atomic backup and write failed: {e}",
547 error_code=ErrorCode.FILE_WRITE_ERROR,
548 ) from e
551class SubprocessPathValidator:
552 """Specialized path validation for subprocess execution contexts."""
554 # Paths that should never be accessible via subprocess
555 FORBIDDEN_SUBPROCESS_PATHS = {
556 "/etc/passwd",
557 "/etc/shadow",
558 "/etc/sudoers",
559 "/etc/hosts",
560 "/boot",
561 "/sys",
562 "/proc",
563 "/dev",
564 "/var/log",
565 "/usr/bin/sudo",
566 "/usr/bin/su",
567 "/bin/su",
568 "/bin/sudo",
569 "/etc/ssh",
570 "/root",
571 "/var/spool/cron",
572 }
574 # Directory patterns that are dangerous for subprocess operations
575 DANGEROUS_DIRECTORY_PATTERNS = [
576 r"^/etc/?", # System configuration
577 r"^/boot/?", # Boot files
578 r"^/sys/?", # System files
579 r"^/proc/?", # Process files
580 r"^/dev/?", # Device files
581 r"^/root/?", # Root home
582 r"^/var/log/?", # System logs
583 r"^/usr/bin/?", # System binaries
584 r"^/bin/?", # Core binaries
585 r"^/sbin/?", # System binaries
586 ]
588 @classmethod
589 def validate_subprocess_cwd(cls, cwd: Path | str | None) -> Path | None:
590 """
591 Validate working directory for subprocess execution.
593 Args:
594 cwd: Working directory path
596 Returns:
597 Validated Path object or None
599 Raises:
600 ExecutionError: If path is dangerous for subprocess execution
601 """
602 if cwd is None:
603 return None
605 # Use base path validation first
606 validated_cwd = SecurePathValidator.validate_safe_path(cwd)
608 # Additional subprocess-specific checks
609 cwd_str = str(validated_cwd)
611 # Check against forbidden paths
612 if cwd_str in cls.FORBIDDEN_SUBPROCESS_PATHS:
613 security_logger = get_security_logger()
614 security_logger.log_dangerous_path_detected(
615 path=cwd_str,
616 dangerous_component="forbidden_subprocess_path",
617 context="subprocess_cwd_validation",
618 )
619 raise ExecutionError(
620 message=f"Forbidden subprocess working directory: {cwd_str}",
621 error_code=ErrorCode.VALIDATION_ERROR,
622 )
624 # Check against dangerous directory patterns
625 for pattern in cls.DANGEROUS_DIRECTORY_PATTERNS:
626 if re.match(pattern, cwd_str):
627 security_logger = get_security_logger()
628 security_logger.log_dangerous_path_detected(
629 path=cwd_str,
630 dangerous_component=f"pattern:{pattern}",
631 context="subprocess_cwd_validation",
632 )
633 raise ExecutionError(
634 message=f"Dangerous subprocess working directory pattern: {cwd_str}",
635 error_code=ErrorCode.VALIDATION_ERROR,
636 )
638 return validated_cwd
640 @classmethod
641 def validate_executable_path(cls, executable: str | Path) -> Path:
642 """
643 Validate executable path for subprocess execution.
645 Args:
646 executable: Executable path or name
648 Returns:
649 Validated Path object
651 Raises:
652 ExecutionError: If executable is dangerous or invalid
653 """
654 exec_path = Path(executable)
656 # If it's just a command name, don't validate as full path
657 if not str(executable).startswith(("/", "./", "../")):
658 return exec_path
660 # For full paths, apply full validation
661 validated_exec = SecurePathValidator.validate_safe_path(exec_path)
663 # Additional checks for executable paths
664 exec_str = str(validated_exec)
666 # Check if trying to execute system-critical files
667 dangerous_executables = {
668 "/usr/bin/sudo",
669 "/bin/sudo",
670 "/usr/bin/su",
671 "/bin/su",
672 "/usr/bin/passwd",
673 "/bin/passwd",
674 "/usr/sbin/visudo",
675 "/usr/bin/ssh",
676 "/usr/bin/scp",
677 "/usr/bin/rsync",
678 "/bin/rm",
679 "/usr/bin/rm",
680 "/bin/rmdir",
681 "/usr/bin/rmdir",
682 "/sbin/reboot",
683 "/sbin/shutdown",
684 "/usr/sbin/reboot",
685 }
687 if exec_str in dangerous_executables:
688 security_logger = get_security_logger()
689 security_logger.log_dangerous_path_detected(
690 path=exec_str,
691 dangerous_component="dangerous_executable",
692 context="subprocess_executable_validation",
693 )
694 raise ExecutionError(
695 message=f"Dangerous executable blocked: {exec_str}",
696 error_code=ErrorCode.VALIDATION_ERROR,
697 )
699 return validated_exec