#!/usr/bin/env python3 """pqmove: move your git off a classical-only door and onto a post-quantum one, and prove it. Some code hosts accept post-quantum key exchange over SSH but not over HTTPS. If your remote starts with https://, everything you push and pull through it is protected by classical key exchange only: traffic recorded today could be read later. This tool measures both doors of your remote's host, and if SSH is the post-quantum one, switches the remote for you. python3 pqmove.py # look at the repository in this folder; change nothing python3 pqmove.py --scan ~/code # every repository under a folder; change nothing python3 pqmove.py --apply # switch this repository's movable remotes python3 pqmove.py --revert # switch them back What it changes, and only with --apply: the remote's address, with `git remote set-url`. It first checks that your SSH key already works for that host, so a switch never locks you out. The old address is kept in this repository's git config, and --revert restores it. What moves: key exchange, which is what protects recorded traffic. What does not: the keys that prove who you and the host are still use classical signatures, on every host, today. Needs: Python 3.9+, git, an OpenSSH client. Standard library only. pqcheck.py must sit beside this file. """ import argparse import json import os import re import subprocess import sys import time import pqcheck VERSION = "0.2.0" PQ_KEX = pqcheck.SSH_PQ_KEX NOTE = "pqmove.{remote}.previous-url" _cache = {} def run(cmd, cwd=None, env=None, timeout=40): try: p = subprocess.run(cmd, cwd=cwd, env=env, capture_output=True, text=True, timeout=timeout) return p.returncode, (p.stdout or "") + (p.stderr or "") except (OSError, subprocess.SubprocessError) as e: return 127, str(e) def redact(url): """Never print a token that sits inside a remote address.""" return re.sub(r"(https?://)[^/@\s]+@", r"\1***@", url) def parse_https(url): """('github.com', 'owner/repo') for an https remote, else None.""" m = re.match(r"^https://(?:[^/@\s]+@)?([A-Za-z0-9.-]+)(?::443)?/(.+?)(?:\.git)?/?$", url.strip()) return (m.group(1).lower(), m.group(2)) if m else None def ssh_address(host, path): return f"git@{host}:{path}.git" def remotes(repo): code, out = run(["git", "remote", "-v"], cwd=repo) found = {} if code == 0: for line in out.splitlines(): parts = line.split() if len(parts) >= 2: found.setdefault(parts[0], parts[1]) return found def doors(host): """Measure both doors of a host once: {'https': verdict, 'ssh': verdict, 'methods': [...]}.""" if host not in _cache: https = pqcheck.check(f"{host}:443", "this machine") ssh = pqcheck.check(f"{host}:22", "this machine") _cache[host] = {"https": https["verdict"], "ssh": ssh["verdict"], "methods": ssh.get("methods", []), "verify_https": https.get("verify", "")} return _cache[host] def client_kex(): """Post-quantum key-exchange methods this machine's ssh client supports.""" code, out = run(["ssh", "-Q", "kex"]) return [m for m in out.split() if m in PQ_KEX] if code == 0 else [] def negotiated_kex(host): """What an ordinary connection from this machine really negotiates. No key is offered, no login happens.""" code, out = run(["ssh", "-vv", "-o", "BatchMode=yes", "-o", "PubkeyAuthentication=no", "-o", "PasswordAuthentication=no", "-o", "StrictHostKeyChecking=accept-new", "-o", "ConnectTimeout=15", "-T", f"git@{host}"], timeout=40) m = re.search(r"kex: algorithm: (\S+)", out) return m.group(1) if m else None def key_works(repo, address): """Can this machine already read the repository over SSH? (git ls-remote, never prompts)""" env = dict(os.environ, GIT_SSH_COMMAND="ssh -o BatchMode=yes -o ConnectTimeout=15 -o StrictHostKeyChecking=accept-new", GIT_TERMINAL_PROMPT="0") code, _ = run(["git", "ls-remote", "--heads", address], cwd=repo, env=env, timeout=60) return code == 0 def look(repo): """One report per remote of a repository. Changes nothing.""" reports = [] for name, url in remotes(repo).items(): r = {"repository": repo, "remote": name, "address": redact(url), "action": "none"} parsed = parse_https(url) if not parsed: r["state"] = "not an https remote" m = re.match(r"^(?:ssh://)?git@([A-Za-z0-9.-]+)[:/]", url) if m: d = doors(m.group(1)) r["state"] = "already on SSH; the host's SSH door " + ("accepts post-quantum key exchange" if d["ssh"] == "accepts" else "is " + d["ssh"]) reports.append(r) continue host, path = parsed d = doors(host) r.update({"host": host, "https_door": d["https"], "ssh_door": d["ssh"]}) if d["https"] == "accepts": r["state"] = "nothing to do: this host's HTTPS door already accepts post-quantum key exchange" elif d["https"] in ("classical only", "older TLS only") and d["ssh"] == "accepts": r["state"] = "movable: HTTPS is " + d["https"] + ", SSH accepts post-quantum key exchange" r["action"] = "move" r["new_address"] = ssh_address(host, path) r["command"] = f"git remote set-url {name} {r['new_address']}" elif d["https"] in ("classical only", "older TLS only"): r["state"] = "cannot move yet: neither door of this host accepts post-quantum key exchange" else: r["state"] = "unclear: could not measure this host" reports.append(r) return reports def apply(repo, report): """Switch one movable remote, safely. Returns the updated report.""" name, new = report["remote"], report["new_address"] if not client_kex(): report["result"] = "not switched: this machine's ssh client has no post-quantum key exchange; update OpenSSH (9.0 or newer) first" return report if not key_works(repo, new): report["result"] = ("not switched: your SSH key does not work for this host yet. Add an SSH key to your account there, " "check it with `git ls-remote " + new + "`, then run --apply again") return report old = remotes(repo)[name] run(["git", "config", NOTE.format(remote=name), old], cwd=repo) code, out = run(["git", "remote", "set-url", name, new], cwd=repo) if code != 0: report["result"] = "not switched: git refused (" + out.strip()[:120] + ")" return report kex = negotiated_kex(report["host"]) report["negotiated"] = kex report["result"] = "moved" if kex in PQ_KEX else "switched, but this machine negotiated " + str(kex) + "; update your ssh client" report["moved_utc"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) report["revert"] = "python3 pqmove.py --revert" return report def revert(repo): done = [] for name in remotes(repo): code, out = run(["git", "config", "--get", NOTE.format(remote=name)], cwd=repo) old = out.strip() if code == 0 and old: run(["git", "remote", "set-url", name, old], cwd=repo) run(["git", "config", "--unset", NOTE.format(remote=name)], cwd=repo) done.append({"remote": name, "restored": redact(old)}) return done def find_repos(top, depth=4): top = os.path.abspath(os.path.expanduser(top)) found = [] for root, dirs, _ in os.walk(top): if ".git" in dirs: found.append(root) dirs[:] = [] continue if root[len(top):].count(os.sep) >= depth: dirs[:] = [] dirs[:] = [d for d in dirs if not d.startswith(".") and d not in ("node_modules", "target", "venv", "__pycache__")] return found def show(report): print(f"\n{report['repository']} [{report['remote']}] {report['address']}") print(" " + report["state"]) if report.get("command") and "result" not in report: print(" to move it: " + report["command"] + " (or run: python3 pqmove.py --apply)") if "result" in report: print(" " + report["result"] + (f"; this machine now negotiates {report['negotiated']}" if report.get("negotiated") else "")) def main(): ap = argparse.ArgumentParser(description="Move your git onto a post-quantum door, where the host has one.") ap.add_argument("--scan", metavar="DIR", help="look at every repository under DIR (changes nothing)") ap.add_argument("--apply", action="store_true", help="switch this repository's movable remotes") ap.add_argument("--revert", action="store_true", help="switch this repository's remotes back") ap.add_argument("--json", metavar="FILE", help="also write the full report to FILE") args = ap.parse_args() here = os.getcwd() if args.revert: done = revert(here) print(json.dumps(done, indent=1) if done else "nothing to switch back in this repository") return repos = find_repos(args.scan) if args.scan else [here] if not args.scan and not remotes(here): sys.exit("no git remotes in this folder; run it inside a repository, or use --scan DIR") kex = client_kex() print("this machine's ssh client:", ("supports " + ", ".join(kex)) if kex else "has NO post-quantum key exchange (update OpenSSH)") reports = [] for repo in repos: for report in look(repo): if args.apply and report["action"] == "move" and not args.scan: report = apply(repo, report) show(report) reports.append(report) movable = sum(1 for r in reports if r["action"] == "move" and "result" not in r) moved = sum(1 for r in reports if r.get("result") == "moved") blocked = sum(1 for r in reports if str(r.get("result", "")).startswith("not switched")) print(f"\n{len(reports)} remotes looked at; {moved} moved; {movable} can be moved" + (" with --apply (run it inside each repository)" if movable else "") + (f"; {blocked} not switched, see why above" if blocked else "")) print("What moved is key exchange. The keys that prove who you and the host are still use classical signatures, everywhere, today.") if args.json: with open(args.json, "w", encoding="utf-8", newline="\n") as f: json.dump({"tool": "pqmove " + VERSION, "reports": reports}, f, indent=1) if __name__ == "__main__": main()