tor_check.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. """A plugin to check if the ip address of the request is a Tor exit-node if the
  4. user searches for ``tor-check``. It fetches the tor exit node list from
  5. https://check.torproject.org/exit-addresses and parses all the IPs into a list,
  6. then checks if the user's IP address is in it.
  7. Enable in ``settings.yml``:
  8. .. code:: yaml
  9. enabled_plugins:
  10. ..
  11. - 'Tor check plugin'
  12. """
  13. import re
  14. from flask_babel import gettext
  15. from httpx import HTTPError
  16. from searx.network import get
  17. default_on = False
  18. name = gettext("Tor check plugin")
  19. '''Translated name of the plugin'''
  20. description = gettext(
  21. "This plugin checks if the address of the request is a Tor exit-node, and"
  22. " informs the user if it is; like check.torproject.org, but from SearXNG."
  23. )
  24. '''Translated description of the plugin.'''
  25. preference_section = 'query'
  26. '''The preference section where the plugin is shown.'''
  27. query_keywords = ['tor-check']
  28. '''Query keywords shown in the preferences.'''
  29. query_examples = ''
  30. '''Query examples shown in the preferences.'''
  31. # Regex for exit node addresses in the list.
  32. reg = re.compile(r"(?<=ExitAddress )\S+")
  33. def post_search(request, search):
  34. if search.search_query.pageno > 1:
  35. return True
  36. if search.search_query.query.lower() == "tor-check":
  37. # Request the list of tor exit nodes.
  38. try:
  39. resp = get("https://check.torproject.org/exit-addresses")
  40. node_list = re.findall(reg, resp.text)
  41. except HTTPError:
  42. # No answer, return error
  43. search.result_container.answers["tor"] = {
  44. "answer": gettext(
  45. "The could not download the list of Tor exit-nodes"
  46. " from https://check.torproject.org/exit-addresses."
  47. )
  48. }
  49. return True
  50. x_forwarded_for = request.headers.getlist("X-Forwarded-For")
  51. if x_forwarded_for:
  52. ip_address = x_forwarded_for[0]
  53. else:
  54. ip_address = request.remote_addr
  55. if ip_address in node_list:
  56. search.result_container.answers["tor"] = {
  57. "answer": gettext(
  58. "You are using Tor. It looks like you have this external IP address: {ip_address}.".format(
  59. ip_address=ip_address
  60. )
  61. )
  62. }
  63. else:
  64. search.result_container.answers["tor"] = {
  65. "answer": gettext(
  66. "You are not using Tor. You have this external IP address: {ip_address}.".format(
  67. ip_address=ip_address
  68. )
  69. )
  70. }
  71. return True