link_token.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  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. from ._helpers import get_real_ip
  34. TOKEN_LIVE_TIME = 600
  35. """Livetime (sec) of limiter's CSS token."""
  36. PING_LIVE_TIME = 3600
  37. """Livetime (sec) of the ping-key from a client (request)"""
  38. PING_KEY = 'SearXNG_limiter.ping'
  39. """Prefix of all ping-keys generated by :py:obj:`get_ping_key`"""
  40. TOKEN_KEY = 'SearXNG_limiter.token'
  41. """Key for which the current token is stored in the DB"""
  42. logger = logger.getChild('botdetection.link_token')
  43. def is_suspicious(request: flask.Request, renew: bool = False):
  44. """Checks if there is a valid ping for this request, if not this request is
  45. rated as *suspicious*. If a valid ping exists and argument ``renew`` is
  46. ``True`` the expire time of this ping is reset to :py:obj:`PING_LIVE_TIME`.
  47. """
  48. redis_client = redisdb.client()
  49. if not redis_client:
  50. return False
  51. ping_key = get_ping_key(request)
  52. if not redis_client.get(ping_key):
  53. logger.warning(
  54. "missing ping (IP: %s) / request: %s",
  55. get_real_ip(request),
  56. ping_key,
  57. )
  58. return True
  59. if renew:
  60. redis_client.set(ping_key, 1, ex=PING_LIVE_TIME)
  61. logger.debug("found ping for client request: %s", ping_key)
  62. return False
  63. def ping(request: flask.Request, token: str):
  64. """This function is called by a request to URL ``/client<token>.css``. If
  65. ``token`` is valid a :py:obj:`PING_KEY` for the client is stored in the DB.
  66. The expire time of this ping-key is :py:obj:`PING_LIVE_TIME`.
  67. """
  68. redis_client = redisdb.client()
  69. if not redis_client:
  70. return
  71. if not token_is_valid(token):
  72. return
  73. ping_key = get_ping_key(request)
  74. logger.debug("store ping for: %s", ping_key)
  75. redis_client.set(ping_key, 1, ex=PING_LIVE_TIME)
  76. def get_ping_key(request: flask.Request):
  77. """Generates a hashed key that fits (more or less) to a client (request).
  78. At least X-Forwarded-For_ is needed to be able to assign the request to an
  79. IP.
  80. """
  81. return (
  82. PING_KEY
  83. + "["
  84. + secret_hash(
  85. get_real_ip(request) + request.headers.get('Accept-Language', '') + request.headers.get('User-Agent', '')
  86. )
  87. + "]"
  88. )
  89. def token_is_valid(token) -> bool:
  90. valid = token == get_token()
  91. logger.debug("token is valid --> %s", valid)
  92. return valid
  93. def get_token() -> str:
  94. """Returns current token. If there is no currently active token a new token
  95. is generated randomly and stored in the redis DB.
  96. - :py:obj:`TOKEN_LIVE_TIME`
  97. - :py:obj:`TOKEN_KEY`
  98. """
  99. redis_client = redisdb.client()
  100. if not redis_client:
  101. # This function is also called when limiter is inactive / no redis DB
  102. # (see render function in webapp.py)
  103. return '12345678'
  104. token = redis_client.get(TOKEN_KEY)
  105. if token:
  106. token = token.decode('UTF-8')
  107. else:
  108. token = ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(16))
  109. redis_client.set(TOKEN_KEY, token, ex=TOKEN_LIVE_TIME)
  110. return token