File size: 13,901 Bytes
53ec230
 
12bea74
53ec230
b326ed7
 
 
53ec230
b326ed7
12bea74
 
53ec230
 
b326ed7
53ec230
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b326ed7
 
 
 
 
53ec230
b326ed7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53ec230
b326ed7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53ec230
 
12bea74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53ec230
 
 
 
 
 
 
12bea74
53ec230
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b326ed7
53ec230
 
 
12bea74
 
 
 
 
53ec230
 
 
 
 
 
12bea74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53ec230
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
#!/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()