import asyncio, base64, re, os
import aiohttp

pairs = [l.rstrip('\n').split('\t') for l in open('saml_issuers.tsv') if '\t' in l]
print("targets", len(pairs), flush=True)
SEM = asyncio.Semaphore(60)
OUT = open('idp_probe.tsv', 'w')
LOCK = asyncio.Lock()
STAT = {}

def classify(body):
    if 'Attack ID' in body or 'Web Page Blocked' in body:
        return 'blocked'
    if 'Security-as-a-service' in body or 'LOG IN AS EMAIL USER' in body:
        return 'login-form'
    return 'other'

async def one(s, ip, iss):
    url = "https://%s/saml/login-forticloud?fallback=https%%3A%%2F%%2F%s%%2Flogin&host=%s&redir=%%2F" % (ip, ip, ip)
    try:
        async with SEM:
            async with s.get(url, ssl=False, timeout=aiohttp.ClientTimeout(total=15)) as r:
                h = await r.text(errors='replace') if r.status == 200 else ''
    except Exception as e:
        async with LOCK:
            OUT.write("%s\t%s\tgeterr\t-\n" % (ip, iss)); STAT['geterr'] = STAT.get('geterr', 0) + 1
        return
    m = re.search(r'name="SAMLRequest" value="([^"]+)"', h)
    a = re.search(r'action="([^"]+)"', h)
    if not m or not a:
        async with LOCK:
            OUT.write("%s\t%s\tnoform\t-\n" % (ip, iss)); STAT['noform'] = STAT.get('noform', 0) + 1
        return
    tenant = a.group(1).rstrip('/').split('/')[-2]
    form = aiohttp.FormData()
    form.add_field('RelayState', '/')
    form.add_field('SAMLRequest', m.group(1))
    try:
        async with SEM:
            async with s.post(a.group(1), data=form, ssl=False,
                              timeout=aiohttp.ClientTimeout(total=20),
                              allow_redirects=False) as r2:
                body = await r2.text(errors='replace')
                code = r2.status
    except Exception:
        async with LOCK:
            OUT.write("%s\t%s\tposterr\t%s\n" % (ip, iss, tenant)); STAT['posterr'] = STAT.get('posterr', 0) + 1
        return
    cls = classify(body)
    async with LOCK:
        OUT.write("%s\t%s\t%s\t%s\t%s\n" % (ip, iss, code, cls, tenant))
        OUT.flush()
        STAT[cls] = STAT.get(cls, 0) + 1

async def main():
    conn = aiohttp.TCPConnector(limit=60, force_close=True)
    async with aiohttp.ClientSession(connector=conn) as s:
        await asyncio.gather(*[one(s, ip, iss) for ip, iss in pairs])
    OUT.close()
    print("stats", STAT, flush=True)

asyncio.run(main())
