proxy_fix.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. """
  2. X-Forwarded-For Proxy Fix
  3. =========================
  4. This module provides a middleware that adjusts the WSGI environ based on
  5. ``X-Forwarded-`` headers that proxies in front of an application may
  6. set.
  7. When an application is running behind a proxy server, WSGI may see the
  8. request as coming from that server rather than the real client. Proxies
  9. set various headers to track where the request actually came from.
  10. This middleware should only be applied if the application is actually
  11. behind such a proxy, and should be configured with the number of proxies
  12. that are chained in front of it. Not all proxies set all the headers.
  13. Since incoming headers can be faked, you must set how many proxies are
  14. setting each header so the middleware knows what to trust.
  15. .. autoclass:: ProxyFix
  16. :copyright: 2007 Pallets
  17. :license: BSD-3-Clause
  18. """
  19. from werkzeug.http import parse_list_header
  20. class ProxyFix(object):
  21. """Adjust the WSGI environ based on ``X-Forwarded-`` that proxies in
  22. front of the application may set.
  23. - ``X-Forwarded-For`` sets ``REMOTE_ADDR``.
  24. - ``X-Forwarded-Proto`` sets ``wsgi.url_scheme``.
  25. - ``X-Forwarded-Host`` sets ``HTTP_HOST``, ``SERVER_NAME``, and
  26. ``SERVER_PORT``.
  27. - ``X-Forwarded-Port`` sets ``HTTP_HOST`` and ``SERVER_PORT``.
  28. - ``X-Forwarded-Prefix`` sets ``SCRIPT_NAME``.
  29. You must tell the middleware how many proxies set each header so it
  30. knows what values to trust. It is a security issue to trust values
  31. that came from the client rather than a proxy.
  32. The original values of the headers are stored in the WSGI
  33. environ as ``werkzeug.proxy_fix.orig``, a dict.
  34. :param app: The WSGI application to wrap.
  35. :param x_for: Number of values to trust for ``X-Forwarded-For``.
  36. :param x_proto: Number of values to trust for ``X-Forwarded-Proto``.
  37. :param x_host: Number of values to trust for ``X-Forwarded-Host``.
  38. :param x_port: Number of values to trust for ``X-Forwarded-Port``.
  39. :param x_prefix: Number of values to trust for
  40. ``X-Forwarded-Prefix``.
  41. .. code-block:: python
  42. from werkzeug.middleware.proxy_fix import ProxyFix
  43. # App is behind one proxy that sets the -For and -Host headers.
  44. app = ProxyFix(app, x_for=1, x_host=1)
  45. .. versionchanged:: 1.0
  46. Deprecated code has been removed:
  47. * The ``num_proxies`` argument and attribute.
  48. * The ``get_remote_addr`` method.
  49. * The environ keys ``orig_remote_addr``,
  50. ``orig_wsgi_url_scheme``, and ``orig_http_host``.
  51. .. versionchanged:: 0.15
  52. All headers support multiple values. The ``num_proxies``
  53. argument is deprecated. Each header is configured with a
  54. separate number of trusted proxies.
  55. .. versionchanged:: 0.15
  56. Original WSGI environ values are stored in the
  57. ``werkzeug.proxy_fix.orig`` dict. ``orig_remote_addr``,
  58. ``orig_wsgi_url_scheme``, and ``orig_http_host`` are deprecated
  59. and will be removed in 1.0.
  60. .. versionchanged:: 0.15
  61. Support ``X-Forwarded-Port`` and ``X-Forwarded-Prefix``.
  62. .. versionchanged:: 0.15
  63. ``X-Forwarded-Host`` and ``X-Forwarded-Port`` modify
  64. ``SERVER_NAME`` and ``SERVER_PORT``.
  65. """
  66. def __init__(self, app, x_for=1, x_proto=1, x_host=0, x_port=0, x_prefix=0):
  67. self.app = app
  68. self.x_for = x_for
  69. self.x_proto = x_proto
  70. self.x_host = x_host
  71. self.x_port = x_port
  72. self.x_prefix = x_prefix
  73. def _get_real_value(self, trusted, value):
  74. """Get the real value from a list header based on the configured
  75. number of trusted proxies.
  76. :param trusted: Number of values to trust in the header.
  77. :param value: Comma separated list header value to parse.
  78. :return: The real value, or ``None`` if there are fewer values
  79. than the number of trusted proxies.
  80. .. versionchanged:: 1.0
  81. Renamed from ``_get_trusted_comma``.
  82. .. versionadded:: 0.15
  83. """
  84. if not (trusted and value):
  85. return
  86. values = parse_list_header(value)
  87. if len(values) >= trusted:
  88. return values[-trusted]
  89. def __call__(self, environ, start_response):
  90. """Modify the WSGI environ based on the various ``Forwarded``
  91. headers before calling the wrapped application. Store the
  92. original environ values in ``werkzeug.proxy_fix.orig_{key}``.
  93. """
  94. environ_get = environ.get
  95. orig_remote_addr = environ_get("REMOTE_ADDR")
  96. orig_wsgi_url_scheme = environ_get("wsgi.url_scheme")
  97. orig_http_host = environ_get("HTTP_HOST")
  98. environ.update(
  99. {
  100. "werkzeug.proxy_fix.orig": {
  101. "REMOTE_ADDR": orig_remote_addr,
  102. "wsgi.url_scheme": orig_wsgi_url_scheme,
  103. "HTTP_HOST": orig_http_host,
  104. "SERVER_NAME": environ_get("SERVER_NAME"),
  105. "SERVER_PORT": environ_get("SERVER_PORT"),
  106. "SCRIPT_NAME": environ_get("SCRIPT_NAME"),
  107. }
  108. }
  109. )
  110. x_for = self._get_real_value(self.x_for, environ_get("HTTP_X_FORWARDED_FOR"))
  111. if x_for:
  112. environ["REMOTE_ADDR"] = x_for
  113. x_proto = self._get_real_value(
  114. self.x_proto, environ_get("HTTP_X_FORWARDED_PROTO")
  115. )
  116. if x_proto:
  117. environ["wsgi.url_scheme"] = x_proto
  118. x_host = self._get_real_value(self.x_host, environ_get("HTTP_X_FORWARDED_HOST"))
  119. if x_host:
  120. environ["HTTP_HOST"] = x_host
  121. parts = x_host.split(":", 1)
  122. environ["SERVER_NAME"] = parts[0]
  123. if len(parts) == 2:
  124. environ["SERVER_PORT"] = parts[1]
  125. x_port = self._get_real_value(self.x_port, environ_get("HTTP_X_FORWARDED_PORT"))
  126. if x_port:
  127. host = environ.get("HTTP_HOST")
  128. if host:
  129. parts = host.split(":", 1)
  130. host = parts[0] if len(parts) == 2 else host
  131. environ["HTTP_HOST"] = "%s:%s" % (host, x_port)
  132. environ["SERVER_PORT"] = x_port
  133. x_prefix = self._get_real_value(
  134. self.x_prefix, environ_get("HTTP_X_FORWARDED_PREFIX")
  135. )
  136. if x_prefix:
  137. environ["SCRIPT_NAME"] = x_prefix
  138. return self.app(environ, start_response)