_helpers.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # pylint: disable=missing-module-docstring, invalid-name
  3. from __future__ import annotations
  4. from ipaddress import (
  5. IPv4Network,
  6. IPv6Network,
  7. IPv4Address,
  8. IPv6Address,
  9. ip_network,
  10. )
  11. import flask
  12. import werkzeug
  13. from searx import logger
  14. from searx.extended_types import SXNG_Request
  15. from . import config
  16. logger = logger.getChild('botdetection')
  17. def dump_request(request: SXNG_Request):
  18. return (
  19. request.path
  20. + " || X-Forwarded-For: %s" % request.headers.get('X-Forwarded-For')
  21. + " || X-Real-IP: %s" % request.headers.get('X-Real-IP')
  22. + " || form: %s" % request.form
  23. + " || Accept: %s" % request.headers.get('Accept')
  24. + " || Accept-Language: %s" % request.headers.get('Accept-Language')
  25. + " || Accept-Encoding: %s" % request.headers.get('Accept-Encoding')
  26. + " || Content-Type: %s" % request.headers.get('Content-Type')
  27. + " || Content-Length: %s" % request.headers.get('Content-Length')
  28. + " || Connection: %s" % request.headers.get('Connection')
  29. + " || User-Agent: %s" % request.headers.get('User-Agent')
  30. )
  31. def too_many_requests(network: IPv4Network | IPv6Network, log_msg: str) -> werkzeug.Response | None:
  32. """Returns a HTTP 429 response object and writes a ERROR message to the
  33. 'botdetection' logger. This function is used in part by the filter methods
  34. to return the default ``Too Many Requests`` response.
  35. """
  36. logger.debug("BLOCK %s: %s", network.compressed, log_msg)
  37. return flask.make_response(('Too Many Requests', 429))
  38. def get_network(real_ip: IPv4Address | IPv6Address, cfg: config.Config) -> IPv4Network | IPv6Network:
  39. """Returns the (client) network of whether the real_ip is part of."""
  40. if real_ip.version == 6:
  41. prefix = cfg['real_ip.ipv6_prefix']
  42. else:
  43. prefix = cfg['real_ip.ipv4_prefix']
  44. network = ip_network(f"{real_ip}/{prefix}", strict=False)
  45. # logger.debug("get_network(): %s", network.compressed)
  46. return network
  47. _logged_errors = []
  48. def _log_error_only_once(err_msg):
  49. if err_msg not in _logged_errors:
  50. logger.error(err_msg)
  51. _logged_errors.append(err_msg)
  52. def get_real_ip(request: SXNG_Request) -> str:
  53. """Returns real IP of the request. Since not all proxies set all the HTTP
  54. headers and incoming headers can be faked it may happen that the IP cannot
  55. be determined correctly.
  56. .. sidebar:: :py:obj:`flask.Request.remote_addr`
  57. SearXNG uses Werkzeug's ProxyFix_ (with it default ``x_for=1``).
  58. This function tries to get the remote IP in the order listed below,
  59. additional some tests are done and if inconsistencies or errors are
  60. detected, they are logged.
  61. The remote IP of the request is taken from (first match):
  62. - X-Forwarded-For_ header
  63. - `X-real-IP header <https://github.com/searxng/searxng/issues/1237#issuecomment-1147564516>`__
  64. - :py:obj:`flask.Request.remote_addr`
  65. .. _ProxyFix:
  66. https://werkzeug.palletsprojects.com/middleware/proxy_fix/
  67. .. _X-Forwarded-For:
  68. https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For
  69. """
  70. forwarded_for = request.headers.get("X-Forwarded-For")
  71. real_ip = request.headers.get('X-Real-IP')
  72. remote_addr = request.remote_addr
  73. # logger.debug(
  74. # "X-Forwarded-For: %s || X-Real-IP: %s || request.remote_addr: %s", forwarded_for, real_ip, remote_addr
  75. # )
  76. if not forwarded_for:
  77. _log_error_only_once("X-Forwarded-For header is not set!")
  78. else:
  79. from . import cfg # pylint: disable=import-outside-toplevel, cyclic-import
  80. forwarded_for = [x.strip() for x in forwarded_for.split(',')]
  81. x_for: int = cfg['real_ip.x_for'] # type: ignore
  82. forwarded_for = forwarded_for[-min(len(forwarded_for), x_for)]
  83. if not real_ip:
  84. _log_error_only_once("X-Real-IP header is not set!")
  85. if forwarded_for and real_ip and forwarded_for != real_ip:
  86. logger.warning("IP from X-Real-IP (%s) is not equal to IP from X-Forwarded-For (%s)", real_ip, forwarded_for)
  87. if forwarded_for and remote_addr and forwarded_for != remote_addr:
  88. logger.warning(
  89. "IP from WSGI environment (%s) is not equal to IP from X-Forwarded-For (%s)", remote_addr, forwarded_for
  90. )
  91. if real_ip and remote_addr and real_ip != remote_addr:
  92. logger.warning("IP from WSGI environment (%s) is not equal to IP from X-Real-IP (%s)", remote_addr, real_ip)
  93. request_ip = forwarded_for or real_ip or remote_addr or '0.0.0.0'
  94. # logger.debug("get_real_ip() -> %s", request_ip)
  95. return request_ip