-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtailscale_integration.py
More file actions
537 lines (465 loc) · 20.6 KB
/
Copy pathtailscale_integration.py
File metadata and controls
537 lines (465 loc) · 20.6 KB
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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
"""Tailscale integration for LinuxGSM Panel.
Auto-detects Tailscale status, manages Serve/Funnel configuration,
provides network diagnostics, and recommends optimal bind settings.
"""
import json
import logging
import re
import socket
import subprocess
import threading
import time
from dataclasses import dataclass, field
from typing import Optional
_log = logging.getLogger(__name__)
@dataclass
class TailscaleInfo:
"""All discovered Tailstate information for this node."""
installed: bool = False
running: bool = False
backend_state: str = "" # Tailscale BackendState: Running, NeedsLogin, Stopped, NoState…
tailscale_ips: list = field(default_factory=list)
hostname: str = ""
dns_name: str = ""
magic_dns_enabled: bool = False
accept_routes: bool = False
version: str = ""
serve_config: dict = field(default_factory=dict)
funnel_enabled: bool = False
peers: list = field(default_factory=list) # List of peer dicts
# Cache results to avoid hammering `tailscale` CLI on every page load
_cache = {"info": None, "ts": 0, "ttl": 15} # 15 second cache
_cache_lock = threading.Lock()
def _run_ts(args, timeout=5):
"""Run a tailscale CLI command. Returns (stdout, stderr, exit_code)."""
try:
r = subprocess.run(
["tailscale"] + args,
capture_output=True, text=True, timeout=timeout,
)
return r.stdout.strip(), r.stderr.strip(), r.returncode
except FileNotFoundError:
return "", "tailscale binary not found", -1
except subprocess.TimeoutExpired:
return "", "tailscale command timed out", -1
except Exception:
# Never return str(e): this stderr channel can surface in the /api/tailscale
# response, and an exception message is a stack-trace-exposure sink. Log it
# server-side for debugging and hand the caller a generic message instead.
_log.exception("tailscale command failed")
return "", "tailscale command failed", -1
def _run_ts_sudo(args, timeout=10):
"""Run a *privileged* tailscale command (serve/funnel/set) with sudo."""
try:
r = subprocess.run(
["sudo", "tailscale"] + args,
capture_output=True, text=True, timeout=timeout,
)
return r.stdout.strip(), r.stderr.strip(), r.returncode
except FileNotFoundError:
return "", "tailscale binary not found", -1
except subprocess.TimeoutExpired:
return "", "tailscale command timed out", -1
except Exception:
# See _run_ts: keep the raw exception text out of any caller-facing string.
_log.exception("privileged tailscale command failed")
return "", "tailscale command failed", -1
def _current_os_user():
"""The OS user the panel runs as (the one that should own Tailscale management)."""
try:
import os
import pwd
return pwd.getpwuid(os.getuid()).pw_name
except Exception:
import getpass
return getpass.getuser()
def ensure_operator():
"""Make the panel's own user the Tailscale 'operator' so `tailscale serve` config AND
`tailscale serve status` work as the panel user without root — Tailscale's recommended
fix for 'Access denied: serve config denied'. Idempotent, best-effort (needs sudo once)."""
user = _current_os_user()
if not user or user == "root":
return True, "root"
_run_ts_sudo(["set", "--operator=" + user], timeout=10)
return True, user
def allow_tailscale_ufw():
"""Best-effort: allow the Tailscale interface through UFW on the panel host, so the node
stays reachable over the tailnet. A common lockout is UFW active but tailscale0 not
allowed — then Serve/SSH over the tailnet silently can't reach the node. Idempotent."""
try:
import system_ops
return system_ops.ufw_allow_tailscale()
except Exception as e:
return False, str(e)
def _run_ts_json(args, timeout=5):
"""Run tailscale with --json flag and parse output."""
out, err, rc = _run_ts(args + ["--json"], timeout=timeout)
if rc != 0 or not out:
return None
try:
return json.loads(out)
except json.JSONDecodeError:
return None
def _get_tailscale_info() -> TailscaleInfo:
"""Internal - discover all Tailscale info by calling the CLI."""
info = TailscaleInfo()
# Check if tailscale binary exists
info.installed = _run_ts(["version"])[0] != "" or \
_run_ts(["--version"])[0] != ""
if not info.installed:
return info
# Get version
ver, _, _ = _run_ts(["version"])
info.version = ver.split("\n")[0] if ver else ""
# Get status
status = _run_ts_json(["status"])
if status:
info.backend_state = status.get("BackendState") or ""
info.running = info.backend_state == "Running"
# NOTE: `.get(key, default)` only uses the default when the key is ABSENT. When
# Tailscale is installed but not yet authenticated (BackendState "NeedsLogin",
# after `tailscale up` prints a login URL the user hasn't clicked), the JSON has
# "Peer": null / "TailscaleIPs": null / "Self": null — .get returns None, and
# None.items()/iteration then 500s the page. Coerce nulls with `or <default>`.
info.tailscale_ips = status.get("TailscaleIPs") or []
self_data = status.get("Self") or {}
if self_data:
info.hostname = self_data.get("HostName", "")
dns = self_data.get("DNSName", "")
info.dns_name = dns.rstrip(".") if dns else ""
info.accept_routes = status.get("TUN", False)
info.magic_dns_enabled = bool(info.dns_name)
# Collect peers. Trust Tailscale's own `Online` field — it is authoritative.
# (Do NOT downgrade based on LastSeen: for an online peer the last handshake
# can legitimately be many minutes old on a long-lived connection, so a
# "last seen > 2 min" heuristic wrongly marks live peers offline.)
peer_data = status.get("Peer") or {}
for peer_id, peer in peer_data.items():
ts_online = bool(peer.get("Online", False))
last_seen_str = peer.get("LastSeen", "")
info.peers.append({
"id": peer_id,
"hostname": peer.get("HostName", ""),
"dns_name": peer.get("DNSName", "").rstrip(".") if peer.get("DNSName") else "",
"ips": peer.get("TailscaleIPs", []),
"os": peer.get("OS", ""),
"online": ts_online,
"last_seen": last_seen_str,
"relay": peer.get("Relay", ""),
})
else:
# Fallback: simpler check
out, _, rc = _run_ts(["status"])
info.running = rc == 0 and "stopped" not in out.lower()
info.backend_state = "Running" if info.running else "Stopped"
# Parse hostname from status
if info.running:
for line in out.split("\n"):
if "100." in line and "@" in line:
parts = line.split()
if len(parts) >= 2:
name = parts[1].split(".")[0] if "." in parts[1] else parts[1]
info.hostname = name
break
# Get Serve status
serve_out, _, serve_rc = _run_ts(["serve", "status"])
if serve_rc == 0 and serve_out:
info.serve_config = _parse_serve_status(serve_out)
info.funnel_enabled = any(
srv.get("funnel", False) for srv in info.serve_config.get("services", [info.serve_config])
)
# Detect MagicDNS from resolveconf or tailscale
if not info.magic_dns_enabled:
try:
# Check if .ts.net resolves
if info.hostname:
test_name = f"{info.hostname}.tailscale.net"
socket.getaddrinfo(test_name, 80, socket.AF_INET)
info.magic_dns_enabled = True
except OSError:
_log.debug("name doesn't resolve → MagicDNS simply stays disabled", exc_info=True)
return info
def _parse_serve_status(text):
"""Parse `tailscale serve status` output into a structured dict."""
result = {"services": [], "raw": text}
current_url = None
current_funnel = False
current_routes = []
for line in text.split("\n"):
stripped = line.strip()
if not stripped:
continue
# Match URL line
url_match = re.match(r'^(https?://\S+)\s*(\(.*\))?$', stripped)
if url_match:
if current_url and current_routes:
result["services"].append({
"url": current_url,
"funnel": current_funnel,
"routes": current_routes,
})
current_url = url_match.group(1).rstrip(".")
current_funnel = "funnel" in (url_match.group(2) or "")
current_routes = []
continue
# Match route line
route_match = re.match(r'\|--\s+(\S+)\s+proxy\s+(\S+)', stripped)
if route_match and current_url:
current_routes.append({
"mount": route_match.group(1),
"target": route_match.group(2),
})
# Funnel-only line
if "funnel" in stripped.lower() and current_url and not current_funnel:
current_funnel = True
if current_url and current_routes:
result["services"].append({
"url": current_url,
"funnel": current_funnel,
"routes": current_routes,
})
return result
def get_tailscale_info(force_refresh=False) -> TailscaleInfo:
"""Get cached Tailscale info. Refreshes every `ttl` seconds."""
# (_cache is a module-level dict mutated in place — no `global` needed.)
now = time.time()
with _cache_lock:
if force_refresh or _cache["info"] is None or (now - _cache["ts"]) > _cache["ttl"]:
_cache["info"] = _get_tailscale_info()
_cache["ts"] = now
return _cache["info"]
def get_magic_url(port=None, protocol="https") -> Optional[str]:
"""Get the MagicDNS URL for this node, optionally with a custom port."""
info = get_tailscale_info()
if info.dns_name:
base = f"{protocol}://{info.dns_name}"
if port and port not in (443, 80):
base += f":{port}"
return base
return None
def get_tailscale_ip(version=4) -> Optional[str]:
"""Get this node's Tailscale IP."""
info = get_tailscale_info()
for ip in info.tailscale_ips:
if version == 4 and "." in ip:
return ip
if version == 6 and ":" in ip:
return ip
return info.tailscale_ips[0] if info.tailscale_ips else None
def check_peer_reachability(host) -> dict:
"""Check if a host (IP or hostname) responds on the tailnet via ping."""
reachable = False
latency_ms = 0
try:
r = subprocess.run(
["ping", "-c", "1", "-W", "3", host],
capture_output=True, text=True, timeout=5,
)
reachable = r.returncode == 0
if reachable:
m = re.search(r'time[=<]\s*(\d+\.?\d*)', r.stdout)
if m:
latency_ms = float(m.group(1))
except Exception: # nosec B110
_log.debug("ping unavailable or output unparseable — return reachable/latency as-is", exc_info=True)
return {"reachable": reachable, "latency_ms": latency_ms}
def setup_tailscale_serve(port=5000, mount="/", funnel=False, backend_scheme="http"):
"""Configure Tailscale Serve to proxy this panel.
Args:
port: Local port the panel runs on (default 5000)
mount: URL mount point (default '/')
funnel: Whether to enable Funnel (public internet access)
backend_scheme: how to reach the panel on loopback — "http" (default) or
"https+insecure" when the panel is terminating its own self-signed TLS.
Tailscale re-terminates TLS with the real ts.net cert either way; this just
has to match how the panel is actually listening or the proxy 502s.
Returns:
(success, message)
"""
upstream = f"{backend_scheme}://127.0.0.1:{port}"
verb = "funnel" if funnel else "serve"
mount = mount or "/"
# serve/funnel is privileged — make the panel user the Tailscale operator first so it
# works (and status reads back) without root. Also make sure the tailnet interface is
# allowed through UFW, or the Serve URL would be unreachable on a firewalled host.
ensure_operator()
allow_tailscale_ufw()
# Two things vary by Tailscale version/setup: (1) the CLI grammar changed — newer
# (~1.58+) takes the target as the only positional with a --set-path mount, older took
# the mount as a positional ("... 443 / URL"); (2) privilege — usually the operator set
# above is enough, but fall back to sudo if not. Try each combination and use the first
# that succeeds, so it works across Tailscale versions and permission setups.
modern = [verb, "--bg", "--https=443"]
if mount != "/":
modern.append("--set-path=" + mount)
modern.append(upstream)
legacy = [verb, "--bg", "--https", "443", mount, upstream]
err = ""
for runner in (_run_ts, _run_ts_sudo): # non-root (operator) first, then sudo
for args in (modern, legacy): # modern grammar first, then legacy
out, e, rc = runner(args, timeout=10)
if rc == 0:
with _cache_lock:
_cache["info"] = None
return True, "Tailscale Serve enabled" + (" (with Funnel)" if funnel else "")
err = e or out or err
return False, f"Failed to configure Tailscale Serve: {err or 'Unknown error'}"
def install_tailscale_local():
"""Install Tailscale on THIS host (needs sudo). Returns (success, log tail)."""
try:
r = subprocess.run(
["sudo", "bash", "-c", "curl -fsSL https://tailscale.com/install.sh | sh"],
capture_output=True, text=True, timeout=180,
)
with _cache_lock:
_cache["info"] = None
return r.returncode == 0, ((r.stdout or "") + (r.stderr or ""))[-1500:]
except Exception:
# This message is echoed back to /api/tailscale/install — keep the raw
# exception text out of the response (stack-trace-exposure); log it instead.
_log.exception("tailscale install failed")
return False, "Install failed — see panel logs for details."
def tailscale_up_local(enable_ssh=True):
"""Run `tailscale up` on THIS host detached and return the browser login URL to
paste in (mirrors the remote flow). Returns (True, url) | (True, 'ALREADY_CONNECTED')
| (False, message)."""
up = "tailscale up --accept-routes --timeout=600s"
if enable_ssh:
up += " --ssh"
cmd = (
"rm -f /tmp/tsup.log ; "
f"nohup {up} > /tmp/tsup.log 2>&1 & "
"for i in $(seq 1 20); do "
"u=$(grep -oE 'https://login\\.tailscale\\.com/[A-Za-z0-9/]+' /tmp/tsup.log | head -1) ; "
"[ -n \"$u\" ] && { echo \"$u\" ; break ; } ; "
"grep -qi 'success' /tmp/tsup.log && { echo ALREADY_CONNECTED ; break ; } ; "
"sleep 1 ; done"
)
try:
r = subprocess.run(["sudo", "bash", "-c", cmd], capture_output=True, text=True, timeout=40)
except Exception:
# Echoed back to /api/tailscale/up — no raw exception text in the response.
_log.exception("tailscale up failed")
return False, "Could not start Tailscale — see panel logs for details."
line = (r.stdout or "").strip().split("\n")[-1].strip()
if line.startswith("https://login.tailscale.com/"):
with _cache_lock:
_cache["info"] = None
return True, line
info = get_tailscale_info(force_refresh=True)
if info.running or line == "ALREADY_CONNECTED":
ensure_operator() # so the panel user can manage Serve without root afterward
allow_tailscale_ufw() # keep the node reachable over the tailnet if UFW is active
return True, "ALREADY_CONNECTED"
return False, (r.stderr or r.stdout or "Could not get a login link — is Tailscale installed on this host?")
def disable_tailscale_serve(mount="/"):
"""Remove a Tailscale Serve/Funnel mapping."""
out, err, rc = _run_ts(
["serve", "--bg", "--remove", mount],
timeout=10,
)
if rc == 0:
with _cache_lock:
_cache["info"] = None
return True, "Tailscale Serve mapping removed"
return False, f"Failed to remove: {err or out}"
def is_tailscale_ip(host):
"""Check if a host/IP looks like a Tailscale address."""
if not host:
return False
if host.startswith("100.") or host.startswith("fd7a:"):
return True
if host.endswith(".ts.net") or ".taile" in host:
return True
return False
def suggest_best_bind(port=5000):
"""Suggest the best way to expose the panel based on what's available.
Returns a dict with keys:
- method: "tailscale-serve", "tailscale-direct", "direct"
- bind_host: recommended bind address
- url: URL the user can reach it at
- description: human-readable explanation
"""
info = get_tailscale_info()
if info.running and info.dns_name and info.serve_config.get("services"):
# Serve is ACTUALLY proxying the panel — bind to localhost and reach it via the ts.net cert.
# (We must confirm Serve is configured, not just that Tailscale is up with a MagicDNS name —
# otherwise a fresh Tailscale-enabled install would bind loopback with nothing proxying to it
# and be unreachable.)
url = f"https://{info.dns_name}"
return {
"method": "tailscale-serve",
"bind_host": "127.0.0.1",
"port": port,
"url": url,
"description": f"Bind to localhost and expose via Tailscale Serve at {url}",
}
elif info.running and info.tailscale_ips:
# Tailscale running but no MagicDNS
ts_ip = get_tailscale_ip(4)
return {
"method": "tailscale-direct",
"bind_host": ts_ip or "0.0.0.0",
"port": port,
"url": f"http://{ts_ip}:{port}" if ts_ip else f"http://<tailscale-ip>:{port}",
"description": f"Bind to Tailscale IP {ts_ip} and access directly",
}
elif info.installed and info.backend_state == "NeedsLogin":
# Installed but never authorized — the recommendation is to finish linking, not to
# open the panel to all interfaces.
return {
"method": "direct",
"bind_host": "0.0.0.0",
"port": port,
"url": f"http://<your-server-ip>:{port}",
"description": ("Tailscale is installed but not linked yet. Link this machine above "
"to reach the panel privately over your tailnet."),
}
else:
return {
"method": "direct",
"bind_host": "0.0.0.0",
"port": port,
"url": f"http://<your-server-ip>:{port}",
"description": "No Tailscale detected. Bind to all interfaces.",
}
# ─── Remote VPS Connectivity via Tailscale ─────────────────────
def check_remote_via_tailscale(remote_server):
"""Check if a RemoteServer is reachable via Tailscale.
Uses the host as-is if it's already a Tailscale IP, otherwise
tries to resolve via MagicDNS and peers.
"""
host = remote_server.host
info = get_tailscale_info()
# Try direct ping
reachable = check_peer_reachability(host)
# If not reachable, check peer list for the hostname
if not reachable["reachable"]:
for peer in info.peers:
if peer["hostname"] == host or host in peer["dns_name"]:
# Found as a peer - try their Tailscale IP
for ip in peer["ips"]:
p = check_peer_reachability(ip)
if p["reachable"]:
return {
"reachable": True,
"latency_ms": p["latency_ms"],
"via": "tailscale_ip",
"ip": ip,
"hostname": peer["dns_name"],
}
if peer["online"]:
return {
"reachable": True,
"latency_ms": -1,
"via": "tailscale_peer",
"ip": peer["ips"][0] if peer["ips"] else host,
"hostname": peer["dns_name"],
}
return {
"reachable": reachable["reachable"],
"latency_ms": reachable["latency_ms"],
"via": "direct" if reachable["reachable"] else "unreachable",
"ip": host,
"hostname": host,
}