limiter.py 7.1 KB

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