limiter.py 4.0 KB

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