ssrf_proxy.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. """
  2. Proxy requests to avoid SSRF
  3. """
  4. import logging
  5. import os
  6. import time
  7. import httpx
  8. SSRF_PROXY_ALL_URL = os.getenv("SSRF_PROXY_ALL_URL", "")
  9. SSRF_PROXY_HTTP_URL = os.getenv("SSRF_PROXY_HTTP_URL", "")
  10. SSRF_PROXY_HTTPS_URL = os.getenv("SSRF_PROXY_HTTPS_URL", "")
  11. SSRF_DEFAULT_MAX_RETRIES = int(os.getenv("SSRF_DEFAULT_MAX_RETRIES", "3"))
  12. proxies = (
  13. {"http://": SSRF_PROXY_HTTP_URL, "https://": SSRF_PROXY_HTTPS_URL}
  14. if SSRF_PROXY_HTTP_URL and SSRF_PROXY_HTTPS_URL
  15. else None
  16. )
  17. BACKOFF_FACTOR = 0.5
  18. STATUS_FORCELIST = [429, 500, 502, 503, 504]
  19. def make_request(method, url, max_retries=SSRF_DEFAULT_MAX_RETRIES, **kwargs):
  20. if "allow_redirects" in kwargs:
  21. allow_redirects = kwargs.pop("allow_redirects")
  22. if "follow_redirects" not in kwargs:
  23. kwargs["follow_redirects"] = allow_redirects
  24. retries = 0
  25. while retries <= max_retries:
  26. try:
  27. if SSRF_PROXY_ALL_URL:
  28. response = httpx.request(method=method, url=url, proxy=SSRF_PROXY_ALL_URL, **kwargs)
  29. elif proxies:
  30. response = httpx.request(method=method, url=url, proxies=proxies, **kwargs)
  31. else:
  32. response = httpx.request(method=method, url=url, **kwargs)
  33. if response.status_code not in STATUS_FORCELIST:
  34. return response
  35. else:
  36. logging.warning(f"Received status code {response.status_code} for URL {url} which is in the force list")
  37. except httpx.RequestError as e:
  38. logging.warning(f"Request to URL {url} failed on attempt {retries + 1}: {e}")
  39. retries += 1
  40. if retries <= max_retries:
  41. time.sleep(BACKOFF_FACTOR * (2 ** (retries - 1)))
  42. raise Exception(f"Reached maximum retries ({max_retries}) for URL {url}")
  43. def get(url, max_retries=SSRF_DEFAULT_MAX_RETRIES, **kwargs):
  44. return make_request("GET", url, max_retries=max_retries, **kwargs)
  45. def post(url, max_retries=SSRF_DEFAULT_MAX_RETRIES, **kwargs):
  46. return make_request("POST", url, max_retries=max_retries, **kwargs)
  47. def put(url, max_retries=SSRF_DEFAULT_MAX_RETRIES, **kwargs):
  48. return make_request("PUT", url, max_retries=max_retries, **kwargs)
  49. def patch(url, max_retries=SSRF_DEFAULT_MAX_RETRIES, **kwargs):
  50. return make_request("PATCH", url, max_retries=max_retries, **kwargs)
  51. def delete(url, max_retries=SSRF_DEFAULT_MAX_RETRIES, **kwargs):
  52. return make_request("DELETE", url, max_retries=max_retries, **kwargs)
  53. def head(url, max_retries=SSRF_DEFAULT_MAX_RETRIES, **kwargs):
  54. return make_request("HEAD", url, max_retries=max_retries, **kwargs)