Я пытаюсь использовать msfrpc (написанный на python2) в python3, и я сталкиваюсь с ошибками аутентификации. Код, который я использую, приведен ниже; см. комментарии в коде об изменениях, которые я внес.
Программа успешно работает в python2 (при использовании httplib, а не http.client) с тем же обменом аутентификацией, что и при использовании python3.
import msgpack
import http.client #Changed from httplib
class Msfrpc:
class MsfError(Exception):
def __init__(self,msg):
self.msg = msg
def __str__(self):
return repr(self.msg)
class MsfAuthError(MsfError):
def __init__(self,msg):
self.msg = msg
def __init__(self,opts=[]):
self.host = opts.get('host') or "127.0.0.1"
self.port = opts.get('port') or 55552
self.uri = opts.get('uri') or "/api/"
self.ssl = opts.get('ssl') or False
self.authenticated = False
self.token = False
self.headers = {"Content-type" : "binary/message-pack" }
if self.ssl:
self.client = http.client.HTTPSConnection(self.host,self.port) #Changed httplib -> http.client
else:
self.client = http.client.HTTPConnection(self.host,self.port) #Changed httplib -> http.client
def encode(self,data):
return msgpack.packb(data)
def decode(self,data):
return msgpack.unpackb(data)
def call(self,meth,opts = []):
if meth != "auth.login":
if not self.authenticated:
raise self.MsfAuthError("MsfRPC: Not Authenticated")
if meth != "auth.login":
opts.insert(0,self.token)
opts.insert(0,meth)
params = self.encode(opts)
self.client.request("POST",self.uri,params,self.headers)
resp = self.client.getresponse()
return self.decode(resp.read())
def login(self,user,password):
ret = self.call('auth.login',[user,password])
if ret.get('result') == 'success':
self.authenticated = True
self.token = ret.get('token')
return True
else:
raise self.MsfAuthError("MsfRPC: Authentication failed")
if __name__ == '__main__':
# Create a new instance of the Msfrpc client with the default options
client = Msfrpc({})
# Login to the msfmsg server using the password "abc123"
client.login('msf','abc123')
# Get a list of the exploits from the server
mod = client.call('module.exploits')
# Grab the first item from the modules value of the returned dict
print ("Compatible payloads for : %s\n" % mod['modules'][0]) #Added ()
# Get the list of compatible payloads for the first option
ret = client.call('module.compatible_payloads',[mod['modules'][0]])
for i in (ret.get('payloads')):
print ("\t%s" % i) #Added ()
При запуске программы результат:
root@kali:~/Dropbox/PythonStuff/python-nmap-test# python3 test3.py
Traceback (most recent call last):
File "test3.py", line 20, in <module>
client.login('msf','abc123')
File "/usr/local/lib/python3.7/dist-packages/msfrpc.py", line 64, in login
raise self.MsfAuthError("MsfRPC: Authentication failed")
msfrpc.MsfAuthError: 'MsfRPC: Authentication failed'
Любопытно, что запуск tcpdump во время выполнения программы показывает успешную аутентификацию и предоставленный токен:
![enter image description here](https://i.stack.imgur.com/iYFyw.png)
Когда программа успешно выполняется с python2, обмен аутентификацией кажется идентичным, но если кто-то чувствует, что отправка пакета захвата программы (запущенной в python2) завершается успешно, поможет ответить на вопрос, я могу легко добавить его.