ip_limit.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. """.. _botdetection.ip_limit:
  4. Method ``ip_limit``
  5. -------------------
  6. The ``ip_limit`` method counts request from an IP in *sliding windows*. If
  7. there are to many requests in a sliding window, the request is evaluated as a
  8. bot request. This method requires a redis DB and needs a HTTP X-Forwarded-For_
  9. header. To take privacy only the hash value of an IP is stored in the redis DB
  10. and at least for a maximum of 10 minutes.
  11. The :py:obj:`.link_token` method can be used to investigate whether a request is
  12. *suspicious*. To activate the :py:obj:`.link_token` method in the
  13. :py:obj:`.ip_limit` method add the following to your
  14. ``/etc/searxng/limiter.toml``:
  15. .. code:: toml
  16. [botdetection.ip_limit]
  17. link_token = true
  18. If the :py:obj:`.link_token` method is activated and a request is *suspicious*
  19. the request rates are reduced:
  20. - :py:obj:`BURST_MAX` -> :py:obj:`BURST_MAX_SUSPICIOUS`
  21. - :py:obj:`LONG_MAX` -> :py:obj:`LONG_MAX_SUSPICIOUS`
  22. To intercept bots that get their IPs from a range of IPs, there is a
  23. :py:obj:`SUSPICIOUS_IP_WINDOW`. In this window the suspicious IPs are stored
  24. for a longer time. IPs stored in this sliding window have a maximum of
  25. :py:obj:`SUSPICIOUS_IP_MAX` accesses before they are blocked. As soon as the IP
  26. makes a request that is not suspicious, the sliding window for this IP is
  27. dropped.
  28. .. _X-Forwarded-For:
  29. https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For
  30. """
  31. from __future__ import annotations
  32. from ipaddress import (
  33. IPv4Network,
  34. IPv6Network,
  35. )
  36. import flask
  37. import werkzeug
  38. from searx.tools import config
  39. from searx import settings
  40. from searx import redisdb
  41. from searx.redislib import incr_sliding_window, drop_counter
  42. from . import link_token
  43. from ._helpers import (
  44. too_many_requests,
  45. logger,
  46. )
  47. logger = logger.getChild('ip_limit')
  48. BURST_WINDOW = 20
  49. """Time (sec) before sliding window for *burst* requests expires."""
  50. BURST_MAX = 15
  51. """Maximum requests from one IP in the :py:obj:`BURST_WINDOW`"""
  52. BURST_MAX_SUSPICIOUS = 2
  53. """Maximum of suspicious requests from one IP in the :py:obj:`BURST_WINDOW`"""
  54. LONG_WINDOW = 600
  55. """Time (sec) before the longer sliding window expires."""
  56. LONG_MAX = 150
  57. """Maximum requests from one IP in the :py:obj:`LONG_WINDOW`"""
  58. LONG_MAX_SUSPICIOUS = 10
  59. """Maximum suspicious requests from one IP in the :py:obj:`LONG_WINDOW`"""
  60. API_WONDOW = 3600
  61. """Time (sec) before sliding window for API requests (format != html) expires."""
  62. API_MAX = 4
  63. """Maximum requests from one IP in the :py:obj:`API_WONDOW`"""
  64. SUSPICIOUS_IP_WINDOW = 3600 * 24 * 30
  65. """Time (sec) before sliding window for one suspicious IP expires."""
  66. SUSPICIOUS_IP_MAX = 3
  67. """Maximum requests from one suspicious IP in the :py:obj:`SUSPICIOUS_IP_WINDOW`."""
  68. def filter_request(
  69. network: IPv4Network | IPv6Network,
  70. request: flask.Request,
  71. cfg: config.Config,
  72. ) -> werkzeug.Response | None:
  73. # pylint: disable=too-many-return-statements
  74. redis_client = redisdb.client()
  75. if network.is_link_local and not cfg['botdetection.ip_limit.filter_link_local']:
  76. logger.debug("network %s is link-local -> not monitored by ip_limit method", network.compressed)
  77. return None
  78. if request.args.get('format', 'html') != 'html':
  79. c = incr_sliding_window(redis_client, 'ip_limit.API_WONDOW:' + network.compressed, API_WONDOW)
  80. if c > API_MAX:
  81. return too_many_requests(network, "too many request in API_WINDOW")
  82. if settings['server']['public_instance'] or cfg['botdetection.ip_limit.link_token']:
  83. suspicious = link_token.is_suspicious(network, request, True)
  84. if not suspicious:
  85. # this IP is no longer suspicious: release ip again / delete the counter of this IP
  86. drop_counter(redis_client, 'ip_limit.SUSPICIOUS_IP_WINDOW' + network.compressed)
  87. return None
  88. # this IP is suspicious: count requests from this IP
  89. c = incr_sliding_window(
  90. redis_client, 'ip_limit.SUSPICIOUS_IP_WINDOW' + network.compressed, SUSPICIOUS_IP_WINDOW
  91. )
  92. if c > SUSPICIOUS_IP_MAX:
  93. logger.error("BLOCK: too many request from %s in SUSPICIOUS_IP_WINDOW (redirect to /)", network)
  94. return flask.redirect(flask.url_for('index'), code=302)
  95. c = incr_sliding_window(redis_client, 'ip_limit.BURST_WINDOW' + network.compressed, BURST_WINDOW)
  96. if c > BURST_MAX_SUSPICIOUS:
  97. return too_many_requests(network, "too many request in BURST_WINDOW (BURST_MAX_SUSPICIOUS)")
  98. c = incr_sliding_window(redis_client, 'ip_limit.LONG_WINDOW' + network.compressed, LONG_WINDOW)
  99. if c > LONG_MAX_SUSPICIOUS:
  100. return too_many_requests(network, "too many request in LONG_WINDOW (LONG_MAX_SUSPICIOUS)")
  101. return None
  102. # vanilla limiter without extensions counts BURST_MAX and LONG_MAX
  103. c = incr_sliding_window(redis_client, 'ip_limit.BURST_WINDOW' + network.compressed, BURST_WINDOW)
  104. if c > BURST_MAX:
  105. return too_many_requests(network, "too many request in BURST_WINDOW (BURST_MAX)")
  106. c = incr_sliding_window(redis_client, 'ip_limit.LONG_WINDOW' + network.compressed, LONG_WINDOW)
  107. if c > LONG_MAX:
  108. return too_many_requests(network, "too many request in LONG_WINDOW (LONG_MAX)")
  109. return None