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

@@ -24,7 +24,7 @@ from lib.core.enums import DBMS
from lib.core.enums import PAYLOAD
from lib.core.enums import PLACE
from lib.core.enums import POST_HINT
from lib.core.exception import sqlmapNoneDataException
from lib.core.exception import SqlmapNoneDataException
from lib.core.settings import ASTERISK_MARKER
from lib.core.settings import CUSTOM_INJECTION_MARK_CHAR
from lib.core.settings import GENERIC_SQL_COMMENT
@@ -252,7 +252,7 @@ class Agent(object):
else:
errMsg = "invalid usage of inference payload without "
errMsg += "knowledge of underlying DBMS"
raise sqlmapNoneDataException, errMsg
raise SqlmapNoneDataException, errMsg
return payload

View File

@@ -67,14 +67,14 @@ from lib.core.enums import PLACE
from lib.core.enums import PAYLOAD
from lib.core.enums import REFLECTIVE_COUNTER
from lib.core.enums import SORT_ORDER
from lib.core.exception import sqlmapDataException
from lib.core.exception import sqlmapFilePathException
from lib.core.exception import sqlmapGenericException
from lib.core.exception import sqlmapNoneDataException
from lib.core.exception import sqlmapMissingDependence
from lib.core.exception import sqlmapSilentQuitException
from lib.core.exception import sqlmapSyntaxException
from lib.core.exception import sqlmapUserQuitException
from lib.core.exception import SqlmapDataException
from lib.core.exception import SqlmapFilePathException
from lib.core.exception import SqlmapGenericException
from lib.core.exception import SqlmapNoneDataException
from lib.core.exception import SqlmapMissingDependence
from lib.core.exception import SqlmapSilentQuitException
from lib.core.exception import SqlmapSyntaxException
from lib.core.exception import SqlmapUserQuitException
from lib.core.log import LOGGER_HANDLER
from lib.core.optiondict import optDict
from lib.core.settings import BOLD_PATTERNS
@@ -539,7 +539,7 @@ def paramToDict(place, parameters=None):
message = "Are you sure you want to continue? [y/N] "
test = readInput(message, default="N")
if test[0] not in ("y", "Y"):
raise sqlmapSilentQuitException
raise SqlmapSilentQuitException
if conf.testParameter and not testableParameters:
paramStr = ", ".join(test for test in conf.testParameter)
@@ -806,7 +806,7 @@ def readInput(message, default=None, checkBatch=True):
except:
time.sleep(0.05) # Reference: http://www.gossamer-threads.com/lists/python/python/781893
kb.prependFlag = True
raise sqlmapUserQuitException
raise SqlmapUserQuitException
finally:
logging._releaseLock()
@@ -853,7 +853,7 @@ def checkFile(filename):
"""
if not os.path.isfile(filename):
raise sqlmapFilePathException, "unable to read file '%s'" % filename
raise SqlmapFilePathException, "unable to read file '%s'" % filename
def banner():
"""
@@ -989,7 +989,7 @@ def parseTargetDirect():
errMsg = "invalid target details, valid syntax is for instance "
errMsg += "'mysql://USER:PASSWORD@DBMS_IP:DBMS_PORT/DATABASE_NAME' "
errMsg += "or 'access://DATABASE_FILEPATH'"
raise sqlmapSyntaxException, errMsg
raise SqlmapSyntaxException, errMsg
for dbmsName, data in DBMS_DICT.items():
if conf.dbms in data[0]:
@@ -1004,7 +1004,7 @@ def parseTargetDirect():
conf.port = 0
elif not remote:
errMsg = "missing remote connection details"
raise sqlmapSyntaxException, errMsg
raise SqlmapSyntaxException, errMsg
if dbmsName in (DBMS.MSSQL, DBMS.SYBASE):
import _mssql
@@ -1014,7 +1014,7 @@ def parseTargetDirect():
errMsg = "'%s' third-party library must be " % data[1]
errMsg += "version >= 1.0.2 to work properly. "
errMsg += "Download from '%s'" % data[2]
raise sqlmapMissingDependence, errMsg
raise SqlmapMissingDependence, errMsg
elif dbmsName == DBMS.MYSQL:
import pymysql
@@ -1032,7 +1032,7 @@ def parseTargetDirect():
errMsg = "sqlmap requires '%s' third-party library " % data[1]
errMsg += "in order to directly connect to the database "
errMsg += "%s. Download from '%s'" % (dbmsName, data[2])
raise sqlmapMissingDependence, errMsg
raise SqlmapMissingDependence, errMsg
def parseTargetUrl():
"""
@@ -1047,7 +1047,7 @@ def parseTargetUrl():
if re.search("\[.+\]", conf.url) and not socket.has_ipv6:
errMsg = "IPv6 addressing is not supported "
errMsg += "on this platform"
raise sqlmapGenericException, errMsg
raise SqlmapGenericException, errMsg
if not re.search("^http[s]*://", conf.url, re.I):
if ":443/" in conf.url:
@@ -1075,14 +1075,14 @@ def parseTargetUrl():
if any((_ is None, re.search(r'\s', conf.hostname), '..' in conf.hostname, conf.hostname.startswith('.'))):
errMsg = "invalid target url"
raise sqlmapSyntaxException, errMsg
raise SqlmapSyntaxException, errMsg
if len(hostnamePort) == 2:
try:
conf.port = int(hostnamePort[1])
except:
errMsg = "invalid target url"
raise sqlmapSyntaxException, errMsg
raise SqlmapSyntaxException, errMsg
elif conf.scheme == "https":
conf.port = 443
else:
@@ -1351,7 +1351,7 @@ def safeStringFormat(format_, params):
if count < len(params):
retVal = retVal[:index] + getUnicode(params[count]) + retVal[index + 2:]
else:
raise sqlmapNoneDataException, "wrong number of parameters during string formatting"
raise SqlmapNoneDataException, "wrong number of parameters during string formatting"
count += 1
return retVal
@@ -2420,11 +2420,11 @@ def initTechnique(technique=None):
warnMsg += "'%s'" % enumValueToNameLookup(PAYLOAD.TECHNIQUE, technique)
logger.warn(warnMsg)
except sqlmapDataException:
except SqlmapDataException:
errMsg = "missing data in old session file(s). "
errMsg += "Please use '--flush-session' to deal "
errMsg += "with this error"
raise sqlmapNoneDataException, errMsg
raise SqlmapNoneDataException, errMsg
def arrayizeValue(value):
"""
@@ -2543,7 +2543,7 @@ def openFile(filename, mode='r'):
errMsg += "Please check %s permissions on a file " % ("write" if \
mode and ('w' in mode or 'a' in mode or '+' in mode) else "read")
errMsg += "and that it's not locked by another process."
raise sqlmapFilePathException, errMsg
raise SqlmapFilePathException, errMsg
def decodeIntToUnicode(value):
"""
@@ -2857,7 +2857,7 @@ def expandMnemonics(mnemonics, parser, args):
if pointer in (None, head):
errMsg = "mnemonic '%s' can't be resolved to any parameter name" % name
raise sqlmapSyntaxException, errMsg
raise SqlmapSyntaxException, errMsg
elif len(pointer.current) > 1:
options = {}
@@ -2896,7 +2896,7 @@ def expandMnemonics(mnemonics, parser, args):
setattr(args, found.dest, True)
else:
errMsg = "mnemonic '%s' requires value of type '%s'" % (name, found.type)
raise sqlmapSyntaxException, errMsg
raise SqlmapSyntaxException, errMsg
def safeCSValue(value):
"""
@@ -3044,7 +3044,7 @@ def findPageForms(content, url, raise_=False, addToTargets=False):
if not content:
errMsg = "can't parse forms as the page content appears to be blank"
if raise_:
raise sqlmapGenericException, errMsg
raise SqlmapGenericException, errMsg
else:
logger.debug(errMsg)
@@ -3064,7 +3064,7 @@ def findPageForms(content, url, raise_=False, addToTargets=False):
except ParseError:
errMsg = "no success"
if raise_:
raise sqlmapGenericException, errMsg
raise SqlmapGenericException, errMsg
else:
logger.debug(errMsg)
@@ -3085,7 +3085,7 @@ def findPageForms(content, url, raise_=False, addToTargets=False):
errMsg = "there has been a problem while "
errMsg += "processing page forms ('%s')" % ex
if raise_:
raise sqlmapGenericException, errMsg
raise SqlmapGenericException, errMsg
else:
logger.debug(errMsg)
else:
@@ -3104,7 +3104,7 @@ def findPageForms(content, url, raise_=False, addToTargets=False):
else:
errMsg = "there were no forms found at the given target url"
if raise_:
raise sqlmapGenericException, errMsg
raise SqlmapGenericException, errMsg
else:
logger.debug(errMsg)
@@ -3152,7 +3152,7 @@ def checkDeprecatedOptions(args):
errMsg = "switch/option '%s' is deprecated" % _
if _ in DEPRECATED_HINTS:
errMsg += " (hint: %s)" % DEPRECATED_HINTS[_]
raise sqlmapSyntaxException, errMsg
raise SqlmapSyntaxException, errMsg
def evaluateCode(code, variables=None):
"""
@@ -3165,7 +3165,7 @@ def evaluateCode(code, variables=None):
raise
except Exception, ex:
errMsg = "an error occured while evaluating provided code ('%s'). " % ex
raise sqlmapGenericException, errMsg
raise SqlmapGenericException, errMsg
def serializeObject(object_):
"""
@@ -3304,7 +3304,7 @@ def resetCookieJar(cookieJar):
except cookielib.LoadError, msg:
errMsg = "there was a problem loading "
errMsg += "cookies file ('%s')" % msg
raise sqlmapGenericException, errMsg
raise SqlmapGenericException, errMsg
def prioritySortColumns(columns):
"""

View File

@@ -8,7 +8,7 @@ See the file 'doc/COPYING' for copying permission
import copy
import types
from lib.core.exception import sqlmapDataException
from lib.core.exception import SqlmapDataException
class AttribDict(dict):
"""
@@ -38,7 +38,7 @@ class AttribDict(dict):
try:
return self.__getitem__(item)
except KeyError:
raise sqlmapDataException, "unable to access item '%s'" % item
raise SqlmapDataException, "unable to access item '%s'" % item
def __setattr__(self, item, value):
"""

View File

@@ -27,8 +27,8 @@ from lib.core.data import logger
from lib.core.dicts import DUMP_REPLACEMENTS
from lib.core.enums import DBMS
from lib.core.enums import DUMP_FORMAT
from lib.core.exception import sqlmapGenericException
from lib.core.exception import sqlmapValueException
from lib.core.exception import SqlmapGenericException
from lib.core.exception import SqlmapValueException
from lib.core.replication import Replication
from lib.core.settings import HTML_DUMP_CSS_STYLE
from lib.core.settings import METADB_SUFFIX
@@ -68,7 +68,7 @@ class Dump(object):
self._outputFP = codecs.open(self._outputFile, "ab", UNICODE_ENCODING)
except IOError, ex:
errMsg = "error occurred while opening log file ('%s')" % ex
raise sqlmapGenericException, errMsg
raise SqlmapGenericException, errMsg
def getOutputFile(self):
return self._outputFile
@@ -490,7 +490,7 @@ class Dump(object):
if conf.dumpFormat == DUMP_FORMAT.SQLITE:
try:
rtable.insert(values)
except sqlmapValueException:
except SqlmapValueException:
pass
elif conf.dumpFormat == DUMP_FORMAT.CSV:
dataToDumpFile(dumpFP, "\n")

View File

@@ -5,79 +5,79 @@ Copyright (c) 2006-2012 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission
"""
class sqlmapCompressionException(Exception):
class SqlmapCompressionException(Exception):
pass
class sqlmapConnectionException(Exception):
class SqlmapConnectionException(Exception):
pass
class sqlmapDataException(Exception):
class SqlmapDataException(Exception):
pass
class sqlmapFilePathException(Exception):
class SqlmapFilePathException(Exception):
pass
class sqlmapGenericException(Exception):
class SqlmapGenericException(Exception):
pass
class sqlmapMissingDependence(Exception):
class SqlmapMissingDependence(Exception):
pass
class sqlmapMissingMandatoryOptionException(Exception):
class SqlmapMissingMandatoryOptionException(Exception):
pass
class sqlmapMissingPrivileges(Exception):
class SqlmapMissingPrivileges(Exception):
pass
class sqlmapNoneDataException(Exception):
class SqlmapNoneDataException(Exception):
pass
class sqlmapNotVulnerableException(Exception):
class SqlmapNotVulnerableException(Exception):
pass
class sqlmapSilentQuitException(Exception):
class SqlmapSilentQuitException(Exception):
pass
class sqlmapUserQuitException(Exception):
class SqlmapUserQuitException(Exception):
pass
class sqlmapRegExprException(Exception):
class SqlmapRegExprException(Exception):
pass
class sqlmapSyntaxException(Exception):
class SqlmapSyntaxException(Exception):
pass
class sqlmapThreadException(Exception):
class SqlmapThreadException(Exception):
pass
class sqlmapUndefinedMethod(Exception):
class SqlmapUndefinedMethod(Exception):
pass
class sqlmapUnsupportedDBMSException(Exception):
class SqlmapUnsupportedDBMSException(Exception):
pass
class sqlmapUnsupportedFeatureException(Exception):
class SqlmapUnsupportedFeatureException(Exception):
pass
class sqlmapValueException(Exception):
class SqlmapValueException(Exception):
pass
exceptionsTuple = (
sqlmapCompressionException,
sqlmapConnectionException,
sqlmapDataException,
sqlmapFilePathException,
sqlmapGenericException,
sqlmapMissingDependence,
sqlmapMissingMandatoryOptionException,
sqlmapNoneDataException,
sqlmapRegExprException,
sqlmapSyntaxException,
sqlmapUndefinedMethod,
sqlmapMissingPrivileges,
sqlmapNotVulnerableException,
sqlmapThreadException,
sqlmapUnsupportedDBMSException,
sqlmapUnsupportedFeatureException,
sqlmapValueException,
SqlmapCompressionException,
SqlmapConnectionException,
SqlmapDataException,
SqlmapFilePathException,
SqlmapGenericException,
SqlmapMissingDependence,
SqlmapMissingMandatoryOptionException,
SqlmapNoneDataException,
SqlmapRegExprException,
SqlmapSyntaxException,
SqlmapUndefinedMethod,
SqlmapMissingPrivileges,
SqlmapNotVulnerableException,
SqlmapThreadException,
SqlmapUnsupportedDBMSException,
SqlmapUnsupportedFeatureException,
SqlmapValueException,
)

