.oO SearXNG Developer Documentation Oo.
Loading...
Searching...
No Matches
searx.botdetection.trusted_proxies.ProxyFix Class Reference

Public Member Functions

None __init__ (self, WSGIApplication wsgi_app)
list[IPv4Network|IPv6Network] trusted_proxies (self)
str trusted_remote_addr (self, list[IPv4Address|IPv6Address] x_forwarded_for, list[IPv4Network|IPv6Network] trusted_proxies)
abc.Iterable[bytes] __call__ (self, WSGIEnvironment environ, StartResponse start_response)

Public Attributes

 wsgi_app = wsgi_app

Detailed Description

A middleware like the ProxyFix_ class, where the ``x_for`` argument is
replaced by a method that determines the number of trusted proxies via the
``botdetection.trusted_proxies`` setting.

.. sidebar:: :py:obj:`flask.Request.remote_addr`

   SearXNG uses Werkzeug's ProxyFix_ (with it default ``x_for=1``).

The remote IP (:py:obj:`flask.Request.remote_addr`) of the request is taken
from (first match):

- X-Forwarded-For_: If the header is set, the first untrusted IP that comes
  before the IPs that are still part of the ``botdetection.trusted_proxies``
  is used.

- `X-Real-IP <https://github.com/searxng/searxng/issues/1237#issuecomment-1147564516>`__:
  If X-Forwarded-For_ is not set, `X-Real-IP` is used
  (``botdetection.trusted_proxies`` is ignored).

If none of the header is set, the REMOTE_ADDR_ from the WSGI layer is used.
If (for whatever reasons) none IP can be determined, an error message is
displayed and ``100::`` is used instead (:rfc:`6666`).

.. _ProxyFix:
   https://werkzeug.palletsprojects.com/middleware/proxy_fix/

.. _X-Forwarded-For:
   https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For

.. _REMOTE_ADDR:
   https://wsgi.readthedocs.io/en/latest/proposals-2.0.html#making-some-keys-required

Definition at line 22 of file trusted_proxies.py.

Constructor & Destructor Documentation

◆ __init__()

None searx.botdetection.trusted_proxies.ProxyFix.__init__ ( self,
WSGIApplication wsgi_app )

Definition at line 57 of file trusted_proxies.py.

57 def __init__(self, wsgi_app: WSGIApplication) -> None:
58 self.wsgi_app = wsgi_app
59

Member Function Documentation

◆ __call__()

abc.Iterable[bytes] searx.botdetection.trusted_proxies.ProxyFix.__call__ ( self,
WSGIEnvironment environ,
StartResponse start_response )

Definition at line 87 of file trusted_proxies.py.

