limiter.py 4.3 KB

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