MCPcopy Create free account
hub / github.com/Keeper-Security/Commander / _validate_log_file_path

Method _validate_log_file_path

keepercommander/cli.py:718–759  ·  view source on GitHub ↗

Validate and sanitize log file path to prevent security issues.

(self, file_path)

Source from the content-addressed store, hash-verified

716 return False
717
718 def _validate_log_file_path(self, file_path):
719 """Validate and sanitize log file path to prevent security issues."""
720 if not file_path or not isinstance(file_path, str):
721 raise ValueError("File path must be a non-empty string")
722
723 sanitized_path = ''.join(char for char in file_path if ord(char) >= 32 and char != '\x7f')
724
725 if not sanitized_path:
726 raise ValueError("File path contains only invalid characters")
727
728 try:
729 path_obj = Path(sanitized_path)
730
731 resolved_path = path_obj.resolve()
732
733 resolved_str = str(resolved_path).lower()
734 forbidden_paths = ['/etc/', '/bin/', '/sbin/', '/usr/bin/', '/usr/sbin/',
735 '/boot/', '/dev/', '/proc/', '/sys/', '/root/']
736
737 for forbidden in forbidden_paths:
738 if resolved_str.startswith(forbidden):
739 raise ValueError(f"Access to system directory '{forbidden}' is not allowed")
740
741 filename = path_obj.name
742 if not filename or filename in ('.', '..'):
743 raise ValueError("Invalid filename")
744
745 suspicious_patterns = ['..', '~/', '$', '`', ';', '|', '&', '<', '>', '*', '?']
746 for pattern in suspicious_patterns:
747 if pattern in filename:
748 raise ValueError(f"Filename contains suspicious pattern: '{pattern}'")
749
750 valid_extensions = ['.log', '.txt', '.out']
751 if not any(filename.lower().endswith(ext) for ext in valid_extensions):
752 logging.warning(f"Log file '{filename}' does not have a standard log extension")
753
754 return str(resolved_path)
755
756 except (OSError, RuntimeError) as e:
757 raise ValueError(f"Invalid file path: {e}")
758 except Exception as e:
759 raise ValueError(f"Path validation failed: {e}")
760
761 def _looks_like_filename(self, token):
762 """Check if a token looks like a filename with proper validation."""

Callers 1

setup_file_loggingMethod · 0.95

Calls 2

resolveMethod · 0.80
warningMethod · 0.80

Tested by

no test coverage detected