link_token.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. """
  4. Method ``link_token``
  5. ---------------------
  6. The ``link_token`` method evaluates a request as :py:obj:`suspicious
  7. <is_suspicious>` if the URL ``/client<token>.css`` is not requested by the
  8. client. By adding a random component (the token) in the URL a bot can not send
  9. a ping by request a static URL.
  10. .. note::
  11. This method requires a redis DB and needs a HTTP X-Forwarded-For_ header.
  12. To get in use of this method a flask URL route needs to be added:
  13. .. code:: python
  14. @app.route('/client<token>.css', methods=['GET', 'POST'])
  15. def client_token(token=None):
  16. link_token.ping(request, token)
  17. return Response('', mimetype='text/css')
  18. And in the HTML template from flask a stylesheet link is needed (the value of
  19. ``link_token`` comes from :py:obj:`get_token`):
  20. .. code:: html
  21. <link rel="stylesheet"
  22. href="{{ url_for('client_token', token=link_token) }}"
  23. type="text/css" />
  24. .. _X-Forwarded-For:
  25. https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For
  26. """
  27. import string
  28. import random
  29. import flask
  30. from searx import logger
  31. from searx import redisdb
  32. from searx.redislib import secret_hash
  33. TOKEN_LIVE_TIME = 600
  34. """Livetime (sec) of limiter's CSS token."""
  35. PING_LIVE_TIME = 3600
  36. """Livetime (sec) of the ping-key from a client (request)"""
  37. PING_KEY = 'SearXNG_limiter.ping'
  38. """Prefix of all ping-keys generated by :py:obj:`get_ping_key`"""
  39. TOKEN_KEY = 'SearXNG_limiter.token'
  40. """Key for which the current token is stored in the DB"""
  41. logger = logger.getChild('botdetection.link_token')
  42. def is_suspicious(request: flask.Request, renew: bool = False):
  43. """Checks if there is a valid ping for this request, if not this request is
  44. rated as *suspicious*. If a valid ping exists and argument ``renew`` is
  45. ``True`` the expire time of this ping is reset to :py:obj:`PING_LIVE_TIME`.
  46. """
  47. redis_client = redisdb.client()
  48. if not redis_client:
  49. return False
  50. ping_key = get_ping_key(request)
  51. if not redis_client.get(ping_key):
  52. logger.warning(
  53. "missing ping (IP: %s) / request: %s",
  54. request.headers.get('X-Forwarded-For', ''),
  55. ping_key,
  56. )
  57. return True
  58. if renew:
  59. redis_client.set(ping_key, 1, ex=PING_LIVE_TIME)
  60. logger.debug("found ping for client request: %s", ping_key)
  61. return False
  62. def ping(request: flask.Request, token: str):
  63. """This function is called by a request to URL ``/client<token>.css``. If
  64. ``token`` is valid a :py:obj:`PING_KEY` for the client is stored in the DB.
  65. The expire time of this ping-key is :py:obj:`PING_LIVE_TIME`.
  66. """
  67. redis_client = redisdb.client()
  68. if not redis_client:
  69. return
  70. if not token_is_valid(token):
  71. return
  72. ping_key = get_ping_key(request)
  73. logger.debug("store ping for: %s", ping_key)
  74. redis_client.set(ping_key, 1, ex=PING_LIVE_TIME)
  75. def get_ping_key(request: flask.Request):
  76. """Generates a hashed key that fits (more or less) to a client (request).
  77. At least X-Forwarded-For_ is needed to be able to assign the request to an
  78. IP.
  79. """
  80. return (
  81. PING_KEY
  82. + "["
  83. + secret_hash(
  84. request.headers.get('X-Forwarded-For', '')
  85. + request.headers.get('Accept-Language', '')
  86. + request.headers.get('User-Agent', '')
  87. )
  88. + "]"
  89. )
  90. def token_is_valid(token) -> bool:
  91. valid = token == get_token()
  92. logger.debug("token is valid --> %s", valid)
  93. return valid
  94. def get_token() -> str:
  95. """Returns current token. If there is no currently active token a new token
  96. is generated randomly and stored in the redis DB.
  97. - :py:obj:`TOKEN_LIVE_TIME`
  98. - :py:obj:`TOKEN_KEY`
  99. """
  100. redis_client = redisdb.client()
  101. if not redis_client:
  102. # This function is also called when limiter is inactive / no redis DB
  103. # (see render function in webapp.py)
  104. return '12345678'
  105. token = redis_client.get(TOKEN_KEY)
  106. if token:
  107. token = token.decode('UTF-8')
  108. else:
  109. token = ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(16))
  110. redis_client.set(TOKEN_KEY, token, ex=TOKEN_LIVE_TIME)
  111. return token