limiter.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. """Bot protection / IP rate limitation. The intention of rate limitation is to
  4. limit suspicious requests from an IP. The motivation behind this is the fact
  5. that SearXNG passes through requests from bots and is thus classified as a bot
  6. itself. As a result, the SearXNG engine then receives a CAPTCHA or is blocked
  7. by the search engine (the origin) in some other way.
  8. To avoid blocking, the requests from bots to SearXNG must also be blocked, this
  9. is the task of the limiter. To perform this task, the limiter uses the methods
  10. from the :ref:`botdetection`:
  11. - Analysis of the HTTP header in the request / :ref:`botdetection probe headers`
  12. can be easily bypassed.
  13. - Block and pass lists in which IPs are listed / :ref:`botdetection ip_lists`
  14. are hard to maintain, since the IPs of bots are not all known and change over
  15. the time.
  16. - Detection & dynamically :ref:`botdetection rate limit` of bots based on the
  17. behavior of the requests. For dynamically changeable IP lists a Redis
  18. database is needed.
  19. The prerequisite for IP based methods is the correct determination of the IP of
  20. the client. The IP of the client is determined via the X-Forwarded-For_ HTTP
  21. header.
  22. .. attention::
  23. A correct setup of the HTTP request headers ``X-Forwarded-For`` and
  24. ``X-Real-IP`` is essential to be able to assign a request to an IP correctly:
  25. - `NGINX RequestHeader`_
  26. - `Apache RequestHeader`_
  27. .. _X-Forwarded-For:
  28. https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For
  29. .. _NGINX RequestHeader:
  30. https://docs.searxng.org/admin/installation-nginx.html#nginx-s-searxng-site
  31. .. _Apache RequestHeader:
  32. https://docs.searxng.org/admin/installation-apache.html#apache-s-searxng-site
  33. Enable Limiter
  34. ==============
  35. To enable the limiter activate:
  36. .. code:: yaml
  37. server:
  38. ...
  39. limiter: true # rate limit the number of request on the instance, block some bots
  40. and set the redis-url connection. Check the value, it depends on your redis DB
  41. (see :ref:`settings redis`), by example:
  42. .. code:: yaml
  43. redis:
  44. url: unix:///usr/local/searxng-redis/run/redis.sock?db=0
  45. Configure Limiter
  46. =================
  47. The methods of :ref:`botdetection` the limiter uses are configured in a local
  48. file ``/etc/searxng/limiter.toml``. The defaults are shown in limiter.toml_ /
  49. Don't copy all values to your local configuration, just enable what you need by
  50. overwriting the defaults. For instance to activate the ``link_token`` method in
  51. the :ref:`botdetection.ip_limit` you only need to set this option to ``true``:
  52. .. code:: toml
  53. [botdetection.ip_limit]
  54. link_token = true
  55. .. _limiter.toml:
  56. ``limiter.toml``
  57. ================
  58. In this file the limiter finds the configuration of the :ref:`botdetection`:
  59. - :ref:`botdetection ip_lists`
  60. - :ref:`botdetection rate limit`
  61. - :ref:`botdetection probe headers`
  62. .. kernel-include:: $SOURCEDIR/limiter.toml
  63. :code: toml
  64. Implementation
  65. ==============
  66. """
  67. from __future__ import annotations
  68. import sys
  69. from pathlib import Path
  70. from ipaddress import ip_address
  71. import flask
  72. import werkzeug
  73. from searx import (
  74. logger,
  75. redisdb,
  76. )
  77. from searx import botdetection
  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. LIMITER_CFG = Path('/etc/searxng/limiter.toml')
  98. """Local Limiter configuration."""
  99. CFG_DEPRECATED = {
  100. # "dummy.old.foo": "config 'dummy.old.foo' exists only for tests. Don't use it in your real project config."
  101. }
  102. def get_cfg() -> config.Config:
  103. global CFG # pylint: disable=global-statement
  104. if CFG is None:
  105. CFG = config.Config.from_toml(LIMITER_CFG_SCHEMA, LIMITER_CFG, CFG_DEPRECATED)
  106. return CFG
  107. def filter_request(request: flask.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(flask.request))
  153. return None
  154. def pre_request():
  155. """See :py:obj:`flask.Flask.before_request`"""
  156. return filter_request(flask.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. if not (settings['server']['limiter'] or settings['server']['public_instance']):
  164. return
  165. redis_client = redisdb.client()
  166. if not redis_client:
  167. logger.error(
  168. "The limiter requires Redis, please consult the documentation: "
  169. "https://docs.searxng.org/admin/searx.limiter.html"
  170. )
  171. if settings['server']['public_instance']:
  172. sys.exit(1)
  173. return
  174. _INSTALLED = True
  175. cfg = get_cfg()
  176. if settings['server']['public_instance']:
  177. # overwrite limiter.toml setting
  178. cfg.set('botdetection.ip_limit.link_token', True)
  179. botdetection.init(cfg, redis_client)
  180. app.before_request(pre_request)