limiter.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """Bot protection / IP rate limitation. The intention of rate limitation is to
  3. limit suspicious requests from an IP. The motivation behind this is the fact
  4. that SearXNG passes through requests from bots and is thus classified as a bot
  5. itself. As a result, the SearXNG engine then receives a CAPTCHA or is blocked
  6. by the search engine (the origin) in some other way.
  7. To avoid blocking, the requests from bots to SearXNG must also be blocked, this
  8. is the task of the limiter. To perform this task, the limiter uses the methods
  9. from the :ref:`botdetection`:
  10. - Analysis of the HTTP header in the request / :ref:`botdetection probe headers`
  11. can be easily bypassed.
  12. - Block and pass lists in which IPs are listed / :ref:`botdetection ip_lists`
  13. are hard to maintain, since the IPs of bots are not all known and change over
  14. the time.
  15. - Detection & dynamically :ref:`botdetection rate limit` of bots based on the
  16. behavior of the requests. For dynamically changeable IP lists a Redis
  17. database is needed.
  18. The prerequisite for IP based methods is the correct determination of the IP of
  19. the client. The IP of the client is determined via the X-Forwarded-For_ HTTP
  20. header.
  21. .. attention::
  22. A correct setup of the HTTP request headers ``X-Forwarded-For`` and
  23. ``X-Real-IP`` is essential to be able to assign a request to an IP correctly:
  24. - `NGINX RequestHeader`_
  25. - `Apache RequestHeader`_
  26. .. _X-Forwarded-For:
  27. https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For
  28. .. _NGINX RequestHeader:
  29. https://docs.searxng.org/admin/installation-nginx.html#nginx-s-searxng-site
  30. .. _Apache RequestHeader:
  31. https://docs.searxng.org/admin/installation-apache.html#apache-s-searxng-site
  32. Enable Limiter
  33. ==============
  34. To enable the limiter activate:
  35. .. code:: yaml
  36. server:
  37. ...
  38. limiter: true # rate limit the number of request on the instance, block some bots
  39. and set the redis-url connection. Check the value, it depends on your redis DB
  40. (see :ref:`settings redis`), by example:
  41. .. code:: yaml
  42. redis:
  43. url: unix:///usr/local/searxng-redis/run/redis.sock?db=0
  44. Configure Limiter
  45. =================
  46. The methods of :ref:`botdetection` the limiter uses are configured in a local
  47. file ``/etc/searxng/limiter.toml``. The defaults are shown in limiter.toml_ /
  48. Don't copy all values to your local configuration, just enable what you need by
  49. overwriting the defaults. For instance to activate the ``link_token`` method in
  50. the :ref:`botdetection.ip_limit` you only need to set this option to ``true``:
  51. .. code:: toml
  52. [botdetection.ip_limit]
  53. link_token = true
  54. .. _limiter.toml:
  55. ``limiter.toml``
  56. ================
  57. In this file the limiter finds the configuration of the :ref:`botdetection`:
  58. - :ref:`botdetection ip_lists`
  59. - :ref:`botdetection rate limit`
  60. - :ref:`botdetection probe headers`
  61. .. kernel-include:: $SOURCEDIR/limiter.toml
  62. :code: toml
  63. Implementation
  64. ==============
  65. """
  66. from __future__ import annotations
  67. import sys
  68. from pathlib import Path
  69. from ipaddress import ip_address
  70. import flask
  71. import werkzeug
  72. from searx import (
  73. logger,
  74. redisdb,
  75. )
  76. from searx import botdetection
  77. from searx.extended_types import SXNG_Request, sxng_request
  78. from searx.botdetection import (
  79. config,
  80. http_accept,
  81. http_accept_encoding,
  82. http_accept_language,
  83. http_user_agent,
  84. http_sec_fetch,
  85. ip_limit,
  86. ip_lists,
  87. get_network,
  88. get_real_ip,
  89. dump_request,
  90. )
  91. # the configuration are limiter.toml and "limiter" in settings.yml so, for
  92. # coherency, the logger is "limiter"
  93. logger = logger.getChild('limiter')
  94. CFG: config.Config = None # type: ignore
  95. _INSTALLED = False
  96. LIMITER_CFG_SCHEMA = Path(__file__).parent / "limiter.toml"
  97. """Base configuration (schema) of the botdetection."""
  98. CFG_DEPRECATED = {
  99. # "dummy.old.foo": "config 'dummy.old.foo' exists only for tests. Don't use it in your real project config."
  100. }
  101. def get_cfg() -> config.Config:
  102. global CFG # pylint: disable=global-statement
  103. if CFG is None:
  104. from . import settings_loader # pylint: disable=import-outside-toplevel
  105. cfg_file = (settings_loader.get_user_cfg_folder() or Path("/etc/searxng")) / "limiter.toml"
  106. CFG = config.Config.from_toml(LIMITER_CFG_SCHEMA, cfg_file, CFG_DEPRECATED)
  107. return CFG
  108. def filter_request(request: SXNG_Request) -> werkzeug.Response | None:
  109. # pylint: disable=too-many-return-statements
  110. cfg = get_cfg()
  111. real_ip = ip_address(get_real_ip(request))
  112. network = get_network(real_ip, cfg)
  113. if request.path == '/healthz':
  114. return None
  115. # link-local
  116. if network.is_link_local:
  117. return None
  118. # block- & pass- lists
  119. #
  120. # 1. The IP of the request is first checked against the pass-list; if the IP
  121. # matches an entry in the list, the request is not blocked.
  122. # 2. If no matching entry is found in the pass-list, then a check is made against
  123. # the block list; if the IP matches an entry in the list, the request is
  124. # blocked.
  125. # 3. If the IP is not in either list, the request is not blocked.
  126. match, msg = ip_lists.pass_ip(real_ip, cfg)
  127. if match:
  128. logger.warning("PASS %s: matched PASSLIST - %s", network.compressed, msg)
  129. return None
  130. match, msg = ip_lists.block_ip(real_ip, cfg)
  131. if match:
  132. logger.error("BLOCK %s: matched BLOCKLIST - %s", network.compressed, msg)
  133. return flask.make_response(('IP is on BLOCKLIST - %s' % msg, 429))
  134. # methods applied on all requests
  135. for func in [
  136. http_user_agent,
  137. ]:
  138. val = func.filter_request(network, request, cfg)
  139. if val is not None:
  140. logger.debug(f"NOT OK ({func.__name__}): {network}: %s", dump_request(sxng_request))
  141. return val
  142. # methods applied on /search requests
  143. if request.path == '/search':
  144. for func in [
  145. http_accept,
  146. http_accept_encoding,
  147. http_accept_language,
  148. http_user_agent,
  149. http_sec_fetch,
  150. ip_limit,
  151. ]:
  152. val = func.filter_request(network, request, cfg)
  153. if val is not None:
  154. logger.debug(f"NOT OK ({func.__name__}): {network}: %s", dump_request(sxng_request))
  155. return val
  156. logger.debug(f"OK {network}: %s", dump_request(sxng_request))
  157. return None
  158. def pre_request():
  159. """See :py:obj:`flask.Flask.before_request`"""
  160. return filter_request(sxng_request)
  161. def is_installed():
  162. """Returns ``True`` if limiter is active and a redis DB is available."""
  163. return _INSTALLED
  164. def initialize(app: flask.Flask, settings):
  165. """Install the limiter"""
  166. global _INSTALLED # pylint: disable=global-statement
  167. # even if the limiter is not activated, the botdetection must be activated
  168. # (e.g. the self_info plugin uses the botdetection to get client IP)
  169. cfg = get_cfg()
  170. redis_client = redisdb.client()
  171. botdetection.init(cfg, redis_client)
  172. if not (settings['server']['limiter'] or settings['server']['public_instance']):
  173. return
  174. if not redis_client:
  175. logger.error(
  176. "The limiter requires Redis, please consult the documentation: "
  177. "https://docs.searxng.org/admin/searx.limiter.html"
  178. )
  179. if settings['server']['public_instance']:
  180. sys.exit(1)
  181. return
  182. _INSTALLED = True
  183. if settings['server']['public_instance']:
  184. # overwrite limiter.toml setting
  185. cfg.set('botdetection.ip_limit.link_token', True)
  186. app.before_request(pre_request)