#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""KeyGuard Local: check the RSA PUBLIC keys of devices in your own private network and print the verdict.

    python3 keyguard-local-v2.py                    # scan the /24 of this computer (asks first)
    python3 keyguard-local-v2.py --hosts 192.168.0.1,192.168.0.20
    python3 keyguard-local-v2.py --ports 443,8443,22 --out keyguard_keys.txt

What it does:  TCP connect, a TLS handshake per open port (on port 22 the SSH key exchange, up to the host key).
What it never does:  no login attempts, no private keys, no internet traffic, no upload. The verdict is computed here and the key file stays on this computer.
The same file can also be opened in the Self-check tab of https://huggingface.co/spaces/FINAL-Bench/KeyGuard (checked inside your browser).
Use it only on networks and devices you own or are authorized to test. Standard library only. MIT License, VIDRAFT.
"""
import argparse, base64, ipaddress, locale, math, os, socket, ssl, sys
from concurrent.futures import ThreadPoolExecutor

NETS = [ipaddress.ip_network(n) for n in ("10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "127.0.0.0/8")]


def private(ip):
    return any(ip in n for n in NETS)


def my_ip():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        s.connect(("192.0.2.1", 9))  # UDP connect sends no packet, it only selects the local interface
        return ipaddress.ip_address(s.getsockname()[0])
    finally:
        s.close()


def is_open(a):
    try:
        with socket.create_connection(a, 1.2):
            return a
    except OSError:
        return None


def cert(ip, port):
    der = None
    for cipher, cap in (("aRSA:@SECLEVEL=0", True), ("ALL:@SECLEVEL=0", False)):
        try:
            c = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
            c.check_hostname = False
            c.verify_mode = ssl.CERT_NONE
            c.options |= getattr(ssl, "OP_LEGACY_SERVER_CONNECT", 0x4)
            try:
                c.set_ciphers(cipher)
            except ssl.SSLError:  # LibreSSL has no @SECLEVEL
                c.set_ciphers(cipher.split(":")[0])
            c.minimum_version = ssl.TLSVersion.TLSv1
            if cap:
                c.maximum_version = ssl.TLSVersion.TLSv1_2
            with socket.create_connection((ip, port), 4) as s:
                s.settimeout(5)
                with c.wrap_socket(s) as w:
                    der = w.getpeercert(True)
            if der:
                return ssl.DER_cert_to_PEM_cert(der).strip()
        except (OSError, ValueError):
            continue
    return None


GROUP14 = "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AACAA68FFFFFFFFFFFFFFFF"
GROUP1 = "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF"
KEX = {"diffie-hellman-group14-sha256": GROUP14, "diffie-hellman-group14-sha1": GROUP14, "diffie-hellman-group1-sha1": GROUP1}


def ssh_rsa(ip, port):
    """RSA host key of an SSH server. Runs the key exchange up to the host key and disconnects: no login step."""
    def st(b):
        return len(b).to_bytes(4, "big") + b

    def send(body):
        pad = 8 - (len(body) + 5) % 8
        pad += 8 if pad < 4 else 0
        s.sendall((len(body) + pad + 1).to_bytes(4, "big") + bytes([pad]) + body + os.urandom(pad))

    def need(n):
        b = b""
        while len(b) < n:
            c = s.recv(n - len(b))
            if not c:
                raise OSError("closed")
            b += c
        return b

    def packet():
        n = int.from_bytes(need(4), "big")
        if not 2 <= n <= 40000:
            raise OSError("bad packet")
        b = need(n)
        return b[1:n - b[0]]

    try:
        with socket.create_connection((ip, port), 4) as s:
            s.settimeout(5)
            for _ in range(20):
                line = b""
                while not line.endswith(b"\n") and len(line) < 512:
                    line += need(1)
                if line.startswith(b"SSH-"):
                    break
            else:
                return None
            s.sendall(b"SSH-2.0-KeyGuardLocal\r\n")
            hk = b"rsa-sha2-512,rsa-sha2-256,ssh-rsa"
            enc = b"aes128-ctr,aes256-ctr,aes128-cbc,3des-cbc"
            mac = b"hmac-sha2-256,hmac-sha2-512,hmac-sha1"
            send(b"\x14" + os.urandom(16) + b"".join(st(x) for x in (",".join(KEX).encode(), hk, enc, enc, mac, mac, b"none", b"none", b"", b"")) + b"\x00" * 5)
            b = packet()
            while b[:1] != b"\x14":
                b = packet()
            n = int.from_bytes(b[17:21], "big")
            theirs = b[21:21 + n].decode("ascii", "replace").split(",")
            kex = next((k for k in KEX if k in theirs), None)
            if not kex:
                return None
            e = pow(2, int.from_bytes(os.urandom(32), "big") | 1 << 255, int(KEX[kex], 16))
            raw = e.to_bytes(e.bit_length() // 8 + 1, "big")
            send(b"\x1e" + st(raw))
            for _ in range(6):
                b = packet()
                if b[:1] == b"\x1f":
                    n = int.from_bytes(b[1:5], "big")
                    key = b[5:5 + n]
                    return "ssh-rsa " + base64.b64encode(key).decode() if key[4:11] == b"ssh-rsa" else None
    except (OSError, ValueError, IndexError):
        pass
    return None


KO = (os.environ.get("LANG") or (locale.getlocale()[0] or "")).lower().startswith(("ko", "korean"))
T = lambda ko, en: ko if KO else en
ROCA = (3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 151, 163, 167)
OID_RSA = bytes.fromhex("06092a864886f70d010101")


def der_ints(b):
    """The first two INTEGERs of a DER SEQUENCE."""
    def tl(i):
        n = b[i + 1]
        if n & 0x80:
            k = n & 0x7F
            return i + 2 + k, int.from_bytes(b[i + 2:i + 2 + k], "big")
        return i + 2, n
    i, _ = tl(0)
    out = []
    for _ in range(2):
        if b[i] != 2:
            return None
        s, n = tl(i)
        out.append(int.from_bytes(b[s:s + n], "big"))
        i = s + n
    return out


def rsa_of(text):
    """(n, e) of an RSA certificate or ssh-rsa line, else None."""
    try:
        if text.startswith("ssh-rsa "):
            b, f, i = base64.b64decode(text.split()[1]), [], 0
            while i + 4 <= len(b) and len(f) < 3:
                n = int.from_bytes(b[i:i + 4], "big")
                f.append(b[i + 4:i + 4 + n])
                i += 4 + n
            return int.from_bytes(f[2], "big"), int.from_bytes(f[1], "big")
        b = base64.b64decode("".join(text.splitlines()[1:-1]))
        i = b.find(OID_RSA)
        if i < 0:
            return None
        i += len(OID_RSA)
        i += 2 if b[i:i + 2] == b"\x05\x00" else 0
        if b[i] != 3:
            return None
        n = b[i + 1]
        i = i + 2 + (n & 0x7F if n & 0x80 else 0)
        v = der_ints(b[i + 1:])
        return (v[0], v[1]) if v else None
    except (ValueError, IndexError):
        return None


def fermat(n, steps=2000):
    if n % 2 == 0:
        return 2
    a = math.isqrt(n)
    a += a * a < n
    for _ in range(steps):
        d = a * a - n
        r = math.isqrt(d)
        if r * r == d and a - r > 1:
            return a - r
        a += 1
    return None


def roca(n):
    for p in ROCA:
        seen, x = set(), 1
        for _ in range(1, p):
            x = x * 65537 % p
            seen.add(x)
        if n % p and n % p not in seen:
            return False
    return True


def verdicts(keys):
    """keys: [(label, n, e)] -> [(label, bits, level, reasons)]  level: 0 safe, 1 caution, 2 danger"""
    shared = {}
    for i in range(len(keys)):
        for j in range(i):
            g = math.gcd(keys[i][1], keys[j][1])
            if g not in (1, keys[i][1], keys[j][1]):
                shared.setdefault(i, []).append(keys[j][0])
                shared.setdefault(j, []).append(keys[i][0])
    out = []
    for i, (lab, n, e) in enumerate(keys):
        bits, lv, why = n.bit_length(), 0, []
        if i in shared:
            lv = 2
            why.append(T("같은 소수를 쓰는 기기: ", "shares a prime with ") + ", ".join(shared[i]))
        if bits <= 768:
            lv = 2
            why.append(T("짧은 키", "short key"))
        elif bits < 2048:
            lv = max(lv, 1)
            why.append(T("2048비트 미만", "under 2048 bits"))
        if e < 3 or e % 2 == 0:
            lv = 2
            why.append(T("비정상 지수", "abnormal exponent"))
        if fermat(n):
            lv = 2
            why.append(T("두 소수가 너무 가까움", "primes too close"))
        if bits >= 512 and roca(n):
            lv = max(lv, 1)
            why.append("ROCA CVE-2017-15361")
        out.append((lab, bits, lv, why))
    return out


def main():
    import warnings
    warnings.simplefilter("ignore", DeprecationWarning)  # TLS 1.0 is allowed on purpose: old devices are the target
    p = argparse.ArgumentParser(description="KeyGuard Local: collect public keys in your own private network")
    p.add_argument("--hosts", help="comma separated private IPs instead of the whole /24")
    p.add_argument("--subnet", help="private /24 or smaller, e.g. 192.168.0.0/24")
    p.add_argument("--ports", default="443,8443,22")
    p.add_argument("--out", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "keyguard_keys.txt"))
    p.add_argument("--yes", action="store_true", help="skip the question (you confirm that you are authorized)")
    a = p.parse_args()
    try:
        ports = sorted({int(x) for x in a.ports.split(",")})
        if a.hosts:
            hosts = [ipaddress.ip_address(x.strip()) for x in a.hosts.split(",")]
        else:
            net = ipaddress.ip_network(a.subnet, strict=False) if a.subnet else ipaddress.ip_network("%s/24" % my_ip(), strict=False)
            if net.version != 4 or net.prefixlen < 24:
                sys.exit("Only IPv4 /24 or smaller networks are allowed.")
            hosts = list(net.hosts()) or [net.network_address]
    except (ValueError, OSError) as e:
        sys.exit("Bad input: %s" % e)
    if len(ports) > 5 or not all(0 < x < 65536 for x in ports) or len(hosts) > 256:
        sys.exit("At most 5 ports and 256 addresses.")
    if not all(h.version == 4 and private(h) for h in hosts):
        sys.exit("Only private addresses are allowed (10.x, 172.16-31.x, 192.168.x).")
    print("KeyGuard Local v2")
    print("Target: %s%s (%d addresses), ports %s" % (hosts[0], " to %s" % hosts[-1] if len(hosts) > 1 else "", len(hosts), ports))
    if not a.yes:
        print("Use this only on a network you own or are authorized to test.\n본인 소유이거나 점검 권한이 있는 네트워크에서만 사용하십시오.")
        for _ in range(3):
            q = input("Type YES to continue, NO to stop / 계속하려면 YES, 그만두려면 NO: ").strip().upper()
            if q in ("YES", "Y", "NO", "N"):
                break
        if q not in ("YES", "Y"):
            sys.exit("Stopped.")
    with ThreadPoolExecutor(64) as ex:
        found = [x for x in ex.map(is_open, [(str(h), q) for h in hosts for q in ports]) if x]
    print("Open ports: %d" % len(found))
    with ThreadPoolExecutor(16) as ex:
        keys = list(ex.map(lambda x: ssh_rsa(*x) if x[1] == 22 else cert(*x), found))
    got, rsa_keys, rows = [], [], []
    for (ip, port), k in zip(found, keys):
        lab = "%s:%d" % (ip, port)
        if k:
            got.append("# %s\n%s\n" % (lab, k))
        v = rsa_of(k) if k else None
        if v:
            rsa_keys.append((lab,) + v)
        else:
            rows.append((lab, T("RSA 키가 아님 (점검 대상 아님)", "not an RSA key (not applicable)") if k else T("공개키를 주지 않음", "no public key offered")))
    res = verdicts(rsa_keys)
    name = (T("안전", "SAFE"), T("주의", "CAUTION"), T("위험", "DANGER"))
    print("\n" + T("=== 점검 결과 ===", "=== RESULT ==="))
    for lab, bits, lv, why in res:
        print("  [%s] %s  RSA %d  %s" % (name[lv], lab, bits, " / ".join(why) or T("4대 결함 없음", "none of the four defects")))
    for lab, why in rows:
        print("  [-] %s  %s" % (lab, why))
    print(T("  합계: 안전 %d, 주의 %d, 위험 %d, 대상 아님 %d", "  Total: safe %d, caution %d, danger %d, not applicable %d") % (sum(r[2] == 0 for r in res), sum(r[2] == 1 for r in res), sum(r[2] == 2 for r in res), len(rows)))
    if not found:
        print(T("  열린 포트를 찾지 못했습니다. 안전 판정은 아닙니다.", "  No open port was found. This is not a Safe verdict."))
    if any(r[2] for r in res):
        print(T("  위험·주의 키: 사용을 멈추고 펌웨어를 갱신한 뒤 새 키를 만드십시오.", "  Danger or Caution: retire the key, update the firmware and generate a new key."))
    try:
        with open(a.out, "w", encoding="utf-8", newline="\n") as f:
            f.write("# KeyGuard Local: public keys only\n" + "".join(got))
        print(T("\n공개키 파일: %s", "\nPublic key file: %s") % a.out)
    except OSError as e:
        print(T("\n파일을 쓰지 못했습니다: %s", "\nCould not write the file: %s") % e)


if __name__ == "__main__":
    main()
