limiter.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  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, secret_hash
  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. PING_KEY = 'SearXNG_limiter.ping'
  37. TOKEN_KEY = 'SearXNG_limiter.token'
  38. def ping():
  39. redis_client = redisdb.client()
  40. user_agent = request.headers.get('User-Agent', 'unknown')
  41. x_forwarded_for = request.headers.get('X-Forwarded-For', '')
  42. ping_key = PING_KEY + user_agent + x_forwarded_for
  43. redis_client.set(secret_hash(ping_key), 1, ex=600)
  44. def is_accepted_request() -> bool:
  45. # pylint: disable=too-many-return-statements
  46. redis_client = redisdb.client()
  47. user_agent = request.headers.get('User-Agent', 'unknown')
  48. x_forwarded_for = request.headers.get('X-Forwarded-For', '')
  49. if request.path == '/healthz':
  50. return True
  51. if block_user_agent.match(user_agent):
  52. logger.debug("BLOCK %s: %s --> detected User-Agent: %s" % (x_forwarded_for, request.path, user_agent))
  53. return False
  54. if request.path == '/search':
  55. c_burst_max = 2
  56. c_10min_max = 10
  57. ping_key = PING_KEY + user_agent + x_forwarded_for
  58. if redis_client.get(secret_hash(ping_key)):
  59. logger.debug('got a ping')
  60. c_burst_max = 15
  61. c_10min_max = 150
  62. else:
  63. logger.debug('missing a ping')
  64. c_burst = incr_sliding_window(redis_client, 'IP limit, burst' + x_forwarded_for, 20)
  65. c_10min = incr_sliding_window(redis_client, 'IP limit, 10 minutes' + x_forwarded_for, 600)
  66. if c_burst > c_burst_max or c_10min > c_10min_max:
  67. logger.debug("BLOCK %s: to many request", x_forwarded_for)
  68. return False
  69. if len(request.headers.get('Accept-Language', '').strip()) == '':
  70. logger.debug("BLOCK %s: missing Accept-Language", x_forwarded_for)
  71. return False
  72. if request.headers.get('Connection') == 'close':
  73. logger.debug("BLOCK %s: got Connection=close", x_forwarded_for)
  74. return False
  75. accept_encoding_list = [l.strip() for l in request.headers.get('Accept-Encoding', '').split(',')]
  76. if 'gzip' not in accept_encoding_list and 'deflate' not in accept_encoding_list:
  77. logger.debug("BLOCK %s: suspicious Accept-Encoding", x_forwarded_for)
  78. return False
  79. if 'text/html' not in request.accept_mimetypes:
  80. logger.debug("BLOCK %s: Accept-Encoding misses text/html", x_forwarded_for)
  81. return False
  82. if request.args.get('format', 'html') != 'html':
  83. c = incr_sliding_window(redis_client, 'API limit' + x_forwarded_for, 3600)
  84. if c > 4:
  85. logger.debug("BLOCK %s: API limit exceeded", x_forwarded_for)
  86. return False
  87. logger.debug(
  88. "OK %s: '%s'" % (x_forwarded_for, request.path)
  89. + " || form: %s" % request.form
  90. + " || Accept: %s" % request.headers.get('Accept', '')
  91. + " || Accept-Language: %s" % request.headers.get('Accept-Language', '')
  92. + " || Accept-Encoding: %s" % request.headers.get('Accept-Encoding', '')
  93. + " || Content-Type: %s" % request.headers.get('Content-Type', '')
  94. + " || Content-Length: %s" % request.headers.get('Content-Length', '')
  95. + " || Connection: %s" % request.headers.get('Connection', '')
  96. + " || User-Agent: %s" % user_agent
  97. )
  98. return True
  99. def pre_request():
  100. if not is_accepted_request():
  101. return 'Too Many Requests', 429
  102. return None
  103. def init(app, settings):
  104. if not settings['server']['limiter']:
  105. return False
  106. if not redisdb.client():
  107. logger.error("The limiter requires Redis") # pylint: disable=undefined-variable
  108. return False
  109. app.before_request(pre_request)
  110. return True