ssrf_proxy.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. """
  2. Proxy requests to avoid SSRF
  3. """
  4. import os
  5. from httpx import get as _get
  6. from httpx import head as _head
  7. from httpx import options as _options
  8. from httpx import patch as _patch
  9. from httpx import post as _post
  10. from httpx import put as _put
  11. from requests import delete as _delete
  12. SSRF_PROXY_HTTP_URL = os.getenv('SSRF_PROXY_HTTP_URL', '')
  13. SSRF_PROXY_HTTPS_URL = os.getenv('SSRF_PROXY_HTTPS_URL', '')
  14. requests_proxies = {
  15. 'http': SSRF_PROXY_HTTP_URL,
  16. 'https': SSRF_PROXY_HTTPS_URL
  17. } if SSRF_PROXY_HTTP_URL and SSRF_PROXY_HTTPS_URL else None
  18. httpx_proxies = {
  19. 'http://': SSRF_PROXY_HTTP_URL,
  20. 'https://': SSRF_PROXY_HTTPS_URL
  21. } if SSRF_PROXY_HTTP_URL and SSRF_PROXY_HTTPS_URL else None
  22. def get(url, *args, **kwargs):
  23. return _get(url=url, *args, proxies=httpx_proxies, **kwargs)
  24. def post(url, *args, **kwargs):
  25. return _post(url=url, *args, proxies=httpx_proxies, **kwargs)
  26. def put(url, *args, **kwargs):
  27. return _put(url=url, *args, proxies=httpx_proxies, **kwargs)
  28. def patch(url, *args, **kwargs):
  29. return _patch(url=url, *args, proxies=httpx_proxies, **kwargs)
  30. def delete(url, *args, **kwargs):
  31. if 'follow_redirects' in kwargs:
  32. if kwargs['follow_redirects']:
  33. kwargs['allow_redirects'] = kwargs['follow_redirects']
  34. kwargs.pop('follow_redirects')
  35. if 'timeout' in kwargs:
  36. timeout = kwargs['timeout']
  37. if timeout is None:
  38. kwargs.pop('timeout')
  39. elif isinstance(timeout, tuple):
  40. # check length of tuple
  41. if len(timeout) == 2:
  42. kwargs['timeout'] = timeout
  43. elif len(timeout) == 1:
  44. kwargs['timeout'] = timeout[0]
  45. elif len(timeout) > 2:
  46. kwargs['timeout'] = (timeout[0], timeout[1])
  47. else:
  48. kwargs['timeout'] = (timeout, timeout)
  49. return _delete(url=url, *args, proxies=requests_proxies, **kwargs)
  50. def head(url, *args, **kwargs):
  51. return _head(url=url, *args, proxies=httpx_proxies, **kwargs)
  52. def options(url, *args, **kwargs):
  53. return _options(url=url, *args, proxies=httpx_proxies, **kwargs)