diff --git a/extra/shutils/pylint.py b/extra/shutils/pylint.py index f2a334585..440f638a6 100644 --- a/extra/shutils/pylint.py +++ b/extra/shutils/pylint.py @@ -18,15 +18,15 @@ def check(module): if module[-3:] == ".py": print "CHECKING ", module - pout = os.popen('pylint --rcfile=/dev/null %s'% module, 'r') + pout = os.popen("pylint --rcfile=/dev/null %s" % module, 'r') for line in pout: if re.match("E....:.", line): print line if __RATING__ and "Your code has been rated at" in line: - print line - score = re.findall("\d.\d\d", line)[0] - total += float(score) - count += 1 + print line + score = re.findall("\d.\d\d", line)[0] + total += float(score) + count += 1 if __name__ == "__main__": try: @@ -46,5 +46,5 @@ if __name__ == "__main__": if __RATING__: print "==" * 50 - print "%d modules found"% count - print "AVERAGE SCORE = %.02f"% (total / count) + print "%d modules found" % count + print "AVERAGE SCORE = %.02f" % (total / count) diff --git a/extra/sqlharvest/sqlharvest.py b/extra/sqlharvest/sqlharvest.py index 1c3f3188a..582110641 100644 --- a/extra/sqlharvest/sqlharvest.py +++ b/extra/sqlharvest/sqlharvest.py @@ -20,7 +20,7 @@ CONFIG_FILE = 'sqlharvest.cfg' TABLES_FILE = 'tables.txt' USER_AGENT = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; AskTB5.3)' SEARCH_URL = 'http://www.google.com/m?source=mobileproducts&dc=gorganic' -MAX_FILE_SIZE = 2 * 1024 * 1024 # if a result (.sql) file for downloading is more than 2MB in size just skip it +MAX_FILE_SIZE = 2 * 1024 * 1024 # if a result (.sql) file for downloading is more than 2MB in size just skip it QUERY = 'CREATE TABLE ext:sql' REGEX_URLS = r';u=([^"]+?)&q=' REGEX_RESULT = r'(?i)CREATE TABLE\s*(/\*.*\*/)?\s*(IF NOT EXISTS)?\s*(?P[^\(;]+)' @@ -33,7 +33,7 @@ def main(): opener.addheaders = [("User-Agent", USER_AGENT)] conn = opener.open(SEARCH_URL) - page = conn.read() #set initial cookie values + page = conn.read() # set initial cookie values config = ConfigParser.ConfigParser() config.read(CONFIG_FILE) @@ -82,7 +82,7 @@ def main(): break sys.stdout.write("\n---------------\n") - sys.stdout.write("Result page #%d\n" % (i+1)) + sys.stdout.write("Result page #%d\n" % (i + 1)) sys.stdout.write("---------------\n") for sqlfile in files: diff --git a/lib/controller/controller.py b/lib/controller/controller.py index bb649298b..0f57eb631 100644 --- a/lib/controller/controller.py +++ b/lib/controller/controller.py @@ -319,7 +319,7 @@ def start(): elif conf.method == HTTPMETHOD.GET: if targetUrl.find("?") > -1: firstPart = targetUrl[:targetUrl.find("?")] - secondPart = targetUrl[targetUrl.find("?")+1:] + secondPart = targetUrl[targetUrl.find("?") + 1:] message = "Edit GET data [default: %s]: " % secondPart test = readInput(message, default=secondPart) test = _randomFillBlankFields(test) @@ -603,7 +603,7 @@ def start(): showHttpErrorCodes() if kb.maxConnectionsFlag: - warnMsg = "it appears that the target " + warnMsg = "it appears that the target " warnMsg += "has a maximum connections " warnMsg += "constraint" logger.warn(warnMsg) @@ -612,8 +612,9 @@ def start(): logger.info("fetched data logged to text files under '%s'" % conf.outputPath) if conf.multipleTargets and conf.resultsFilename: - infoMsg = "you can find results of scanning in multiple targets " + infoMsg = "you can find results of scanning in multiple targets " infoMsg += "mode inside the CSV file '%s'" % conf.resultsFilename logger.info(infoMsg) return True + diff --git a/lib/core/agent.py b/lib/core/agent.py index 4bcb409c8..53cbaf8fc 100644 --- a/lib/core/agent.py +++ b/lib/core/agent.py @@ -758,7 +758,7 @@ class Agent(object): limitStr = queries[Backend.getIdentifiedDbms()].limit.query fromIndex = limitedQuery.index(" FROM ") untilFrom = limitedQuery[:fromIndex] - fromFrom = limitedQuery[fromIndex+1:] + fromFrom = limitedQuery[fromIndex + 1:] orderBy = False if Backend.getIdentifiedDbms() in (DBMS.MYSQL, DBMS.PGSQL, DBMS.SQLITE): @@ -766,7 +766,7 @@ class Agent(object): limitedQuery += " %s" % limitStr elif Backend.isDbms(DBMS.FIREBIRD): - limitStr = queries[Backend.getIdentifiedDbms()].limit.query % (num+1, num+1) + limitStr = queries[Backend.getIdentifiedDbms()].limit.query % (num + 1, num + 1) limitedQuery += " %s" % limitStr elif Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2): diff --git a/lib/core/common.py b/lib/core/common.py index 5b12d4fb9..7d1e6b90b 100644 --- a/lib/core/common.py +++ b/lib/core/common.py @@ -560,7 +560,7 @@ def paramToDict(place, parameters=None): elif len(conf.testParameter) != len(testableParameters.keys()): for parameter in conf.testParameter: if parameter not in testableParameters: - warnMsg = "provided parameter '%s' " % parameter + warnMsg = "provided parameter '%s' " % parameter warnMsg += "is not inside the %s" % place logger.warn(warnMsg) @@ -1489,7 +1489,7 @@ def getConsoleWidth(default=80): if os.getenv("COLUMNS", "").isdigit(): width = int(os.getenv("COLUMNS")) else: - output=execute('stty size', shell=True, stdout=PIPE, stderr=PIPE).stdout.read() + output = execute("stty size", shell=True, stdout=PIPE, stderr=PIPE).stdout.read() items = output.split() if len(items) == 2 and items[1].isdigit(): diff --git a/lib/core/convert.py b/lib/core/convert.py index ceae15931..792b6ea31 100644 --- a/lib/core/convert.py +++ b/lib/core/convert.py @@ -54,8 +54,8 @@ def md5hash(value): return md5.new(value).hexdigest() def orddecode(value): - packedString = struct.pack("!"+"I" * len(value), *value) - return "".join(chr(char) for char in struct.unpack("!"+"I"*(len(packedString)/4), packedString)) + packedString = struct.pack("!" + "I" * len(value), *value) + return "".join(chr(char) for char in struct.unpack("!" + "I" * (len(packedString) / 4), packedString)) def ordencode(value): return tuple(ord(char) for char in value) diff --git a/lib/core/defaults.py b/lib/core/defaults.py index f9b79ba54..ed51735b0 100644 --- a/lib/core/defaults.py +++ b/lib/core/defaults.py @@ -7,7 +7,7 @@ See the file 'doc/COPYING' for copying permission from lib.core.datatype import AttribDict -_defaults = { +_defaults = { "csvDel": ",", "timeSec": 5, "googlePage": 1, @@ -23,6 +23,6 @@ _defaults = { "dumpFormat": "CSV", "tech": "BEUSTQ", "torType": "HTTP" - } + } defaults = AttribDict(_defaults) diff --git a/lib/core/dicts.py b/lib/core/dicts.py index e9dd58cb2..842314783 100644 --- a/lib/core/dicts.py +++ b/lib/core/dicts.py @@ -69,38 +69,38 @@ SYBASE_TYPES = { } MYSQL_PRIVS = { - 1:"select_priv", - 2:"insert_priv", - 3:"update_priv", - 4:"delete_priv", - 5:"create_priv", - 6:"drop_priv", - 7:"reload_priv", - 8:"shutdown_priv", - 9:"process_priv", - 10:"file_priv", - 11:"grant_priv", - 12:"references_priv", - 13:"index_priv", - 14:"alter_priv", - 15:"show_db_priv", - 16:"super_priv", - 17:"create_tmp_table_priv", - 18:"lock_tables_priv", - 19:"execute_priv", - 20:"repl_slave_priv", - 21:"repl_client_priv", - 22:"create_view_priv", - 23:"show_view_priv", - 24:"create_routine_priv", - 25:"alter_routine_priv", - 26:"create_user_priv", + 1: "select_priv", + 2: "insert_priv", + 3: "update_priv", + 4: "delete_priv", + 5: "create_priv", + 6: "drop_priv", + 7: "reload_priv", + 8: "shutdown_priv", + 9: "process_priv", + 10: "file_priv", + 11: "grant_priv", + 12: "references_priv", + 13: "index_priv", + 14: "alter_priv", + 15: "show_db_priv", + 16: "super_priv", + 17: "create_tmp_table_priv", + 18: "lock_tables_priv", + 19: "execute_priv", + 20: "repl_slave_priv", + 21: "repl_client_priv", + 22: "create_view_priv", + 23: "show_view_priv", + 24: "create_routine_priv", + 25: "alter_routine_priv", + 26: "create_user_priv", } PGSQL_PRIVS = { - 1:"createdb", - 2:"super", - 3:"catupd", + 1: "createdb", + 2: "super", + 3: "catupd", } FIREBIRD_PRIVS = { diff --git a/lib/core/dump.py b/lib/core/dump.py index 688e23718..5dcc207f7 100644 --- a/lib/core/dump.py +++ b/lib/core/dump.py @@ -117,13 +117,13 @@ class Dump(object): if elements: self._write("") - def banner(self,data): + def banner(self, data): self.string("banner", data) - def currentUser(self,data): + def currentUser(self, data): self.string("current user", data) - def currentDb(self,data): + def currentDb(self, data): if Backend.isDbms(DBMS.MAXDB): self.string("current database (no practical usage on %s)" % Backend.getIdentifiedDbms(), data) elif Backend.isDbms(DBMS.ORACLE): @@ -131,13 +131,13 @@ class Dump(object): else: self.string("current database", data) - def hostname(self,data): + def hostname(self, data): self.string("hostname", data) - def dba(self,data): + def dba(self, data): self.string("current user is DBA", data) - def users(self,users): + def users(self, users): self.lister("database management system users", users) def userSettings(self, header, userSettings, subHeader): @@ -174,7 +174,7 @@ class Dump(object): self.singleString("") - def dbs(self,dbs): + def dbs(self, dbs): self.lister("available databases", dbs) def dbTables(self, dbTables): diff --git a/lib/core/option.py b/lib/core/option.py index cbd2d4522..2a9bcaaaf 100644 --- a/lib/core/option.py +++ b/lib/core/option.py @@ -272,7 +272,7 @@ def _feedTargetsDict(reqFile, addedTargetUrls): index = 5 url = line[index:line.index(" HTTP/")] - method = line[:index-1] + method = line[:index - 1] if "?" in line and "=" in line: params = True @@ -587,7 +587,7 @@ def _findPageForms(): for i in xrange(len(targets)): try: target = targets[i] - page, _, _= Request.getPage(url=target.strip(), crawling=True, raise404=False) + page, _, _ = Request.getPage(url=target.strip(), crawling=True, raise404=False) findPageForms(page, target, False, True) if conf.verbose in (1, 2): @@ -942,7 +942,7 @@ def _setHTTPProxy(): try: port = int(hostnamePort[1]) except: - pass #drops into the next check block + pass # drops into the next check block 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)) @@ -1373,8 +1373,9 @@ def _cleanupOptions(): conf.data = re.sub(INJECT_HERE_MARK.replace(" ", r"[^A-Za-z]*"), CUSTOM_INJECTION_MARK_CHAR, conf.data, re.I) if re.search(r'%[0-9a-f]{2}', conf.data, re.I): + class _(unicode): + pass original = conf.data - class _(unicode): pass conf.data = _(urldecode(conf.data)) setattr(conf.data, UNENCODED_ORIGINAL_VALUE, original) else: @@ -1409,7 +1410,7 @@ def _cleanupOptions(): conf.code = int(conf.code) if conf.csvDel: - conf.csvDel = conf.csvDel.decode("string_escape") # e.g. '\\t' -> '\t' + conf.csvDel = conf.csvDel.decode("string_escape") # e.g. '\\t' -> '\t' if conf.torPort and conf.torPort.isdigit(): conf.torPort = int(conf.torPort) @@ -1504,7 +1505,7 @@ def _setKnowledgeBaseAttributes(flushAll=True): kb.authHeader = None kb.bannerFp = AttribDict() - kb.brute = AttribDict({"tables":[], "columns":[]}) + kb.brute = AttribDict({"tables": [], "columns": []}) kb.bruteMode = False kb.cache = AttribDict() @@ -1592,7 +1593,7 @@ def _setKnowledgeBaseAttributes(flushAll=True): kb.redirectChoice = None kb.redirectSetCookie = None kb.reflectiveMechanism = True - kb.reflectiveCounters = {REFLECTIVE_COUNTER.MISS:0, REFLECTIVE_COUNTER.HIT:0} + kb.reflectiveCounters = {REFLECTIVE_COUNTER.MISS: 0, REFLECTIVE_COUNTER.HIT: 0} kb.responseTimes = [] kb.resumeValues = True kb.safeCharEncode = False diff --git a/lib/core/profiling.py b/lib/core/profiling.py index 6f0e0cdb4..ff3798f54 100644 --- a/lib/core/profiling.py +++ b/lib/core/profiling.py @@ -65,7 +65,7 @@ def profile(profileOutputFile=None, dotOutputFile=None, imageOutputFile=None): dotFilePointer = codecs.open(dotOutputFile, 'wt', UNICODE_ENCODING) parser = gprof2dot.PstatsParser(profileOutputFile) profile = parser.parse() - profile.prune(0.5/100.0, 0.1/100.0) + profile.prune(0.5 / 100.0, 0.1 / 100.0) dot = gprof2dot.DotWriter(dotFilePointer) dot.graph(profile, gprof2dot.TEMPERATURE_COLORMAP) dotFilePointer.close() diff --git a/lib/core/purge.py b/lib/core/purge.py index a4e747e39..feaf87896 100644 --- a/lib/core/purge.py +++ b/lib/core/purge.py @@ -64,7 +64,7 @@ def purge(directory): except: pass - dirpaths.sort(cmp = lambda x, y: y.count(os.path.sep) - x.count(os.path.sep)) + dirpaths.sort(cmp=lambda x, y: y.count(os.path.sep) - x.count(os.path.sep)) logger.debug("renaming directory names to random values...") for dirpath in dirpaths: diff --git a/lib/core/replication.py b/lib/core/replication.py index 2c40af316..7bc40d26c 100644 --- a/lib/core/replication.py +++ b/lib/core/replication.py @@ -61,7 +61,7 @@ class Replication(object): """ if len(values) == len(self.columns): - self.execute('INSERT INTO "%s" VALUES (%s)' % (self.name, ','.join(['?']*len(values))), safechardecode(values)) + 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) diff --git a/lib/core/settings.py b/lib/core/settings.py index 9859c9e76..d43cc5ba0 100644 --- a/lib/core/settings.py +++ b/lib/core/settings.py @@ -234,7 +234,7 @@ EMPTY_FORM_FIELDS_REGEX = r'(&|\A)(?P[^=]+=(&|\Z))' COMMON_PASSWORD_SUFFIXES = ("1", "123", "2", "12", "3", "13", "7", "11", "5", "22", "23", "01", "4", "07", "21", "14", "10", "06", "08", "8", "15", "69", "16", "6", "18") # Reference: http://www.the-interweb.com/serendipity/index.php?/archives/94-A-brief-analysis-of-40,000-leaked-MySpace-passwords.html -COMMON_PASSWORD_SUFFIXES += ("!", ".", "*", "!!", "?", ";", "..", "!!!", ",", "@") +COMMON_PASSWORD_SUFFIXES += ("!", ".", "*", "!!", "?", ";", "..", "!!!", ", ", "@") # Splitter used between requests in WebScarab log files WEBSCARAB_SPLITTER = "### Conversation" @@ -363,7 +363,7 @@ DUMMY_SQL_INJECTION_CHARS = ";()'" DUMMY_USER_INJECTION = r"(?i)[^\w](AND|OR)\s+[^\s]+[=><]" # Extensions skipped by crawler -CRAWL_EXCLUDE_EXTENSIONS = ("gif","jpg","jar","tif","bmp","war","ear","mpg","wmv","mpeg","scm","iso","dmp","dll","cab","so","avi","bin","exe","iso","tar","png","pdf","ps","mp3","zip","rar","gz") +CRAWL_EXCLUDE_EXTENSIONS = ("gif", "jpg", "jar", "tif", "bmp", "war", "ear", "mpg", "wmv", "mpeg", "scm", "iso", "dmp", "dll", "cab", "so", "avi", "bin", "exe", "iso", "tar", "png", "pdf", "ps", "mp3", "zip", "rar", "gz") # Template used for common table existence check BRUTE_TABLE_EXISTS_TEMPLATE = "EXISTS(SELECT %d FROM %s)" @@ -420,7 +420,7 @@ HASHDB_FLUSH_RETRIES = 3 HASHDB_MILESTONE_VALUE = "cAWxkLYCQT" # r5129 "".join(random.sample(string.letters, 10)) # Warn user of possible delay due to large page dump in full UNION query injections -LARGE_OUTPUT_THRESHOLD = 1024**2 +LARGE_OUTPUT_THRESHOLD = 1024 ** 2 # On huge tables there is a considerable slowdown if every row retrieval requires ORDER BY (most noticable in table dumping using ERROR injections) SLOW_ORDER_COUNT_THRESHOLD = 10000 diff --git a/lib/core/subprocessng.py b/lib/core/subprocessng.py index 9742b8935..a8e5a56ea 100644 --- a/lib/core/subprocessng.py +++ b/lib/core/subprocessng.py @@ -142,7 +142,7 @@ class Popen(subprocess.Popen): try: written = os.write(self.stdin.fileno(), input) except OSError, why: - if why[0] == errno.EPIPE: #broken pipe + if why[0] == errno.EPIPE: # broken pipe return self._close('stdin') raise @@ -155,7 +155,7 @@ class Popen(subprocess.Popen): flags = fcntl.fcntl(conn, fcntl.F_GETFL) if not conn.closed: - fcntl.fcntl(conn, fcntl.F_SETFL, flags| os.O_NONBLOCK) + fcntl.fcntl(conn, fcntl.F_SETFL, flags | os.O_NONBLOCK) try: if not select.select([conn], [], [], 0)[0]: @@ -175,7 +175,7 @@ class Popen(subprocess.Popen): def recv_some(p, t=.1, e=1, tr=5, stderr=0): if tr < 1: tr = 1 - x = time.time()+t + x = time.time() + t y = [] r = '' if stderr: @@ -189,7 +189,7 @@ def recv_some(p, t=.1, e=1, tr=5, stderr=0): elif r: y.append(r) else: - time.sleep(max((x-time.time())/tr, 0)) + time.sleep(max((x - time.time()) / tr, 0)) return ''.join(y) def send_all(p, data): diff --git a/lib/core/target.py b/lib/core/target.py index b47891f0b..8fa9a984a 100644 --- a/lib/core/target.py +++ b/lib/core/target.py @@ -131,7 +131,7 @@ def _setRequestParams(): kb.processUserMarks = True if kb.postHint else kb.processUserMarks if re.search(URI_INJECTABLE_REGEX, conf.url, re.I) and not any(map(lambda place: place in conf.parameters, [PLACE.GET, PLACE.POST])): - warnMsg = "you've provided target url without any GET " + warnMsg = "you've provided target url without any GET " warnMsg += "parameters (e.g. www.site.com/article.php?id=1) " warnMsg += "and without providing any POST parameters " warnMsg += "through --data option" diff --git a/lib/core/testing.py b/lib/core/testing.py index cf8971c50..41b3ac323 100644 --- a/lib/core/testing.py +++ b/lib/core/testing.py @@ -234,7 +234,7 @@ def runCase(switches=None, parse=None): logger.error("unhandled exception occurred ('%s')" % str(exception)) tback = traceback.format_exc() retVal = False - elif result is False: # if None, ignore + elif result is False: # if None, ignore logger.error("the test did not run") retVal = False diff --git a/lib/parse/cmdline.py b/lib/parse/cmdline.py index f3b02981a..b55d856bd 100644 --- a/lib/parse/cmdline.py +++ b/lib/parse/cmdline.py @@ -755,7 +755,7 @@ def cmdLineParser(): # Expand given mnemonic options (e.g. -z "ign,flu,bat") for i in xrange(len(sys.argv) - 1): if sys.argv[i] == '-z': - expandMnemonics(sys.argv[i+1], parser, args) + expandMnemonics(sys.argv[i + 1], parser, args) if not any((args.direct, args.url, args.logFile, args.bulkFile, args.googleDork, args.configFile, \ args.requestFile, args.updateAll, args.smokeTest, args.liveTest, args.wizard, args.dependencies, \ diff --git a/lib/parse/handler.py b/lib/parse/handler.py index 28f792c34..c1a8a599b 100644 --- a/lib/parse/handler.py +++ b/lib/parse/handler.py @@ -44,7 +44,7 @@ class FingerprintHandler(ContentHandler): def startElement(self, name, attrs): if name == "regexp": self._regexp = sanitizeStr(attrs.get("value")) - _ = re.match("\A[A-Za-z0-9]+", self._regexp) # minor trick avoiding compiling of large amount of regexes + _ = re.match("\A[A-Za-z0-9]+", self._regexp) # minor trick avoiding compiling of large amount of regexes if _ and _.group(0).lower() in self._banner.lower() or not _: self._match = re.search(self._regexp, self._banner, re.I | re.M) diff --git a/lib/request/basic.py b/lib/request/basic.py index 320828e8d..30c226cdc 100644 --- a/lib/request/basic.py +++ b/lib/request/basic.py @@ -110,7 +110,7 @@ def checkCharEncoding(encoding, warn=True): else: return encoding - # http://www.destructor.de/charsets/index.htm + # Reference: http://www.destructor.de/charsets/index.htm translate = { "windows-874": "iso-8859-11", "en_us": "utf8", "macintosh": "iso-8859-1", "euc_tw": "big5_tw", "th": "tis-620", "unicode": "utf8", "utc8": "utf8", "ebcdic": "ebcdic-cp-be"} for delimiter in (';', ',', '('): @@ -119,17 +119,17 @@ def checkCharEncoding(encoding, warn=True): # popular typos/errors if "8858" in encoding: - encoding = encoding.replace("8858", "8859") # iso-8858 -> iso-8859 + encoding = encoding.replace("8858", "8859") # iso-8858 -> iso-8859 elif "8559" in encoding: - encoding = encoding.replace("8559", "8859") # iso-8559 -> iso-8859 + encoding = encoding.replace("8559", "8859") # iso-8559 -> iso-8859 elif "5889" in encoding: - encoding = encoding.replace("5889", "8859") # iso-5889 -> iso-8859 + encoding = encoding.replace("5889", "8859") # iso-5889 -> iso-8859 elif "5589" in encoding: - encoding = encoding.replace("5589", "8859") # iso-5589 -> iso-8859 + encoding = encoding.replace("5589", "8859") # iso-5589 -> iso-8859 elif "2313" in encoding: - encoding = encoding.replace("2313", "2312") # gb2313 -> gb2312 + encoding = encoding.replace("2313", "2312") # gb2313 -> gb2312 elif "x-euc" in encoding: - encoding = encoding.replace("x-euc", "euc") # x-euc-kr -> euc-kr + encoding = encoding.replace("x-euc", "euc") # x-euc-kr -> euc-kr # name adjustment for compatibility if encoding.startswith("8859"): @@ -149,14 +149,14 @@ def checkCharEncoding(encoding, warn=True): elif encoding.find("utf8") > 0: encoding = "utf8" - # http://philip.html5.org/data/charsets-2.html + # Reference: http://philip.html5.org/data/charsets-2.html if encoding in translate: encoding = translate[encoding] elif encoding in ("null", "{charset}", "*"): return None - # http://www.iana.org/assignments/character-sets - # http://docs.python.org/library/codecs.html + # Reference: http://www.iana.org/assignments/character-sets + # Reference: http://docs.python.org/library/codecs.html try: codecs.lookup(encoding) except LookupError: @@ -216,7 +216,7 @@ def decodePage(page, contentEncoding, contentType): if not conf.charset: httpCharset, metaCharset = None, None - # http://stackoverflow.com/questions/1020892/python-urllib2-read-to-unicode + # Reference: http://stackoverflow.com/questions/1020892/python-urllib2-read-to-unicode if contentType and (contentType.find("charset=") != -1): httpCharset = checkCharEncoding(contentType.split("charset=")[-1]) diff --git a/lib/request/certhandler.py b/lib/request/certhandler.py index c40534b26..dcda4dc7c 100644 --- a/lib/request/certhandler.py +++ b/lib/request/certhandler.py @@ -21,7 +21,7 @@ class HTTPSCertAuthHandler(urllib2.HTTPSHandler): return self.do_open(self.getConnection, req) def getConnection(self, host): - if sys.version_info >= (2,6): + if sys.version_info >= (2, 6): retVal = httplib.HTTPSConnection(host, key_file=self.key_file, cert_file=self.cert_file, timeout=conf.timeout) else: retVal = httplib.HTTPSConnection(host, key_file=self.key_file, cert_file=self.cert_file) diff --git a/lib/request/connect.py b/lib/request/connect.py index b6a186b83..17f12fada 100644 --- a/lib/request/connect.py +++ b/lib/request/connect.py @@ -398,7 +398,7 @@ class Connect(object): if url.lower().startswith('http://'): kwargs['url'] = url else: - kwargs['url'] = conf.url[:conf.url.rfind('/')+1] + url + kwargs['url'] = conf.url[:conf.url.rfind('/') + 1] + url threadData.lastRedirectMsg = (threadData.lastRequestUID, page) kwargs['refreshing'] = True diff --git a/lib/request/dns.py b/lib/request/dns.py index 3706e3f04..913921fbf 100644 --- a/lib/request/dns.py +++ b/lib/request/dns.py @@ -32,7 +32,7 @@ class DNSQuery(object): j = ord(raw[i]) while j != 0: - self._query += raw[i+1:i+j+1] + '.' + self._query += raw[i + 1:i + j + 1] + '.' i = i + j + 1 j = ord(raw[i]) @@ -137,4 +137,3 @@ if __name__ == "__main__": finally: if server: server._running = False - diff --git a/lib/request/inject.py b/lib/request/inject.py index fa74bd8d2..c33ef508e 100644 --- a/lib/request/inject.py +++ b/lib/request/inject.py @@ -361,7 +361,7 @@ def getValue(expression, blind=True, union=True, error=True, time=True, fromUser found = (value is not None) or (value is None and expectingNone) or count >= MAX_TECHNIQUES_PER_VALUE if found and conf.dnsName: - _ = "".join(filter(None, (key if isTechniqueAvailable(value) else None for key, value in {"E":PAYLOAD.TECHNIQUE.ERROR, "Q":PAYLOAD.TECHNIQUE.QUERY, "U":PAYLOAD.TECHNIQUE.UNION}.items()))) + _ = "".join(filter(None, (key if isTechniqueAvailable(value) else None for key, value in {"E": PAYLOAD.TECHNIQUE.ERROR, "Q": PAYLOAD.TECHNIQUE.QUERY, "U": PAYLOAD.TECHNIQUE.UNION}.items()))) warnMsg = "option '--dns-domain' will be ignored " warnMsg += "as faster techniques are usable " warnMsg += "(%s) " % _ diff --git a/lib/request/proxy.py b/lib/request/proxy.py index 7fc32b506..018430679 100644 --- a/lib/request/proxy.py +++ b/lib/request/proxy.py @@ -17,7 +17,7 @@ if PYVERSION >= "2.6": import ssl class ProxyHTTPConnection(httplib.HTTPConnection): - _ports = {"http" : 80, "https" : 443} + _ports = {"http": 80, "https": 443} def request(self, method, url, body=None, headers={}): # Request is called before connect, so can interpret url and get diff --git a/lib/takeover/web.py b/lib/takeover/web.py index 31e171ea1..09d7e2271 100644 --- a/lib/takeover/web.py +++ b/lib/takeover/web.py @@ -93,7 +93,7 @@ class Web: return self._webFileStreamUpload(stream, destFileName, directory) def _webFileStreamUpload(self, stream, destFileName, directory): - stream.seek(0) # Rewind + stream.seek(0) # Rewind try: setattr(stream, "name", destFileName) diff --git a/lib/techniques/blind/inference.py b/lib/techniques/blind/inference.py index 7821a84f6..a5d68ed6c 100644 --- a/lib/techniques/blind/inference.py +++ b/lib/techniques/blind/inference.py @@ -157,16 +157,16 @@ def bisection(payload, expression, length=None, charsetType=None, firstChar=None if hintValue is not None and len(hintValue) >= idx: if Backend.getIdentifiedDbms() in (DBMS.SQLITE, DBMS.ACCESS, DBMS.MAXDB, DBMS.DB2): - posValue = hintValue[idx-1] + posValue = hintValue[idx - 1] else: - posValue = ord(hintValue[idx-1]) + posValue = ord(hintValue[idx - 1]) forgedPayload = safeStringFormat(payload.replace(INFERENCE_GREATER_CHAR, INFERENCE_EQUALS_CHAR), (expressionUnescaped, idx, posValue)) result = Request.queryPage(forgedPayload, timeBasedCompare=timeBasedCompare, raise404=False) incrementCounter(kb.technique) if result: - return hintValue[idx-1] + return hintValue[idx - 1] with hintlock: kb.hintValue = None @@ -406,7 +406,7 @@ def bisection(payload, expression, length=None, charsetType=None, firstChar=None if startCharIndex > 0: output = '..' + output[2:] - if (endCharIndex - startCharIndex == conf.progressWidth) and (endCharIndex < length-1): + if (endCharIndex - startCharIndex == conf.progressWidth) and (endCharIndex < length - 1): output = output[:-2] + '..' if conf.verbose in (1, 2) and not showEta: @@ -471,7 +471,7 @@ def bisection(payload, expression, length=None, charsetType=None, firstChar=None if showEta: etaProgressUpdate(time.time() - charStart, len(commonValue)) elif conf.verbose in (1, 2): - dataToStdout(filterControlChars(commonValue[index-1:])) + dataToStdout(filterControlChars(commonValue[index - 1:])) finalValue = commonValue @@ -490,8 +490,8 @@ def bisection(payload, expression, length=None, charsetType=None, firstChar=None # Did we have luck? if result: - val = commonPattern[index-1:] - index += len(val)-1 + val = commonPattern[index - 1:] + index += len(val) - 1 # Otherwise if there is no commonValue (single match from # txt/common-outputs.txt) and no commonPattern diff --git a/lib/techniques/union/test.py b/lib/techniques/union/test.py index d9e4a18f6..119ba13fc 100644 --- a/lib/techniques/union/test.py +++ b/lib/techniques/union/test.py @@ -100,7 +100,7 @@ def _findUnionCharCount(comment, place, parameter, value, prefix, suffix, where= min_, max_ = MAX_RATIO, MIN_RATIO pages = {} - for count in xrange(lowerCount, upperCount+1): + for count in xrange(lowerCount, upperCount + 1): query = agent.forgeUnionQuery('', -1, count, comment, prefix, suffix, kb.uChar, where) payload = agent.payload(place=place, parameter=parameter, newValue=query, where=where) page, headers = Request.queryPage(payload, place=place, content=True, raise404=False) diff --git a/lib/utils/api.py b/lib/utils/api.py index 6e0b4fcbc..4f45c3f27 100644 --- a/lib/utils/api.py +++ b/lib/utils/api.py @@ -95,19 +95,19 @@ def security_headers(): # HTTP Status Code functions # ############################## -@error(401) # Access Denied +@error(401) # Access Denied def error401(error=None): return "Access denied" -@error(404) # Not Found +@error(404) # Not Found def error404(error=None): return "Nothing here" -@error(405) # Method Not Allowed (e.g. when requesting a POST method via GET) +@error(405) # Method Not Allowed (e.g. when requesting a POST method via GET) def error405(error=None): return "Method not allowed" -@error(500) # Internal Server Error +@error(500) # Internal Server Error def error500(error=None): return "Internal server error" @@ -324,7 +324,7 @@ def scan_log_limited(taskid, start, end): if not start.isdigit() or not end.isdigit() or end <= start: abort(500, "Invalid start or end value, must be digits") - start = max(0, int(start)-1) + start = max(0, int(start) - 1) end = max(1, int(end)) pickledLog = os.read(pipes[taskid][0], 100000) diff --git a/lib/utils/crawler.py b/lib/utils/crawler.py index 3ddfaa982..2bee455af 100644 --- a/lib/utils/crawler.py +++ b/lib/utils/crawler.py @@ -88,7 +88,7 @@ def crawl(target): threadData.shared.deeper.add(url) if re.search(r"(.*?)\?(.+)", url): threadData.shared.value.add(url) - except UnicodeEncodeError: # for non-HTML files + except UnicodeEncodeError: # for non-HTML files pass finally: if conf.forms: diff --git a/lib/utils/getch.py b/lib/utils/getch.py index f38854ac2..1fa7b94c4 100644 --- a/lib/utils/getch.py +++ b/lib/utils/getch.py @@ -19,7 +19,8 @@ class _Getch(object): except(AttributeError, ImportError): self.impl = _GetchUnix() - def __call__(self): return self.impl() + def __call__(self): + return self.impl() class _GetchUnix(object): @@ -56,11 +57,11 @@ class _GetchMacCarbon(object): """ def __init__(self): import Carbon - Carbon.Evt #see if it has this (in Unix, it doesn't) + Carbon.Evt # see if it has this (in Unix, it doesn't) def __call__(self): import Carbon - if Carbon.Evt.EventAvail(0x0008)[0]==0: # 0x0008 is the keyDownMask + if Carbon.Evt.EventAvail(0x0008)[0] == 0: # 0x0008 is the keyDownMask return '' else: # @@ -72,8 +73,9 @@ class _GetchMacCarbon(object): # number is converted to an ASCII character with chr() and # returned # - (what,msg,when,where,mod)=Carbon.Evt.GetNextEvent(0x0008)[1] + (what, msg, when, where, mod) = Carbon.Evt.GetNextEvent(0x0008)[1] return chr(msg & 0x000000FF) getch = _Getch() + diff --git a/lib/utils/google.py b/lib/utils/google.py index b47e104d7..c66a0798c 100644 --- a/lib/utils/google.py +++ b/lib/utils/google.py @@ -61,7 +61,7 @@ class Google(object): url = "http://www.google.com/search?" url += "q=%s&" % urlencode(dork, convall=True) url += "num=100&hl=en&complete=0&safe=off&filter=0&btnG=Search" - url += "&start=%d" % ((gpage-1) * 100) + url += "&start=%d" % ((gpage - 1) * 100) try: conn = self.opener.open(url) diff --git a/lib/utils/hash.py b/lib/utils/hash.py index 686ff43a5..769f9bc3d 100644 --- a/lib/utils/hash.py +++ b/lib/utils/hash.py @@ -81,7 +81,7 @@ def mysql_passwd(password, uppercase=True): return retVal.upper() if uppercase else retVal.lower() -def mysql_old_passwd(password, uppercase=True): # prior to version '4.1' +def mysql_old_passwd(password, uppercase=True): # prior to version '4.1' """ Reference(s): http://www.sfr-fresh.com/unix/privat/tpop3d-1.5.5.tar.gz:a/tpop3d-1.5.5/password.c @@ -136,7 +136,7 @@ def mssql_passwd(password, salt, uppercase=False): return "0x%s" % (retVal.upper() if uppercase else retVal.lower()) -def mssql_old_passwd(password, salt, uppercase=True): # prior to version '2005' +def mssql_old_passwd(password, salt, uppercase=True): # prior to version '2005' """ Reference(s): www.exploit-db.com/download_pdf/15537/ @@ -167,11 +167,11 @@ def oracle_passwd(password, salt, uppercase=True): binsalt = hexdecode(salt) - retVal="s:%s%s" % (sha1(utf8encode(password) + binsalt).hexdigest(), salt) + retVal = "s:%s%s" % (sha1(utf8encode(password) + binsalt).hexdigest(), salt) return retVal.upper() if uppercase else retVal.lower() -def oracle_old_passwd(password, username, uppercase=True): # prior to version '11g' +def oracle_old_passwd(password, username, uppercase=True): # prior to version '11g' """ Reference(s): http://www.notesbit.com/index.php/scripts-oracle/oracle-11g-new-password-algorithm-is-revealed-by-seclistsorg/ @@ -180,10 +180,10 @@ def oracle_old_passwd(password, username, uppercase=True): # prior to version '1 'F894844C34402B67' """ - IV, pad = "\0"*8, "\0" + IV, pad = "\0" * 8, "\0" if isinstance(username, unicode): - username = unicode.encode(username, UNICODE_ENCODING) #pyDes has issues with unicode strings + username = unicode.encode(username, UNICODE_ENCODING) # pyDes has issues with unicode strings unistr = "".join("\0%s" % c for c in (username + password).upper()) @@ -255,7 +255,7 @@ def wordpress_passwd(password, salt, count, prefix, uppercase=False): if i < count: value = value | (ord(input_[i]) << 8) - output = output + ITOA64[(value>>6) & 0x3f] + output = output + ITOA64[(value >> 6) & 0x3f] i += 1 if i >= count: @@ -264,13 +264,13 @@ def wordpress_passwd(password, salt, count, prefix, uppercase=False): if i < count: value = value | (ord(input_[i]) << 16) - output = output + ITOA64[(value>>12) & 0x3f] + output = output + ITOA64[(value >> 12) & 0x3f] i += 1 if i >= count: break - output = output + ITOA64[(value>>18) & 0x3f] + output = output + ITOA64[(value >> 18) & 0x3f] return output @@ -463,7 +463,7 @@ def _bruteProcessVariantA(attack_info, hash_regex, suffix, retVal, proc_id, proc word = word + suffix try: - current = __functions__[hash_regex](password = word, uppercase = False) + current = __functions__[hash_regex](password=word, uppercase=False) count += 1 @@ -498,7 +498,7 @@ def _bruteProcessVariantA(attack_info, hash_regex, suffix, retVal, proc_id, proc raise except (UnicodeEncodeError, UnicodeDecodeError): - pass # ignore possible encoding problems caused by some words in custom dictionaries + pass # ignore possible encoding problems caused by some words in custom dictionaries except Exception: warnMsg = "there was a problem while hashing entry: %s. " % repr(word) @@ -523,7 +523,7 @@ def _bruteProcessVariantB(user, hash_, kwargs, hash_regex, suffix, retVal, found if found.value: break - current = __functions__[hash_regex](password = word, uppercase = False, **kwargs) + current = __functions__[hash_regex](password=word, uppercase=False, **kwargs) count += 1 if not isinstance(word, basestring): @@ -534,7 +534,7 @@ def _bruteProcessVariantB(user, hash_, kwargs, hash_regex, suffix, retVal, found try: if hash_ == current: - if hash_regex == HASH.ORACLE_OLD: #only for cosmetic purposes + if hash_regex == HASH.ORACLE_OLD: # only for cosmetic purposes word = word.upper() retVal.put((user, hash_, word)) @@ -565,7 +565,7 @@ def _bruteProcessVariantB(user, hash_, kwargs, hash_regex, suffix, retVal, found raise except (UnicodeEncodeError, UnicodeDecodeError): - pass # ignore possible encoding problems caused by some words in custom dictionaries + pass # ignore possible encoding problems caused by some words in custom dictionaries except Exception, e: warnMsg = "there was a problem while hashing entry: %s (%s). " % (repr(word), e) @@ -629,7 +629,7 @@ def dictionaryAttack(attack_dict): elif hash_regex in (HASH.CRYPT_GENERIC): item = [(user, hash_), {'salt': hash_[0:2]}] elif hash_regex in (HASH.WORDPRESS): - item = [(user, hash_), {'salt': hash_[4:12], 'count': 1<0", "CHAR_LENGTH(%d)>0"]), - ("2.1", ["BIN_XOR(%d,%d)=0", "PI()>0.%d", "RAND()<1.%d", "FLOOR(1.%d)>=0"]) + ("1.0", ("EXISTS(SELECT CURRENT_USER FROM RDB$DATABASE)",)), + ("1.5", ("NULLIF(%d,%d) IS NULL", "EXISTS(SELECT CURRENT_TRANSACTION FROM RDB$DATABASE)")), + ("2.0", ("EXISTS(SELECT CURRENT_TIME(0) FROM RDB$DATABASE)", "BIT_LENGTH(%d)>0", "CHAR_LENGTH(%d)>0")), + ("2.1", ("BIN_XOR(%d,%d)=0", "PI()>0.%d", "RAND()<1.%d", "FLOOR(1.%d)>=0")) ) for i in xrange(len(table)): version, checks = table[i] failed = False - check = checks[randomRange(0, len(checks)-1)].replace("%d", getUnicode(randomRange(1,100))) + check = checks[randomRange(0, len(checks) - 1)].replace("%d", getUnicode(randomRange(1, 100))) result = inject.checkBooleanExpression(check) if result: diff --git a/plugins/dbms/maxdb/enumeration.py b/plugins/dbms/maxdb/enumeration.py index f1760de1d..a4afc42df 100644 --- a/plugins/dbms/maxdb/enumeration.py +++ b/plugins/dbms/maxdb/enumeration.py @@ -148,7 +148,7 @@ class Enumeration(GenericEnumeration): randStr = randomStr() query = rootQuery.inband.query % (unsafeSQLIdentificatorNaming(tbl), ("'%s'" % unsafeSQLIdentificatorNaming(conf.db)) if unsafeSQLIdentificatorNaming(conf.db) != "USER" else 'USER') - retVal = pivotDumpTable("(%s) AS %s" % (query, randStr), ['%s.columnname' % randStr,'%s.datatype' % randStr,'%s.len' % randStr], blind=True) + retVal = pivotDumpTable("(%s) AS %s" % (query, randStr), ['%s.columnname' % randStr, '%s.datatype' % randStr, '%s.len' % randStr], blind=True) if retVal: table = {} diff --git a/plugins/dbms/mssqlserver/filesystem.py b/plugins/dbms/mssqlserver/filesystem.py index a35f2aa79..69e18f679 100644 --- a/plugins/dbms/mssqlserver/filesystem.py +++ b/plugins/dbms/mssqlserver/filesystem.py @@ -44,7 +44,7 @@ class Filesystem(GenericFilesystem): for fileLine in xrange(0, len(fileContent), lineLen): scrString = "" - for lineChar in fileContent[fileLine:fileLine+lineLen]: + for lineChar in fileContent[fileLine:fileLine + lineLen]: strLineChar = hexencode(lineChar) if not scrString: diff --git a/plugins/dbms/mssqlserver/takeover.py b/plugins/dbms/mssqlserver/takeover.py index 7feaec045..09415cfa5 100644 --- a/plugins/dbms/mssqlserver/takeover.py +++ b/plugins/dbms/mssqlserver/takeover.py @@ -68,7 +68,7 @@ class Takeover(GenericTakeover): hexStr = binascii.hexlify(self.shellcodeString[:-1]) for hexPair in xrange(0, len(hexStr), 2): - shellcodeChar += "CHAR(0x%s)+" % hexStr[hexPair:hexPair+2] + shellcodeChar += "CHAR(0x%s)+" % hexStr[hexPair:hexPair + 2] shellcodeChar = shellcodeChar[:-1] diff --git a/plugins/dbms/mysql/fingerprint.py b/plugins/dbms/mysql/fingerprint.py index ef89fcc29..fa48031cc 100644 --- a/plugins/dbms/mysql/fingerprint.py +++ b/plugins/dbms/mysql/fingerprint.py @@ -206,7 +206,7 @@ class Fingerprint(GenericFingerprint): elif inject.checkBooleanExpression("@@table_open_cache=@@table_open_cache"): if inject.checkBooleanExpression("%s=(SELECT %s FROM information_schema.GLOBAL_STATUS LIMIT 0, 1)" % (randInt, randInt)): Backend.setVersionList([">= 5.1.12", "< 5.5.0"]) - elif inject.checkBooleanExpression("%s=(SELECT %s FROM information_schema.PROCESSLIST LIMIT 0, 1)" % (randInt,randInt)): + elif inject.checkBooleanExpression("%s=(SELECT %s FROM information_schema.PROCESSLIST LIMIT 0, 1)" % (randInt, randInt)): Backend.setVersionList([">= 5.1.7", "< 5.1.12"]) elif inject.checkBooleanExpression("%s=(SELECT %s FROM information_schema.PARTITIONS LIMIT 0, 1)" % (randInt, randInt)): Backend.setVersion("= 5.1.6") diff --git a/plugins/dbms/sqlite/syntax.py b/plugins/dbms/sqlite/syntax.py index 0cc609d18..7c25b4488 100644 --- a/plugins/dbms/sqlite/syntax.py +++ b/plugins/dbms/sqlite/syntax.py @@ -39,7 +39,7 @@ class Syntax(GenericSyntax): break firstIndex = index - index = expression[firstIndex+2:].find("'") + index = expression[firstIndex + 2:].find("'") if index == -1: raise SqlmapSyntaxException("Unenclosed ' in '%s'" % expression) @@ -49,8 +49,8 @@ class Syntax(GenericSyntax): oldUpper = old.upper() oldUpper = oldUpper.replace("X'", "").replace("'", "") - for i in xrange(len(oldUpper)/2): - char = oldUpper[i*2:i*2+2] + for i in xrange(len(oldUpper) / 2): + char = oldUpper[i * 2:i * 2 + 2] escaped = "'%s'" % chr(int(char, 16)) expression = expression.replace(old, escaped) diff --git a/plugins/dbms/sybase/enumeration.py b/plugins/dbms/sybase/enumeration.py index 928902757..5f6085d41 100644 --- a/plugins/dbms/sybase/enumeration.py +++ b/plugins/dbms/sybase/enumeration.py @@ -233,7 +233,7 @@ class Enumeration(GenericEnumeration): for blind in blinds: randStr = randomStr() query = rootQuery.inband.query % (conf.db, conf.db, conf.db, conf.db, conf.db, conf.db, conf.db, unsafeSQLIdentificatorNaming(tbl)) - retVal = pivotDumpTable("(%s) AS %s" % (query, randStr), ['%s.name' % randStr,'%s.usertype' % randStr], blind=blind) + retVal = pivotDumpTable("(%s) AS %s" % (query, randStr), ['%s.name' % randStr, '%s.usertype' % randStr], blind=blind) if retVal: table = {} diff --git a/plugins/generic/filesystem.py b/plugins/generic/filesystem.py index 0f150f491..a142ae55a 100644 --- a/plugins/generic/filesystem.py +++ b/plugins/generic/filesystem.py @@ -115,7 +115,7 @@ class Filesystem: if not single: if len(content) > 256: for i in xrange(0, len(content), 256): - _ = content[i:i+256] + _ = content[i:i + 256] if encoding == "hex": _ = "0x%s" % _ diff --git a/plugins/generic/takeover.py b/plugins/generic/takeover.py index c5fb03598..e46f300ba 100644 --- a/plugins/generic/takeover.py +++ b/plugins/generic/takeover.py @@ -184,9 +184,9 @@ class Takeover(Abstraction, Metasploit, ICMPsh, Registry, Miscellaneous): goUdf = True if goUdf: - exitfunc="thread" + exitfunc = "thread" else: - exitfunc="process" + exitfunc = "process" self.createMsfShellcode(exitfunc=exitfunc, format="raw", extra="BufferRegister=EAX", encode="x86/alpha_mixed") diff --git a/tamper/__init__.py b/tamper/__init__.py index ee9da5b1d..72630d2e8 100644 --- a/tamper/__init__.py +++ b/tamper/__init__.py @@ -5,4 +5,4 @@ Copyright (c) 2006-2012 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ -pass \ No newline at end of file +pass diff --git a/tamper/between.py b/tamper/between.py index 18ef3e9f7..35f7cddc2 100644 --- a/tamper/between.py +++ b/tamper/between.py @@ -55,9 +55,9 @@ def tamper(payload, **kwargs): doublequote = not doublequote elif payload[i] == ">" and not doublequote and not quote: - retVal += " " if i > 0 and not payload[i-1].isspace() else "" - retVal += "NOT BETWEEN %s AND" % ('0' if re.search(r"\A[^\w]*\d", payload[i+1:]) else "NULL") - retVal += " " if i < len(payload) - 1 and not payload[i+1:i+2].isspace() else "" + retVal += " " if i > 0 and not payload[i - 1].isspace() else "" + retVal += "NOT BETWEEN %s AND" % ('0' if re.search(r"\A[^\w]*\d", payload[i + 1:]) else "NULL") + retVal += " " if i < len(payload) - 1 and not payload[i + 1:i + 2].isspace() else "" continue diff --git a/tamper/chardoubleencode.py b/tamper/chardoubleencode.py index 14dce2592..12c3c31b9 100644 --- a/tamper/chardoubleencode.py +++ b/tamper/chardoubleencode.py @@ -36,8 +36,8 @@ def tamper(payload, **kwargs): i = 0 while i < len(payload): - if payload[i] == '%' and (i < len(payload) - 2) and payload[i+1:i+2] in string.hexdigits and payload[i+2:i+3] in string.hexdigits: - retVal += payload[i:i+3] + if payload[i] == '%' and (i < len(payload) - 2) and payload[i + 1:i + 2] in string.hexdigits and payload[i + 2:i + 3] in string.hexdigits: + retVal += payload[i:i + 3] i += 3 else: retVal += '%%25%.2X' % ord(payload[i]) diff --git a/tamper/charencode.py b/tamper/charencode.py index b9569542c..364808805 100644 --- a/tamper/charencode.py +++ b/tamper/charencode.py @@ -43,8 +43,8 @@ def tamper(payload, **kwargs): i = 0 while i < len(payload): - if payload[i] == '%' and (i < len(payload) - 2) and payload[i+1:i+2] in string.hexdigits and payload[i+2:i+3] in string.hexdigits: - retVal += payload[i:i+3] + if payload[i] == '%' and (i < len(payload) - 2) and payload[i + 1:i + 2] in string.hexdigits and payload[i + 2:i + 3] in string.hexdigits: + retVal += payload[i:i + 3] i += 3 else: retVal += '%%%.2X' % ord(payload[i]) diff --git a/tamper/charunicodeencode.py b/tamper/charunicodeencode.py index 4f31f0e8c..71f928ca9 100644 --- a/tamper/charunicodeencode.py +++ b/tamper/charunicodeencode.py @@ -48,8 +48,8 @@ def tamper(payload, **kwargs): i = 0 while i < len(payload): - if payload[i] == '%' and (i < len(payload) - 2) and payload[i+1:i+2] in string.hexdigits and payload[i+2:i+3] in string.hexdigits: - retVal += "%%u00%s" % payload[i+1:i+3] + if payload[i] == '%' and (i < len(payload) - 2) and payload[i + 1:i + 2] in string.hexdigits and payload[i + 2:i + 3] in string.hexdigits: + retVal += "%%u00%s" % payload[i + 1:i + 3] i += 3 else: retVal += '%%u%.4X' % ord(payload[i]) diff --git a/tamper/ifnull2ifisnull.py b/tamper/ifnull2ifisnull.py index ad84fdfc0..69ad45e49 100644 --- a/tamper/ifnull2ifisnull.py +++ b/tamper/ifnull2ifisnull.py @@ -57,7 +57,7 @@ def tamper(payload, **kwargs): _ = payload[index + len("IFNULL("):comma] __ = payload[comma + 1:end] newVal = "IF(ISNULL(%s),%s,%s)" % (_, __, _) - payload = payload[:index] + newVal + payload[end+1:] + payload = payload[:index] + newVal + payload[end + 1:] else: break diff --git a/tamper/multiplespaces.py b/tamper/multiplespaces.py index fa800d42a..fe203cd0b 100644 --- a/tamper/multiplespaces.py +++ b/tamper/multiplespaces.py @@ -43,7 +43,7 @@ def tamper(payload, **kwargs): words.add(word) for word in words: - retVal = re.sub("(?<=\W)%s(?=[^A-Za-z_(]|\Z)" % word, "%s%s%s" % (' '*random.randrange(1,4), word, ' '*random.randrange(1,4)), retVal) - retVal = re.sub("(?<=\W)%s(?=[(])" % word, "%s%s" % (' '*random.randrange(1,4), word), retVal) + retVal = re.sub("(?<=\W)%s(?=[^A-Za-z_(]|\Z)" % word, "%s%s%s" % (' ' * random.randrange(1, 4), word, ' ' * random.randrange(1, 4)), retVal) + retVal = re.sub("(?<=\W)%s(?=[(])" % word, "%s%s" % (' ' * random.randrange(1, 4), word), retVal) return retVal diff --git a/tamper/percentage.py b/tamper/percentage.py index 14235cf7e..00524e7ba 100644 --- a/tamper/percentage.py +++ b/tamper/percentage.py @@ -41,8 +41,8 @@ def tamper(payload, **kwargs): i = 0 while i < len(payload): - if payload[i] == '%' and (i < len(payload) - 2) and payload[i+1:i+2] in string.hexdigits and payload[i+2:i+3] in string.hexdigits: - retVal += payload[i:i+3] + if payload[i] == '%' and (i < len(payload) - 2) and payload[i + 1:i + 2] in string.hexdigits and payload[i + 2:i + 3] in string.hexdigits: + retVal += payload[i:i + 3] i += 3 elif payload[i] != ' ': retVal += '%%%s' % payload[i] diff --git a/tamper/space2comment.py b/tamper/space2comment.py index e3bb6fe46..2f4687fb5 100644 --- a/tamper/space2comment.py +++ b/tamper/space2comment.py @@ -49,7 +49,7 @@ def tamper(payload, **kwargs): elif payload[i] == '"': doublequote = not doublequote - elif payload[i]==" " and not doublequote and not quote: + elif payload[i] == " " and not doublequote and not quote: retVal += "/**/" continue diff --git a/tamper/space2dash.py b/tamper/space2dash.py index e70b62c61..b35aab505 100644 --- a/tamper/space2dash.py +++ b/tamper/space2dash.py @@ -40,7 +40,7 @@ def tamper(payload, **kwargs): if payload[i].isspace(): randomStr = ''.join(random.choice(string.ascii_uppercase + string.lowercase) for _ in xrange(random.randint(6, 12))) retVal += "--%s%%0A" % randomStr - elif payload[i] == '#' or payload[i:i+3] == '-- ': + elif payload[i] == '#' or payload[i:i + 3] == '-- ': retVal += payload[i:] break else: diff --git a/tamper/space2hash.py b/tamper/space2hash.py index 3a423415c..78e0aa64b 100644 --- a/tamper/space2hash.py +++ b/tamper/space2hash.py @@ -46,7 +46,7 @@ def tamper(payload, **kwargs): if payload[i].isspace(): randomStr = ''.join(random.choice(string.ascii_uppercase + string.lowercase) for _ in xrange(random.randint(6, 12))) retVal += "%%23%s%%0A" % randomStr - elif payload[i] == '#' or payload[i:i+3] == '-- ': + elif payload[i] == '#' or payload[i:i + 3] == '-- ': retVal += payload[i:] break else: diff --git a/tamper/space2morehash.py b/tamper/space2morehash.py index b1d16b64d..34f4ad8dd 100644 --- a/tamper/space2morehash.py +++ b/tamper/space2morehash.py @@ -60,7 +60,7 @@ def tamper(payload, **kwargs): if payload[i].isspace(): randomStr = ''.join(random.choice(string.ascii_uppercase + string.lowercase) for _ in xrange(random.randint(6, 12))) retVal += "%%23%s%%0A" % randomStr - elif payload[i] == '#' or payload[i:i+3] == '-- ': + elif payload[i] == '#' or payload[i:i + 3] == '-- ': retVal += payload[i:] break else: diff --git a/tamper/space2mssqlblank.py b/tamper/space2mssqlblank.py index 44df5dcf0..49cf06f0c 100644 --- a/tamper/space2mssqlblank.py +++ b/tamper/space2mssqlblank.py @@ -73,7 +73,7 @@ def tamper(payload, **kwargs): elif payload[i] == '"': doublequote = not doublequote - elif payload[i] == '#' or payload[i:i+3] == '-- ': + elif payload[i] == '#' or payload[i:i + 3] == '-- ': end = True elif payload[i] == " " and not doublequote and not quote: diff --git a/tamper/space2mssqlhash.py b/tamper/space2mssqlhash.py index d9aa81149..3342e3f3d 100644 --- a/tamper/space2mssqlhash.py +++ b/tamper/space2mssqlhash.py @@ -32,7 +32,7 @@ def tamper(payload, **kwargs): for i in xrange(len(payload)): if payload[i].isspace(): retVal += "%23%0A" - elif payload[i] == '#' or payload[i:i+3] == '-- ': + elif payload[i] == '#' or payload[i:i + 3] == '-- ': retVal += payload[i:] break else: diff --git a/tamper/space2mysqldash.py b/tamper/space2mysqldash.py index c2870f5fb..79b9e21fd 100644 --- a/tamper/space2mysqldash.py +++ b/tamper/space2mysqldash.py @@ -41,7 +41,7 @@ def tamper(payload, **kwargs): for i in xrange(len(payload)): if payload[i].isspace(): retVal += "--%0A" - elif payload[i] == '#' or payload[i:i+3] == '-- ': + elif payload[i] == '#' or payload[i:i + 3] == '-- ': retVal += payload[i:] break else: diff --git a/tamper/space2plus.py b/tamper/space2plus.py index 11787e1ad..d11532ce9 100644 --- a/tamper/space2plus.py +++ b/tamper/space2plus.py @@ -45,7 +45,7 @@ def tamper(payload, **kwargs): elif payload[i] == '"': doublequote = not doublequote - elif payload[i]==" " and not doublequote and not quote: + elif payload[i] == " " and not doublequote and not quote: retVal += "+" continue