torwire 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
torwire/bridge.py ADDED
@@ -0,0 +1,324 @@
1
+ """Pure-Python asyncio HTTP/HTTPS forward proxy bridging to Tor's SOCKS5 port."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import logging
7
+ import struct
8
+ import threading
9
+ from urllib.parse import urlparse
10
+
11
+ from torwire.errors import BridgeError
12
+
13
+ logger = logging.getLogger("torwire")
14
+
15
+ _HOP_BY_HOP_HEADERS = frozenset(
16
+ {
17
+ "connection",
18
+ "proxy-connection",
19
+ "keep-alive",
20
+ "proxy-authenticate",
21
+ "proxy-authorization",
22
+ "te",
23
+ "trailer",
24
+ "transfer-encoding",
25
+ "upgrade",
26
+ }
27
+ )
28
+
29
+
30
+ def encode_socks5_connect(host: str, port: int) -> bytes:
31
+ """Encode a SOCKS5 domain-name CONNECT request packet.
32
+
33
+ Uses address type ``0x03`` (DOMAINNAME) so DNS resolution always happens
34
+ inside Tor rather than leaking locally.
35
+ """
36
+ host_bytes = host.encode("utf-8")
37
+ if len(host_bytes) > 255:
38
+ raise BridgeError(f"Destination hostname too long for SOCKS5: {len(host_bytes)} bytes")
39
+ return (
40
+ struct.pack("!BBBB", 0x05, 0x01, 0x00, 0x03)
41
+ + struct.pack("!B", len(host_bytes))
42
+ + host_bytes
43
+ + struct.pack("!H", port)
44
+ )
45
+
46
+
47
+ class HttpBridge:
48
+ """In-process asyncio HTTP/HTTPS proxy server forwarding over Tor SOCKS5.
49
+
50
+ Supports both ``CONNECT host:port`` (HTTPS tunneling) and plain HTTP
51
+ absolute-URI requests (``GET http://example.com/...``).
52
+ """
53
+
54
+ def __init__(
55
+ self,
56
+ socks_host: str = "127.0.0.1",
57
+ socks_port: int = 9050,
58
+ listen_host: str = "127.0.0.1",
59
+ listen_port: int = 0,
60
+ ) -> None:
61
+ self._socks_host = socks_host
62
+ self._socks_port = socks_port
63
+ self._listen_host = listen_host
64
+ self._listen_port = listen_port
65
+ self._bound_port: int = listen_port
66
+ self._loop: asyncio.AbstractEventLoop | None = None
67
+ self._server: asyncio.AbstractServer | None = None
68
+ self._thread: threading.Thread | None = None
69
+ self._ready = threading.Event()
70
+ self._start_error: BaseException | None = None
71
+ self._running = False
72
+
73
+ @property
74
+ def port(self) -> int:
75
+ """Return the TCP port the HTTP bridge is listening on."""
76
+ return self._bound_port
77
+
78
+ @property
79
+ def url(self) -> str:
80
+ """Return the HTTP proxy URL, e.g. ``http://127.0.0.1:8118``."""
81
+ return f"http://{self._listen_host}:{self._bound_port}"
82
+
83
+ @property
84
+ def running(self) -> bool:
85
+ """Return ``True`` if the bridge server is currently running."""
86
+ return self._running
87
+
88
+ def start(self) -> None:
89
+ """Start the HTTP bridge in a background daemon thread."""
90
+ if self._running:
91
+ return
92
+ self._ready.clear()
93
+ self._start_error = None
94
+ self._thread = threading.Thread(
95
+ target=self._run_loop,
96
+ daemon=True,
97
+ name="torwire-http-bridge",
98
+ )
99
+ self._thread.start()
100
+ self._ready.wait(timeout=10.0)
101
+ if self._start_error is not None:
102
+ raise BridgeError(f"Failed to start HTTP bridge: {self._start_error}") from self._start_error
103
+ if not self._running:
104
+ raise BridgeError("HTTP bridge failed to start within timeout.")
105
+
106
+ def stop(self) -> None:
107
+ """Stop the HTTP bridge and shut down its event loop."""
108
+ self._running = False
109
+ loop = self._loop
110
+ server = self._server
111
+ if loop is not None and loop.is_running():
112
+ def _shutdown() -> None:
113
+ if server is not None:
114
+ server.close()
115
+ loop.stop()
116
+
117
+ loop.call_soon_threadsafe(_shutdown)
118
+ if self._thread is not None and self._thread.is_alive():
119
+ self._thread.join(timeout=3.0)
120
+ self._thread = None
121
+ self._server = None
122
+ self._loop = None
123
+
124
+ def _run_loop(self) -> None:
125
+ loop = asyncio.new_event_loop()
126
+ asyncio.set_event_loop(loop)
127
+ self._loop = loop
128
+ try:
129
+ loop.run_until_complete(self._start_server())
130
+ self._running = True
131
+ self._ready.set()
132
+ loop.run_forever()
133
+ except Exception as exc:
134
+ self._start_error = exc
135
+ self._ready.set()
136
+ finally:
137
+ self._running = False
138
+ try:
139
+ pending = asyncio.all_tasks(loop)
140
+ for task in pending:
141
+ task.cancel()
142
+ if pending:
143
+ loop.run_until_complete(asyncio.gather(*pending, return_exceptions=True))
144
+ except Exception:
145
+ pass
146
+ loop.close()
147
+
148
+ async def _start_server(self) -> None:
149
+ self._server = await asyncio.start_server(
150
+ self._handle_client,
151
+ host=self._listen_host,
152
+ port=self._listen_port,
153
+ )
154
+ sockets = self._server.sockets
155
+ if sockets:
156
+ self._bound_port = int(sockets[0].getsockname()[1])
157
+
158
+ async def _open_socks5(
159
+ self, target_host: str, target_port: int
160
+ ) -> tuple[asyncio.StreamReader, asyncio.StreamWriter]:
161
+ """Open a SOCKS5 tunnel to *target_host*:*target_port* through Tor."""
162
+ reader, writer = await asyncio.open_connection(self._socks_host, self._socks_port)
163
+ try:
164
+ # Greeting: SOCKS5, 1 auth method, NO AUTH (0x00)
165
+ writer.write(b"\x05\x01\x00")
166
+ await writer.drain()
167
+ greeting_resp = await reader.readexactly(2)
168
+ if greeting_resp != b"\x05\x00":
169
+ raise BridgeError(f"SOCKS5 auth negotiation failed: {greeting_resp!r}")
170
+
171
+ # CONNECT request using DOMAINNAME (0x03)
172
+ writer.write(encode_socks5_connect(target_host, target_port))
173
+ await writer.drain()
174
+
175
+ header = await reader.readexactly(4)
176
+ if header[0] != 0x05 or header[1] != 0x00:
177
+ raise BridgeError(f"SOCKS5 CONNECT failed with status code {header[1]}")
178
+
179
+ atyp = header[3]
180
+ if atyp == 0x01: # IPv4
181
+ await reader.readexactly(4 + 2)
182
+ elif atyp == 0x03: # Domain
183
+ length = (await reader.readexactly(1))[0]
184
+ await reader.readexactly(length + 2)
185
+ elif atyp == 0x04: # IPv6
186
+ await reader.readexactly(16 + 2)
187
+ else:
188
+ raise BridgeError(f"Unknown SOCKS5 address type: {atyp}")
189
+ return reader, writer
190
+ except Exception:
191
+ writer.close()
192
+ raise
193
+
194
+ async def _handle_client(
195
+ self, client_reader: asyncio.StreamReader, client_writer: asyncio.StreamWriter
196
+ ) -> None:
197
+ """Handle a single incoming HTTP proxy client connection."""
198
+ remote_writer: asyncio.StreamWriter | None = None
199
+ try:
200
+ request_line_raw = await asyncio.wait_for(client_reader.readline(), timeout=30.0)
201
+ if not request_line_raw:
202
+ return
203
+ request_line = request_line_raw.decode("latin-1").rstrip("\r\n")
204
+ parts = request_line.split(" ", 2)
205
+ if len(parts) != 3:
206
+ client_writer.write(b"HTTP/1.1 400 Bad Request\r\n\r\n")
207
+ await client_writer.drain()
208
+ return
209
+
210
+ method, target, version = parts
211
+
212
+ # Read headers (do not log URLs or headers for privacy)
213
+ headers: list[tuple[str, str]] = []
214
+ while True:
215
+ line_raw = await asyncio.wait_for(client_reader.readline(), timeout=30.0)
216
+ if not line_raw or line_raw in (b"\r\n", b"\n"):
217
+ break
218
+ decoded = line_raw.decode("latin-1").rstrip("\r\n")
219
+ if ":" in decoded:
220
+ name, val = decoded.split(":", 1)
221
+ headers.append((name.strip(), val.strip()))
222
+
223
+ if method.upper() == "CONNECT":
224
+ host, port = self._parse_host_port(target, default_port=443)
225
+ remote_reader, remote_writer = await self._open_socks5(host, port)
226
+ client_writer.write(b"HTTP/1.1 200 Connection Established\r\n\r\n")
227
+ await client_writer.drain()
228
+ await self._pipe_bidirectional(
229
+ client_reader, client_writer, remote_reader, remote_writer
230
+ )
231
+ else:
232
+ parsed = urlparse(target)
233
+ host = parsed.hostname or ""
234
+ if not host:
235
+ for name, val in headers:
236
+ if name.lower() == "host":
237
+ host, port = self._parse_host_port(val, default_port=80)
238
+ break
239
+ else:
240
+ client_writer.write(b"HTTP/1.1 400 Bad Request\r\n\r\n")
241
+ await client_writer.drain()
242
+ return
243
+ else:
244
+ port = parsed.port or (443 if parsed.scheme == "https" else 80)
245
+
246
+ path = parsed.path or "/"
247
+ if parsed.query:
248
+ path = f"{path}?{parsed.query}"
249
+
250
+ remote_reader, remote_writer = await self._open_socks5(host, port)
251
+
252
+ # Rewrite request line to origin form and strip hop-by-hop headers
253
+ out_lines = [f"{method} {path} {version}"]
254
+ for name, val in headers:
255
+ if name.lower() in _HOP_BY_HOP_HEADERS:
256
+ continue
257
+ out_lines.append(f"{name}: {val}")
258
+ out_lines.append("Connection: close")
259
+ raw_req = ("\r\n".join(out_lines) + "\r\n\r\n").encode("latin-1")
260
+ remote_writer.write(raw_req)
261
+ await remote_writer.drain()
262
+
263
+ await self._pipe_bidirectional(
264
+ client_reader, client_writer, remote_reader, remote_writer
265
+ )
266
+ except Exception:
267
+ try:
268
+ client_writer.write(b"HTTP/1.1 502 Bad Gateway\r\n\r\n")
269
+ await client_writer.drain()
270
+ except Exception:
271
+ pass
272
+ finally:
273
+ for writer in (client_writer, remote_writer):
274
+ if writer is not None:
275
+ try:
276
+ writer.close()
277
+ except Exception:
278
+ pass
279
+
280
+ @staticmethod
281
+ def _parse_host_port(authority: str, default_port: int) -> tuple[str, int]:
282
+ if authority.startswith("[") and "]" in authority:
283
+ end = authority.index("]")
284
+ host = authority[1:end]
285
+ rest = authority[end + 1 :]
286
+ port = int(rest[1:]) if rest.startswith(":") else default_port
287
+ return host, port
288
+ if ":" in authority:
289
+ host, port_str = authority.rsplit(":", 1)
290
+ return host, int(port_str)
291
+ return authority, default_port
292
+
293
+ @staticmethod
294
+ async def _pipe_bidirectional(
295
+ r1: asyncio.StreamReader,
296
+ w1: asyncio.StreamWriter,
297
+ r2: asyncio.StreamReader,
298
+ w2: asyncio.StreamWriter,
299
+ ) -> None:
300
+ async def _copy(src: asyncio.StreamReader, dst: asyncio.StreamWriter) -> None:
301
+ try:
302
+ while True:
303
+ data = await src.read(65536)
304
+ if not data:
305
+ break
306
+ dst.write(data)
307
+ await dst.drain()
308
+ except (asyncio.CancelledError, ConnectionError, OSError):
309
+ pass
310
+ finally:
311
+ try:
312
+ if dst.can_write_eof():
313
+ dst.write_eof()
314
+ except Exception:
315
+ pass
316
+
317
+ t1 = asyncio.create_task(_copy(r1, w2))
318
+ t2 = asyncio.create_task(_copy(r2, w1))
319
+ done, pending = await asyncio.wait(
320
+ {t1, t2}, return_when=asyncio.FIRST_COMPLETED
321
+ )
322
+ for task in pending:
323
+ task.cancel()
324
+ await asyncio.gather(*pending, return_exceptions=True)
torwire/checks.py ADDED
@@ -0,0 +1,195 @@
1
+ """IP, health, and leak checking utilities for torwire."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import logging
7
+ import time
8
+ import urllib.error
9
+ import urllib.request
10
+ from dataclasses import dataclass, field
11
+ from typing import Any
12
+ from urllib.parse import urlparse
13
+
14
+ logger = logging.getLogger("torwire")
15
+
16
+ TOR_CHECK_URL = "https://check.torproject.org/api/ip"
17
+ IPIFY_URL = "https://api.ipify.org?format=json"
18
+
19
+
20
+ @dataclass
21
+ class HealthReport:
22
+ """Report returned by :func:`health_check`."""
23
+
24
+ process_alive: bool = False
25
+ bootstrapped: bool = False
26
+ control_responsive: bool = False
27
+ can_fetch_ip: bool = False
28
+ exit_ip: str | None = None
29
+ latency_seconds: float | None = None
30
+ errors: list[str] = field(default_factory=list)
31
+
32
+ @property
33
+ def healthy(self) -> bool:
34
+ """Return ``True`` if all health checks passed."""
35
+ return (
36
+ self.process_alive
37
+ and self.bootstrapped
38
+ and self.control_responsive
39
+ and self.can_fetch_ip
40
+ )
41
+
42
+
43
+ @dataclass
44
+ class LeakReport:
45
+ """Report returned by :func:`leak_check`."""
46
+
47
+ tor_ip: str | None = None
48
+ real_ip: str | None = None
49
+ is_tor: bool = False
50
+ leak_detected: bool = False
51
+ errors: list[str] = field(default_factory=list)
52
+
53
+ @property
54
+ def safe(self) -> bool:
55
+ """Return ``True`` if traffic is routed through Tor with no leak detected."""
56
+ return self.is_tor and not self.leak_detected and not self.errors
57
+
58
+
59
+ def get_exit_ip(proxy_url: str | None = None) -> str:
60
+ """Return the current exit IP address, optionally through *proxy_url*.
61
+
62
+ Queries ``check.torproject.org/api/ip`` and falls back to ``api.ipify.org``.
63
+ """
64
+ last_error: Exception | None = None
65
+ for url in (TOR_CHECK_URL, IPIFY_URL):
66
+ try:
67
+ ip = _fetch_ip(url, proxy_url)
68
+ if ip:
69
+ return ip
70
+ except Exception as exc:
71
+ last_error = exc
72
+ continue
73
+ raise RuntimeError(f"Could not determine exit IP from any check service: {last_error}")
74
+
75
+
76
+ def is_tor(proxy_url: str) -> bool:
77
+ """Return ``True`` if requests through *proxy_url* exit via the Tor network."""
78
+ try:
79
+ data = _fetch_json(TOR_CHECK_URL, proxy_url)
80
+ return bool(data.get("IsTor", False))
81
+ except Exception:
82
+ return False
83
+
84
+
85
+ def health_check(
86
+ process_alive: bool,
87
+ control_alive: bool,
88
+ proxy_url: str | None = None,
89
+ ) -> HealthReport:
90
+ """Run a diagnostic health check on the Tor setup."""
91
+ report = HealthReport(
92
+ process_alive=process_alive,
93
+ bootstrapped=process_alive,
94
+ control_responsive=control_alive,
95
+ )
96
+
97
+ if proxy_url:
98
+ start = time.monotonic()
99
+ try:
100
+ ip = get_exit_ip(proxy_url)
101
+ report.can_fetch_ip = True
102
+ report.exit_ip = ip
103
+ report.latency_seconds = time.monotonic() - start
104
+ except Exception as exc:
105
+ report.errors.append(f"IP fetch failed: {exc}")
106
+
107
+ return report
108
+
109
+
110
+ def leak_check(proxy_url: str) -> LeakReport:
111
+ """Compare the direct public IP against the IP seen through *proxy_url*."""
112
+ report = LeakReport()
113
+
114
+ try:
115
+ data = _fetch_json(TOR_CHECK_URL, proxy_url)
116
+ report.tor_ip = data.get("IP")
117
+ report.is_tor = bool(data.get("IsTor", False))
118
+ except Exception as exc:
119
+ report.errors.append(f"Could not get Tor IP: {exc}")
120
+ return report
121
+
122
+ try:
123
+ report.real_ip = _fetch_ip(IPIFY_URL, None)
124
+ except Exception as exc:
125
+ report.errors.append(f"Could not get real IP: {exc}")
126
+ return report
127
+
128
+ if report.tor_ip and report.real_ip:
129
+ if report.tor_ip == report.real_ip:
130
+ report.leak_detected = True
131
+ report.errors.append("Tor IP matches real IP - possible leak!")
132
+ if not report.is_tor:
133
+ report.leak_detected = True
134
+ report.errors.append("Traffic not detected as Tor by check.torproject.org")
135
+
136
+ return report
137
+
138
+
139
+ def _fetch_ip(url: str, proxy_url: str | None) -> str:
140
+ data = _fetch_json(url, proxy_url)
141
+ return str(data.get("IP") or data.get("ip") or "")
142
+
143
+
144
+ def _fetch_json(url: str, proxy_url: str | None) -> dict[str, Any]:
145
+ if proxy_url:
146
+ if proxy_url.startswith("socks"):
147
+ return _fetch_via_socks(url, proxy_url)
148
+ proxy_handler = urllib.request.ProxyHandler({"http": proxy_url, "https": proxy_url})
149
+ opener = urllib.request.build_opener(proxy_handler)
150
+ else:
151
+ opener = urllib.request.build_opener()
152
+
153
+ req = urllib.request.Request(url, headers={"User-Agent": "torwire"})
154
+ with opener.open(req, timeout=15) as resp:
155
+ return json.loads(resp.read().decode("utf-8")) # type: ignore[no-any-return]
156
+
157
+
158
+ def _fetch_via_socks(url: str, socks_url: str) -> dict[str, Any]:
159
+ """Fetch JSON over a SOCKS5 proxy using ``requests[socks]`` or ``PySocks``."""
160
+ # Prefer requests if installed (ships/uses PySocks cleanly)
161
+ try:
162
+ import requests
163
+
164
+ resp = requests.get(
165
+ url,
166
+ proxies={"http": socks_url, "https": socks_url},
167
+ headers={"User-Agent": "torwire"},
168
+ timeout=15,
169
+ )
170
+ resp.raise_for_status()
171
+ return resp.json() # type: ignore[no-any-return]
172
+ except ImportError:
173
+ pass
174
+
175
+ # Try PySocks sockshandler
176
+ try:
177
+ import socks # type: ignore[import-untyped]
178
+ from sockshandler import SocksiPyHandler # type: ignore[import-untyped]
179
+
180
+ parsed = urlparse(socks_url)
181
+ handler = SocksiPyHandler(
182
+ socks.SOCKS5,
183
+ parsed.hostname or "127.0.0.1",
184
+ parsed.port or 9050,
185
+ rdns=True,
186
+ )
187
+ opener = urllib.request.build_opener(handler)
188
+ req = urllib.request.Request(url, headers={"User-Agent": "torwire"})
189
+ with opener.open(req, timeout=15) as resp:
190
+ return json.loads(resp.read().decode("utf-8")) # type: ignore[no-any-return]
191
+ except ImportError as exc:
192
+ raise ImportError(
193
+ "Checking IP over SOCKS5 requires requests[socks] or PySocks. "
194
+ "Install with: pip install torwire[requests]"
195
+ ) from exc