limiter.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. """.. _limiter src:
  4. Limiter
  5. =======
  6. .. sidebar:: info
  7. The limiter requires a :ref:`Redis <settings redis>` database.
  8. Bot protection / IP rate limitation. The intention of rate limitation is to
  9. limit suspicious requests from an IP. The motivation behind this is the fact
  10. that SearXNG passes through requests from bots and is thus classified as a bot
  11. itself. As a result, the SearXNG engine then receives a CAPTCHA or is blocked
  12. by the search engine (the origin) in some other way.
  13. To avoid blocking, the requests from bots to SearXNG must also be blocked, this
  14. is the task of the limiter. To perform this task, the limiter uses the methods
  15. from the :py:obj:`searx.botdetection`.
  16. To enable the limiter activate:
  17. .. code:: yaml
  18. server:
  19. ...
  20. limiter: true # rate limit the number of request on the instance, block some bots
  21. and set the redis-url connection. Check the value, it depends on your redis DB
  22. (see :ref:`settings redis`), by example:
  23. .. code:: yaml
  24. redis:
  25. url: unix:///usr/local/searxng-redis/run/redis.sock?db=0
  26. """
  27. from __future__ import annotations
  28. from pathlib import Path
  29. from ipaddress import ip_address
  30. import flask
  31. import werkzeug
  32. from searx.tools import config
  33. from searx import logger
  34. from . import (
  35. http_accept,
  36. http_accept_encoding,
  37. http_accept_language,
  38. http_connection,
  39. http_user_agent,
  40. ip_limit,
  41. ip_lists,
  42. )
  43. from ._helpers import (
  44. get_network,
  45. get_real_ip,
  46. dump_request,
  47. )
  48. logger = logger.getChild('botdetection.limiter')
  49. CFG: config.Config = None # type: ignore
  50. LIMITER_CFG_SCHEMA = Path(__file__).parent / "limiter.toml"
  51. """Base configuration (schema) of the botdetection."""
  52. LIMITER_CFG = Path('/etc/searxng/limiter.toml')
  53. """Lokal Limiter configuration."""
  54. CFG_DEPRECATED = {
  55. # "dummy.old.foo": "config 'dummy.old.foo' exists only for tests. Don't use it in your real project config."
  56. }
  57. def get_cfg() -> config.Config:
  58. global CFG # pylint: disable=global-statement
  59. if CFG is None:
  60. CFG = config.Config.from_toml(LIMITER_CFG_SCHEMA, LIMITER_CFG, CFG_DEPRECATED)
  61. return CFG
  62. def filter_request(request: flask.Request) -> werkzeug.Response | None:
  63. # pylint: disable=too-many-return-statements
  64. cfg = get_cfg()
  65. real_ip = ip_address(get_real_ip(request))
  66. network = get_network(real_ip, cfg)
  67. if request.path == '/healthz':
  68. return None
  69. # link-local
  70. if network.is_link_local:
  71. return None
  72. # block- & pass- lists
  73. #
  74. # 1. The IP of the request is first checked against the pass-list; if the IP
  75. # matches an entry in the list, the request is not blocked.
  76. # 2. If no matching entry is found in the pass-list, then a check is made against
  77. # the block list; if the IP matches an entry in the list, the request is
  78. # blocked.
  79. # 3. If the IP is not in either list, the request is not blocked.
  80. match, msg = ip_lists.pass_ip(real_ip, cfg)
  81. if match:
  82. logger.warning("PASS %s: matched PASSLIST - %s", network.compressed, msg)
  83. return None
  84. match, msg = ip_lists.block_ip(real_ip, cfg)
  85. if match:
  86. logger.error("BLOCK %s: matched BLOCKLIST - %s", network.compressed, msg)
  87. return flask.make_response(('IP is on BLOCKLIST - %s' % msg, 429))
  88. # methods applied on /
  89. for func in [
  90. http_user_agent,
  91. ]:
  92. val = func.filter_request(network, request, cfg)
  93. if val is not None:
  94. return val
  95. # methods applied on /search
  96. if request.path == '/search':
  97. for func in [
  98. http_accept,
  99. http_accept_encoding,
  100. http_accept_language,
  101. http_connection,
  102. http_user_agent,
  103. ip_limit,
  104. ]:
  105. val = func.filter_request(network, request, cfg)
  106. if val is not None:
  107. return val
  108. logger.debug(f"OK {network}: %s", dump_request(flask.request))
  109. return None