limiter.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. # pyright: basic
  4. """Some bot protection / rate limitation
  5. To monitore rate limits and protect privacy the IP addresses are getting stored
  6. with a hash so the limiter plugin knows who to block. A redis database is
  7. needed to store the hash values.
  8. Enable the plugin in ``settings.yml``:
  9. - ``server.limiter: true``
  10. - ``redis.url: ...`` check the value, see :ref:`settings redis`
  11. """
  12. import hmac
  13. import re
  14. from flask import request
  15. from searx.shared import redisdb
  16. name = "Request limiter"
  17. description = "Limit the number of request"
  18. default_on = False
  19. preference_section = 'service'
  20. re_bot = re.compile(
  21. r'('
  22. + r'[Cc][Uu][Rr][Ll]|[wW]get|Scrapy|splash|JavaFX|FeedFetcher|python-requests|Go-http-client|Java|Jakarta|okhttp'
  23. + r'|HttpClient|Jersey|Python|libwww-perl|Ruby|SynHttpClient|UniversalFeedParser|Googlebot|GoogleImageProxy'
  24. + r'|bingbot|Baiduspider|yacybot|YandexMobileBot|YandexBot|Yahoo! Slurp|MJ12bot|AhrefsBot|archive.org_bot|msnbot'
  25. + r'|MJ12bot|SeznamBot|linkdexbot|Netvibes|SMTBot|zgrab|James BOT|Sogou|Abonti|Pixray|Spinn3r|SemrushBot|Exabot'
  26. + r'|ZmEu|BLEXBot|bitlybot'
  27. + r')'
  28. )
  29. def is_accepted_request(inc_get_counter) -> bool:
  30. # pylint: disable=too-many-return-statements
  31. user_agent = request.headers.get('User-Agent', '')
  32. x_forwarded_for = request.headers.get('X-Forwarded-For', '')
  33. if request.path == '/image_proxy':
  34. if re_bot.match(user_agent):
  35. return False
  36. return True
  37. if request.path == '/search':
  38. c_burst = inc_get_counter(interval=20, keys=[b'IP limit, burst', x_forwarded_for])
  39. c_10min = inc_get_counter(interval=600, keys=[b'IP limit, 10 minutes', x_forwarded_for])
  40. if c_burst > 15 or c_10min > 150:
  41. return False
  42. if re_bot.match(user_agent):
  43. return False
  44. if len(request.headers.get('Accept-Language', '').strip()) == '':
  45. return False
  46. if request.headers.get('Connection') == 'close':
  47. return False
  48. accept_encoding_list = [l.strip() for l in request.headers.get('Accept-Encoding', '').split(',')]
  49. if 'gzip' not in accept_encoding_list or 'deflate' not in accept_encoding_list:
  50. return False
  51. if 'text/html' not in request.accept_mimetypes:
  52. return False
  53. if request.args.get('format', 'html') != 'html':
  54. c = inc_get_counter(interval=3600, keys=[b'API limit', x_forwarded_for])
  55. if c > 4:
  56. return False
  57. return True
  58. def create_inc_get_counter(redis_client, secret_key_bytes):
  59. lua_script = """
  60. local slidingWindow = KEYS[1]
  61. local key = KEYS[2]
  62. local now = tonumber(redis.call('TIME')[1])
  63. local id = redis.call('INCR', 'counter')
  64. if (id > 2^46)
  65. then
  66. redis.call('SET', 'count', 0)
  67. end
  68. redis.call('ZREMRANGEBYSCORE', key, 0, now - slidingWindow)
  69. redis.call('ZADD', key, now, id)
  70. local result = redis.call('ZCOUNT', key, 0, now+1)
  71. redis.call('EXPIRE', key, slidingWindow)
  72. return result
  73. """
  74. script_sha = redis_client.script_load(lua_script)
  75. def inc_get_counter(interval, keys):
  76. m = hmac.new(secret_key_bytes, digestmod='sha256')
  77. for k in keys:
  78. m.update(bytes(str(k), encoding='utf-8') or b'')
  79. m.update(b"\0")
  80. key = m.digest()
  81. return redis_client.evalsha(script_sha, 2, interval, key)
  82. return inc_get_counter
  83. def create_pre_request(get_aggregation_count):
  84. def pre_request():
  85. if not is_accepted_request(get_aggregation_count):
  86. return '', 429
  87. return None
  88. return pre_request
  89. def init(app, settings):
  90. if not settings['server']['limiter']:
  91. return False
  92. logger.debug("init limiter DB") # pylint: disable=undefined-variable
  93. if not redisdb.init():
  94. logger.error("init limiter DB failed!!!") # pylint: disable=undefined-variable
  95. return False
  96. redis_client = redisdb.client()
  97. secret_key_bytes = bytes(settings['server']['secret_key'], encoding='utf-8')
  98. inc_get_counter = create_inc_get_counter(redis_client, secret_key_bytes)
  99. app.before_request(create_pre_request(inc_get_counter))
  100. return True