Removed windows absolute paths

This commit is contained in:
Saifeddine ALOUI 2024-07-22 00:57:22 +02:00
parent 30e7eaba2c
commit 28ee567a9a

View File

@ -183,10 +183,11 @@ def sanitize_path(path: str, allow_absolute_path: bool = False, error_text="Abso
# Normalize path to use forward slashes
path = path.replace('\\', '/')
if not allow_absolute_path and path.strip().startswith("/"):
path = path.strip()
if not allow_absolute_path and (path.startswith("/") or (len(path) == 2 and path[1] == ':')):
raise HTTPException(status_code=400, detail=exception_text)
# Regular expression to detect patterns like "....", multiple forward slashes, and command injection attempts like $(whoami)
suspicious_patterns = re.compile(r'(\.\.+)|(/+/)|(\$\(.*\))')
@ -288,8 +289,43 @@ def is_allowed_url(url):
if __name__=="__main__":
sanitize_path_from_endpoint("main")
sanitize_path_from_endpoint("cat/main")
print("Main passed")
sanitize_path_from_endpoint(".../user")
print("hi")
test_cases = [
# Unix-style paths
("valid/path/to/file.txt", False),
("../../etc/passwd", False),
("/absolute/path/file.txt", False),
("relative/path/file.txt", False),
("valid/path/with/..", False),
("valid/path/with/./file.txt", False),
("another/valid/path/file.txt", True),
("/absolute/path/allowed.txt", True),
("$(whoami)", False),
("path/with/unauthorized&chars", False),
(None, False),
# Windows-style paths
(r"valid\path\to\file.txt", False),
(r"..\..\etc\passwd", False),
(r"C:\absolute\path\file.txt", False),
(r"relative\path\file.txt", False),
(r"valid\path\with\..", False),
(r"valid\path\with\.\file.txt", False),
(r"another\valid\path\file.txt", True),
(r"C:\absolute\path\allowed.txt", True),
(r"$(whoami)", False),
(r"path\with\unauthorized&chars", False),
# New test cases with C: drive
(r"C:\valid\path\to\file.txt", False),
(r"C:\another\valid\path\file.txt", True),
(r"C:\..\etc\passwd", False),
(r"C:\valid\path\with\..", False),
(r"C:", False),
]
for path, allow_absolute in test_cases:
try:
sanitized = sanitize_path(path, allow_absolute)
print(f"Original: {path}, Sanitized: {sanitized}")
except HTTPException as e:
print(f"Original: {path}, Exception: {e.detail}")