limiter.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  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 request.path == '/healthz':
  41. return True
  42. if block_user_agent.match(user_agent):
  43. logger.debug("BLOCK %s: %s --> detected User-Agent: %s" % (x_forwarded_for, request.path, user_agent))
  44. return False
  45. if request.path == '/search':
  46. c_burst = incr_sliding_window(redis_client, 'IP limit, burst' + x_forwarded_for, 20)
  47. c_10min = incr_sliding_window(redis_client, 'IP limit, 10 minutes' + x_forwarded_for, 600)
  48. if c_burst > 15 or c_10min > 150:
  49. logger.debug("BLOCK %s: to many request", x_forwarded_for)
  50. return False
  51. if len(request.headers.get('Accept-Language', '').strip()) == '':
  52. logger.debug("BLOCK %s: missing Accept-Language", x_forwarded_for)
  53. return False
  54. if request.headers.get('Connection') == 'close':
  55. logger.debug("BLOCK %s: got Connection=close", x_forwarded_for)
  56. return False
  57. accept_encoding_list = [l.strip() for l in request.headers.get('Accept-Encoding', '').split(',')]
  58. if 'gzip' not in accept_encoding_list and 'deflate' not in accept_encoding_list:
  59. logger.debug("BLOCK %s: suspicious Accept-Encoding", x_forwarded_for)
  60. return False
  61. if 'text/html' not in request.accept_mimetypes:
  62. logger.debug("BLOCK %s: Accept-Encoding misses text/html", x_forwarded_for)
  63. return False
  64. if request.args.get('format', 'html') != 'html':
  65. c = incr_sliding_window(redis_client, 'API limit' + x_forwarded_for, 3600)
  66. if c > 4:
  67. logger.debug("BLOCK %s: API limit exceeded", x_forwarded_for)
  68. return False
  69. logger.debug(
  70. "OK %s: '%s'" % (x_forwarded_for, request.path)
  71. + " || form: %s" % request.form
  72. + " || Accept: %s" % request.headers.get('Accept', '')
  73. + " || Accept-Language: %s" % request.headers.get('Accept-Language', '')
  74. + " || Accept-Encoding: %s" % request.headers.get('Accept-Encoding', '')
  75. + " || Content-Type: %s" % request.headers.get('Content-Type', '')
  76. + " || Content-Length: %s" % request.headers.get('Content-Length', '')
  77. + " || Connection: %s" % request.headers.get('Connection', '')
  78. + " || User-Agent: %s" % user_agent
  79. )
  80. return True
  81. def pre_request():
  82. if not is_accepted_request():
  83. return 'Too Many Requests', 429
  84. return None
  85. def init(app, settings):
  86. if not settings['server']['limiter']:
  87. return False
  88. if not redisdb.client():
  89. logger.error("The limiter requires Redis") # pylint: disable=undefined-variable
  90. return False
  91. app.before_request(pre_request)
  92. return True