limiter.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. # pyright: basic
  4. """Some bot protection / rate limitation
  5. To monitor 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 re
  13. from flask import request
  14. from searx.shared import redisdb
  15. from searx.redislib import incr_sliding_window
  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() -> bool:
  30. # pylint: disable=too-many-return-statements
  31. redis_client = redisdb.client()
  32. user_agent = request.headers.get('User-Agent', '')
  33. x_forwarded_for = request.headers.get('X-Forwarded-For', '')
  34. if request.path == '/image_proxy':
  35. if re_bot.match(user_agent):
  36. return False
  37. return True
  38. if request.path == '/search':
  39. c_burst = incr_sliding_window(redis_client, 'IP limit, burst' + x_forwarded_for, 20)
  40. c_10min = incr_sliding_window(redis_client, 'IP limit, 10 minutes' + x_forwarded_for, 600)
  41. if c_burst > 15 or c_10min > 150:
  42. logger.debug("to many request") # pylint: disable=undefined-variable
  43. return False
  44. if re_bot.match(user_agent):
  45. logger.debug("detected bot") # pylint: disable=undefined-variable
  46. return False
  47. if len(request.headers.get('Accept-Language', '').strip()) == '':
  48. logger.debug("missing Accept-Language") # pylint: disable=undefined-variable
  49. return False
  50. if request.headers.get('Connection') == 'close':
  51. logger.debug("got Connection=close") # pylint: disable=undefined-variable
  52. return False
  53. accept_encoding_list = [l.strip() for l in request.headers.get('Accept-Encoding', '').split(',')]
  54. if 'gzip' not in accept_encoding_list or 'deflate' not in accept_encoding_list:
  55. logger.debug("suspicious Accept-Encoding") # pylint: disable=undefined-variable
  56. return False
  57. if 'text/html' not in request.accept_mimetypes:
  58. logger.debug("Accept-Encoding misses text/html") # pylint: disable=undefined-variable
  59. return False
  60. if request.args.get('format', 'html') != 'html':
  61. c = incr_sliding_window(redis_client, 'API limit' + x_forwarded_for, 3600)
  62. if c > 4:
  63. logger.debug("API limit exceeded") # pylint: disable=undefined-variable
  64. return False
  65. return True
  66. def pre_request():
  67. if not is_accepted_request():
  68. return '', 429
  69. return None
  70. def init(app, settings):
  71. if not settings['server']['limiter']:
  72. return False
  73. logger.debug("init limiter DB") # pylint: disable=undefined-variable
  74. if not redisdb.init():
  75. logger.error("init limiter DB failed!!!") # pylint: disable=undefined-variable
  76. return False
  77. app.before_request(pre_request)
  78. return True