ip_limit.py 5.1 KB

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