View File

@@ -71,16 +71,16 @@ from lib.core.enums import PRIORITY
from lib.core.enums import PROXY_TYPE
from lib.core.enums import REFLECTIVE_COUNTER
from lib.core.enums import WIZARD
from lib.core.exception import sqlmapConnectionException
from lib.core.exception import sqlmapFilePathException
from lib.core.exception import sqlmapGenericException
from lib.core.exception import sqlmapMissingDependence
from lib.core.exception import sqlmapMissingMandatoryOptionException
from lib.core.exception import sqlmapMissingPrivileges
from lib.core.exception import sqlmapSilentQuitException
from lib.core.exception import sqlmapSyntaxException
from lib.core.exception import sqlmapUnsupportedDBMSException
from lib.core.exception import sqlmapUserQuitException
from lib.core.exception import SqlmapConnectionException
from lib.core.exception import SqlmapFilePathException
from lib.core.exception import SqlmapGenericException
from lib.core.exception import SqlmapMissingDependence
from lib.core.exception import SqlmapMissingMandatoryOptionException
from lib.core.exception import SqlmapMissingPrivileges
from lib.core.exception import SqlmapSilentQuitException
from lib.core.exception import SqlmapSyntaxException
from lib.core.exception import SqlmapUnsupportedDBMSException
from lib.core.exception import SqlmapUserQuitException
from lib.core.log import FORMATTER
from lib.core.log import LOGGER_HANDLER
from lib.core.optiondict import optDict
@@ -186,12 +186,12 @@ def __urllib2Opener():
opener = urllib2.build_opener(*handlers)
urllib2.install_opener(opener)
def __feedTargetsDict(reqFile, addedTargetUrls):
def _feedTargetsDict(reqFile, addedTargetUrls):
"""
Parses web scarab and burp logs and adds results to the target url list
"""
def __parseWebScarabLog(content):
def _parseWebScarabLog(content):
"""
Parses web scarab logs (POST method not supported)
"""
@@ -219,7 +219,7 @@ def __feedTargetsDict(reqFile, addedTargetUrls):
kb.targets.add((url, method, None, cookie))
addedTargetUrls.add(url)
def __parseBurpLog(content):
def _parseBurpLog(content):
"""
Parses burp logs
"""
@@ -337,10 +337,10 @@ def __feedTargetsDict(reqFile, addedTargetUrls):
if conf.scope:
logger.info("using regular expression '%s' for filtering targets" % conf.scope)
__parseBurpLog(content)
__parseWebScarabLog(content)
_parseBurpLog(content)
_parseWebScarabLog(content)
def __loadQueries():
def _loadQueries():
"""
Loads queries from 'xml/queries.xml' file.
"""
@@ -371,7 +371,7 @@ def __loadQueries():
for node in tree.findall("*"):
queries[node.attrib['value']] = iterate(node)
def __setMultipleTargets():
def _setMultipleTargets():
"""
Define a configuration parameter if we are running in multiple target
mode.
@@ -388,10 +388,10 @@ def __setMultipleTargets():
if not os.path.exists(conf.logFile):
errMsg = "the specified list of targets does not exist"
raise sqlmapFilePathException, errMsg
raise SqlmapFilePathException, errMsg
if os.path.isfile(conf.logFile):
__feedTargetsDict(conf.logFile, addedTargetUrls)
_feedTargetsDict(conf.logFile, addedTargetUrls)
elif os.path.isdir(conf.logFile):
files = os.listdir(conf.logFile)
@@ -401,12 +401,12 @@ def __setMultipleTargets():
if not re.search("([\d]+)\-request", reqFile):
continue
__feedTargetsDict(os.path.join(conf.logFile, reqFile), addedTargetUrls)
_feedTargetsDict(os.path.join(conf.logFile, reqFile), addedTargetUrls)
else:
errMsg = "the specified list of targets is not a file "
errMsg += "nor a directory"
raise sqlmapFilePathException, errMsg
raise SqlmapFilePathException, errMsg
updatedTargetsCount = len(kb.targets)
@@ -415,7 +415,7 @@ def __setMultipleTargets():
infoMsg += "testable requests from the targets list"
logger.info(infoMsg)
def __adjustLoggingFormatter():
def _adjustLoggingFormatter():
"""
Solves problem of line deletition caused by overlapping logging messages
and retrieved data info in inference mode
@@ -434,7 +434,7 @@ def __adjustLoggingFormatter():
FORMATTER._format = FORMATTER.format
FORMATTER.format = format
def __setRequestFromFile():
def _setRequestFromFile():
"""
This function checks if the way to make a HTTP request is through supplied
textual file, parses it and saves the information into the knowledge base.
@@ -453,18 +453,18 @@ def __setRequestFromFile():
if not os.path.isfile(conf.requestFile):
errMsg = "the specified HTTP request file "
errMsg += "does not exist"
raise sqlmapFilePathException, errMsg
raise SqlmapFilePathException, errMsg
__feedTargetsDict(conf.requestFile, addedTargetUrls)
_feedTargetsDict(conf.requestFile, addedTargetUrls)
def __setCrawler():
def _setCrawler():
if not conf.crawlDepth:
return
crawler = Crawler()
crawler.getTargetUrls()
def __setGoogleDorking():
def _setGoogleDorking():
"""
This function checks if the way to request testable hosts is through
Google dorking then requests to Google the search parameter, parses
@@ -504,7 +504,7 @@ def __setGoogleDorking():
if not links:
errMsg = "unable to find results for your "
errMsg += "Google dork expression"
raise sqlmapGenericException, errMsg
raise SqlmapGenericException, errMsg
for link in links:
link = urldecode(link)
@@ -544,11 +544,11 @@ def __setGoogleDorking():
test = readInput(message, default="Y")
if test[0] in ("n", "N"):
raise sqlmapSilentQuitException
raise SqlmapSilentQuitException
else:
conf.googlePage += 1
def __setBulkMultipleTargets():
def _setBulkMultipleTargets():
if not conf.bulkFile:
return
@@ -560,13 +560,13 @@ def __setBulkMultipleTargets():
if not os.path.isfile(conf.bulkFile):
errMsg = "the specified bulk file "
errMsg += "does not exist"
raise sqlmapFilePathException, errMsg
raise SqlmapFilePathException, errMsg
for line in getFileItems(conf.bulkFile):
if re.search(r"[^ ]+\?(.+)", line, re.I):
kb.targets.add((line.strip(), None, None, None))
def __findPageForms():
def _findPageForms():
if not conf.forms or conf.crawlDepth:
return
@@ -580,7 +580,7 @@ def __findPageForms():
findPageForms(page, conf.url, True, True)
def __setDBMSAuthentication():
def _setDBMSAuthentication():
"""
Check and set the DBMS authentication credentials to run statements as
another user, not the session user
@@ -597,12 +597,12 @@ def __setDBMSAuthentication():
if not match:
errMsg = "DBMS authentication credentials value must be in format "
errMsg += "username:password"
raise sqlmapSyntaxException, errMsg
raise SqlmapSyntaxException, errMsg
conf.dbmsUsername = match.group(1)
conf.dbmsPassword = match.group(2)
def __setMetasploit():
def _setMetasploit():
if not conf.osPwn and not conf.osSmb and not conf.osBof:
return
@@ -636,7 +636,7 @@ def __setMetasploit():
errMsg += "if you want to perform a SMB relay attack because "
errMsg += "it will need to listen on a user-specified SMB "
errMsg += "TCP port for incoming connection attempts"
raise sqlmapMissingPrivileges, errMsg
raise SqlmapMissingPrivileges, errMsg
if conf.msfPath:
for path in (conf.msfPath, os.path.join(conf.msfPath, "bin")):
@@ -685,9 +685,9 @@ def __setMetasploit():
if not msfEnvPathExists:
errMsg = "unable to locate Metasploit Framework installation. "
errMsg += "Get it from http://metasploit.com/framework/download/"
raise sqlmapFilePathException, errMsg
raise SqlmapFilePathException, errMsg
def __setWriteFile():
def _setWriteFile():
if not conf.wFile:
return
@@ -696,16 +696,16 @@ def __setWriteFile():
if not os.path.exists(conf.wFile):
errMsg = "the provided local file '%s' does not exist" % conf.wFile
raise sqlmapFilePathException, errMsg
raise SqlmapFilePathException, errMsg
if not conf.dFile:
errMsg = "you did not provide the back-end DBMS absolute path "
errMsg += "where you want to write the local file '%s'" % conf.wFile
raise sqlmapMissingMandatoryOptionException, errMsg
raise SqlmapMissingMandatoryOptionException, errMsg
conf.wFileType = getFileType(conf.wFile)
def __setOS():
def _setOS():
"""
Force the back-end DBMS operating system option.
"""
@@ -720,7 +720,7 @@ def __setOS():
errMsg += "If you do not know the back-end DBMS underlying OS, "
errMsg += "do not provide it and sqlmap will fingerprint it for "
errMsg += "you."
raise sqlmapUnsupportedDBMSException, errMsg
raise SqlmapUnsupportedDBMSException, errMsg
debugMsg = "forcing back-end DBMS operating system to user defined "
debugMsg += "value '%s'" % conf.os
@@ -728,7 +728,7 @@ def __setOS():
Backend.setOs(conf.os)
def __setTechnique():
def _setTechnique():
validTechniques = sorted(getPublicTypeMembers(PAYLOAD.TECHNIQUE), key=lambda x: x[1])
validLetters = map(lambda x: x[0][0].upper(), validTechniques)
@@ -740,7 +740,7 @@ def __setTechnique():
errMsg = "value for --technique must be a string composed "
errMsg += "by the letters %s. Refer to the " % ", ".join(validLetters)
errMsg += "user's manual for details"
raise sqlmapSyntaxException, errMsg
raise SqlmapSyntaxException, errMsg
for validTech, validInt in validTechniques:
if letter == validTech[0]:
@@ -749,7 +749,7 @@ def __setTechnique():
conf.tech = _
def __setDBMS():
def _setDBMS():
"""
Force the back-end DBMS option.
"""
@@ -772,7 +772,7 @@ def __setDBMS():
errMsg += "system. The supported DBMS are %s. " % ', '.join([d for d in DBMS_DICT])
errMsg += "If you do not know the back-end DBMS, do not provide "
errMsg += "it and sqlmap will fingerprint it for you."
raise sqlmapUnsupportedDBMSException, errMsg
raise SqlmapUnsupportedDBMSException, errMsg
for aliases in (MSSQL_ALIASES, MYSQL_ALIASES, PGSQL_ALIASES, ORACLE_ALIASES, \
SQLITE_ALIASES, ACCESS_ALIASES, FIREBIRD_ALIASES, \
@@ -782,7 +782,7 @@ def __setDBMS():
break
def __setTamperingFunctions():
def _setTamperingFunctions():
"""
Loads tampering functions from given script(s)
"""
@@ -806,11 +806,11 @@ def __setTamperingFunctions():
elif not os.path.exists(tfile):
errMsg = "tamper script '%s' does not exist" % tfile
raise sqlmapFilePathException, errMsg
raise SqlmapFilePathException, errMsg
elif not tfile.endswith('.py'):
errMsg = "tamper script '%s' should have an extension '.py'" % tfile
raise sqlmapSyntaxException, errMsg
raise SqlmapSyntaxException, errMsg
dirname, filename = os.path.split(tfile)
dirname = os.path.abspath(dirname)
@@ -821,7 +821,7 @@ def __setTamperingFunctions():
if not os.path.exists(os.path.join(dirname, '__init__.py')):
errMsg = "make sure that there is an empty file '__init__.py' "
errMsg += "inside of tamper scripts directory '%s'" % dirname
raise sqlmapGenericException, errMsg
raise SqlmapGenericException, errMsg
if dirname not in sys.path:
sys.path.insert(0, dirname)
@@ -829,7 +829,7 @@ def __setTamperingFunctions():
try:
module = __import__(filename[:-3])
except ImportError, msg:
raise sqlmapSyntaxException, "cannot import tamper script '%s' (%s)" % (filename[:-3], msg)
raise SqlmapSyntaxException, "cannot import tamper script '%s' (%s)" % (filename[:-3], msg)
priority = PRIORITY.NORMAL if not hasattr(module, '__priority__') else module.__priority__
@@ -850,7 +850,7 @@ def __setTamperingFunctions():
elif test[0] in ("n", "N"):
resolve_priorities = False
elif test[0] in ("q", "Q"):
raise sqlmapUserQuitException
raise SqlmapUserQuitException
check_priority = False
@@ -864,7 +864,7 @@ def __setTamperingFunctions():
if not found:
errMsg = "missing function 'tamper(payload, headers)' "
errMsg += "in tamper script '%s'" % tfile
raise sqlmapGenericException, errMsg
raise SqlmapGenericException, errMsg
if resolve_priorities and priorities:
priorities.sort(reverse=True)
@@ -873,11 +873,11 @@ def __setTamperingFunctions():
for _, function in priorities:
kb.tamperFunctions.append(function)
def __setThreads():
def _setThreads():
if not isinstance(conf.threads, int) or conf.threads <= 0:
conf.threads = 1
def __setDNSCache():
def _setDNSCache():
"""
Makes a cached version of socket._getaddrinfo to avoid subsequent DNS requests.
"""
@@ -894,7 +894,7 @@ def __setDNSCache():
socket._getaddrinfo = socket.getaddrinfo
socket.getaddrinfo = _getaddrinfo
def __setHTTPProxy():
def _setHTTPProxy():
"""
Check and set the HTTP proxy to pass by all HTTP requests.
"""
@@ -927,14 +927,14 @@ def __setHTTPProxy():
if not all((scheme, hasattr(PROXY_TYPE, scheme), hostname, port)):
errMsg = "proxy value must be in format '(%s)://url:port'" % "|".join(_[0].lower() for _ in getPublicTypeMembers(PROXY_TYPE))
raise sqlmapSyntaxException, errMsg
raise SqlmapSyntaxException, errMsg
if conf.pCred:
_ = re.search("^(.*?):(.*?)$", conf.pCred)
if not _:
errMsg = "Proxy authentication credentials "
errMsg += "value must be in format username:password"
raise sqlmapSyntaxException, errMsg
raise SqlmapSyntaxException, errMsg
else:
username = _.group(1)
password = _.group(2)
@@ -962,7 +962,7 @@ def __setHTTPProxy():
else:
proxyHandler = urllib2.ProxyHandler({"http": proxyString})
def __setSafeUrl():
def _setSafeUrl():
"""
Check and set the safe URL options.
"""
@@ -977,9 +977,9 @@ def __setSafeUrl():
if conf.saFreq <= 0:
errMsg = "please provide a valid value (>0) for safe frequency (--safe-freq) while using safe url feature"
raise sqlmapSyntaxException, errMsg
raise SqlmapSyntaxException, errMsg
def __setPrefixSuffix():
def _setPrefixSuffix():
if conf.prefix is not None and conf.suffix is not None:
# Create a custom boundary object for user's supplied prefix
# and suffix
@@ -1007,7 +1007,7 @@ def __setPrefixSuffix():
# to be tested for
conf.boundaries = [ boundary ]
def __setAuthCred():
def _setAuthCred():
"""
Adds authentication credentials (if any) for current target to the password manager
(used by connection handler)
@@ -1016,7 +1016,7 @@ def __setAuthCred():
if kb.passwordMgr:
kb.passwordMgr.add_password(None, "%s://%s" % (conf.scheme, conf.hostname), conf.authUsername, conf.authPassword)
def __setHTTPAuthentication():
def _setHTTPAuthentication():
"""
Check and set the HTTP(s) authentication method (Basic, Digest, NTLM or Certificate),
username and password for first three methods, or key file and certification file for
@@ -1031,12 +1031,12 @@ def __setHTTPAuthentication():
elif conf.aType and not conf.aCred:
errMsg = "you specified the HTTP authentication type, but "
errMsg += "did not provide the credentials"
raise sqlmapSyntaxException, errMsg
raise SqlmapSyntaxException, errMsg
elif not conf.aType and conf.aCred:
errMsg = "you specified the HTTP authentication credentials, "
errMsg += "but did not provide the type"
raise sqlmapSyntaxException, errMsg
raise SqlmapSyntaxException, errMsg
if not conf.aCert:
debugMsg = "setting the HTTP authentication type and credentials"
@@ -1047,7 +1047,7 @@ def __setHTTPAuthentication():
if aTypeLower not in ( "basic", "digest", "ntlm" ):
errMsg = "HTTP authentication type value must be "
errMsg += "Basic, Digest or NTLM"
raise sqlmapSyntaxException, errMsg
raise SqlmapSyntaxException, errMsg
elif aTypeLower in ( "basic", "digest" ):
regExp = "^(.*?):(.*?)$"
errMsg = "HTTP %s authentication credentials " % aTypeLower
@@ -1060,14 +1060,14 @@ def __setHTTPAuthentication():
aCredRegExp = re.search(regExp, conf.aCred)
if not aCredRegExp:
raise sqlmapSyntaxException, errMsg
raise SqlmapSyntaxException, errMsg
conf.authUsername = aCredRegExp.group(1)
conf.authPassword = aCredRegExp.group(2)
kb.passwordMgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
__setAuthCred()
_setAuthCred()
if aTypeLower == "basic":
authHandler = SmartHTTPBasicAuthHandler(kb.passwordMgr)
@@ -1082,7 +1082,7 @@ def __setHTTPAuthentication():
errMsg = "sqlmap requires Python NTLM third-party library "
errMsg += "in order to authenticate via NTLM, "
errMsg += "http://code.google.com/p/python-ntlm/"
raise sqlmapMissingDependence, errMsg
raise SqlmapMissingDependence, errMsg
authHandler = HTTPNtlmAuthHandler.HTTPNtlmAuthHandler(kb.passwordMgr)
else:
@@ -1094,7 +1094,7 @@ def __setHTTPAuthentication():
if not aCertRegExp:
errMsg = "HTTP authentication certificate option "
errMsg += "must be in format key_file,cert_file"
raise sqlmapSyntaxException, errMsg
raise SqlmapSyntaxException, errMsg
# os.path.expanduser for support of paths with ~
key_file = os.path.expanduser(aCertRegExp.group(1))
@@ -1103,11 +1103,11 @@ def __setHTTPAuthentication():
for ifile in (key_file, cert_file):
if not os.path.exists(ifile):
errMsg = "File '%s' does not exist" % ifile
raise sqlmapSyntaxException, errMsg
raise SqlmapSyntaxException, errMsg
authHandler = HTTPSCertAuthHandler(key_file, cert_file)
def __setHTTPMethod():
def _setHTTPMethod():
"""
Check and set the HTTP method to perform HTTP requests through.
"""
@@ -1117,7 +1117,7 @@ def __setHTTPMethod():
debugMsg = "setting the HTTP method to %s" % conf.method
logger.debug(debugMsg)
def __setHTTPExtraHeaders():
def _setHTTPExtraHeaders():
if conf.headers:
debugMsg = "setting extra HTTP headers"
logger.debug(debugMsg)
@@ -1132,7 +1132,7 @@ def __setHTTPExtraHeaders():
conf.httpHeaders.append((header, value))
else:
errMsg = "invalid header value: %s. Valid header format is 'name:value'" % repr(headerValue).lstrip('u')
raise sqlmapSyntaxException, errMsg
raise SqlmapSyntaxException, errMsg
elif not conf.httpHeaders or len(conf.httpHeaders) == 1:
conf.httpHeaders.append((HTTPHEADER.ACCEPT_LANGUAGE, "en-us,en;q=0.5"))
@@ -1146,7 +1146,7 @@ def __setHTTPExtraHeaders():
conf.httpHeaders.append((HTTPHEADER.CACHE_CONTROL, "no-cache,no-store"))
conf.httpHeaders.append((HTTPHEADER.PRAGMA, "no-cache"))
def __defaultHTTPUserAgent():
def _defaultHTTPUserAgent():
"""
@return: default sqlmap HTTP User-Agent header
@rtype: C{str}
@@ -1161,7 +1161,7 @@ def __defaultHTTPUserAgent():
# updated at March 2009
#return "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.04506.648; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)"
def __setHTTPUserAgent():
def _setHTTPUserAgent():
"""
Set the HTTP User-Agent header.
Depending on the user options it can be:
@@ -1205,7 +1205,7 @@ def __setHTTPUserAgent():
break
if _:
conf.httpHeaders.append((HTTPHEADER.USER_AGENT, __defaultHTTPUserAgent()))
conf.httpHeaders.append((HTTPHEADER.USER_AGENT, _defaultHTTPUserAgent()))
else:
if not kb.userAgents:
@@ -1220,7 +1220,7 @@ def __setHTTPUserAgent():
warnMsg += "file '%s'" % paths.USER_AGENTS
logger.warn(warnMsg)
conf.httpHeaders.append((HTTPHEADER.USER_AGENT, __defaultHTTPUserAgent()))
conf.httpHeaders.append((HTTPHEADER.USER_AGENT, _defaultHTTPUserAgent()))
return
count = len(kb.userAgents)
@@ -1237,7 +1237,7 @@ def __setHTTPUserAgent():
infoMsg += "file '%s': %s" % (paths.USER_AGENTS, userAgent)
logger.info(infoMsg)
def __setHTTPReferer():
def _setHTTPReferer():
"""
Set the HTTP Referer
"""
@@ -1248,7 +1248,7 @@ def __setHTTPReferer():
conf.httpHeaders.append((HTTPHEADER.REFERER, conf.referer))
def __setHTTPCookies():
def _setHTTPCookies():
"""
Set the HTTP Cookie header
"""
@@ -1259,7 +1259,7 @@ def __setHTTPCookies():
conf.httpHeaders.append((HTTPHEADER.COOKIE, conf.cookie))
def __setHTTPTimeout():
def _setHTTPTimeout():
"""
Set the HTTP timeout
"""
@@ -1281,7 +1281,7 @@ def __setHTTPTimeout():
socket.setdefaulttimeout(conf.timeout)
def __checkDependencies():
def _checkDependencies():
"""
Checks for missing dependencies.
"""
@@ -1289,7 +1289,7 @@ def __checkDependencies():
if conf.dependencies:
checkDependencies()
def __cleanupOptions():
def _cleanupOptions():
"""
Cleanup configuration attributes.
"""
@@ -1425,7 +1425,7 @@ def __cleanupOptions():
threadData = getCurrentThreadData()
threadData.reset()
def __purgeOutput():
def _purgeOutput():
"""
Safely removes (purges) output directory.
"""
@@ -1433,7 +1433,7 @@ def __purgeOutput():
if conf.purgeOutput:
purge(paths.SQLMAP_OUTPUT_PATH)
def __setConfAttributes():
def _setConfAttributes():
"""
This function set some needed attributes into the configuration
singleton.
@@ -1469,7 +1469,7 @@ def __setConfAttributes():
conf.trafficFP = None
conf.wFileType = None
def __setKnowledgeBaseAttributes(flushAll=True):
def _setKnowledgeBaseAttributes(flushAll=True):
"""
This function set some needed attributes into the knowledge base
singleton.
@@ -1604,7 +1604,7 @@ def __setKnowledgeBaseAttributes(flushAll=True):
kb.vulnHosts = set()
kb.wordlists = None
def __useWizardInterface():
def _useWizardInterface():
"""
Presents simple wizard interface for beginner users
"""
@@ -1674,7 +1674,7 @@ def __useWizardInterface():
dataToStdout("\nsqlmap is running, please wait..\n\n")
def __saveCmdline():
def _saveCmdline():
"""
Saves the command line options on a sqlmap configuration INI file
Format.
@@ -1730,7 +1730,7 @@ def __saveCmdline():
infoMsg = "saved command line options on '%s' configuration file" % paths.SQLMAP_CONFIG
logger.info(infoMsg)
def __setVerbosity():
def _setVerbosity():
"""
This function set the verbosity of sqlmap output messages.
"""
@@ -1756,7 +1756,7 @@ def __setVerbosity():
elif conf.verbose >= 5:
logger.setLevel(CUSTOM_LOGGING.TRAFFIC_IN)
def __mergeOptions(inputOptions, overrideOptions):
def _mergeOptions(inputOptions, overrideOptions):
"""
Merge command line options with configuration file and default options.
@@ -1784,14 +1784,14 @@ def __mergeOptions(inputOptions, overrideOptions):
if conf[key] is None:
conf[key] = value
def __setTrafficOutputFP():
def _setTrafficOutputFP():
if conf.trafficFile:
infoMsg = "setting file for logging HTTP traffic"
logger.info(infoMsg)
conf.trafficFP = openFile(conf.trafficFile, "w+")
def __setDNSServer():
def _setDNSServer():
if not conf.dnsName:
return
@@ -1807,24 +1807,24 @@ def __setDNSServer():
except socket.error, msg:
errMsg = "there was an error while setting up "
errMsg += "DNS server instance ('%s')" % msg
raise sqlmapGenericException, errMsg
raise SqlmapGenericException, errMsg
else:
errMsg = "you need to run sqlmap as an administrator "
errMsg += "if you want to perform a DNS data exfiltration attack "
errMsg += "as it will need to listen on privileged UDP port 53 "
errMsg += "for incoming address resolution attempts"
raise sqlmapMissingPrivileges, errMsg
raise SqlmapMissingPrivileges, errMsg
def __setTorProxySettings():
def _setTorProxySettings():
if not conf.tor:
return
if conf.torType == PROXY_TYPE.HTTP:
__setTorHttpProxySettings()
_setTorHttpProxySettings()
else:
__setTorSocksProxySettings()
_setTorSocksProxySettings()
def __setTorHttpProxySettings():
def _setTorHttpProxySettings():
infoMsg = "setting Tor HTTP proxy settings"
logger.info(infoMsg)
@@ -1854,7 +1854,7 @@ def __setTorHttpProxySettings():
else:
errMsg += "(e.g. http://www.coresec.org/2011/04/24/sqlmap-with-tor/)"
raise sqlmapConnectionException, errMsg
raise SqlmapConnectionException, errMsg
if not conf.checkTor:
warnMsg = "use switch '--check-tor' at "
@@ -1865,7 +1865,7 @@ def __setTorHttpProxySettings():
warnMsg += "(e.g. Vidalia)"
logger.warn(warnMsg)
def __setTorSocksProxySettings():
def _setTorSocksProxySettings():
infoMsg = "setting Tor SOCKS proxy settings"
logger.info(infoMsg)
@@ -1873,7 +1873,7 @@ def __setTorSocksProxySettings():
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5 if conf.torType == PROXY_TYPE.SOCKS5 else socks.PROXY_TYPE_SOCKS4, LOCALHOST, conf.torPort or DEFAULT_TOR_SOCKS_PORT)
socks.wrapmodule(urllib2)
def __checkTor():
def _checkTor():
if not conf.checkTor:
return
@@ -1883,143 +1883,143 @@ def __checkTor():
page, _, _ = Request.getPage(url="https://check.torproject.org/", raise404=False)
if not page or 'Congratulations' not in page:
errMsg = "it seems that Tor is not properly set. Please try using options '--tor-type' and/or '--tor-port'"
raise sqlmapConnectionException, errMsg
raise SqlmapConnectionException, errMsg
else:
infoMsg = "Tor is properly being used"
logger.info(infoMsg)
def __basicOptionValidation():
def _basicOptionValidation():
if conf.limitStart is not None and not (isinstance(conf.limitStart, int) and conf.limitStart > 0):
errMsg = "value for option '--start' (limitStart) must be an integer value greater than zero (>0)"
raise sqlmapSyntaxException, errMsg
raise SqlmapSyntaxException, errMsg
if conf.limitStop is not None and not (isinstance(conf.limitStop, int) and conf.limitStop > 0):
errMsg = "value for option '--stop' (limitStop) must be an integer value greater than zero (>0)"
raise sqlmapSyntaxException, errMsg
raise SqlmapSyntaxException, errMsg
if conf.level is not None and not (isinstance(conf.level, int) and conf.level > 0):
errMsg = "value for option '--level' must be an integer value greater than zero (>0)"
raise sqlmapSyntaxException, errMsg
raise SqlmapSyntaxException, errMsg
if conf.risk is not None and not (isinstance(conf.risk, int) and conf.risk > 0):
errMsg = "value for option '--risk' must be an integer value greater than zero (>0)"
raise sqlmapSyntaxException, errMsg
raise SqlmapSyntaxException, errMsg
if conf.limitStart is not None and isinstance(conf.limitStart, int) and conf.limitStart > 0 and \
conf.limitStop is not None and isinstance(conf.limitStop, int) and conf.limitStop < conf.limitStart:
errMsg = "value for option '--start' (limitStart) must be smaller or equal than value for --stop (limitStop) option"
raise sqlmapSyntaxException, errMsg
raise SqlmapSyntaxException, errMsg
if conf.firstChar is not None and isinstance(conf.firstChar, int) and conf.firstChar > 0 and \
conf.lastChar is not None and isinstance(conf.lastChar, int) and conf.lastChar < conf.firstChar:
errMsg = "value for option '--first' (firstChar) must be smaller than or equal to value for --last (lastChar) option"
raise sqlmapSyntaxException, errMsg
raise SqlmapSyntaxException, errMsg
if conf.cpuThrottle is not None and isinstance(conf.cpuThrottle, int) and (conf.cpuThrottle > 100 or conf.cpuThrottle < 0):
errMsg = "value for option '--cpu-throttle' (cpuThrottle) must be in range [0,100]"
raise sqlmapSyntaxException, errMsg
raise SqlmapSyntaxException, errMsg
if conf.textOnly and conf.nullConnection:
errMsg = "switch '--text-only' is incompatible with switch '--null-connection'"
raise sqlmapSyntaxException, errMsg
raise SqlmapSyntaxException, errMsg
if conf.titles and conf.nullConnection:
errMsg = "switch '--titles' is incompatible with switch '--null-connection'"
raise sqlmapSyntaxException, errMsg
raise SqlmapSyntaxException, errMsg
if conf.data and conf.nullConnection:
errMsg = "option '--data' is incompatible with switch '--null-connection'"
raise sqlmapSyntaxException, errMsg
raise SqlmapSyntaxException, errMsg
if conf.string and conf.nullConnection:
errMsg = "option '--string' is incompatible with switch '--null-connection'"
raise sqlmapSyntaxException, errMsg
raise SqlmapSyntaxException, errMsg
if conf.notString and conf.nullConnection:
errMsg = "option '--not-string' is incompatible with switch '--null-connection'"
raise sqlmapSyntaxException, errMsg
raise SqlmapSyntaxException, errMsg
if conf.string and conf.notString:
errMsg = "option '--string' is incompatible with switch '--not-string'"
raise sqlmapSyntaxException, errMsg
raise SqlmapSyntaxException, errMsg
if conf.regexp and conf.nullConnection:
errMsg = "option '--regexp' is incompatible with switch '--null-connection'"
raise sqlmapSyntaxException, errMsg
raise SqlmapSyntaxException, errMsg
if conf.dumpTable and conf.dumpAll:
errMsg = "switch '--dump' is incompatible with switch '--dump-all'"
raise sqlmapSyntaxException, errMsg
raise SqlmapSyntaxException, errMsg
if conf.predictOutput and (conf.threads > 1 or conf.optimize):
errMsg = "switch '--predict-output' is incompatible with option '--threads' and switch '-o'"
raise sqlmapSyntaxException, errMsg
raise SqlmapSyntaxException, errMsg
if conf.threads > MAX_NUMBER_OF_THREADS:
errMsg = "maximum number of used threads is %d avoiding possible connection issues" % MAX_NUMBER_OF_THREADS
raise sqlmapSyntaxException, errMsg
raise SqlmapSyntaxException, errMsg
if conf.forms and not conf.url:
errMsg = "switch '--forms' requires usage of option '-u' (--url)"
raise sqlmapSyntaxException, errMsg
raise SqlmapSyntaxException, errMsg
if conf.requestFile and conf.url:
errMsg = "option '-r' is incompatible with option '-u' (--url)"
raise sqlmapSyntaxException, errMsg
raise SqlmapSyntaxException, errMsg
if conf.tor and conf.ignoreProxy:
errMsg = "switch '--tor' is incompatible with switch '--ignore-proxy'"
raise sqlmapSyntaxException, errMsg
raise SqlmapSyntaxException, errMsg
if conf.tor and conf.proxy:
errMsg = "switch '--tor' is incompatible with option '--proxy'"
raise sqlmapSyntaxException, errMsg
raise SqlmapSyntaxException, errMsg
if conf.checkTor and not any((conf.tor, conf.proxy)):
errMsg = "switch '--check-tor' requires usage of switch '--tor' (or option '--proxy' with HTTP proxy address using Tor)"
raise sqlmapSyntaxException, errMsg
raise SqlmapSyntaxException, errMsg
if conf.torPort is not None and not (isinstance(conf.torPort, int) and conf.torPort > 0):
errMsg = "value for option '--tor-port' must be a positive integer"
raise sqlmapSyntaxException, errMsg
raise SqlmapSyntaxException, errMsg
if conf.torType not in getPublicTypeMembers(PROXY_TYPE, True):
errMsg = "option '--tor-type' accepts one of following values: %s" % ", ".join(getPublicTypeMembers(PROXY_TYPE, True))
raise sqlmapSyntaxException, errMsg
raise SqlmapSyntaxException, errMsg
if conf.dumpFormat not in getPublicTypeMembers(DUMP_FORMAT, True):
errMsg = "option '--dump-format' accepts one of following values: %s" % ", ".join(getPublicTypeMembers(DUMP_FORMAT, True))
raise sqlmapSyntaxException, errMsg
raise SqlmapSyntaxException, errMsg
if conf.skip and conf.testParameter:
errMsg = "option '--skip' is incompatible with option '-p'"
raise sqlmapSyntaxException, errMsg
raise SqlmapSyntaxException, errMsg
if conf.mobile and conf.agent:
errMsg = "switch '--mobile' is incompatible with option '--user-agent'"
raise sqlmapSyntaxException, errMsg
raise SqlmapSyntaxException, errMsg
if conf.proxy and conf.ignoreProxy:
errMsg = "option '--proxy' is incompatible with switch '--ignore-proxy'"
raise sqlmapSyntaxException, errMsg
raise SqlmapSyntaxException, errMsg
if conf.forms and any([conf.logFile, conf.bulkFile, conf.direct, conf.requestFile, conf.googleDork]):
errMsg = "switch '--forms' is compatible only with option '-u' (--url)"
raise sqlmapSyntaxException, errMsg
raise SqlmapSyntaxException, errMsg
if conf.timeSec < 1:
errMsg = "value for option '--time-sec' must be a positive integer"
raise sqlmapSyntaxException, errMsg
raise SqlmapSyntaxException, errMsg
if conf.uChar and not re.match(UNION_CHAR_REGEX, conf.uChar):
errMsg = "value for option '--union-char' must be an alpha-numeric value (e.g. 1)"
raise sqlmapSyntaxException, errMsg
raise SqlmapSyntaxException, errMsg
if isinstance(conf.uCols, basestring):
if not conf.uCols.isdigit() and ("-" not in conf.uCols or len(conf.uCols.split("-")) != 2):
errMsg = "value for option '--union-cols' must be a range with hyphon "
errMsg += "(e.g. 1-10) or integer value (e.g. 5)"
raise sqlmapSyntaxException, errMsg
raise SqlmapSyntaxException, errMsg
if conf.charset:
_ = checkCharEncoding(conf.charset, False)
@@ -2027,16 +2027,16 @@ def __basicOptionValidation():
errMsg = "unknown charset '%s'. Please visit " % conf.charset
errMsg += "'%s' to get the full list of " % CODECS_LIST_PAGE
errMsg += "supported charsets"
raise sqlmapSyntaxException, errMsg
raise SqlmapSyntaxException, errMsg
else:
conf.charset = _
if conf.loadCookies:
if not os.path.exists(conf.loadCookies):
errMsg = "cookies file '%s' does not exist" % conf.loadCookies
raise sqlmapFilePathException, errMsg
raise SqlmapFilePathException, errMsg
def __resolveCrossReferences():
def _resolveCrossReferences():
lib.core.threads.readInput = readInput
lib.core.common.getPageTemplate = getPageTemplate
lib.core.convert.singleTimeWarnMessage = singleTimeWarnMessage
@@ -2052,54 +2052,54 @@ def init(inputOptions=AttribDict(), overrideOptions=False):
else:
if hasattr(LOGGER_HANDLER, "disable_coloring"):
LOGGER_HANDLER.disable_coloring = True
__setConfAttributes()
__setKnowledgeBaseAttributes()
__mergeOptions(inputOptions, overrideOptions)
__useWizardInterface()
__setVerbosity()
__saveCmdline()
__setRequestFromFile()
__cleanupOptions()
__purgeOutput()
__checkDependencies()
__basicOptionValidation()
__setTorProxySettings()
__setDNSServer()
__adjustLoggingFormatter()
__setMultipleTargets()
__setTamperingFunctions()
__setTrafficOutputFP()
__resolveCrossReferences()
_setConfAttributes()
_setKnowledgeBaseAttributes()
_mergeOptions(inputOptions, overrideOptions)
_useWizardInterface()
_setVerbosity()
_saveCmdline()
_setRequestFromFile()
_cleanupOptions()
_purgeOutput()
_checkDependencies()
_basicOptionValidation()
_setTorProxySettings()
_setDNSServer()
_adjustLoggingFormatter()
_setMultipleTargets()
_setTamperingFunctions()
_setTrafficOutputFP()
_resolveCrossReferences()
parseTargetUrl()
parseTargetDirect()
if any((conf.url, conf.logFile, conf.bulkFile, conf.requestFile, conf.googleDork, conf.liveTest)):
__setHTTPTimeout()
__setHTTPExtraHeaders()
__setHTTPCookies()
__setHTTPReferer()
__setHTTPUserAgent()
__setHTTPMethod()
__setHTTPAuthentication()
__setHTTPProxy()
__setDNSCache()
__setSafeUrl()
__setGoogleDorking()
__setBulkMultipleTargets()
_setHTTPTimeout()
_setHTTPExtraHeaders()
_setHTTPCookies()
_setHTTPReferer()
_setHTTPUserAgent()
_setHTTPMethod()
_setHTTPAuthentication()
_setHTTPProxy()
_setDNSCache()
_setSafeUrl()
_setGoogleDorking()
_setBulkMultipleTargets()
__urllib2Opener()
__checkTor()
__setCrawler()
__findPageForms()
__setDBMS()
__setTechnique()
_checkTor()
_setCrawler()
_findPageForms()
_setDBMS()
_setTechnique()
__setThreads()
__setOS()
__setWriteFile()
__setMetasploit()
__setDBMSAuthentication()
_setThreads()
_setOS()
_setWriteFile()
_setMetasploit()
_setDBMSAuthentication()
loadPayloads()
__setPrefixSuffix()
_setPrefixSuffix()
update()
__loadQueries()
_loadQueries()

View File

@@ -15,8 +15,8 @@ class ProgressBar(object):
"""
def __init__(self, minValue=0, maxValue=10, totalWidth=None):
self.__progBar = "[]"
self.__oldProgBar = ""
self._progBar = "[]"
self._oldProgBar = ""
self.__min = int(minValue)
self.__max = int(maxValue)
self.__span = self.__max - self.__min
@@ -24,7 +24,7 @@ class ProgressBar(object):
self.__amount = 0
self.update()
def __convertSeconds(self, value):
def _convertSeconds(self, value):
seconds = value
minutes = seconds / 60
seconds = seconds - (minutes * 60)
@@ -56,34 +56,34 @@ class ProgressBar(object):
# Build a progress bar with an arrow of equal signs
if numHashes == 0:
self.__progBar = "[>%s]" % (" " * (allFull - 1))
self._progBar = "[>%s]" % (" " * (allFull - 1))
elif numHashes == allFull:
self.__progBar = "[%s]" % ("=" * allFull)
self._progBar = "[%s]" % ("=" * allFull)
else:
self.__progBar = "[%s>%s]" % ("=" * (numHashes - 1),
self._progBar = "[%s>%s]" % ("=" * (numHashes - 1),
" " * (allFull - numHashes))
# Add the percentage at the beginning of the progress bar
percentString = getUnicode(percentDone) + "%"
self.__progBar = "%s %s" % (percentString, self.__progBar)
self._progBar = "%s %s" % (percentString, self._progBar)
def draw(self, eta=0):
"""
This method draws the progress bar if it has changed
"""
if self.__progBar != self.__oldProgBar:
self.__oldProgBar = self.__progBar
if self._progBar != self._oldProgBar:
self._oldProgBar = self._progBar
if eta and self.__amount < self.__max:
dataToStdout("\r%s %d/%d ETA %s" % (self.__progBar, self.__amount, self.__max, self.__convertSeconds(int(eta))))
dataToStdout("\r%s %d/%d ETA %s" % (self._progBar, self.__amount, self.__max, self._convertSeconds(int(eta))))
else:
blank = " " * (80 - len("\r%s %d/%d" % (self.__progBar, self.__amount, self.__max)))
dataToStdout("\r%s %d/%d%s" % (self.__progBar, self.__amount, self.__max, blank))
blank = " " * (80 - len("\r%s %d/%d" % (self._progBar, self.__amount, self.__max)))
dataToStdout("\r%s %d/%d%s" % (self._progBar, self.__amount, self.__max, blank))
def __str__(self):
"""
This method returns the progress bar string
"""
return getUnicode(self.__progBar)
return getUnicode(self._progBar)

View File

@@ -9,8 +9,8 @@ import sqlite3
from extra.safe2bin.safe2bin import safechardecode
from lib.core.common import unsafeSQLIdentificatorNaming
from lib.core.exception import sqlmapGenericException
from lib.core.exception import sqlmapValueException
from lib.core.exception import SqlmapGenericException
from lib.core.exception import SqlmapValueException
class Replication(object):
"""
@@ -64,7 +64,7 @@ class Replication(object):
self.execute('INSERT INTO "%s" VALUES (%s)' % (self.name, ','.join(['?']*len(values))), safechardecode(values))
else:
errMsg = "wrong number of columns used in replicating insert"
raise sqlmapValueException, errMsg
raise SqlmapValueException, errMsg
def execute(self, sql, parameters=[]):
try:
@@ -73,7 +73,7 @@ class Replication(object):
errMsg = "problem occurred ('%s') while accessing sqlite database " % ex
errMsg += "located at '%s'. Please make sure that " % self.parent.dbpath
errMsg += "it's not used by some other program"
raise sqlmapGenericException, errMsg
raise SqlmapGenericException, errMsg
def beginTransaction(self):
"""

View File

@@ -31,14 +31,14 @@ from lib.core.enums import HTTPHEADER
from lib.core.enums import HTTPMETHOD
from lib.core.enums import PLACE
from lib.core.enums import POST_HINT
from lib.core.exception import sqlmapFilePathException
from lib.core.exception import sqlmapGenericException
from lib.core.exception import sqlmapMissingPrivileges
from lib.core.exception import sqlmapSyntaxException
from lib.core.exception import sqlmapUserQuitException
from lib.core.option import __setDBMS
from lib.core.option import __setKnowledgeBaseAttributes
from lib.core.option import __setAuthCred
from lib.core.exception import SqlmapFilePathException
from lib.core.exception import SqlmapGenericException
from lib.core.exception import SqlmapMissingPrivileges
from lib.core.exception import SqlmapSyntaxException
from lib.core.exception import SqlmapUserQuitException
from lib.core.option import _setDBMS
from lib.core.option import _setKnowledgeBaseAttributes
from lib.core.option import _setAuthCred
from lib.core.settings import CUSTOM_INJECTION_MARK_CHAR
from lib.core.settings import HOST_ALIASES
from lib.core.settings import JSON_RECOGNITION_REGEX
@@ -55,7 +55,7 @@ from lib.utils.hashdb import HashDB
from lib.core.xmldump import dumper as xmldumper
from thirdparty.odict.odict import OrderedDict
def __setRequestParams():
def _setRequestParams():
"""
Check and set the parameters and perform checks on 'data' option for
HTTP method POST.
@@ -79,7 +79,7 @@ def __setRequestParams():
# Perform checks on POST parameters
if conf.method == HTTPMETHOD.POST and conf.data is None:
errMsg = "HTTP POST method depends on HTTP data value to be posted"
raise sqlmapSyntaxException, errMsg
raise SqlmapSyntaxException, errMsg
if conf.data is not None:
conf.method = HTTPMETHOD.POST
@@ -92,7 +92,7 @@ def __setRequestParams():
message += "Do you want to process it? [Y/n/q] "
test = readInput(message, default="Y")
if test and test[0] in ("q", "Q"):
raise sqlmapUserQuitException
raise SqlmapUserQuitException
elif test[0] not in ("n", "N"):
conf.data = re.sub(r'("[^"]+"\s*:\s*"[^"]+)"', r'\g<1>%s"' % CUSTOM_INJECTION_MARK_CHAR, conf.data)
conf.data = re.sub(r'("[^"]+"\s*:\s*)(-?\d[\d\.]*\b)', r'\g<0>%s' % CUSTOM_INJECTION_MARK_CHAR, conf.data)
@@ -103,7 +103,7 @@ def __setRequestParams():
message += "Do you want to process it? [Y/n/q] "
test = readInput(message, default="Y")
if test and test[0] in ("q", "Q"):
raise sqlmapUserQuitException
raise SqlmapUserQuitException
elif test[0] not in ("n", "N"):
conf.data = re.sub(r"(<([^>]+)( [^<]*)?>)([^<]+)(</\2)", r"\g<1>\g<4>%s\g<5>" % CUSTOM_INJECTION_MARK_CHAR, conf.data)
kb.postHint = POST_HINT.SOAP if "soap" in conf.data.lower() else POST_HINT.XML
@@ -113,7 +113,7 @@ def __setRequestParams():
message += "Do you want to process it? [Y/n/q] "
test = readInput(message, default="Y")
if test and test[0] in ("q", "Q"):
raise sqlmapUserQuitException
raise SqlmapUserQuitException
elif test[0] not in ("n", "N"):
conf.data = re.sub(r"(?si)(Content-Disposition.+?)((\r)?\n--)", r"\g<1>%s\g<2>" % CUSTOM_INJECTION_MARK_CHAR, conf.data)
kb.postHint = POST_HINT.MULTIPART
@@ -145,7 +145,7 @@ def __setRequestParams():
conf.url = "%s%s" % (conf.url, CUSTOM_INJECTION_MARK_CHAR)
kb.processUserMarks = True
elif test[0] in ("q", "Q"):
raise sqlmapUserQuitException
raise SqlmapUserQuitException
for place, value in ((PLACE.URI, conf.url), (PLACE.CUSTOM_POST, conf.data)):
if CUSTOM_INJECTION_MARK_CHAR in (value or ""):
@@ -155,7 +155,7 @@ def __setRequestParams():
message += "'%s'. Do you want to process it? [Y/n/q] " % _[place]
test = readInput(message, default="Y")
if test and test[0] in ("q", "Q"):
raise sqlmapUserQuitException
raise SqlmapUserQuitException
else:
kb.processUserMarks = not test or test[0] not in ("n", "N")
@@ -236,14 +236,14 @@ def __setRequestParams():
if not conf.parameters:
errMsg = "you did not provide any GET, POST and Cookie "
errMsg += "parameter, neither an User-Agent, Referer or Host header value"
raise sqlmapGenericException, errMsg
raise SqlmapGenericException, errMsg
elif not testableParameters:
errMsg = "all testable parameters you provided are not present "
errMsg += "within the GET, POST and Cookie parameters"
raise sqlmapGenericException, errMsg
raise SqlmapGenericException, errMsg
def __setHashDB():
def _setHashDB():
"""
Check and set the HashDB SQLite file for query resume functionality.
"""
@@ -258,11 +258,11 @@ def __setHashDB():
logger.info("flushing session file")
except OSError, msg:
errMsg = "unable to flush the session file (%s)" % msg
raise sqlmapFilePathException, errMsg
raise SqlmapFilePathException, errMsg
conf.hashDB = HashDB(conf.hashDBFile)
def __resumeHashDBValues():
def _resumeHashDBValues():
"""
Resume stored data values from HashDB
"""
@@ -287,10 +287,10 @@ def __resumeHashDBValues():
if injection not in kb.injections:
kb.injections.append(injection)
__resumeDBMS()
__resumeOS()
_resumeDBMS()
_resumeOS()
def __resumeDBMS():
def _resumeDBMS():
"""
Resume stored DBMS information from HashDB
"""
@@ -335,7 +335,7 @@ def __resumeDBMS():
Backend.setDbms(dbms)
Backend.setVersionList(dbmsVersion)
def __resumeOS():
def _resumeOS():
"""
Resume stored OS information from HashDB
"""
@@ -367,7 +367,7 @@ def __resumeOS():
Backend.setOs(conf.os)
def __setResultsFile():
def _setResultsFile():
"""
Create results file for storing results of running in a
multiple target mode.
@@ -383,7 +383,7 @@ def __setResultsFile():
logger.info("using '%s' as the CSV results file in multiple targets mode" % conf.resultsFilename)
def __createFilesDir():
def _createFilesDir():
"""
Create the file directory.
"""
@@ -396,7 +396,7 @@ def __createFilesDir():
if not os.path.isdir(conf.filePath):
os.makedirs(conf.filePath, 0755)
def __createDumpDir():
def _createDumpDir():
"""
Create the dump directory.
"""
@@ -409,7 +409,7 @@ def __createDumpDir():
if not os.path.isdir(conf.dumpPath):
os.makedirs(conf.dumpPath, 0755)
def __configureDumper():
def _configureDumper():
if hasattr(conf, 'xmlFile') and conf.xmlFile:
conf.dumper = xmldumper
else:
@@ -417,7 +417,7 @@ def __configureDumper():
conf.dumper.setOutputFile()
def __createTargetDirs():
def _createTargetDirs():
"""
Create the output directory.
"""
@@ -459,13 +459,13 @@ def __createTargetDirs():
errMsg = "something went wrong while trying "
errMsg += "to write to the output directory '%s' (%s)" % (paths.SQLMAP_OUTPUT_PATH, msg)
raise sqlmapMissingPrivileges, errMsg
raise SqlmapMissingPrivileges, errMsg
__createDumpDir()
__createFilesDir()
__configureDumper()
_createDumpDir()
_createFilesDir()
_configureDumper()
def __restoreCmdLineOptions():
def _restoreCmdLineOptions():
"""
Restore command line options that could be possibly
changed during the testing of previous target.
@@ -490,14 +490,14 @@ def initTargetEnv():
conf.parameters = {}
conf.hashDBFile = None
__setKnowledgeBaseAttributes(False)
__restoreCmdLineOptions()
__setDBMS()
_setKnowledgeBaseAttributes(False)
_restoreCmdLineOptions()
_setDBMS()
def setupTargetEnv():
__createTargetDirs()
__setRequestParams()
__setHashDB()
__resumeHashDBValues()
__setResultsFile()
__setAuthCred()
_createTargetDirs()
_setRequestParams()
_setHashDB()
_resumeHashDBValues()
_setResultsFile()
_setAuthCred()

View File

@@ -9,6 +9,7 @@ import doctest
import os
import re
import shutil
import string
import sys
import tempfile
import time
@@ -22,7 +23,7 @@ from lib.core.data import conf
from lib.core.data import logger
from lib.core.data import paths
from lib.core.option import init
from lib.core.option import __setVerbosity
from lib.core.option import _setVerbosity
from lib.core.optiondict import optDict
from lib.parse.cmdline import cmdLineParser
@@ -45,13 +46,36 @@ def smokeTest():
continue
for ifile in files:
if os.path.splitext(ifile)[1].lower() == ".py" and ifile != "__init__.py":
if os.path.splitext(ifile)[1].lower() == ".py":
content = None
with open(os.path.join(root, ifile), "r+b") as f:
content = f.read()
active = content
active = re.sub(r"(?s)\"\"\".+?\"\"\"", "", active)
active = re.sub(r"\".+?\"", "", active)
active = re.sub(r"\'.+?\'", "", active)
active = re.sub(r"#.+", "", active)
for ss in re.findall(r"\b_*?[a-z]+[A-Z].*?\b", active):
original = ss
if ss.startswith("sqlmap") and any(_ in ss.lower() for _ in ("exception", "sqlmapmissing", "sqlmapundefinedmethod")):
ss = "S" + ss[1:]
if ss.startswith("_"):
ss = "_" + ss.lstrip("_")
content = content.replace(original, ss)
if content:
with open(os.path.join(root, ifile), "w+b") as f:
f.write(content)
path = os.path.join(root, os.path.splitext(ifile)[0])
path = path.replace(paths.SQLMAP_ROOT_PATH, '.')
path = path.replace(os.sep, '.').lstrip('.')
try:
__import__(path)
module = sys.modules[path]
#for name in dir(module):
#_ = getattr(module, name)
#if type(_) == type(lambda x: x):
#if re.match(r"\b_*?[a-z]+[A-Z]", name):
#print name
except Exception, msg:
retVal = False
dataToStdout("\r")
@@ -66,7 +90,7 @@ def smokeTest():
count += 1
status = '%d/%d (%d%s) ' % (count, length, round(100.0*count/length), '%')
dataToStdout("\r[%s] [INFO] complete: %s" % (time.strftime("%X"), status))
#dataToStdout("\r[%s] [INFO] complete: %s" % (time.strftime("%X"), status))
clearConsoleLine()
if retVal:
@@ -171,7 +195,7 @@ def initCase(switches=None):
cmdLineOptions.__dict__[key] = value
init(cmdLineOptions, True)
__setVerbosity()
_setVerbosity()
def cleanCase():
shutil.rmtree(paths.SQLMAP_OUTPUT_PATH, True)
@@ -179,7 +203,7 @@ def cleanCase():
paths.SQLMAP_DUMP_PATH = os.path.join(paths.SQLMAP_OUTPUT_PATH, "%s", "dump")
paths.SQLMAP_FILES_PATH = os.path.join(paths.SQLMAP_OUTPUT_PATH, "%s", "files")
conf.verbose = 1
__setVerbosity()
_setVerbosity()
def runCase(switches=None, log=None):
retVal = True
@@ -211,4 +235,4 @@ def replaceVars(item, vars_):
for var in re.findall("\$\{([^}]+)\}", item):
if var in vars_:
retVal = retVal.replace("${%s}" % var, vars_[var])
return retVal
return retVal

View File

@@ -17,9 +17,9 @@ from lib.core.data import kb
from lib.core.data import logger
from lib.core.datatype import AttribDict
from lib.core.enums import PAYLOAD
from lib.core.exception import sqlmapConnectionException
from lib.core.exception import sqlmapThreadException
from lib.core.exception import sqlmapValueException
from lib.core.exception import SqlmapConnectionException
from lib.core.exception import SqlmapThreadException
from lib.core.exception import SqlmapValueException
from lib.core.settings import MAX_NUMBER_OF_THREADS
from lib.core.settings import PYVERSION
@@ -166,12 +166,12 @@ def runThreads(numThreads, threadFunction, cleanupFunction=None, forwardExceptio
pass
except KeyboardInterrupt:
raise sqlmapThreadException, "user aborted (Ctrl+C was pressed multiple times)"
raise SqlmapThreadException, "user aborted (Ctrl+C was pressed multiple times)"
if forwardException:
raise
except (sqlmapConnectionException, sqlmapValueException), errMsg:
except (SqlmapConnectionException, SqlmapValueException), errMsg:
print
kb.threadException = True
logger.error("thread %s: %s" % (threading.currentThread().getName(), errMsg))

View File

@@ -8,7 +8,7 @@ See the file 'doc/COPYING' for copying permission
import os
import zipfile
from lib.core.exception import sqlmapDataException
from lib.core.exception import SqlmapDataException
from lib.core.settings import UNICODE_ENCODING
class Wordlist(object):
@@ -42,7 +42,7 @@ class Wordlist(object):
_ = zipfile.ZipFile(current, 'r')
if len(_.namelist()) == 0:
errMsg = "no file(s) inside '%s'" % current
raise sqlmapDataException, errMsg
raise SqlmapDataException, errMsg
self.fp = _.open(_.namelist()[0])
else:
self.fp = open(current, 'r')

View File

@@ -11,7 +11,7 @@ from lib.core.common import getUnicode
from lib.core.data import conf
from lib.core.data import kb
from lib.core.data import logger
from lib.core.exception import sqlmapFilePathException
from lib.core.exception import SqlmapFilePathException
from lib.core.settings import UNICODE_ENCODING
from thirdparty.prettyprint import prettyprint
from xml.dom.minidom import Document
@@ -81,12 +81,12 @@ class XMLDump(object):
'''
def __init__(self):
self.__outputFile = None
self.__outputFP = None
self._outputFile = None
self._outputFP = None
self.__root = None
self.__doc = Document()
def __addToRoot(self, element):
def _addToRoot(self, element):
'''
Adds element to the root element
'''
@@ -97,15 +97,15 @@ class XMLDump(object):
Writes the data into the file
'''
if n:
self.__outputFP.write("%s\n" % data)
self._outputFP.write("%s\n" % data)
else:
self.__outputFP.write("%s " % data)
self._outputFP.write("%s " % data)
self.__outputFP.flush()
self._outputFP.flush()
kb.dataOutputFlag = True
def __getRootChild(self, elemName):
def _getRootChild(self, elemName):
'''
Returns the child of the root with the described name
'''
@@ -115,7 +115,7 @@ class XMLDump(object):
return elements
def __createTextNode(self, data):
def _createTextNode(self, data):
'''
Creates a text node with utf8 data inside.
The text is escaped to an fit the xml text Format.
@@ -126,7 +126,7 @@ class XMLDump(object):
escaped_data = saxutils.escape(data, ENTITIES)
return self.__doc.createTextNode(escaped_data)
def __createAttribute(self, attrName, attrValue):
def _createAttribute(self, attrName, attrValue):
'''
Creates an attribute node with utf8 data inside.
The text is escaped to an fit the xml text Format.
@@ -146,19 +146,19 @@ class XMLDump(object):
self.lister(header, data, sort)
return
messagesElem = self.__getRootChild(MESSAGES_ELEM_NAME)
messagesElem = self._getRootChild(MESSAGES_ELEM_NAME)
if (not(messagesElem)):
messagesElem = self.__doc.createElement(MESSAGES_ELEM_NAME)
self.__addToRoot(messagesElem)
self._addToRoot(messagesElem)
if data:
data = self.__formatString(data)
data = self._formatString(data)
else:
data = ""
elem = self.__doc.createElement(MESSAGE_ELEM)
elem.setAttributeNode(self.__createAttribute(TYPE_ATTR, header))
elem.appendChild(self.__createTextNode(data))
elem.setAttributeNode(self._createAttribute(TYPE_ATTR, header))
elem.appendChild(self._createTextNode(data))
messagesElem.appendChild(elem)
def lister(self, header, elements, sort=True):
@@ -166,7 +166,7 @@ class XMLDump(object):
Adds information formatted as list element
'''
lstElem = self.__doc.createElement(LST_ELEM_NAME)
lstElem.setAttributeNode(self.__createAttribute(TYPE_ATTR, header))
lstElem.setAttributeNode(self._createAttribute(TYPE_ATTR, header))
if elements:
if sort:
try:
@@ -180,19 +180,19 @@ class XMLDump(object):
memberElem = self.__doc.createElement(MEMBER_ELEM)
lstElem.appendChild(memberElem)
if isinstance(element, basestring):
memberElem.setAttributeNode(self.__createAttribute(TYPE_ATTR, "string"))
memberElem.appendChild(self.__createTextNode(element))
memberElem.setAttributeNode(self._createAttribute(TYPE_ATTR, "string"))
memberElem.appendChild(self._createTextNode(element))
elif isinstance(element, (list, tuple, set)):
memberElem.setAttributeNode(self.__createAttribute(TYPE_ATTR, "list"))
memberElem.setAttributeNode(self._createAttribute(TYPE_ATTR, "list"))
for e in element:
memberElemStr = self.__doc.createElement(MEMBER_ELEM)
memberElemStr.setAttributeNode(self.__createAttribute(TYPE_ATTR, "string"))
memberElemStr.appendChild(self.__createTextNode(getUnicode(e)))
memberElemStr.setAttributeNode(self._createAttribute(TYPE_ATTR, "string"))
memberElemStr.appendChild(self._createTextNode(getUnicode(e)))
memberElem.appendChild(memberElemStr)
listsElem = self.__getRootChild(LSTS_ELEM_NAME)
listsElem = self._getRootChild(LSTS_ELEM_NAME)
if not(listsElem):
listsElem = self.__doc.createElement(LSTS_ELEM_NAME)
self.__addToRoot(listsElem)
self._addToRoot(listsElem)
listsElem.appendChild(lstElem)
def technic(self, technicType, data):
@@ -200,13 +200,13 @@ class XMLDump(object):
Adds information about the technic used to extract data from the db
'''
technicElem = self.__doc.createElement(TECHNIC_ELEM_NAME)
technicElem.setAttributeNode(self.__createAttribute(TYPE_ATTR, technicType))
textNode = self.__createTextNode(data)
technicElem.setAttributeNode(self._createAttribute(TYPE_ATTR, technicType))
textNode = self._createTextNode(data)
technicElem.appendChild(textNode)
technicsElem = self.__getRootChild(TECHNICS_ELEM_NAME)
technicsElem = self._getRootChild(TECHNICS_ELEM_NAME)
if not(technicsElem):
technicsElem = self.__doc.createElement(TECHNICS_ELEM_NAME)
self.__addToRoot(technicsElem)
self._addToRoot(technicsElem)
technicsElem.appendChild(technicElem)
def banner(self, data):
@@ -215,34 +215,34 @@ class XMLDump(object):
The banner contains information about the type and the version of the database.
'''
bannerElem = self.__doc.createElement(BANNER_ELEM_NAME)
bannerElem.appendChild(self.__createTextNode(data))
self.__addToRoot(bannerElem)
bannerElem.appendChild(self._createTextNode(data))
self._addToRoot(bannerElem)
def currentUser(self, data):
'''
Adds information about the current database user to the xml
'''
currentUserElem = self.__doc.createElement(CURRENT_USER_ELEM_NAME)
textNode = self.__createTextNode(data)
textNode = self._createTextNode(data)
currentUserElem.appendChild(textNode)
self.__addToRoot(currentUserElem)
self._addToRoot(currentUserElem)
def currentDb(self, data):
'''
Adds information about the current database is use to the xml
'''
currentDBElem = self.__doc.createElement(CURRENT_DB_ELEM_NAME)
textNode = self.__createTextNode(data)
textNode = self._createTextNode(data)
currentDBElem.appendChild(textNode)
self.__addToRoot(currentDBElem)
self._addToRoot(currentDBElem)
def dba(self, isDBA):
'''
Adds information to the xml that indicates whether the user has DBA privileges
'''
isDBAElem = self.__doc.createElement(IS_DBA_ELEM_NAME)
isDBAElem.setAttributeNode(self.__createAttribute(VALUE_ATTR, getUnicode(isDBA)))
self.__addToRoot(isDBAElem)
isDBAElem.setAttributeNode(self._createAttribute(VALUE_ATTR, getUnicode(isDBA)))
self._addToRoot(isDBAElem)
def users(self, users):
'''
@@ -255,8 +255,8 @@ class XMLDump(object):
for user in users:
userElem = self.__doc.createElement(DB_USER_ELEM_NAME)
usersElem.appendChild(userElem)
userElem.appendChild(self.__createTextNode(user))
self.__addToRoot(usersElem)
userElem.appendChild(self._createTextNode(user))
self._addToRoot(usersElem)
def dbs(self, dbs):
'''
@@ -267,25 +267,25 @@ class XMLDump(object):
for db in dbs:
dbElem = self.__doc.createElement(DB_NAME_ELEM_NAME)
dbsElem.appendChild(dbElem)
dbElem.appendChild(self.__createTextNode(db))
self.__addToRoot(dbsElem)
dbElem.appendChild(self._createTextNode(db))
self._addToRoot(dbsElem)
def userSettings(self, header, userSettings, subHeader):
'''
Adds information about the user's settings to the xml.
The information can be user's passwords, privileges and etc..
'''
self.__areAdmins = set()
userSettingsElem = self.__getRootChild(USER_SETTINGS_ELEM_NAME)
self._areAdmins = set()
userSettingsElem = self._getRootChild(USER_SETTINGS_ELEM_NAME)
if (not(userSettingsElem)):
userSettingsElem = self.__doc.createElement(USER_SETTINGS_ELEM_NAME)
self.__addToRoot(userSettingsElem)
self._addToRoot(userSettingsElem)
userSettingElem = self.__doc.createElement(USER_SETTING_ELEM_NAME)
userSettingElem.setAttributeNode(self.__createAttribute(TYPE_ATTR, header))
userSettingElem.setAttributeNode(self._createAttribute(TYPE_ATTR, header))
if isinstance(userSettings, (tuple, list, set)):
self.__areAdmins = userSettings[1]
self._areAdmins = userSettings[1]
userSettings = userSettings[0]
users = userSettings.keys()
@@ -294,10 +294,10 @@ class XMLDump(object):
for user in users:
userElem = self.__doc.createElement(USER_ELEM_NAME)
userSettingElem.appendChild(userElem)
if user in self.__areAdmins:
userElem.setAttributeNode(self.__createAttribute(TYPE_ATTR, ADMIN_USER))
if user in self._areAdmins:
userElem.setAttributeNode(self._createAttribute(TYPE_ATTR, ADMIN_USER))
else:
userElem.setAttributeNode(self.__createAttribute(TYPE_ATTR, REGULAR_USER))
userElem.setAttributeNode(self._createAttribute(TYPE_ATTR, REGULAR_USER))
settings = userSettings[user]
@@ -305,8 +305,8 @@ class XMLDump(object):
for setting in settings:
settingsElem = self.__doc.createElement(SETTINGS_ELEM_NAME)
settingsElem.setAttributeNode(self.__createAttribute(TYPE_ATTR, subHeader))
settingTextNode = self.__createTextNode(setting)
settingsElem.setAttributeNode(self._createAttribute(TYPE_ATTR, subHeader))
settingTextNode = self._createTextNode(setting)
settingsElem.appendChild(settingTextNode)
userElem.appendChild(settingsElem)
userSettingsElem.appendChild(userSettingElem)
@@ -324,20 +324,20 @@ class XMLDump(object):
for db, tables in dbTables.items():
tables.sort(key=lambda x: x.lower())
dbElem = self.__doc.createElement(DATABASE_ELEM_NAME)
dbElem.setAttributeNode(self.__createAttribute(NAME_ATTR, db))
dbElem.setAttributeNode(self._createAttribute(NAME_ATTR, db))
dbTablesElem.appendChild(dbElem)
for table in tables:
tableElem = self.__doc.createElement(DB_TABLE_ELEM_NAME)
tableElem.appendChild(self.__createTextNode(table))
tableElem.appendChild(self._createTextNode(table))
dbElem.appendChild(tableElem)
self.__addToRoot(dbTablesElem)
self._addToRoot(dbTablesElem)
def dbTableColumns(self, tableColumns):
'''
Adds information about the columns of the existing tables to the xml
'''
columnsElem = self.__getRootChild(COLUMNS_ELEM_NAME)
columnsElem = self._getRootChild(COLUMNS_ELEM_NAME)
if not(columnsElem):
columnsElem = self.__doc.createElement(COLUMNS_ELEM_NAME)
@@ -345,12 +345,12 @@ class XMLDump(object):
if not db:
db = DEFAULT_DB
dbElem = self.__doc.createElement(DATABASE_COLUMNS_ELEM)
dbElem.setAttributeNode(self.__createAttribute(NAME_ATTR, db))
dbElem.setAttributeNode(self._createAttribute(NAME_ATTR, db))
columnsElem.appendChild(dbElem)
for table, columns in tables.items():
tableElem = self.__doc.createElement(TABLE_ELEM_NAME)
tableElem.setAttributeNode(self.__createAttribute(NAME_ATTR, table))
tableElem.setAttributeNode(self._createAttribute(NAME_ATTR, table))
colList = columns.keys()
colList.sort(key=lambda x: x.lower())
@@ -359,13 +359,13 @@ class XMLDump(object):
colType = columns[column]
colElem = self.__doc.createElement(COLUMN_ELEM_NAME)
if colType is not None:
colElem.setAttributeNode(self.__createAttribute(TYPE_ATTR, colType))
colElem.setAttributeNode(self._createAttribute(TYPE_ATTR, colType))
else:
colElem.setAttributeNode(self.__createAttribute(TYPE_ATTR, UNKNOWN_COLUMN_TYPE))
colElem.appendChild(self.__createTextNode(column))
colElem.setAttributeNode(self._createAttribute(TYPE_ATTR, UNKNOWN_COLUMN_TYPE))
colElem.appendChild(self._createTextNode(column))
tableElem.appendChild(colElem)
self.__addToRoot(columnsElem)
self._addToRoot(columnsElem)
def dbTableValues(self, tableValues):
'''
@@ -383,8 +383,8 @@ class XMLDump(object):
columns = tableValues.keys()
columns.sort(key=lambda x: x.lower())
tableElem.setAttributeNode(self.__createAttribute(DB_ATTR, db))
tableElem.setAttributeNode(self.__createAttribute(NAME_ATTR, table))
tableElem.setAttributeNode(self._createAttribute(DB_ATTR, db))
tableElem.setAttributeNode(self._createAttribute(NAME_ATTR, table))
for i in range(count):
rowElem = self.__doc.createElement(ROW_ELEM_NAME)
@@ -398,14 +398,14 @@ class XMLDump(object):
value = "NULL"
cellElem = self.__doc.createElement(CELL_ELEM_NAME)
cellElem.setAttributeNode(self.__createAttribute(COLUMN_ATTR, column))
cellElem.appendChild(self.__createTextNode(value))
cellElem.setAttributeNode(self._createAttribute(COLUMN_ATTR, column))
cellElem.appendChild(self._createTextNode(value))
rowElem.appendChild(cellElem)
dbValuesElem = self.__getRootChild(DB_VALUES_ELEM)
dbValuesElem = self._getRootChild(DB_VALUES_ELEM)
if (not(dbValuesElem)):
dbValuesElem = self.__doc.createElement(DB_VALUES_ELEM)
self.__addToRoot(dbValuesElem)
self._addToRoot(dbValuesElem)
dbValuesElem.appendChild(tableElem)
@@ -440,12 +440,12 @@ class XMLDump(object):
The query details are the query itself and it's results.
'''
queryElem = self.__doc.createElement(QUERY_ELEM_NAME)
queryElem.setAttributeNode(self.__createAttribute(VALUE_ATTR, query))
queryElem.appendChild(self.__createTextNode(queryRes))
queriesElem = self.__getRootChild(QUERIES_ELEM_NAME)
queryElem.setAttributeNode(self._createAttribute(VALUE_ATTR, query))
queryElem.appendChild(self._createTextNode(queryRes))
queriesElem = self._getRootChild(QUERIES_ELEM_NAME)
if (not(queriesElem)):
queriesElem = self.__doc.createElement(QUERIES_ELEM_NAME)
self.__addToRoot(queriesElem)
self._addToRoot(queriesElem)
queriesElem.appendChild(queryElem)
def registerValue(self, registerData):
@@ -453,11 +453,11 @@ class XMLDump(object):
Adds information about an extracted registry key to the xml
'''
registerElem = self.__doc.createElement(REGISTER_DATA_ELEM_NAME)
registerElem.appendChild(self.__createTextNode(registerData))
registriesElem = self.__getRootChild(REGISTERY_ENTRIES_ELEM_NAME)
registerElem.appendChild(self._createTextNode(registerData))
registriesElem = self._getRootChild(REGISTERY_ENTRIES_ELEM_NAME)
if (not(registriesElem)):
registriesElem = self.__doc.createElement(REGISTERY_ENTRIES_ELEM_NAME)
self.__addToRoot(registriesElem)
self._addToRoot(registriesElem)
registriesElem.appendChild(registerElem)
def rFile(self, filePath, data):
@@ -465,9 +465,9 @@ class XMLDump(object):
Adds an extracted file's content to the xml
'''
fileContentElem = self.__doc.createElement(FILE_CONTENT_ELEM_NAME)
fileContentElem.setAttributeNode(self.__createAttribute(NAME_ATTR, filePath))
fileContentElem.appendChild(self.__createTextNode(data))
self.__addToRoot(fileContentElem)
fileContentElem.setAttributeNode(self._createAttribute(NAME_ATTR, filePath))
fileContentElem.appendChild(self._createTextNode(data))
self._addToRoot(fileContentElem)
def setOutputFile(self):
'''
@@ -475,28 +475,28 @@ class XMLDump(object):
'''
if (conf.xmlFile):
try:
self.__outputFile = conf.xmlFile
self._outputFile = conf.xmlFile
self.__root = None
if os.path.exists(self.__outputFile):
if os.path.exists(self._outputFile):
try:
self.__doc = xml.dom.minidom.parse(self.__outputFile)
self.__doc = xml.dom.minidom.parse(self._outputFile)
self.__root = self.__doc.childNodes[0]
except ExpatError:
self.__doc = Document()
self.__outputFP = codecs.open(self.__outputFile, "w+", UNICODE_ENCODING)
self._outputFP = codecs.open(self._outputFile, "w+", UNICODE_ENCODING)
if self.__root is None:
self.__root = self.__doc.createElementNS(NAME_SPACE_ATTR, RESULTS_ELEM_NAME)
self.__root.setAttributeNode(self.__createAttribute(XMLNS_ATTR, NAME_SPACE_ATTR))
self.__root.setAttributeNode(self.__createAttribute(SCHEME_NAME_ATTR, SCHEME_NAME))
self.__root.setAttributeNode(self._createAttribute(XMLNS_ATTR, NAME_SPACE_ATTR))
self.__root.setAttributeNode(self._createAttribute(SCHEME_NAME_ATTR, SCHEME_NAME))
self.__doc.appendChild(self.__root)
except IOError:
raise sqlmapFilePathException("Wrong filename provided for saving the xml file: %s" % conf.xmlFile)
raise SqlmapFilePathException("Wrong filename provided for saving the xml file: %s" % conf.xmlFile)
def getOutputFile(self):
return self.__outputFile
return self._outputFile
def finish(self, resultStatus, resultMsg=""):
'''
@@ -505,24 +505,24 @@ class XMLDump(object):
2. Writes the xml to the file
3. Closes the xml file
'''
if ((self.__outputFP is not None) and not(self.__outputFP.closed)):
if ((self._outputFP is not None) and not(self._outputFP.closed)):
statusElem = self.__doc.createElement(STATUS_ELEM_NAME)
statusElem.setAttributeNode(self.__createAttribute(SUCESS_ATTR, getUnicode(resultStatus)))
statusElem.setAttributeNode(self._createAttribute(SUCESS_ATTR, getUnicode(resultStatus)))
if not resultStatus:
errorElem = self.__doc.createElement(ERROR_ELEM_NAME)
if isinstance(resultMsg, Exception):
errorElem.setAttributeNode(self.__createAttribute(TYPE_ATTR, type(resultMsg).__name__))
errorElem.setAttributeNode(self._createAttribute(TYPE_ATTR, type(resultMsg).__name__))
else:
errorElem.setAttributeNode(self.__createAttribute(TYPE_ATTR, UNHANDLED_PROBLEM_TYPE))
errorElem.setAttributeNode(self._createAttribute(TYPE_ATTR, UNHANDLED_PROBLEM_TYPE))
errorElem.appendChild(self.__createTextNode(getUnicode(resultMsg)))
errorElem.appendChild(self._createTextNode(getUnicode(resultMsg)))
statusElem.appendChild(errorElem)
self.__addToRoot(statusElem)
self._addToRoot(statusElem)
self.__write(prettyprint.formatXML(self.__doc, encoding=UNICODE_ENCODING))
self.__outputFP.close()
self._outputFP.close()
def closeDumper(status, msg=""):