summaryrefslogtreecommitdiffstats
path: root/network/tor_manager.py
blob: 8f91b6834b50b3be5521f9535cc75a0613469900 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
import os
import subprocess
import asyncio
import socket
import socks
from typing import Optional
import shutil
import platform
import sys
import stat

class TorManager:
    def __init__(self):
        self.tor_process: Optional[subprocess.Popen] = None
        self.onion_address: Optional[str] = None
        self.socks_port = 9052
        self.control_port = 9053
        self.base_dir = self._get_base_dir()

    def _get_base_dir(self) -> str:
        """Get the portable base directory for Tor files"""
        if getattr(sys, 'frozen', False):
            # If running as compiled executable
            base_path = os.path.dirname(sys.executable)
        else:
            # If running from source
            base_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

        # Use a hidden directory in the user's home
        return os.path.join(os.path.expanduser("~"), ".tormesh")

    def _secure_dir_permissions(self, path: str):
        """Set secure permissions on directory"""
        os.chmod(path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)  # 700

    def _get_tor_path(self) -> str:
        """Get platform-specific Tor binary path with fallbacks"""
        if platform.system() == 'Windows':
            tor_names = ['tor.exe']
        else:
            tor_names = ['tor']

        # Search in system paths first
        search_paths = [
            "/usr/bin",
            "/usr/local/bin",
            "/opt/homebrew/bin",  # For MacOS
            os.path.join(self.base_dir, "bin")
        ]

        # Add PATH directories
        if os.environ.get('PATH'):
            search_paths.extend(os.environ['PATH'].split(os.pathsep))

        for path in search_paths:
            for name in tor_names:
                tor_path = os.path.join(path, name)
                if os.path.exists(tor_path) and os.access(tor_path, os.X_OK):
                    return tor_path

        raise FileNotFoundError(
            "Tor binary not found. Please ensure Tor is installed."
        )

    async def start(self):
        """Start Tor with robust error handling and retries"""
        # Create base directory with secure permissions
        os.makedirs(self.base_dir, exist_ok=True)
        self._secure_dir_permissions(self.base_dir)

        # Create necessary subdirectories
        data_dir = os.path.join(self.base_dir, "data")
        hidden_service_dir = os.path.join(self.base_dir, "hidden_service")

        for directory in [data_dir, hidden_service_dir]:
            os.makedirs(directory, exist_ok=True)
            self._secure_dir_permissions(directory)

        # Create torrc configuration
        torrc_path = os.path.join(self.base_dir, "torrc")
        with open(torrc_path, "w") as f:
            f.write(f"""
SocksPort 127.0.0.1:{self.socks_port}
ControlPort 127.0.0.1:{self.control_port}
DataDirectory {data_dir}
HiddenServiceDir {hidden_service_dir}
HiddenServicePort 12345 127.0.0.1:12345
# Improve anonymity
UseEntryGuards 1
NumEntryGuards 4
# Improve resilience
CircuitBuildTimeout 60
LearnCircuitBuildTimeout 1
MaxCircuitDirtiness 600
NewCircuitPeriod 300
""")
        self._secure_dir_permissions(os.path.dirname(torrc_path))

        # Start Tor process with retries
        max_retries = 3
        retry_delay = 2

        for attempt in range(max_retries):
            try:
                tor_path = self._get_tor_path()
                print(f"Starting Tor from: {tor_path}")

                self.tor_process = subprocess.Popen(
                    [tor_path, "-f", torrc_path],
                    stdout=subprocess.PIPE,
                    stderr=subprocess.PIPE
                )

                # Wait for Tor to start and verify it's running
                if await self._wait_for_tor():
                    print(f"Tor started successfully on attempt {attempt + 1}")
                    return

            except Exception as e:
                print(f"Tor start attempt {attempt + 1} failed: {str(e)}")
                if self.tor_process:
                    self.tor_process.terminate()
                    await asyncio.sleep(1)

                if attempt < max_retries - 1:
                    await asyncio.sleep(retry_delay)
                else:
                    raise Exception(f"Failed to start Tor after {max_retries} attempts")

    async def _wait_for_tor(self) -> bool:
        """Wait for Tor to start with improved verification"""
        hostname_file = os.path.join(
            self.base_dir, "hidden_service", "hostname"
        )

        for _ in range(30):  # Wait up to 30 seconds
            # Check if process is still running
            if self.tor_process and self.tor_process.poll() is not None:
                if self.tor_process.stderr:
                    stderr = self.tor_process.stderr.read().decode()
                    raise Exception(f"Tor process died: {stderr}")
                raise Exception("Tor process died unexpectedly")

            # Check for hostname file
            if os.path.exists(hostname_file):
                try:
                    with open(hostname_file, "r") as f:
                        self.onion_address = f.read().strip()

                    # Verify SOCKS port is listening
                    sock = socket.socket()
                    try:
                        sock.connect(("127.0.0.1", self.socks_port))
                        sock.close()
                        return True
                    except:
                        pass
                except:
                    pass

            await asyncio.sleep(1)

        return False

    async def stop(self):
        """Stop Tor with graceful shutdown"""
        if self.tor_process:
            try:
                self.tor_process.terminate()
                try:
                    await asyncio.wait_for(
                        asyncio.create_task(self.tor_process.wait()),
                        timeout=5
                    )
                except asyncio.TimeoutError:
                    self.tor_process.kill()

                # Clear sensitive data
                if self.onion_address:
                    self.onion_address = None

                # Clean up temporary files securely
                if os.path.exists(self.base_dir):
                    try:
                        # Securely delete sensitive files
                        for root, dirs, files in os.walk(self.base_dir):
                            for f in files:
                                path = os.path.join(root, f)
                                with open(path, 'wb') as fd:
                                    fd.write(os.urandom(os.path.getsize(path)))
                        # Remove directory tree
                        shutil.rmtree(self.base_dir)
                    except:
                        pass
            except:
                pass  # Ensure cleanup doesn't raise errors