87 def __call__(self, environ: WSGIEnvironment, start_response: StartResponse) -> abc.Iterable[bytes]:
88 # pylint: disable=too-many-statements
89
90 trusted_proxies = self.trusted_proxies()
91
92 # We do not rely on the REMOTE_ADDR from the WSGI environment / the
93 # variable is first removed from the WSGI environment and explicitly set
94 # in this function!
95
96 orig_remote_addr: str | None = environ.pop("REMOTE_ADDR")
97
98 # Validate the IPs involved in this game and delete all invalid ones
99 # from the WSGI environment.
100
101 if orig_remote_addr:
102 try:
103 addr = ip_address(orig_remote_addr)
104 if addr.version == 6 and addr.ipv4_mapped:
105 addr = addr.ipv4_mapped
106 orig_remote_addr = addr.compressed
107 except ValueError as exc:
108 logger.error("REMOTE_ADDR: %s / discard REMOTE_ADDR from WSGI environment", exc)
109 orig_remote_addr = None
110
111 x_real_ip: str | None = environ.get("HTTP_X_REAL_IP")
112 if x_real_ip:
113 try:
114 addr = ip_address(x_real_ip)
115 if addr.version == 6 and addr.ipv4_mapped:
116 addr = addr.ipv4_mapped
117 x_real_ip = addr.compressed
118 except ValueError as exc:
119 logger.error("X-Real-IP: %s / discard HTTP_X_REAL_IP from WSGI environment", exc)
120 environ.pop("HTTP_X_REAL_IP")
121 x_real_ip = None
122
123 x_forwarded_for: list[IPv4Address | IPv6Address] = []
124 if environ.get("HTTP_X_FORWARDED_FOR"):
125 for x_for_ip in parse_list_header(str(environ.get("HTTP_X_FORWARDED_FOR"))):
126 try:
127 addr = ip_address(x_for_ip)
128 except ValueError as exc:
129 logger.error("X-Forwarded-For: %s / discard HTTP_X_FORWARDED_FOR from WSGI environment", exc)
130 environ.pop("HTTP_X_FORWARDED_FOR")
131 x_forwarded_for = []
132 break
133
134 if addr.version == 6 and addr.ipv4_mapped:
135 addr = addr.ipv4_mapped
136 x_forwarded_for.append(addr)
137
138 # log questionable WSGI environments
139
140 if not x_forwarded_for and not x_real_ip:
141 log_error_only_once("X-Forwarded-For nor X-Real-IP header is set!")
142
143 if x_forwarded_for and not trusted_proxies:
144 log_error_only_once("missing botdetection.trusted_proxies config")
145 # without trusted_proxies, this variable is useless for determining
146 # the real IP
147 x_forwarded_for = []
148
149 # securing the WSGI environment variables that are adjusted
150
151 environ.update({"botdetection.trusted_proxies.orig": {"REMOTE_ADDR": orig_remote_addr}})
152
153 # determine *the real IP*
154
155 if x_forwarded_for:
156 environ["REMOTE_ADDR"] = self.trusted_remote_addr(x_forwarded_for, trusted_proxies)
157
158 elif x_real_ip:
159 environ["REMOTE_ADDR"] = x_real_ip
160
161 elif orig_remote_addr:
162 environ["REMOTE_ADDR"] = orig_remote_addr
163
164 else:
165 logger.error("No remote IP could be determined, use black-hole address: 100::")
166 environ["REMOTE_ADDR"] = "100::"
167
168 try:
169 _ = ip_address(environ["REMOTE_ADDR"])
170 except ValueError as exc:
171 logger.error("REMOTE_ADDR: %s, use black-hole address: 100::", exc)
172 environ["REMOTE_ADDR"] = "100::"
173
174 logger.debug("final REMOTE_ADDR is: %s", environ["REMOTE_ADDR"])
175 return self.wsgi_app(environ, start_response)

References trusted_proxies(), trusted_remote_addr(), and wsgi_app.

Here is the call graph for this function:

◆ trusted_proxies()

list[IPv4Network | IPv6Network] searx.botdetection.trusted_proxies.ProxyFix.trusted_proxies ( self)

Definition at line 60 of file trusted_proxies.py.

60 def trusted_proxies(self) -> list[IPv4Network | IPv6Network]:
61 cfg = config.get_global_cfg()
62 proxy_list: list[str] = cfg.get("botdetection.trusted_proxies", default=[])
63 return [ip_network(net, strict=False) for net in proxy_list]
64

Referenced by __call__().

Here is the caller graph for this function:

◆ trusted_remote_addr()

str searx.botdetection.trusted_proxies.ProxyFix.trusted_remote_addr ( self,
list[IPv4Address | IPv6Address] x_forwarded_for,
list[IPv4Network | IPv6Network] trusted_proxies )

Definition at line 65 of file trusted_proxies.py.

69 ) -> str:
70 # always rtl
71 for addr in reversed(x_forwarded_for):
72 trust: bool = False
73
74 for net in trusted_proxies:
75 if addr.version == net.version and addr in net:
76 logger.debug("trust proxy %s (member of %s)", addr, net)
77 trust = True
78 break
79
80 # client address
81 if not trust:
82 return addr.compressed
83
84 # fallback to first address
85 return x_forwarded_for[0].compressed
86

Referenced by __call__().

Here is the caller graph for this function:

Member Data Documentation

◆ wsgi_app

searx.botdetection.trusted_proxies.ProxyFix.wsgi_app = wsgi_app

Definition at line 58 of file trusted_proxies.py.

Referenced by __call__(), and searx.flaskfix.ReverseProxyPathFix.__call__().


The documentation for this class was generated from the following file: