2024-03-31 21:18:26 +02:00
|
|
|
import re
|
2024-12-19 13:48:57 +01:00
|
|
|
from pathlib import Path
|
|
|
|
|
2024-03-31 21:18:26 +02:00
|
|
|
import pytest
|
2024-12-19 13:48:57 +01:00
|
|
|
from ascii_colors import ASCIIColors
|
|
|
|
from fastapi import HTTPException
|
|
|
|
|
|
|
|
|
|
|
|
def sanitize_path_from_endpoint(
|
|
|
|
path: str,
|
|
|
|
error_text="A suspected LFI attack detected. The path sent to the server has suspicious elements in it!",
|
|
|
|
exception_text="Invalid path!",
|
|
|
|
):
|
2024-04-04 18:20:24 +02:00
|
|
|
if path.strip().startswith("/"):
|
|
|
|
raise HTTPException(status_code=400, detail=exception_text)
|
2024-03-31 21:18:26 +02:00
|
|
|
# Fix the case of "/" at the beginning on the path
|
|
|
|
if path is None:
|
|
|
|
return path
|
2024-12-19 13:48:57 +01:00
|
|
|
|
2024-03-31 21:18:26 +02:00
|
|
|
# Regular expression to detect patterns like "...." and multiple forward slashes
|
2024-12-19 13:48:57 +01:00
|
|
|
suspicious_patterns = re.compile(r"(\.\.+)|(/+/)")
|
|
|
|
|
2024-03-31 21:18:26 +02:00
|
|
|
if suspicious_patterns.search(path) or Path(path).is_absolute():
|
|
|
|
ASCIIColors.error(error_text)
|
|
|
|
raise HTTPException(status_code=400, detail=exception_text)
|
2024-12-19 13:48:57 +01:00
|
|
|
|
|
|
|
path = path.lstrip("/")
|
2024-03-31 21:18:26 +02:00
|
|
|
return path
|
|
|
|
|
|
|
|
|
|
|
|
def test_sanitize_path_from_endpoint():
|
|
|
|
# Test a valid path
|
|
|
|
valid_path = "example/path"
|
|
|
|
assert sanitize_path_from_endpoint(valid_path) == "example/path"
|
2024-12-19 13:48:57 +01:00
|
|
|
|
2024-03-31 21:18:26 +02:00
|
|
|
# Test a path with suspicious elements
|
2024-04-04 18:20:24 +02:00
|
|
|
suspicious_path = "/D:/POC/secret.txt"
|
2024-12-19 13:48:57 +01:00
|
|
|
|
|
|
|
# suspicious_path = "/images//D:/POC/secret.txt"
|
2024-03-31 21:18:26 +02:00
|
|
|
with pytest.raises(HTTPException):
|
|
|
|
sanitize_path_from_endpoint(suspicious_path)
|
2024-12-19 13:48:57 +01:00
|
|
|
|
2024-03-31 21:18:26 +02:00
|
|
|
# Add more test cases as needed
|
|
|
|
|
2024-12-19 13:48:57 +01:00
|
|
|
|
2024-03-31 21:18:26 +02:00
|
|
|
if __name__ == "__main__":
|
|
|
|
test_sanitize_path_from_endpoint()
|