import sys
sys.path.insert(0, "/root/recon")
import cp_oracle as co

ip = sys.argv[1]
ders, org = co.get_ica(ip)
if len(ders) < 2:
    print("%s\tNOCHAIN\t%d" % (ip, len(ders)))
    sys.exit()
ica = ders[1]
subj = co.x509.load_der_x509_certificate(ica).subject


def run(label, chain, issuer):
    f = co.forge("vpnuser", ica, org, issuer, chain)
    f.chain_ders = chain
    s = co.Session(ip, "vpnuser", timeout=6.0)
    r = s.run(f, with_hash=False, fast=True)
    s.close()
    txt = " | ".join(n[2:] for n in r["notes"] if n.startswith("t:"))
    print("%s\t%s\t%s" % (ip, label, txt[:150].replace("\t", " ")), flush=True)


fake = co.x509.Name([co.x509.NameAttribute(co.NameOID.ORGANIZATION_NAME, "AcmeProbeOrg",
                                            _type=co._ASN1Type.PrintableString)])
run("nofakechain", [], fake)
bad = bytearray(ica)
for i in range(4):
    bad[-(i + 1)] ^= 0xFF
run("badica     ", [bytes(bad)], subj)
run("okica      ", [ica], subj)
