ip_limit.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  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 redisdb
  40. from searx.redislib import incr_sliding_window, drop_counter
  41. from . import link_token
  42. from ._helpers import (
  43. too_many_requests,
  44. logger,
  45. )
  46. logger = logger.getChild('ip_limit')
  47. BURST_WINDOW = 20
  48. """Time (sec) before sliding window for *burst* requests expires."""
  49. BURST_MAX = 15
  50. """Maximum requests from one IP in the :py:obj:`BURST_WINDOW`"""
  51. BURST_MAX_SUSPICIOUS = 2
  52. """Maximum of suspicious requests from one IP in the :py:obj:`BURST_WINDOW`"""
  53. LONG_WINDOW = 600
  54. """Time (sec) before the longer sliding window expires."""
  55. LONG_MAX = 150
  56. """Maximum requests from one IP in the :py:obj:`LONG_WINDOW`"""
  57. LONG_MAX_SUSPICIOUS = 10
  58. """Maximum suspicious requests from one IP in the :py:obj:`LONG_WINDOW`"""
  59. API_WONDOW = 3600
  60. """Time (sec) before sliding window for API requests (format != html) expires."""
  61. API_MAX = 4
  62. """Maximum requests from one IP in the :py:obj:`API_WONDOW`"""
  63. SUSPICIOUS_IP_WINDOW = 3600 * 24 * 30
  64. """Time (sec) before sliding window for one suspicious IP expires."""
  65. SUSPICIOUS_IP_MAX = 3
  66. """Maximum requests from one suspicious IP in the :py:obj:`SUSPICIOUS_IP_WINDOW`."""
  67. def filter_request(
  68. network: IPv4Network | IPv6Network,
  69. request: flask.Request,
  70. cfg: config.Config,
  71. ) -> werkzeug.Response | None:
  72. # pylint: disable=too-many-return-statements
  73. redis_client = redisdb.client()
  74. if network.is_link_local and not cfg['botdetection.ip_limit.filter_link_local']:
  75. logger.debug("network %s is link-local -> not monitored by ip_limit method", network.compressed)
  76. return None
  77. if request.args.get('format', 'html') != 'html':
  78. c = incr_sliding_window(redis_client, 'ip_limit.API_WONDOW:' + network.compressed, API_WONDOW)
  79. if c > API_MAX:
  80. return too_many_requests(network, "too many request in API_WINDOW")
  81. if cfg['botdetection.ip_limit.link_token']:
  82. suspicious = link_token.is_suspicious(network, request, True)
  83. if not suspicious:
  84. # this IP is no longer suspicious: release ip again / delete the counter of this IP
  85. drop_counter(redis_client, 'ip_limit.SUSPICIOUS_IP_WINDOW' + network.compressed)
  86. return None
  87. # this IP is suspicious: count requests from this IP
  88. c = incr_sliding_window(
  89. redis_client, 'ip_limit.SUSPICIOUS_IP_WINDOW' + network.compressed, SUSPICIOUS_IP_WINDOW
  90. )
  91. if c > SUSPICIOUS_IP_MAX:
  92. logger.error("BLOCK: too many request from %s in SUSPICIOUS_IP_WINDOW (redirect to /)", network)
  93. return flask.redirect(flask.url_for('index'), code=302)
  94. c = incr_sliding_window(redis_client, 'ip_limit.BURST_WINDOW' + network.compressed, BURST_WINDOW)
  95. if c > BURST_MAX_SUSPICIOUS:
  96. return too_many_requests(network, "too many request in BURST_WINDOW (BURST_MAX_SUSPICIOUS)")
  97. c = incr_sliding_window(redis_client, 'ip_limit.LONG_WINDOW' + network.compressed, LONG_WINDOW)
  98. if c > LONG_MAX_SUSPICIOUS:
  99. return too_many_requests(network, "too many request in LONG_WINDOW (LONG_MAX_SUSPICIOUS)")
  100. return None
  101. # vanilla limiter without extensions counts BURST_MAX and LONG_MAX
  102. c = incr_sliding_window(redis_client, 'ip_limit.BURST_WINDOW' + network.compressed, BURST_WINDOW)
  103. if c > BURST_MAX:
  104. return too_many_requests(network, "too many request in BURST_WINDOW (BURST_MAX)")
  105. c = incr_sliding_window(redis_client, 'ip_limit.LONG_WINDOW' + network.compressed, LONG_WINDOW)
  106. if c > LONG_MAX:
  107. return too_many_requests(network, "too many request in LONG_WINDOW (LONG_MAX)")
  108. return None