223 lines
9.5 KiB
Python
223 lines
9.5 KiB
Python
#!/usr/bin/env python3
|
||
"""Download a restricted Homegate SSH config. Requires Python 3.9+, no packages."""
|
||
import argparse
|
||
import ipaddress
|
||
import os
|
||
from pathlib import Path
|
||
import re
|
||
import ssl
|
||
import sys
|
||
import tempfile
|
||
import time
|
||
from urllib.parse import urlsplit
|
||
from urllib.request import build_opener, ProxyHandler, HTTPSHandler, HTTPRedirectHandler
|
||
|
||
MAX_BYTES = 512 * 1024
|
||
HEADER = "# Homegate SSH config v1"
|
||
BEGIN = "# BEGIN HOMEGATE INCLUDE"
|
||
END = "# END HOMEGATE INCLUDE"
|
||
ALIAS = re.compile(r"[a-z0-9][a-z0-9_.-]{0,252}$")
|
||
USER = re.compile(r"[A-Za-z0-9_][A-Za-z0-9_.@-]{0,63}$")
|
||
PRIVATE = [ipaddress.ip_network(n) for n in
|
||
("10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "fc00::/7")]
|
||
|
||
|
||
def check(ok, message):
|
||
if not ok:
|
||
raise ValueError(message)
|
||
|
||
|
||
def validate_entry(entry):
|
||
check(isinstance(entry, dict) and not set(entry) - {"aliases", "host", "port", "user"},
|
||
"Unknown SSH field")
|
||
aliases = entry.get("aliases")
|
||
check(isinstance(aliases, list) and 0 < len(aliases) <= 16, "SSH aliases must contain 1–16 names")
|
||
for alias in aliases:
|
||
check(isinstance(alias, str) and ALIAS.fullmatch(alias), "SSH aliases must be literal names; no patterns or tokens")
|
||
try:
|
||
ipaddress.ip_address(alias)
|
||
except ValueError:
|
||
pass
|
||
else:
|
||
raise ValueError("Use an SSH alias, not an IP address, in Host")
|
||
check(len(set(aliases)) == len(aliases), "Duplicate SSH alias")
|
||
check(isinstance(entry.get("host"), str), "SSH HostName must be an IP string")
|
||
address = ipaddress.ip_address(entry["host"])
|
||
check(address.version != 6 or address.scope_id is None, "Scoped IPv6 and SSH percent tokens are not allowed")
|
||
check(any(address.version == net.version and address in net for net in PRIVATE),
|
||
"SSH HostName must be an RFC1918 or ULA address")
|
||
check(type(entry.get("port")) is int and 1 <= entry["port"] <= 65535, "Invalid SSH port")
|
||
if "user" in entry:
|
||
check(isinstance(entry["user"], str) and USER.fullmatch(entry["user"]), "Invalid SSH user")
|
||
return entry
|
||
|
||
|
||
def render_ssh(entries):
|
||
check(isinstance(entries, list) and len(entries) <= 1024, "Too many SSH hosts")
|
||
lines = [HEADER, "# Public connection metadata only. Private keys stay on this computer.", ""]
|
||
seen = set()
|
||
for entry in entries:
|
||
validate_entry(entry)
|
||
check(not seen.intersection(entry["aliases"]), "SSH aliases must be unique across all hosts")
|
||
seen.update(entry["aliases"])
|
||
lines += ["Host " + " ".join(entry["aliases"]), " HostName " + entry["host"],
|
||
" Port " + str(entry["port"])]
|
||
if "user" in entry:
|
||
lines.append(" User " + entry["user"])
|
||
lines += [" StrictHostKeyChecking ask", ""]
|
||
# Do not leave an included file in its final host's conditional scope.
|
||
lines += ["Host *", ""]
|
||
result = "\n".join(lines)
|
||
check(len(result.encode()) <= MAX_BYTES, "SSH config exceeds size limit")
|
||
return result
|
||
|
||
|
||
def validate_download(raw):
|
||
"""Never pass arbitrary downloaded SSH directives to ssh (Match exec can execute)."""
|
||
check(len(raw) <= MAX_BYTES, "SSH config exceeds size limit")
|
||
text = raw.decode("ascii").replace("\r\n", "\n")
|
||
check(all(c == "\n" or c == "\t" or 32 <= ord(c) < 127 for c in text), "Control characters in SSH config")
|
||
check(text.splitlines()[:1] == [HEADER], "Not a Homegate SSH config")
|
||
entries, current, fields = [], None, set()
|
||
finished = False
|
||
|
||
def flush():
|
||
if current is not None:
|
||
check({"hostname", "port", "stricthostkeychecking"}.issubset(fields), "Incomplete SSH host")
|
||
validate_entry(current)
|
||
entries.append(current)
|
||
|
||
for line in text.splitlines()[1:]:
|
||
line = line.strip()
|
||
if not line or line.startswith("#"):
|
||
continue
|
||
check(not finished, "Directives after final Host * are forbidden")
|
||
parts = line.split()
|
||
directive, values = parts[0].lower(), parts[1:]
|
||
if directive == "host":
|
||
flush()
|
||
current, fields = None, set()
|
||
if values == ["*"]:
|
||
finished = True
|
||
else:
|
||
current = {"aliases": values}
|
||
continue
|
||
check(current is not None, "Global directives are forbidden")
|
||
check(directive in {"hostname", "port", "user", "stricthostkeychecking"},
|
||
"Forbidden SSH directive: " + directive)
|
||
check(directive not in fields and len(values) == 1, "Duplicate directive or unexpected arguments")
|
||
fields.add(directive)
|
||
value = values[0]
|
||
if directive == "hostname":
|
||
current["host"] = value
|
||
elif directive == "port":
|
||
check(value.isascii() and value.isdecimal(), "Invalid SSH port")
|
||
current["port"] = int(value)
|
||
elif directive == "user":
|
||
current["user"] = value
|
||
else:
|
||
check(value == "ask", "Host key verification must remain enabled")
|
||
check(finished, "Missing final Host *")
|
||
# Rebuild from validated values; don't install source text from the network.
|
||
return render_ssh(entries)
|
||
|
||
|
||
class NoRedirect(HTTPRedirectHandler):
|
||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||
raise ValueError("Redirects are refused; provide the final /ssh-config URL")
|
||
|
||
|
||
def download(url, ca_file=None):
|
||
parsed = urlsplit(url)
|
||
check(parsed.scheme in ("http", "https") and parsed.hostname and not parsed.username
|
||
and not parsed.password and not parsed.fragment, "Use an HTTP(S) URL without credentials")
|
||
context = ssl.create_default_context(cafile=ca_file)
|
||
# Ignore HTTP(S)_PROXY for LAN fetches. HTTPS verification cannot be disabled.
|
||
opener = build_opener(ProxyHandler({}), HTTPSHandler(context=context), NoRedirect())
|
||
with opener.open(url, timeout=15) as response:
|
||
check(response.status == 200, "Server did not return HTTP 200")
|
||
raw = response.read(MAX_BYTES + 1)
|
||
return validate_download(raw)
|
||
|
||
|
||
def atomic_write(path, data):
|
||
check(not path.is_symlink(), "Refusing to overwrite a symlink: " + str(path))
|
||
fd, temporary = tempfile.mkstemp(dir=path.parent, prefix=".homegate-")
|
||
try:
|
||
with os.fdopen(fd, "wb") as stream:
|
||
stream.write(data)
|
||
stream.flush()
|
||
os.fsync(stream.fileno())
|
||
os.chmod(temporary, 0o600)
|
||
os.replace(temporary, path)
|
||
finally:
|
||
if os.path.exists(temporary):
|
||
os.unlink(temporary)
|
||
|
||
|
||
def include_update(original, include_path="config.d/homegate.conf"):
|
||
text = original.decode("utf-8")
|
||
expected = BEGIN + '\nHost *\n Include "' + include_path + '"\n' + END
|
||
check((BEGIN in text) == (END in text), "Incomplete Homegate Include block; repair it manually")
|
||
if BEGIN in text:
|
||
check(text.count(BEGIN) == 1 and text.count(END) == 1, "Duplicate Homegate Include block")
|
||
check(expected in text.replace("\r\n", "\n"), "Homegate Include block was edited; inspect it manually")
|
||
return original
|
||
suffix = ("\n" if original and not original.endswith(b"\n") else "")
|
||
suffix += "\n" + expected + "\n"
|
||
return original + suffix.encode()
|
||
|
||
|
||
def install_config(text, ssh_dir, add_include=False):
|
||
# Validate before creating directories or changing any existing files.
|
||
text = validate_download(text.encode())
|
||
check(not ssh_dir.is_symlink(), "SSH directory is a symlink; use its real path with --ssh-dir")
|
||
target_dir = ssh_dir / "config.d"
|
||
target = target_dir / "homegate.conf"
|
||
main = ssh_dir / "config"
|
||
check(not target_dir.is_symlink() and not target.is_symlink(), "Generated config path must not be a symlink")
|
||
original, updated = b"", b""
|
||
if add_include:
|
||
check(not main.is_symlink(), "Main config is a symlink; add Include manually")
|
||
original = main.read_bytes() if main.exists() else b""
|
||
include_path = target.resolve().as_posix()
|
||
check(not any(c in include_path for c in '\r\n\x00"$%*?[]'), "SSH directory contains unsupported Include path characters")
|
||
updated = include_update(original, include_path)
|
||
ssh_dir.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||
target_dir.mkdir(exist_ok=True, mode=0o700)
|
||
os.chmod(ssh_dir, 0o700)
|
||
os.chmod(target_dir, 0o700)
|
||
if not target.exists() or target.read_bytes() != text.encode():
|
||
atomic_write(target, text.encode())
|
||
else:
|
||
os.chmod(target, 0o600)
|
||
if add_include and updated != original:
|
||
if main.exists():
|
||
atomic_write(ssh_dir / ("config.before-homegate-" + str(time.time_ns())), original)
|
||
atomic_write(main, updated)
|
||
return target
|
||
|
||
|
||
def main():
|
||
parser = argparse.ArgumentParser(description=__doc__)
|
||
parser.add_argument("url", help="e.g. http://192.168.0.10:8099/ssh-config")
|
||
parser.add_argument("--install", action="store_true", help="Also append one Include block; back up existing config")
|
||
parser.add_argument("--ssh-dir", type=Path, default=Path.home() / ".ssh")
|
||
parser.add_argument("--ca-file", help="Trusted PEM CA file for HTTPS")
|
||
args = parser.parse_args()
|
||
text = download(args.url, args.ca_file)
|
||
target = install_config(text, args.ssh_dir.expanduser(), args.install)
|
||
print("Updated:", target)
|
||
if args.install:
|
||
print("Include installed. Existing settings take precedence; check an alias with: ssh -G ALIAS")
|
||
else:
|
||
print("To add the Include on first use, run again with --install.")
|
||
|
||
|
||
if __name__ == "__main__":
|
||
try:
|
||
main()
|
||
except Exception as exc:
|
||
print("Homegate SSH sync failed:", exc, file=sys.stderr)
|
||
sys.exit(1)
|