398 lines
15 KiB
Python
398 lines
15 KiB
Python
#!/usr/bin/env python3
|
|
"""Dependency-free LD FDPI enrollment agent (host, Docker access only locally)."""
|
|
import base64, hashlib, hmac, json, os, re, secrets, sqlite3, subprocess, sys
|
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
from datetime import datetime, timezone
|
|
|
|
DB = os.environ.get("LD_FDPI_ENROLL_DB", "/opt/ld-fdpi-enroll/enroll.db")
|
|
CONTAINER = os.environ.get("LD_FDPI_AWG_CONTAINER", "amnezia-awg2")
|
|
CONF = os.environ.get("LD_FDPI_AWG_CONF", "/opt/amnezia/awg/awg0.conf")
|
|
SERVER_PUB = os.environ["LD_FDPI_SERVER_PUB"]
|
|
ENDPOINT = os.environ.get("LD_FDPI_ENDPOINT", "116.202.14.171:42771")
|
|
APP_SECRET = os.environ.get("LD_FDPI_APP_SECRET", "")
|
|
AWG_JSON = os.environ.get("LD_FDPI_AWG_PARAMS_FILE", "/opt/ld-fdpi-enroll/awg.json")
|
|
try:
|
|
with open(AWG_JSON, encoding="utf-8") as fh:
|
|
AWG = json.load(fh)
|
|
except Exception:
|
|
AWG = {}
|
|
PUBKEY_RE = re.compile(r"^[A-Za-z0-9+/]{42}[AEIMQUYcgkosw048]=$")
|
|
DEVICE_RE = re.compile(r"^[a-f0-9]{64}$")
|
|
|
|
|
|
def conn():
|
|
c = sqlite3.connect(DB, timeout=10, isolation_level=None)
|
|
c.execute("PRAGMA journal_mode=WAL")
|
|
c.execute("PRAGMA busy_timeout=10000")
|
|
c.execute("""CREATE TABLE IF NOT EXISTS tokens (
|
|
token_hash TEXT PRIMARY KEY, used_by_device TEXT, allocated_ip TEXT,
|
|
public_key TEXT, psk TEXT, used_at TEXT)""")
|
|
c.execute("""CREATE TABLE IF NOT EXISTS devices (
|
|
device_id TEXT PRIMARY KEY, allocated_ip TEXT UNIQUE, public_key TEXT UNIQUE,
|
|
psk TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL)""")
|
|
c.execute("""CREATE TABLE IF NOT EXISTS rate (
|
|
bucket TEXT PRIMARY KEY, ts INTEGER NOT NULL, count INTEGER NOT NULL)""")
|
|
return c
|
|
|
|
|
|
def th(token):
|
|
return hashlib.sha256(token.encode()).hexdigest()
|
|
|
|
|
|
def rate(c, bucket, limit=5):
|
|
now = int(datetime.now(timezone.utc).timestamp())
|
|
row = c.execute("SELECT ts,count FROM rate WHERE bucket=?", (bucket,)).fetchone()
|
|
if not row or now - row[0] > 60:
|
|
c.execute("INSERT OR REPLACE INTO rate VALUES(?,?,1)", (bucket, now))
|
|
elif row[1] >= limit:
|
|
raise ValueError("rate")
|
|
else:
|
|
c.execute("UPDATE rate SET count=count+1 WHERE bucket=?", (bucket,))
|
|
|
|
|
|
def ensure_pool_route():
|
|
"""Keep the expanded pool routed through awg0 after container restarts."""
|
|
subprocess.run(
|
|
["docker", "exec", CONTAINER, "ip", "route", "replace",
|
|
"10.8.0.0/16", "dev", "awg0"],
|
|
check=False,
|
|
)
|
|
|
|
|
|
def candidate_ips():
|
|
for i in range(20, 255):
|
|
yield f"10.8.1.{i}"
|
|
for third in range(2, 255):
|
|
for fourth in range(2, 255):
|
|
yield f"10.8.{third}.{fourth}"
|
|
|
|
|
|
def ip_alloc(c, evict=False):
|
|
def used_ips():
|
|
return {r[0] for r in c.execute(
|
|
"SELECT allocated_ip FROM devices WHERE allocated_ip IS NOT NULL "
|
|
"UNION SELECT allocated_ip FROM tokens WHERE allocated_ip IS NOT NULL"
|
|
)}
|
|
|
|
used = used_ips()
|
|
for ip in candidate_ips():
|
|
if ip not in used:
|
|
if not ip.startswith("10.8.1."):
|
|
ensure_pool_route()
|
|
return ip
|
|
if evict:
|
|
evicted = evict_inactive(c)
|
|
if evicted:
|
|
used = used_ips()
|
|
for ip in candidate_ips():
|
|
if ip not in used:
|
|
if not ip.startswith("10.8.1."):
|
|
ensure_pool_route()
|
|
return ip
|
|
raise ValueError("pool")
|
|
|
|
|
|
def awg_handshakes():
|
|
result = subprocess.run(
|
|
["docker", "exec", CONTAINER, "awg", "show", "awg0", "latest-handshakes"],
|
|
capture_output=True, text=True, check=False,
|
|
)
|
|
if result.returncode != 0:
|
|
return None
|
|
handshakes = {}
|
|
for line in result.stdout.splitlines():
|
|
parts = line.split()
|
|
if len(parts) >= 2 and parts[1].isdigit():
|
|
handshakes[parts[0]] = int(parts[1])
|
|
return handshakes
|
|
|
|
|
|
def evict_inactive(c):
|
|
"""Free one IP from a peer with no handshake for 30+ days."""
|
|
handshakes = awg_handshakes()
|
|
if handshakes is None:
|
|
return False
|
|
cutoff = int(datetime.now(timezone.utc).timestamp()) - 30 * 24 * 3600
|
|
rows = list(c.execute(
|
|
"SELECT device_id, public_key, allocated_ip, updated_at FROM devices"
|
|
))
|
|
candidates = []
|
|
for device, pub, ip, updated in rows:
|
|
last = handshakes.get(pub, 0)
|
|
if last == 0 or last < cutoff:
|
|
candidates.append((last, updated or "", device, pub, ip))
|
|
candidates.sort()
|
|
for last, _updated, device, pub, ip in candidates:
|
|
subprocess.run(
|
|
["docker", "exec", CONTAINER, "awg", "set", "awg0", "peer", pub, "remove"],
|
|
check=False,
|
|
)
|
|
awg_remove_conf(pub)
|
|
c.execute("DELETE FROM devices WHERE device_id=?", (device,))
|
|
print(f"evicted inactive peer device={device[:8]} ip={ip} last={last}", file=sys.stderr)
|
|
return True
|
|
return False
|
|
|
|
|
|
def awg_remove_conf(pub):
|
|
"""Drop a rotated peer block so a container restart cannot revive it."""
|
|
script = (
|
|
f"awk -v pub='{pub}' '"
|
|
"/^\\[Peer\\]$/ { inpeer=1; block=$0 \"\\n\"; next } "
|
|
"inpeer { block=block $0 \"\\n\"; "
|
|
"if ($0 ~ /^AllowedIPs[[:space:]]*=/) { "
|
|
"if (index(block, \"PublicKey = \" pub) == 0) printf \"%s\", block; "
|
|
"inpeer=0; block=\"\" } next } "
|
|
"{ print } END { if (inpeer) printf \"%s\", block }' "
|
|
f"{CONF} > {CONF}.tmp && mv {CONF}.tmp {CONF}"
|
|
)
|
|
subprocess.run(["docker", "exec", CONTAINER, "sh", "-c", script], check=False)
|
|
|
|
|
|
def awg_set(pub, ip, psk, persist=True):
|
|
append = ""
|
|
if persist:
|
|
append = (
|
|
f"printf '\\n[Peer]\\nPublicKey = {pub}\\nPresharedKey = ' >> {CONF}; "
|
|
f"cat /tmp/ld-fdpi.psk >> {CONF}; "
|
|
f"printf '\\nAllowedIPs = {ip}/32\\n' >> {CONF}; "
|
|
)
|
|
script = (
|
|
"umask 077; cat > /tmp/ld-fdpi.psk; "
|
|
f"awg set awg0 peer {pub} preshared-key /tmp/ld-fdpi.psk allowed-ips {ip}/32; "
|
|
+ append +
|
|
"rm -f /tmp/ld-fdpi.psk"
|
|
)
|
|
subprocess.run(["docker", "exec", "-i", CONTAINER, "sh", "-c", script],
|
|
input=psk.encode(), check=True)
|
|
|
|
|
|
def legacy_enrollment(pub, device):
|
|
c = conn()
|
|
try:
|
|
c.execute("BEGIN IMMEDIATE")
|
|
row = c.execute("SELECT used_by_device,allocated_ip,public_key,psk FROM tokens WHERE used_by_device=?",
|
|
(device,)).fetchone()
|
|
if not row:
|
|
raise ValueError("unauthorized")
|
|
used, ip, old_pub, psk = row
|
|
if old_pub == pub:
|
|
c.execute("COMMIT")
|
|
return ip, psk
|
|
token = c.execute("SELECT token_hash FROM tokens WHERE used_by_device=?", (device,)).fetchone()[0]
|
|
if old_pub:
|
|
subprocess.run(["docker", "exec", CONTAINER, "awg", "set", "awg0", "peer", old_pub, "remove"], check=False)
|
|
awg_remove_conf(old_pub)
|
|
psk = base64.b64encode(secrets.token_bytes(32)).decode()
|
|
awg_set(pub, ip, psk)
|
|
c.execute("UPDATE tokens SET public_key=?,psk=?,used_at=? WHERE token_hash=?",
|
|
(pub, psk, datetime.now(timezone.utc).isoformat(), token))
|
|
c.execute("COMMIT")
|
|
return ip, psk
|
|
finally:
|
|
c.close()
|
|
|
|
|
|
def auto_enrollment(pub, device):
|
|
"""Idempotent per-device enrollment. Same key returns the same peer/IP."""
|
|
c = conn()
|
|
try:
|
|
c.execute("BEGIN IMMEDIATE")
|
|
row = c.execute("SELECT allocated_ip,public_key,psk FROM devices WHERE device_id=?",
|
|
(device,)).fetchone()
|
|
if row:
|
|
ip, old_pub, psk = row
|
|
if old_pub == pub:
|
|
# Idempotent retry: re-apply the peer, because it may have been
|
|
# removed from the container while the DB record remained.
|
|
awg_set(pub, ip, psk, persist=False)
|
|
c.execute("COMMIT")
|
|
return ip, psk
|
|
other = c.execute("SELECT device_id FROM devices WHERE public_key=? AND device_id<>?",
|
|
(pub, device)).fetchone()
|
|
if other:
|
|
c.execute("ROLLBACK")
|
|
raise ValueError("key-in-use")
|
|
if old_pub:
|
|
subprocess.run(["docker", "exec", CONTAINER, "awg", "set", "awg0", "peer", old_pub, "remove"], check=False)
|
|
awg_remove_conf(old_pub)
|
|
psk = base64.b64encode(secrets.token_bytes(32)).decode()
|
|
awg_set(pub, ip, psk, persist=True)
|
|
c.execute("UPDATE devices SET public_key=?,psk=?,updated_at=? WHERE device_id=?",
|
|
(pub, psk, datetime.now(timezone.utc).isoformat(), device))
|
|
c.execute("COMMIT")
|
|
return ip, psk
|
|
|
|
other = c.execute("SELECT device_id FROM devices WHERE public_key=?", (pub,)).fetchone()
|
|
if other:
|
|
c.execute("ROLLBACK")
|
|
raise ValueError("key-in-use")
|
|
ip = ip_alloc(c, evict=True)
|
|
psk = base64.b64encode(secrets.token_bytes(32)).decode()
|
|
awg_set(pub, ip, psk, persist=True)
|
|
now = datetime.now(timezone.utc).isoformat()
|
|
c.execute("INSERT INTO devices(device_id,allocated_ip,public_key,psk,created_at,updated_at) "
|
|
"VALUES(?,?,?,?,?,?)", (device, ip, pub, psk, now, now))
|
|
c.execute("COMMIT")
|
|
return ip, psk
|
|
except Exception:
|
|
try:
|
|
c.execute("ROLLBACK")
|
|
except Exception:
|
|
pass
|
|
raise
|
|
finally:
|
|
c.close()
|
|
|
|
|
|
def response_for(ip, psk):
|
|
return 200, {
|
|
"address": f"{ip}/32",
|
|
"dns": ["1.1.1.1", "1.0.0.1"],
|
|
"server_public_key": SERVER_PUB,
|
|
"preshared_key": psk,
|
|
"endpoint": ENDPOINT,
|
|
"allowed_ips": ["0.0.0.0/0", "::/0"],
|
|
"awg": {
|
|
"jc": 5, "jmin": 10, "jmax": 50,
|
|
"s1": 12, "s2": 12, "s3": 12, "s4": 12,
|
|
"h1": 1, "h2": 2, "h3": 3, "h4": 4,
|
|
"header_protection_key": AWG.get("header_protection_key", ""),
|
|
"rekey_after_time": "100-120", "rekey_timeout": "3-7",
|
|
"reject_after_time": "150-180", "keepalive_timeout": "5-15",
|
|
"max_handshake_attempts": "15-20",
|
|
"random_trailers": True, "disable_cookies": True,
|
|
},
|
|
}
|
|
|
|
|
|
def parse_request(handler):
|
|
length = int(handler.headers.get("Content-Length", "0"))
|
|
if length <= 0 or length > 8192:
|
|
raise ValueError("bad request")
|
|
body = json.loads(handler.rfile.read(length))
|
|
pub = str(body.get("public_key", ""))
|
|
device = str(body.get("device_id", ""))
|
|
if not PUBKEY_RE.match(pub) or not DEVICE_RE.match(device):
|
|
raise ValueError("invalid key/device")
|
|
base64.b64decode(pub, validate=True)
|
|
return pub, device
|
|
|
|
|
|
def handle_enroll(handler):
|
|
try:
|
|
pub, device = parse_request(handler)
|
|
except Exception:
|
|
return 400, {"error": "bad request"}
|
|
token = handler.headers.get("Authorization", "").removeprefix("Bearer ").strip()
|
|
if not token:
|
|
return 401, {"error": "missing token"}
|
|
c = conn()
|
|
try:
|
|
c.execute("BEGIN IMMEDIATE")
|
|
rate(c, th(token))
|
|
row = c.execute("SELECT used_by_device,allocated_ip,public_key,psk FROM tokens WHERE token_hash=?",
|
|
(th(token),)).fetchone()
|
|
if not row:
|
|
c.execute("ROLLBACK")
|
|
return 401, {"error": "invalid token"}
|
|
used, ip, old_pub, psk = row
|
|
if used is not None and used != device:
|
|
c.execute("ROLLBACK")
|
|
return 409, {"error": "token used on another device"}
|
|
if used == device and ip and psk:
|
|
if old_pub and old_pub != pub:
|
|
subprocess.run(["docker", "exec", CONTAINER, "awg", "set", "awg0", "peer", old_pub, "remove"], check=False)
|
|
psk = base64.b64encode(secrets.token_bytes(32)).decode()
|
|
awg_set(pub, ip, psk)
|
|
else:
|
|
ip = ip_alloc(c)
|
|
psk = base64.b64encode(secrets.token_bytes(32)).decode()
|
|
awg_set(pub, ip, psk)
|
|
c.execute("UPDATE tokens SET used_by_device=?,allocated_ip=?,public_key=?,psk=?,used_at=? WHERE token_hash=?",
|
|
(device, ip, pub, psk, datetime.now(timezone.utc).isoformat(), th(token)))
|
|
c.execute("COMMIT")
|
|
except ValueError as e:
|
|
c.execute("ROLLBACK")
|
|
return (429 if str(e) == "rate" else 401), {"error": str(e)}
|
|
except Exception:
|
|
c.execute("ROLLBACK")
|
|
return 500, {"error": "enrollment failed"}
|
|
finally:
|
|
c.close()
|
|
return response_for(ip, psk)
|
|
|
|
|
|
def handle_auto_enroll(handler):
|
|
if not APP_SECRET:
|
|
return 503, {"error": "auto-enroll disabled"}
|
|
if not hmac.compare_digest(handler.headers.get("X-App-Secret", ""), APP_SECRET):
|
|
return 401, {"error": "unauthorized"}
|
|
try:
|
|
pub, device = parse_request(handler)
|
|
except Exception:
|
|
return 400, {"error": "bad request"}
|
|
ip_hint = (handler.headers.get("X-Real-IP") or handler.headers.get("CF-Connecting-IP")
|
|
or handler.client_address[0])
|
|
c = conn()
|
|
try:
|
|
c.execute("BEGIN IMMEDIATE")
|
|
rate(c, "ip:" + ip_hint, 20)
|
|
rate(c, "dev:" + ip_hint + ":" + device, 5)
|
|
c.execute("COMMIT")
|
|
except ValueError as e:
|
|
c.execute("ROLLBACK")
|
|
return (429 if str(e) == "rate" else 400), {"error": str(e)}
|
|
except Exception:
|
|
c.execute("ROLLBACK")
|
|
return 500, {"error": "enrollment failed"}
|
|
finally:
|
|
c.close()
|
|
try:
|
|
ip, psk = auto_enrollment(pub, device)
|
|
except ValueError as e:
|
|
if str(e) == "pool":
|
|
return 503, {"error": "pool exhausted"}
|
|
if str(e) == "key-in-use":
|
|
return 409, {"error": "public key already enrolled"}
|
|
return 400, {"error": str(e)}
|
|
except Exception:
|
|
return 502, {"error": "peer setup failed"}
|
|
return response_for(ip, psk)
|
|
|
|
|
|
class Handler(BaseHTTPRequestHandler):
|
|
def log_message(self, fmt, *args):
|
|
sys.stderr.write("enroll: " + fmt % args + "\n")
|
|
|
|
def do_POST(self):
|
|
if self.path == "/api/v1/enroll":
|
|
code, payload = handle_enroll(self)
|
|
elif self.path == "/api/v1/auto-enroll":
|
|
code, payload = handle_auto_enroll(self)
|
|
else:
|
|
code, payload = 404, {"error": "not found"}
|
|
self.reply(code, payload)
|
|
|
|
def reply(self, code, payload):
|
|
data = json.dumps(payload).encode()
|
|
self.send_response(code)
|
|
self.send_header("Content-Type", "application/json")
|
|
self.send_header("Content-Length", str(len(data)))
|
|
self.end_headers()
|
|
self.wfile.write(data)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
if len(sys.argv) > 1 and sys.argv[1] == "--mint":
|
|
token = "LDFDPI-" + "-".join(
|
|
"".join(secrets.choice("ABCDEFGHJKLMNPQRSTUVWXYZ23456789") for _ in range(4))
|
|
for _ in range(3)
|
|
)
|
|
c = conn()
|
|
c.execute("INSERT INTO tokens(token_hash) VALUES(?)", (th(token),))
|
|
c.close()
|
|
print(token)
|
|
raise SystemExit(0)
|
|
ensure_pool_route()
|
|
ThreadingHTTPServer(("172.17.0.1", 9471), Handler).serve_forever()
|