limiter.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  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 import redisdb
  15. from searx.plugins import logger
  16. from searx.redislib import incr_sliding_window
  17. name = "Request limiter"
  18. description = "Limit the number of request"
  19. default_on = False
  20. preference_section = 'service'
  21. logger = logger.getChild('limiter')
  22. re_bot = re.compile(
  23. r'('
  24. + r'[Cc][Uu][Rr][Ll]|[wW]get|Scrapy|splash|JavaFX|FeedFetcher|python-requests|Go-http-client|Java|Jakarta|okhttp'
  25. + r'|HttpClient|Jersey|Python|libwww-perl|Ruby|SynHttpClient|UniversalFeedParser|Googlebot|GoogleImageProxy'
  26. + r'|bingbot|Baiduspider|yacybot|YandexMobileBot|YandexBot|Yahoo! Slurp|MJ12bot|AhrefsBot|archive.org_bot|msnbot'
  27. + r'|MJ12bot|SeznamBot|linkdexbot|Netvibes|SMTBot|zgrab|James BOT|Sogou|Abonti|Pixray|Spinn3r|SemrushBot|Exabot'
  28. + r'|ZmEu|BLEXBot|bitlybot'
  29. + r')'
  30. )
  31. def is_accepted_request() -> bool:
  32. # pylint: disable=too-many-return-statements
  33. redis_client = redisdb.client()
  34. user_agent = request.headers.get('User-Agent', '')
  35. x_forwarded_for = request.headers.get('X-Forwarded-For', '')
  36. if re_bot.match(user_agent):
  37. logger.debug("BLOCK %s: detected bot", x_forwarded_for)
  38. return False
  39. if request.path == '/search':
  40. c_burst = incr_sliding_window(redis_client, 'IP limit, burst' + x_forwarded_for, 20)
  41. c_10min = incr_sliding_window(redis_client, 'IP limit, 10 minutes' + x_forwarded_for, 600)
  42. if c_burst > 15 or c_10min > 150:
  43. logger.debug("BLOCK %s: to many request", x_forwarded_for)
  44. return False
  45. if len(request.headers.get('Accept-Language', '').strip()) == '':
  46. logger.debug("BLOCK %s: missing Accept-Language", x_forwarded_for)
  47. return False
  48. if request.headers.get('Connection') == 'close':
  49. logger.debug("BLOCK %s: got Connection=close", x_forwarded_for)
  50. return False
  51. accept_encoding_list = [l.strip() for l in request.headers.get('Accept-Encoding', '').split(',')]
  52. if 'gzip' not in accept_encoding_list and 'deflate' not in accept_encoding_list:
  53. logger.debug("BLOCK %s: suspicious Accept-Encoding", x_forwarded_for)
  54. return False
  55. if 'text/html' not in request.accept_mimetypes:
  56. logger.debug("BLOCK %s: Accept-Encoding misses text/html", x_forwarded_for)
  57. return False
  58. if request.args.get('format', 'html') != 'html':
  59. c = incr_sliding_window(redis_client, 'API limit' + x_forwarded_for, 3600)
  60. if c > 4:
  61. logger.debug("BLOCK %s: API limit exceeded", x_forwarded_for)
  62. return False
  63. logger.debug(
  64. "OK %s: '%s'" % (x_forwarded_for, request.path)
  65. + " || form: %s" % request.form
  66. + " || Accept: %s" % request.headers.get('Accept', '')
  67. + " || Accept-Language: %s" % request.headers.get('Accept-Language', '')
  68. + " || Accept-Encoding: %s" % request.headers.get('Accept-Encoding', '')
  69. + " || Content-Type: %s" % request.headers.get('Content-Type', '')
  70. + " || Content-Length: %s" % request.headers.get('Content-Length', '')
  71. + " || Connection: %s" % request.headers.get('Connection', '')
  72. + " || User-Agent: %s" % user_agent
  73. )
  74. return True
  75. def pre_request():
  76. if not is_accepted_request():
  77. return 'Too Many Requests', 429
  78. return None
  79. def init(app, settings):
  80. if not settings['server']['limiter']:
  81. return False
  82. if not redisdb.client():
  83. logger.error("The limiter requires Redis") # pylint: disable=undefined-variable
  84. return False
  85. app.before_request(pre_request)
  86. return True