limiter.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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. ip_limit,
  85. ip_lists,
  86. get_network,
  87. get_real_ip,
  88. dump_request,
  89. )
  90. # the configuration are limiter.toml and "limiter" in settings.yml so, for
  91. # coherency, the logger is "limiter"
  92. logger = logger.getChild('limiter')
  93. CFG: config.Config = None # type: ignore
  94. _INSTALLED = False
  95. LIMITER_CFG_SCHEMA = Path(__file__).parent / "limiter.toml"
  96. """Base configuration (schema) of the botdetection."""
  97. CFG_DEPRECATED = {
  98. # "dummy.old.foo": "config 'dummy.old.foo' exists only for tests. Don't use it in your real project config."
  99. }
  100. def get_cfg() -> config.Config:
  101. global CFG # pylint: disable=global-statement
  102. if CFG is None:
  103. from . import settings_loader # pylint: disable=import-outside-toplevel
  104. cfg_file = (settings_loader.get_user_cfg_folder() or Path("/etc/searxng")) / "limiter.toml"
  105. CFG = config.Config.from_toml(LIMITER_CFG_SCHEMA, cfg_file, CFG_DEPRECATED)
  106. return CFG
  107. def filter_request(request: SXNG_Request) -> werkzeug.Response | None:
  108. # pylint: disable=too-many-return-statements
  109. cfg = get_cfg()
  110. real_ip = ip_address(get_real_ip(request))
  111. network = get_network(real_ip, cfg)
  112. if request.path == '/healthz':
  113. return None
  114. # link-local
  115. if network.is_link_local:
  116. return None
  117. # block- & pass- lists
  118. #
  119. # 1. The IP of the request is first checked against the pass-list; if the IP
  120. # matches an entry in the list, the request is not blocked.
  121. # 2. If no matching entry is found in the pass-list, then a check is made against
  122. # the block list; if the IP matches an entry in the list, the request is
  123. # blocked.
  124. # 3. If the IP is not in either list, the request is not blocked.
  125. match, msg = ip_lists.pass_ip(real_ip, cfg)
  126. if match:
  127. logger.warning("PASS %s: matched PASSLIST - %s", network.compressed, msg)
  128. return None
  129. match, msg = ip_lists.block_ip(real_ip, cfg)
  130. if match:
  131. logger.error("BLOCK %s: matched BLOCKLIST - %s", network.compressed, msg)
  132. return flask.make_response(('IP is on BLOCKLIST - %s' % msg, 429))
  133. # methods applied on /
  134. for func in [
  135. http_user_agent,
  136. ]:
  137. val = func.filter_request(network, request, cfg)
  138. if val is not None:
  139. return val
  140. # methods applied on /search
  141. if request.path == '/search':
  142. for func in [
  143. http_accept,
  144. http_accept_encoding,
  145. http_accept_language,
  146. http_user_agent,
  147. ip_limit,
  148. ]:
  149. val = func.filter_request(network, request, cfg)
  150. if val is not None:
  151. return val
  152. logger.debug(f"OK {network}: %s", dump_request(sxng_request))
  153. return None
  154. def pre_request():
  155. """See :py:obj:`flask.Flask.before_request`"""
  156. return filter_request(sxng_request)
  157. def is_installed():
  158. """Returns ``True`` if limiter is active and a redis DB is available."""
  159. return _INSTALLED
  160. def initialize(app: flask.Flask, settings):
  161. """Install the limiter"""
  162. global _INSTALLED # pylint: disable=global-statement
  163. # even if the limiter is not activated, the botdetection must be activated
  164. # (e.g. the self_info plugin uses the botdetection to get client IP)
  165. cfg = get_cfg()
  166. redis_client = redisdb.client()
  167. botdetection.init(cfg, redis_client)
  168. if not (settings['server']['limiter'] or settings['server']['public_instance']):
  169. return
  170. if not redis_client:
  171. logger.error(
  172. "The limiter requires Redis, please consult the documentation: "
  173. "https://docs.searxng.org/admin/searx.limiter.html"
  174. )
  175. if settings['server']['public_instance']:
  176. sys.exit(1)
  177. return
  178. _INSTALLED = True
  179. if settings['server']['public_instance']:
  180. # overwrite limiter.toml setting
  181. cfg.set('botdetection.ip_limit.link_token', True)
  182. app.before_request(pre_request)