tor_check.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. """
  7. from __future__ import annotations
  8. import typing
  9. import re
  10. from flask_babel import gettext
  11. from httpx import HTTPError
  12. from searx.network import get
  13. from searx.plugins import Plugin, PluginInfo
  14. from searx.result_types import EngineResults
  15. from searx.botdetection import get_real_ip
  16. if typing.TYPE_CHECKING:
  17. from searx.search import SearchWithPlugins
  18. from searx.extended_types import SXNG_Request
  19. from searx.plugins import PluginCfg
  20. # Regex for exit node addresses in the list.
  21. reg = re.compile(r"(?<=ExitAddress )\S+")
  22. url_exit_list = "https://check.torproject.org/exit-addresses"
  23. """URL to load Tor exit list from."""
  24. class SXNGPlugin(Plugin):
  25. """Rewrite hostnames, remove results or prioritize them."""
  26. id = "tor_check"
  27. keywords = ["tor-check"]
  28. def __init__(self, plg_cfg: "PluginCfg") -> None:
  29. super().__init__(plg_cfg)
  30. self.info = PluginInfo(
  31. id=self.id,
  32. name=gettext("Tor check plugin"),
  33. description=gettext(
  34. "This plugin checks if the address of the request is a Tor exit-node, and"
  35. " informs the user if it is; like check.torproject.org, but from SearXNG."
  36. ),
  37. preference_section="query",
  38. )
  39. def post_search(self, request: "SXNG_Request", search: "SearchWithPlugins") -> EngineResults:
  40. results = EngineResults()
  41. if search.search_query.pageno > 1:
  42. return results
  43. if search.search_query.query.lower() == "tor-check":
  44. # Request the list of tor exit nodes.
  45. try:
  46. resp = get(url_exit_list)
  47. node_list = re.findall(reg, resp.text) # type: ignore
  48. except HTTPError:
  49. # No answer, return error
  50. msg = gettext("Could not download the list of Tor exit-nodes from")
  51. results.add(results.types.Answer(answer=f"{msg} {url_exit_list}"))
  52. return results
  53. real_ip = get_real_ip(request)
  54. if real_ip in node_list:
  55. msg = gettext("You are using Tor and it looks like you have the external IP address")
  56. results.add(results.types.Answer(answer=f"{msg} {real_ip}"))
  57. else:
  58. msg = gettext("You are not using Tor and you have the external IP address")
  59. results.add(results.types.Answer(answer=f"{msg} {real_ip}"))
  60. return results