limiter.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  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':
  35. c_burst = inc_get_counter(interval=20, keys=[b'IP limit, burst', x_forwarded_for])
  36. c_10min = inc_get_counter(interval=600, keys=[b'IP limit, 10 minutes', x_forwarded_for])
  37. if c_burst > 15 or c_10min > 150:
  38. return False
  39. if re_bot.match(user_agent):
  40. return False
  41. if len(request.headers.get('Accept-Language', '').strip()) == '':
  42. return False
  43. if request.headers.get('Connection') == 'close':
  44. return False
  45. accept_encoding_list = [l.strip() for l in request.headers.get('Accept-Encoding', '').split(',')]
  46. if 'gzip' not in accept_encoding_list or 'deflate' not in accept_encoding_list:
  47. return False
  48. if 'text/html' not in request.accept_mimetypes:
  49. return False
  50. if request.args.get('format', 'html') != 'html':
  51. c = inc_get_counter(interval=3600, keys=[b'API limit', x_forwarded_for])
  52. if c > 4:
  53. return False
  54. return True
  55. def create_inc_get_counter(redis_client, secret_key_bytes):
  56. lua_script = """
  57. local slidingWindow = KEYS[1]
  58. local key = KEYS[2]
  59. local now = tonumber(redis.call('TIME')[1])
  60. local id = redis.call('INCR', 'counter')
  61. if (id > 2^46)
  62. then
  63. redis.call('SET', 'count', 0)
  64. end
  65. redis.call('ZREMRANGEBYSCORE', key, 0, now - slidingWindow)
  66. redis.call('ZADD', key, now, id)
  67. local result = redis.call('ZCOUNT', key, 0, now+1)
  68. redis.call('EXPIRE', key, slidingWindow)
  69. return result
  70. """
  71. script_sha = redis_client.script_load(lua_script)
  72. def inc_get_counter(interval, keys):
  73. m = hmac.new(secret_key_bytes, digestmod='sha256')
  74. for k in keys:
  75. m.update(bytes(str(k), encoding='utf-8') or b'')
  76. m.update(b"\0")
  77. key = m.digest()
  78. return redis_client.evalsha(script_sha, 2, interval, key)
  79. return inc_get_counter
  80. def create_pre_request(get_aggregation_count):
  81. def pre_request():
  82. if not is_accepted_request(get_aggregation_count):
  83. return '', 429
  84. return None
  85. return pre_request
  86. def init(app, settings):
  87. if not settings['server']['limiter']:
  88. return False
  89. logger.debug("init limiter DB") # pylint: disable=undefined-variable
  90. if not redisdb.init():
  91. logger.error("init limiter DB failed!!!") # pylint: disable=undefined-variable
  92. return False
  93. redis_client = redisdb.client()
  94. secret_key_bytes = bytes(settings['server']['secret_key'], encoding='utf-8')
  95. inc_get_counter = create_inc_get_counter(redis_client, secret_key_bytes)
  96. app.before_request(create_pre_request(inc_get_counter))
  97. return True