limiter.py 4.2 KB

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