ip_limit.py 5.2 KB

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