209 lines
7.2 KiB
Python
209 lines
7.2 KiB
Python
"""LD FDPI one-time, device-bound enrollment agent.
|
|
|
|
Run as a host systemd service (not inside the public FastAPI container) so it
|
|
can call `docker exec` without exposing the Docker socket to the web app.
|
|
|
|
Environment:
|
|
LD_FDPI_ENROLL_DB default /opt/ld-fdpi-enroll/enroll.db
|
|
LD_FDPI_AWG_CONTAINER default amnezia-awg2
|
|
LD_FDPI_SERVER_PUB AmneziaWG server public key (base64)
|
|
LD_FDPI_ENDPOINT default 116.202.14.171:42771
|
|
LD_FDPI_AWG_PARAMS_JSON optional JSON object with jc/jmin/... fields
|
|
LD_FDPI_ADMIN_TOKEN token that can mint enrollment codes via /admin/token
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import base64
|
|
import hashlib
|
|
import hmac
|
|
import json
|
|
import os
|
|
import re
|
|
import secrets
|
|
import sqlite3
|
|
import subprocess
|
|
from datetime import datetime, timezone
|
|
|
|
from fastapi import FastAPI, Header, HTTPException
|
|
from pydantic import BaseModel, Field
|
|
|
|
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")
|
|
ADMIN_TOKEN = os.environ.get("LD_FDPI_ADMIN_TOKEN", "")
|
|
AWG = json.loads(os.environ.get("LD_FDPI_AWG_PARAMS_JSON", "{}"))
|
|
PUBKEY_RE = re.compile(r"^[A-Za-z0-9+/]{42}[AEIMQUYcgkosw048]=$")
|
|
DEVICE_RE = re.compile(r"^[a-f0-9]{64}$")
|
|
|
|
app = FastAPI(title="LD FDPI enrollment", docs_url=None, redoc_url=None)
|
|
|
|
|
|
def db() -> sqlite3.Connection:
|
|
conn = sqlite3.connect(DB, timeout=10, isolation_level=None)
|
|
conn.execute("PRAGMA journal_mode=WAL")
|
|
conn.execute("PRAGMA busy_timeout=10000")
|
|
conn.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
|
|
)"""
|
|
)
|
|
conn.execute(
|
|
"""CREATE TABLE IF NOT EXISTS rate (
|
|
bucket TEXT PRIMARY KEY,
|
|
ts INTEGER NOT NULL,
|
|
count INTEGER NOT NULL
|
|
)"""
|
|
)
|
|
return conn
|
|
|
|
|
|
def token_hash(token: str) -> str:
|
|
return hashlib.sha256(token.encode()).hexdigest()
|
|
|
|
|
|
def check_rate(conn: sqlite3.Connection, bucket: str) -> None:
|
|
now = int(datetime.now(timezone.utc).timestamp())
|
|
row = conn.execute("SELECT ts, count FROM rate WHERE bucket=?", (bucket,)).fetchone()
|
|
if not row or now - row[0] > 60:
|
|
conn.execute("INSERT OR REPLACE INTO rate(bucket, ts, count) VALUES(?,?,1)", (bucket, now))
|
|
return
|
|
if row[1] >= 5:
|
|
raise HTTPException(429, "rate limit")
|
|
conn.execute("UPDATE rate SET count=count+1 WHERE bucket=?", (bucket,))
|
|
|
|
|
|
def allocate_ip(conn: sqlite3.Connection) -> str:
|
|
used = {
|
|
row[0]
|
|
for row in conn.execute("SELECT allocated_ip FROM tokens WHERE allocated_ip IS NOT NULL")
|
|
}
|
|
for i in range(20, 251):
|
|
ip = f"10.8.1.{i}"
|
|
if ip not in used:
|
|
return ip
|
|
raise HTTPException(503, "IP pool exhausted")
|
|
|
|
|
|
def awg_set(public_key: str, ip: str, psk: str) -> None:
|
|
script = (
|
|
"umask 077; cat > /tmp/ld-fdpi.psk; "
|
|
f"awg set awg0 peer {public_key} preshared-key /tmp/ld-fdpi.psk allowed-ips {ip}/32; "
|
|
f"printf '\\n[Peer]\\nPublicKey = {public_key}\\nPresharedKey = %s\\nAllowedIPs = {ip}/32\\n' "
|
|
'"$(cat /tmp/ld-fdpi.psk)" >> ' + CONF + "; rm -f /tmp/ld-fdpi.psk"
|
|
)
|
|
subprocess.run(
|
|
["docker", "exec", "-i", CONTAINER, "sh", "-c", script],
|
|
input=psk.encode(),
|
|
check=True,
|
|
)
|
|
|
|
|
|
class Enroll(BaseModel):
|
|
public_key: str = Field(min_length=44, max_length=44)
|
|
client_version: str = Field(max_length=32)
|
|
device_id: str = Field(min_length=64, max_length=64)
|
|
|
|
|
|
@app.post("/api/v1/enroll")
|
|
def enroll(req: Enroll, authorization: str = Header(default="")):
|
|
token = authorization.removeprefix("Bearer ").strip()
|
|
if not token or not PUBKEY_RE.match(req.public_key) or not DEVICE_RE.match(req.device_id):
|
|
raise HTTPException(400, "invalid request")
|
|
|
|
base64.b64decode(req.public_key, validate=True)
|
|
th = token_hash(token)
|
|
conn = db()
|
|
try:
|
|
conn.execute("BEGIN IMMEDIATE")
|
|
check_rate(conn, th)
|
|
row = conn.execute(
|
|
"SELECT used_by_device, allocated_ip, public_key, psk FROM tokens WHERE token_hash=?",
|
|
(th,),
|
|
).fetchone()
|
|
if not row:
|
|
raise HTTPException(401, "invalid token")
|
|
|
|
used_by, ip, old_pub, psk = row
|
|
if used_by is not None and used_by != req.device_id:
|
|
raise HTTPException(409, "token already used on another device")
|
|
|
|
if used_by == req.device_id and ip and psk:
|
|
# Idempotent re-install: same device gets the same IP/PSK.
|
|
if old_pub and old_pub != req.public_key:
|
|
subprocess.run(
|
|
["docker", "exec", CONTAINER, "awg", "set", "awg0", "peer", old_pub, "remove"],
|
|
check=False,
|
|
)
|
|
psk = base64.b64encode(secrets.token_bytes(32)).decode()
|
|
awg_set(req.public_key, ip, psk)
|
|
else:
|
|
ip = allocate_ip(conn)
|
|
psk = base64.b64encode(secrets.token_bytes(32)).decode()
|
|
awg_set(req.public_key, ip, psk)
|
|
|
|
conn.execute(
|
|
"UPDATE tokens SET used_by_device=?, allocated_ip=?, public_key=?, psk=?, used_at=? "
|
|
"WHERE token_hash=?",
|
|
(req.device_id, ip, req.public_key, psk, datetime.now(timezone.utc).isoformat(), th),
|
|
)
|
|
conn.execute("COMMIT")
|
|
except HTTPException:
|
|
conn.execute("ROLLBACK")
|
|
raise
|
|
except Exception as exc:
|
|
conn.execute("ROLLBACK")
|
|
raise HTTPException(500, "enrollment failed") from exc
|
|
finally:
|
|
conn.close()
|
|
|
|
return {
|
|
"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,
|
|
},
|
|
}
|
|
|
|
|
|
class TokenRequest(BaseModel):
|
|
note: str = ""
|
|
|
|
|
|
@app.post("/admin/token")
|
|
def mint_token(req: TokenRequest, authorization: str = Header(default="")):
|
|
if not ADMIN_TOKEN or not hmac.compare_digest(
|
|
authorization.removeprefix("Bearer ").strip(), ADMIN_TOKEN
|
|
):
|
|
raise HTTPException(401, "unauthorized")
|
|
token = "LDFDPI-" + "-".join(
|
|
"".join(secrets.choice("ABCDEFGHJKLMNPQRSTUVWXYZ23456789") for _ in range(4))
|
|
for _ in range(3)
|
|
)
|
|
conn = db()
|
|
try:
|
|
conn.execute(
|
|
"INSERT INTO tokens(token_hash) VALUES(?)",
|
|
(token_hash(token),),
|
|
)
|
|
finally:
|
|
conn.close()
|
|
return {"token": token, "note": req.note}
|