Validate and sanitize log file path to prevent security issues.
(self, file_path)
| 688 | return False |
| 689 | |
| 690 | def _validate_log_file_path(self, file_path): |
| 691 | """Validate and sanitize log file path to prevent security issues.""" |
| 692 | if not file_path or not isinstance(file_path, str): |
| 693 | raise ValueError("File path must be a non-empty string") |
| 694 | |
| 695 | sanitized_path = ''.join(char for char in file_path if ord(char) >= 32 and char != '\x7f') |
| 696 | |
| 697 | if not sanitized_path: |
| 698 | raise ValueError("File path contains only invalid characters") |
| 699 | |
| 700 | try: |
| 701 | path_obj = Path(sanitized_path) |
| 702 | |
| 703 | resolved_path = path_obj.resolve() |
| 704 | |
| 705 | resolved_str = str(resolved_path).lower() |
| 706 | forbidden_paths = ['/etc/', '/bin/', '/sbin/', '/usr/bin/', '/usr/sbin/', |
| 707 | '/boot/', '/dev/', '/proc/', '/sys/', '/root/'] |
| 708 | |
| 709 | for forbidden in forbidden_paths: |
| 710 | if resolved_str.startswith(forbidden): |
| 711 | raise ValueError(f"Access to system directory '{forbidden}' is not allowed") |
| 712 | |
| 713 | filename = path_obj.name |
| 714 | if not filename or filename in ('.', '..'): |
| 715 | raise ValueError("Invalid filename") |
| 716 | |
| 717 | suspicious_patterns = ['..', '~/', '$', '`', ';', '|', '&', '<', '>', '*', '?'] |
| 718 | for pattern in suspicious_patterns: |
| 719 | if pattern in filename: |
| 720 | raise ValueError(f"Filename contains suspicious pattern: '{pattern}'") |
| 721 | |
| 722 | valid_extensions = ['.log', '.txt', '.out'] |
| 723 | if not any(filename.lower().endswith(ext) for ext in valid_extensions): |
| 724 | logging.warning(f"Log file '{filename}' does not have a standard log extension") |
| 725 | |
| 726 | return str(resolved_path) |
| 727 | |
| 728 | except (OSError, RuntimeError) as e: |
| 729 | raise ValueError(f"Invalid file path: {e}") |
| 730 | except Exception as e: |
| 731 | raise ValueError(f"Path validation failed: {e}") |
| 732 | |
| 733 | def _looks_like_filename(self, token): |
| 734 | """Check if a token looks like a filename with proper validation.""" |
no test coverage detected