tor_check.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """A plugin to check if the ip address of the request is a Tor exit-node if the
  3. user searches for ``tor-check``. It fetches the tor exit node list from
  4. :py:obj:`url_exit_list` and parses all the IPs into a list, then checks if the
  5. user's IP address is in it.
  6. Enable in ``settings.yml``:
  7. .. code:: yaml
  8. enabled_plugins:
  9. ..
  10. - 'Tor check plugin'
  11. """
  12. from __future__ import annotations
  13. import re
  14. from flask_babel import gettext
  15. from httpx import HTTPError
  16. from searx.network import get
  17. from searx.result_types import Answer
  18. default_on = False
  19. name = gettext("Tor check plugin")
  20. '''Translated name of the plugin'''
  21. description = gettext(
  22. "This plugin checks if the address of the request is a Tor exit-node, and"
  23. " informs the user if it is; like check.torproject.org, but from SearXNG."
  24. )
  25. '''Translated description of the plugin.'''
  26. preference_section = 'query'
  27. '''The preference section where the plugin is shown.'''
  28. query_keywords = ['tor-check']
  29. '''Query keywords shown in the preferences.'''
  30. query_examples = ''
  31. '''Query examples shown in the preferences.'''
  32. # Regex for exit node addresses in the list.
  33. reg = re.compile(r"(?<=ExitAddress )\S+")
  34. url_exit_list = "https://check.torproject.org/exit-addresses"
  35. """URL to load Tor exit list from."""
  36. def post_search(request, search) -> list[Answer]:
  37. results = []
  38. if search.search_query.pageno > 1:
  39. return results
  40. if search.search_query.query.lower() == "tor-check":
  41. # Request the list of tor exit nodes.
  42. try:
  43. resp = get(url_exit_list)
  44. node_list = re.findall(reg, resp.text) # type: ignore
  45. except HTTPError:
  46. # No answer, return error
  47. msg = gettext("Could not download the list of Tor exit-nodes from")
  48. Answer(results=results, answer=f"{msg} {url_exit_list}")
  49. return results
  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. msg = gettext("You are using Tor and it looks like you have the external IP address")
  57. Answer(results=results, answer=f"{msg} {ip_address}")
  58. else:
  59. msg = gettext("You are not using Tor and you have the external IP address")
  60. Answer(results=results, answer=f"{msg} {ip_address}")
  61. return results