proxy_fix.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  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 used 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 __future__ import annotations
  20. import typing as t
  21. from ..http import parse_list_header
  22. if t.TYPE_CHECKING:
  23. from _typeshed.wsgi import StartResponse
  24. from _typeshed.wsgi import WSGIApplication
  25. from _typeshed.wsgi import WSGIEnvironment
  26. class ProxyFix:
  27. """Adjust the WSGI environ based on ``X-Forwarded-`` that proxies in
  28. front of the application may set.
  29. - ``X-Forwarded-For`` sets ``REMOTE_ADDR``.
  30. - ``X-Forwarded-Proto`` sets ``wsgi.url_scheme``.
  31. - ``X-Forwarded-Host`` sets ``HTTP_HOST``, ``SERVER_NAME``, and
  32. ``SERVER_PORT``.
  33. - ``X-Forwarded-Port`` sets ``HTTP_HOST`` and ``SERVER_PORT``.
  34. - ``X-Forwarded-Prefix`` sets ``SCRIPT_NAME``.
  35. You must tell the middleware how many proxies set each header so it
  36. knows what values to trust. It is a security issue to trust values
  37. that came from the client rather than a proxy.
  38. The original values of the headers are stored in the WSGI
  39. environ as ``werkzeug.proxy_fix.orig``, a dict.
  40. :param app: The WSGI application to wrap.
  41. :param x_for: Number of values to trust for ``X-Forwarded-For``.
  42. :param x_proto: Number of values to trust for ``X-Forwarded-Proto``.
  43. :param x_host: Number of values to trust for ``X-Forwarded-Host``.
  44. :param x_port: Number of values to trust for ``X-Forwarded-Port``.
  45. :param x_prefix: Number of values to trust for
  46. ``X-Forwarded-Prefix``.
  47. .. code-block:: python
  48. from werkzeug.middleware.proxy_fix import ProxyFix
  49. # App is behind one proxy that sets the -For and -Host headers.
  50. app = ProxyFix(app, x_for=1, x_host=1)
  51. .. versionchanged:: 1.0
  52. The ``num_proxies`` argument and attribute; the ``get_remote_addr`` method; and
  53. the environ keys ``orig_remote_addr``, ``orig_wsgi_url_scheme``, and
  54. ``orig_http_host`` were removed.
  55. .. versionchanged:: 0.15
  56. All headers support multiple values. Each header is configured with a separate
  57. number of trusted proxies.
  58. .. versionchanged:: 0.15
  59. Original WSGI environ values are stored in the ``werkzeug.proxy_fix.orig`` dict.
  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__(
  67. self,
  68. app: WSGIApplication,
  69. x_for: int = 1,
  70. x_proto: int = 1,
  71. x_host: int = 0,
  72. x_port: int = 0,
  73. x_prefix: int = 0,
  74. ) -> None:
  75. self.app = app
  76. self.x_for = x_for
  77. self.x_proto = x_proto
  78. self.x_host = x_host
  79. self.x_port = x_port
  80. self.x_prefix = x_prefix
  81. def _get_real_value(self, trusted: int, value: str | None) -> str | None:
  82. """Get the real value from a list header based on the configured
  83. number of trusted proxies.
  84. :param trusted: Number of values to trust in the header.
  85. :param value: Comma separated list header value to parse.
  86. :return: The real value, or ``None`` if there are fewer values
  87. than the number of trusted proxies.
  88. .. versionchanged:: 1.0
  89. Renamed from ``_get_trusted_comma``.
  90. .. versionadded:: 0.15
  91. """
  92. if not (trusted and value):
  93. return None
  94. values = parse_list_header(value)
  95. if len(values) >= trusted:
  96. return values[-trusted]
  97. return None
  98. def __call__(
  99. self, environ: WSGIEnvironment, start_response: StartResponse
  100. ) -> t.Iterable[bytes]:
  101. """Modify the WSGI environ based on the various ``Forwarded``
  102. headers before calling the wrapped application. Store the
  103. original environ values in ``werkzeug.proxy_fix.orig_{key}``.
  104. """
  105. environ_get = environ.get
  106. orig_remote_addr = environ_get("REMOTE_ADDR")
  107. orig_wsgi_url_scheme = environ_get("wsgi.url_scheme")
  108. orig_http_host = environ_get("HTTP_HOST")
  109. environ.update(
  110. {
  111. "werkzeug.proxy_fix.orig": {
  112. "REMOTE_ADDR": orig_remote_addr,
  113. "wsgi.url_scheme": orig_wsgi_url_scheme,
  114. "HTTP_HOST": orig_http_host,
  115. "SERVER_NAME": environ_get("SERVER_NAME"),
  116. "SERVER_PORT": environ_get("SERVER_PORT"),
  117. "SCRIPT_NAME": environ_get("SCRIPT_NAME"),
  118. }
  119. }
  120. )
  121. x_for = self._get_real_value(self.x_for, environ_get("HTTP_X_FORWARDED_FOR"))
  122. if x_for:
  123. environ["REMOTE_ADDR"] = x_for
  124. x_proto = self._get_real_value(
  125. self.x_proto, environ_get("HTTP_X_FORWARDED_PROTO")
  126. )
  127. if x_proto:
  128. environ["wsgi.url_scheme"] = x_proto
  129. x_host = self._get_real_value(self.x_host, environ_get("HTTP_X_FORWARDED_HOST"))
  130. if x_host:
  131. environ["HTTP_HOST"] = environ["SERVER_NAME"] = x_host
  132. # "]" to check for IPv6 address without port
  133. if ":" in x_host and not x_host.endswith("]"):
  134. environ["SERVER_NAME"], environ["SERVER_PORT"] = x_host.rsplit(":", 1)
  135. x_port = self._get_real_value(self.x_port, environ_get("HTTP_X_FORWARDED_PORT"))
  136. if x_port:
  137. host = environ.get("HTTP_HOST")
  138. if host:
  139. # "]" to check for IPv6 address without port
  140. if ":" in host and not host.endswith("]"):
  141. host = host.rsplit(":", 1)[0]
  142. environ["HTTP_HOST"] = f"{host}:{x_port}"
  143. environ["SERVER_PORT"] = x_port
  144. x_prefix = self._get_real_value(
  145. self.x_prefix, environ_get("HTTP_X_FORWARDED_PREFIX")
  146. )
  147. if x_prefix:
  148. environ["SCRIPT_NAME"] = x_prefix
  149. return self.app(environ, start_response)