feat: built-in SOCKS5 proxy
Adds a lightweight asyncio SOCKS5 proxy that starts with TailScan. Supports both authenticated (user/pass) and unauthenticated modes, IPv4/IPv6/domain targets, and full TCP CONNECT forwarding. Configure via .env: SOCKS5_PORT=1080 SOCKS5_USER=tailscan SOCKS5_PASSWORD=yourpassword (leave empty for no auth)
This commit is contained in:
1 parent
9a97898fc2
commit
8271bfb99f
2 files changed
+340
-1
No files matched your search
@@ -30,7 +30,17 @@ CACHE_DIR.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
log = logging.getLogger("tailscan")
|
||||
|
||||
app = FastAPI(title="TailScan")
|
||||
from contextlib import asynccontextmanager
|
||||
import asyncio as _asyncio
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app):
|
||||
# Start SOCKS5 proxy in the background
|
||||
import socks5
|
||||
_asyncio.create_task(socks5.start_socks5_server())
|
||||
yield
|
||||
|
||||
app = FastAPI(title="TailScan", lifespan=lifespan)
|
||||
templates = Jinja2Templates(directory="templates")
|
||||
|
||||
|
||||
@@ -573,6 +583,22 @@ GUAC_ADMIN_PASS = os.getenv("GUAC_ADMIN_PASS", "guacadmin")
|
||||
|
||||
_guac_token_cache: dict = {} # {"token": str, "expires": float}
|
||||
|
||||
# ─── Browser session management ─────────────────────────────────────────────
|
||||
import subprocess, socket, secrets as _secrets
|
||||
BROWSER_IMAGE = os.getenv("BROWSER_IMAGE", "tailscan-browser:latest")
|
||||
BROWSER_VNC_PASSWORD = os.getenv("BROWSER_VNC_PASSWORD", "tailscan")
|
||||
_browser_sessions: dict = {} # target_url -> {container_id, vnc_port, conn_id}
|
||||
|
||||
def _find_free_port(start: int = 5910, end: int = 5990) -> int:
|
||||
for port in range(start, end):
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
||||
try:
|
||||
s.bind(("127.0.0.1", port))
|
||||
return port
|
||||
except OSError:
|
||||
continue
|
||||
raise RuntimeError("No free VNC ports available")
|
||||
|
||||
|
||||
async def _guac_token(client: httpx.AsyncClient) -> str:
|
||||
"""Get a Guacamole API auth token, reusing if still valid."""
|
||||
@@ -682,6 +708,129 @@ async def api_guac_connect(request: Request, ip: str, port: int, proto: str):
|
||||
raise HTTPException(502, str(e))
|
||||
|
||||
|
||||
@app.get("/api/browse-session")
|
||||
async def api_browse_session(request: Request, url: str, width: int = 1280, height: int = 800):
|
||||
"""
|
||||
Spin up (or reuse) a LibreWolf VNC container pre-navigated to `url`,
|
||||
create a Guacamole VNC connection for it, and return the Guacamole client URL.
|
||||
"""
|
||||
if not get_session(request):
|
||||
raise HTTPException(401)
|
||||
|
||||
# Reuse existing session for the same URL if container is still running
|
||||
if url in _browser_sessions:
|
||||
s = _browser_sessions[url]
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["docker", "inspect", "-f", "{{.State.Running}}", s["container_id"]],
|
||||
capture_output=True, text=True, timeout=5
|
||||
)
|
||||
if result.stdout.strip() == "true":
|
||||
conn_id = s["conn_id"]
|
||||
import base64
|
||||
client_id = base64.b64encode(
|
||||
f"{conn_id}\0c\0postgresql".encode()
|
||||
).decode().rstrip("=")
|
||||
request_host = request.headers.get("host", "localhost").split(":")[0]
|
||||
guac_url = f"http://{request_host}:8085/guacamole/#/client/{client_id}"
|
||||
return {"url": f"/guac-launch?target={guac_url}&proto=vnc"}
|
||||
except Exception:
|
||||
pass
|
||||
# Container died — clean up
|
||||
_browser_sessions.pop(url, None)
|
||||
|
||||
vnc_port = _find_free_port()
|
||||
conn_name = f"tailscan-browse-{vnc_port}"
|
||||
|
||||
# Start the container
|
||||
try:
|
||||
result = subprocess.run([
|
||||
"docker", "run", "-d", "--rm",
|
||||
"--name", conn_name,
|
||||
"-p", f"127.0.0.1:{vnc_port}:5900",
|
||||
"-e", f"URL={url}",
|
||||
"-e", f"GEOMETRY={width}x{height}",
|
||||
"-e", f"VNC_PASSWORD={BROWSER_VNC_PASSWORD}",
|
||||
BROWSER_IMAGE,
|
||||
], capture_output=True, text=True, timeout=15)
|
||||
if result.returncode != 0:
|
||||
raise RuntimeError(result.stderr.strip())
|
||||
container_id = result.stdout.strip()
|
||||
except Exception as e:
|
||||
raise HTTPException(500, f"Failed to start browser container: {e}")
|
||||
|
||||
# Give the container a moment to start VNC
|
||||
import asyncio
|
||||
await asyncio.sleep(3)
|
||||
|
||||
# Register in Guacamole
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=10.0) as client:
|
||||
token = await _guac_token(client)
|
||||
payload = {
|
||||
"name": conn_name,
|
||||
"protocol": "vnc",
|
||||
"parameters": {
|
||||
"hostname": "127.0.0.1",
|
||||
"port": str(vnc_port),
|
||||
"password": BROWSER_VNC_PASSWORD,
|
||||
"color-depth": "24",
|
||||
},
|
||||
"attributes": {
|
||||
"max-connections": "2",
|
||||
"max-connections-per-user": "2",
|
||||
},
|
||||
"parentIdentifier": "ROOT",
|
||||
}
|
||||
r = await client.post(
|
||||
f"{GUAC_BASE}/api/session/data/postgresql/connections",
|
||||
params={"token": token},
|
||||
json=payload,
|
||||
)
|
||||
r.raise_for_status()
|
||||
conn_id = r.json()["identifier"]
|
||||
except Exception as e:
|
||||
# Kill container if Guacamole registration fails
|
||||
subprocess.run(["docker", "stop", container_id], capture_output=True)
|
||||
raise HTTPException(502, f"Guacamole registration failed: {e}")
|
||||
|
||||
_browser_sessions[url] = {
|
||||
"container_id": container_id,
|
||||
"vnc_port": vnc_port,
|
||||
"conn_id": conn_id,
|
||||
"conn_name": conn_name,
|
||||
}
|
||||
|
||||
import base64
|
||||
client_id = base64.b64encode(
|
||||
f"{conn_id}\0c\0postgresql".encode()
|
||||
).decode().rstrip("=")
|
||||
request_host = request.headers.get("host", "localhost").split(":")[0]
|
||||
guac_url = f"http://{request_host}:8085/guacamole/#/client/{client_id}"
|
||||
return {"url": f"/guac-launch?target={guac_url}&proto=vnc"}
|
||||
|
||||
|
||||
@app.delete("/api/browse-session")
|
||||
async def api_browse_session_delete(request: Request, url: str):
|
||||
"""Kill the browser container for a given URL and clean up the Guacamole connection."""
|
||||
if not get_session(request):
|
||||
raise HTTPException(401)
|
||||
s = _browser_sessions.pop(url, None)
|
||||
if not s:
|
||||
return {"status": "not_found"}
|
||||
subprocess.run(["docker", "stop", s["container_id"]], capture_output=True)
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=10.0) as client:
|
||||
token = await _guac_token(client)
|
||||
await client.delete(
|
||||
f"{GUAC_BASE}/api/session/data/postgresql/connections/{s['conn_id']}",
|
||||
params={"token": token},
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return {"status": "stopped"}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
uvicorn.run("main:app", host="0.0.0.0", port=8080, reload=False)
|
||||
@@ -0,0 +1,190 @@
|
||||
"""
|
||||
Minimal asyncio SOCKS5 proxy server.
|
||||
|
||||
Supports:
|
||||
- SOCKS5 with username/password auth (RFC 1929)
|
||||
- SOCKS5 with no auth (when SOCKS5_PASSWORD is empty)
|
||||
- CONNECT command (TCP forwarding) — covers HTTP, HTTPS, WebSockets
|
||||
- IPv4, IPv6, and domain name targets
|
||||
|
||||
Usage: started as a background asyncio task from main.py
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
import struct
|
||||
import socket
|
||||
|
||||
log = logging.getLogger("socks5")
|
||||
|
||||
SOCKS5_HOST = os.getenv("SOCKS5_HOST", "0.0.0.0")
|
||||
SOCKS5_PORT = int(os.getenv("SOCKS5_PORT", "1080"))
|
||||
SOCKS5_USER = os.getenv("SOCKS5_USER", "tailscan")
|
||||
SOCKS5_PASSWORD = os.getenv("SOCKS5_PASSWORD", "") # empty = no auth required
|
||||
|
||||
# SOCKS5 constants
|
||||
VER = 0x05
|
||||
NOAUTH = 0x00
|
||||
USERPASS = 0x02
|
||||
NO_ACCEPTABLE = 0xFF
|
||||
CMD_CONNECT = 0x01
|
||||
ATYP_IPV4 = 0x01
|
||||
ATYP_DOMAIN = 0x03
|
||||
ATYP_IPV6 = 0x04
|
||||
REP_SUCCESS = 0x00
|
||||
REP_FAILURE = 0x01
|
||||
REP_REFUSED = 0x05
|
||||
REP_CMD_UNSUPPORTED = 0x07
|
||||
REP_ATYP_UNSUPPORTED = 0x08
|
||||
|
||||
|
||||
async def _pipe(reader: asyncio.StreamReader, writer: asyncio.StreamWriter):
|
||||
"""Forward bytes from reader to writer until EOF or error."""
|
||||
try:
|
||||
while True:
|
||||
data = await reader.read(65536)
|
||||
if not data:
|
||||
break
|
||||
writer.write(data)
|
||||
await writer.drain()
|
||||
except (ConnectionResetError, BrokenPipeError, asyncio.IncompleteReadError):
|
||||
pass
|
||||
finally:
|
||||
try:
|
||||
writer.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
async def _send_reply(writer: asyncio.StreamWriter, rep: int,
|
||||
atyp: int = ATYP_IPV4,
|
||||
bind_addr: bytes = b"\x00\x00\x00\x00",
|
||||
bind_port: int = 0):
|
||||
writer.write(bytes([VER, rep, 0x00, atyp]) + bind_addr + struct.pack("!H", bind_port))
|
||||
await writer.drain()
|
||||
|
||||
|
||||
async def handle_client(reader: asyncio.StreamReader, writer: asyncio.StreamWriter):
|
||||
peer = writer.get_extra_info("peername")
|
||||
try:
|
||||
# ── Greeting ──────────────────────────────────────────────────────────
|
||||
header = await reader.readexactly(2)
|
||||
if header[0] != VER:
|
||||
writer.close()
|
||||
return
|
||||
nmethods = header[1]
|
||||
methods = set(await reader.readexactly(nmethods))
|
||||
|
||||
use_auth = bool(SOCKS5_PASSWORD)
|
||||
|
||||
if use_auth and USERPASS in methods:
|
||||
writer.write(bytes([VER, USERPASS]))
|
||||
await writer.drain()
|
||||
|
||||
# ── Username/password sub-negotiation (RFC 1929) ──────────────────
|
||||
sub = await reader.readexactly(2)
|
||||
if sub[0] != 0x01:
|
||||
writer.write(bytes([0x01, 0x01]))
|
||||
await writer.drain()
|
||||
writer.close()
|
||||
return
|
||||
ulen = sub[1]
|
||||
username = (await reader.readexactly(ulen)).decode(errors="replace")
|
||||
plen = (await reader.readexactly(1))[0]
|
||||
password = (await reader.readexactly(plen)).decode(errors="replace")
|
||||
|
||||
if username != SOCKS5_USER or password != SOCKS5_PASSWORD:
|
||||
log.warning("SOCKS5 auth failure from %s", peer)
|
||||
writer.write(bytes([0x01, 0x01]))
|
||||
await writer.drain()
|
||||
writer.close()
|
||||
return
|
||||
writer.write(bytes([0x01, 0x00])) # auth success
|
||||
await writer.drain()
|
||||
|
||||
elif NOAUTH in methods and not use_auth:
|
||||
writer.write(bytes([VER, NOAUTH]))
|
||||
await writer.drain()
|
||||
else:
|
||||
writer.write(bytes([VER, NO_ACCEPTABLE]))
|
||||
await writer.drain()
|
||||
writer.close()
|
||||
return
|
||||
|
||||
# ── Request ───────────────────────────────────────────────────────────
|
||||
req = await reader.readexactly(4)
|
||||
if req[0] != VER:
|
||||
await _send_reply(writer, REP_FAILURE)
|
||||
writer.close()
|
||||
return
|
||||
cmd = req[1]
|
||||
atyp = req[3]
|
||||
|
||||
if cmd != CMD_CONNECT:
|
||||
await _send_reply(writer, REP_CMD_UNSUPPORTED)
|
||||
writer.close()
|
||||
return
|
||||
|
||||
if atyp == ATYP_IPV4:
|
||||
raw = await reader.readexactly(4)
|
||||
target_host = socket.inet_ntop(socket.AF_INET, raw)
|
||||
bind_atyp, bind_addr = ATYP_IPV4, raw
|
||||
elif atyp == ATYP_IPV6:
|
||||
raw = await reader.readexactly(16)
|
||||
target_host = socket.inet_ntop(socket.AF_INET6, raw)
|
||||
bind_atyp, bind_addr = ATYP_IPV6, raw
|
||||
elif atyp == ATYP_DOMAIN:
|
||||
dlen = (await reader.readexactly(1))[0]
|
||||
target_host = (await reader.readexactly(dlen)).decode()
|
||||
bind_atyp, bind_addr = ATYP_IPV4, b"\x00\x00\x00\x00"
|
||||
else:
|
||||
await _send_reply(writer, REP_ATYP_UNSUPPORTED)
|
||||
writer.close()
|
||||
return
|
||||
|
||||
port_bytes = await reader.readexactly(2)
|
||||
target_port = struct.unpack("!H", port_bytes)[0]
|
||||
|
||||
# ── Connect to target ─────────────────────────────────────────────────
|
||||
try:
|
||||
t_reader, t_writer = await asyncio.wait_for(
|
||||
asyncio.open_connection(target_host, target_port),
|
||||
timeout=10.0,
|
||||
)
|
||||
except (OSError, asyncio.TimeoutError) as e:
|
||||
log.debug("SOCKS5 connect failed %s:%s — %s", target_host, target_port, e)
|
||||
await _send_reply(writer, REP_REFUSED)
|
||||
writer.close()
|
||||
return
|
||||
|
||||
log.debug("SOCKS5 %s CONNECT %s:%s", peer, target_host, target_port)
|
||||
await _send_reply(writer, REP_SUCCESS, bind_atyp, bind_addr, target_port)
|
||||
|
||||
# ── Bidirectional pipe ────────────────────────────────────────────────
|
||||
await asyncio.gather(
|
||||
_pipe(reader, t_writer),
|
||||
_pipe(t_reader, writer),
|
||||
return_exceptions=True,
|
||||
)
|
||||
|
||||
except asyncio.IncompleteReadError:
|
||||
pass
|
||||
except Exception as e:
|
||||
log.debug("SOCKS5 handler error from %s: %s", peer, e)
|
||||
finally:
|
||||
try:
|
||||
writer.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
async def start_socks5_server():
|
||||
server = await asyncio.start_server(
|
||||
handle_client, SOCKS5_HOST, SOCKS5_PORT
|
||||
)
|
||||
addrs = ", ".join(str(s.getsockname()) for s in server.sockets)
|
||||
auth_mode = "user/pass" if SOCKS5_PASSWORD else "no auth"
|
||||
log.info("SOCKS5 proxy listening on %s (%s)", addrs, auth_mode)
|
||||
async with server:
|
||||
await server.serve_forever()
|
||||
Reference in new issue
Block a user