diff --git a/extra/shutils/pylint.py b/extra/shutils/pylint.py index f0b684322..e6b475351 100755 --- a/extra/shutils/pylint.py +++ b/extra/shutils/pylint.py @@ -20,11 +20,11 @@ def check(module): print "CHECKING ", module pout = os.popen("pylint --rcfile=/dev/null %s" % module, 'r') for line in pout: - if re.match("\AE:", line): + if re.match(r"\AE:", line): print line.strip() if __RATING__ and "Your code has been rated at" in line: print line - score = re.findall("\d.\d\d", line)[0] + score = re.findall(r"\d.\d\d", line)[0] total += float(score) count += 1 diff --git a/lib/core/agent.py b/lib/core/agent.py index 2a66a356c..b89da862b 100644 --- a/lib/core/agent.py +++ b/lib/core/agent.py @@ -138,7 +138,7 @@ class Agent(object): value = origValue elif where == PAYLOAD.WHERE.NEGATIVE: if conf.invalidLogical: - match = re.search(r'\A[^ ]+', newValue) + match = re.search(r"\A[^ ]+", newValue) newValue = newValue[len(match.group() if match else ""):] _ = randomInt(2) value = "%s%s AND %s=%s" % (origValue, match.group() if match else "", _, _ + 1) @@ -756,13 +756,13 @@ class Agent(object): if fromTable and query.endswith(fromTable): query = query[:-len(fromTable)] - topNumRegex = re.search("\ATOP\s+([\d]+)\s+", query, re.I) + topNumRegex = re.search(r"\ATOP\s+([\d]+)\s+", query, re.I) if topNumRegex: topNum = topNumRegex.group(1) query = query[len("TOP %s " % topNum):] unionQuery += "TOP %s " % topNum - intoRegExp = re.search("(\s+INTO (DUMP|OUT)FILE\s+\'(.+?)\')", query, re.I) + intoRegExp = re.search(r"(\s+INTO (DUMP|OUT)FILE\s+'(.+?)')", query, re.I) if intoRegExp: intoRegExp = intoRegExp.group(1) @@ -810,7 +810,7 @@ class Agent(object): stopLimit = None limitCond = True - topLimit = re.search("TOP\s+([\d]+)\s+", expression, re.I) + topLimit = re.search(r"TOP\s+([\d]+)\s+", expression, re.I) limitRegExp = re.search(queries[Backend.getIdentifiedDbms()].limitregexp.query, expression, re.I) @@ -958,7 +958,7 @@ class Agent(object): orderBy = limitedQuery[limitedQuery.index(" ORDER BY "):] limitedQuery = limitedQuery[:limitedQuery.index(" ORDER BY ")] - notDistincts = re.findall("DISTINCT[\(\s+](.+?)\)*\s+", limitedQuery, re.I) + notDistincts = re.findall(r"DISTINCT[\(\s+](.+?)\)*\s+", limitedQuery, re.I) for notDistinct in notDistincts: limitedQuery = limitedQuery.replace("DISTINCT(%s)" % notDistinct, notDistinct) @@ -975,7 +975,7 @@ class Agent(object): limitedQuery = limitedQuery.replace(" (SELECT TOP %s" % startTopNums, " (SELECT TOP %d" % num) forgeNotIn = False else: - topNum = re.search("TOP\s+([\d]+)\s+", limitedQuery, re.I).group(1) + topNum = re.search(r"TOP\s+([\d]+)\s+", limitedQuery, re.I).group(1) limitedQuery = limitedQuery.replace("TOP %s " % topNum, "") if forgeNotIn: @@ -991,7 +991,7 @@ class Agent(object): limitedQuery += "NOT IN (%s" % (limitStr % num) limitedQuery += "%s %s ORDER BY %s) ORDER BY %s" % (self.nullAndCastField(uniqueField or field), fromFrom, uniqueField or "1", uniqueField or "1") else: - match = re.search(" ORDER BY (\w+)\Z", query) + match = re.search(r" ORDER BY (\w+)\Z", query) field = match.group(1) if match else field if " WHERE " in limitedQuery: @@ -1071,7 +1071,7 @@ class Agent(object): """ _ = re.escape(PAYLOAD_DELIMITER) - return extractRegexResult("(?s)%s(?P.*?)%s" % (_, _), value) + return extractRegexResult(r"(?s)%s(?P.*?)%s" % (_, _), value) def replacePayload(self, value, payload): """ @@ -1079,7 +1079,7 @@ class Agent(object): """ _ = re.escape(PAYLOAD_DELIMITER) - return re.sub("(?s)(%s.*?%s)" % (_, _), ("%s%s%s" % (PAYLOAD_DELIMITER, getUnicode(payload), PAYLOAD_DELIMITER)).replace("\\", r"\\"), value) if value else value + return re.sub(r"(?s)(%s.*?%s)" % (_, _), ("%s%s%s" % (PAYLOAD_DELIMITER, getUnicode(payload), PAYLOAD_DELIMITER)).replace("\\", r"\\"), value) if value else value def runAsDBMSUser(self, query): if conf.dbmsCred and "Ad Hoc Distributed Queries" not in query: diff --git a/lib/core/common.py b/lib/core/common.py index 585859263..fd4bb16a6 100644 --- a/lib/core/common.py +++ b/lib/core/common.py @@ -1208,7 +1208,7 @@ def cleanQuery(query): for sqlStatements in SQL_STATEMENTS.values(): for sqlStatement in sqlStatements: - queryMatch = re.search("(?i)\b(%s)\b" % sqlStatement.replace("(", "").replace(")", "").strip(), query) + queryMatch = re.search(r"(?i)\b(%s)\b" % sqlStatement.replace("(", "").replace(")", "").strip(), query) if queryMatch and "sys_exec" not in query: retVal = retVal.replace(queryMatch.group(1), sqlStatement.upper()) @@ -1387,13 +1387,12 @@ def parseTargetUrl(): originalUrl = conf.url - if re.search("\[.+\]", conf.url) and not socket.has_ipv6: + if re.search(r"\[.+\]", conf.url) and not socket.has_ipv6: errMsg = "IPv6 addressing is not supported " errMsg += "on this platform" raise SqlmapGenericException(errMsg) - if not re.search("^http[s]*://", conf.url, re.I) and \ - not re.search("^ws[s]*://", conf.url, re.I): + if not re.search(r"^http[s]*://", conf.url, re.I) and not re.search(r"^ws[s]*://", conf.url, re.I): if ":443/" in conf.url: conf.url = "https://" + conf.url else: @@ -1410,7 +1409,7 @@ def parseTargetUrl(): errMsg += "in the hostname part" raise SqlmapGenericException(errMsg) - hostnamePort = urlSplit.netloc.split(":") if not re.search("\[.+\]", urlSplit.netloc) else filter(None, (re.search("\[.+\]", urlSplit.netloc).group(0), re.search("\](:(?P\d+))?", urlSplit.netloc).group("port"))) + hostnamePort = urlSplit.netloc.split(":") if not re.search(r"\[.+\]", urlSplit.netloc) else filter(None, (re.search("\[.+\]", urlSplit.netloc).group(0), re.search(r"\](:(?P\d+))?", urlSplit.netloc).group("port"))) conf.scheme = (urlSplit.scheme.strip().lower() or "http") if not conf.forceSSL else "https" conf.path = urlSplit.path.strip() @@ -1426,7 +1425,7 @@ def parseTargetUrl(): except UnicodeError: _ = None - if any((_ is None, re.search(r'\s', conf.hostname), '..' in conf.hostname, conf.hostname.startswith('.'), '\n' in originalUrl)): + if any((_ is None, re.search(r"\s", conf.hostname), '..' in conf.hostname, conf.hostname.startswith('.'), '\n' in originalUrl)): errMsg = "invalid target URL ('%s')" % originalUrl raise SqlmapSyntaxException(errMsg) @@ -1559,7 +1558,7 @@ def parseUnionPage(page): data = BigArray() keys = set() - for match in re.finditer("%s(.*?)%s" % (kb.chars.start, kb.chars.stop), page, re.DOTALL | re.IGNORECASE): + for match in re.finditer(r"%s(.*?)%s" % (kb.chars.start, kb.chars.stop), page, re.DOTALL | re.IGNORECASE): entry = match.group(1) if kb.chars.start in entry: @@ -1885,7 +1884,7 @@ def isWindowsDriveLetterPath(filepath): False """ - return re.search("\A[\w]\:", filepath) is not None + return re.search(r"\A[\w]\:", filepath) is not None def posixToNtSlashes(filepath): """ @@ -2579,7 +2578,7 @@ def urlencode(value, safe="%&=-_", convall=False, limit=False, spaceplus=False): # encoded (when not representing URL encoded char) # except in cases when tampering scripts are used if all('%' in _ for _ in (safe, value)) and not kb.tamperFunctions: - value = re.sub("%(?![0-9a-fA-F]{2})", "%25", value) + value = re.sub(r"%(?![0-9a-fA-F]{2})", "%25", value) while True: result = urllib.quote(utf8encode(value), safe) @@ -3277,7 +3276,7 @@ def unhandledExceptionMessage(): errMsg += "sqlmap version: %s\n" % VERSION_STRING[VERSION_STRING.find('/') + 1:] errMsg += "Python version: %s\n" % PYVERSION errMsg += "Operating system: %s\n" % PLATFORM - errMsg += "Command line: %s\n" % re.sub(r".+?\bsqlmap.py\b", "sqlmap.py", getUnicode(" ".join(sys.argv), encoding=sys.stdin.encoding)) + errMsg += "Command line: %s\n" % re.sub(r".+?\bsqlmap\.py\b", "sqlmap.py", getUnicode(" ".join(sys.argv), encoding=sys.stdin.encoding)) errMsg += "Technique: %s\n" % (enumValueToNameLookup(PAYLOAD.TECHNIQUE, kb.technique) if kb.get("technique") else ("DIRECT" if conf.get("direct") else None)) errMsg += "Back-end DBMS:" @@ -3376,7 +3375,7 @@ def maskSensitiveData(msg): retVal = getUnicode(msg) for item in filter(None, (conf.get(_) for _ in SENSITIVE_OPTIONS)): - regex = SENSITIVE_DATA_REGEX % re.sub("(\W)", r"\\\1", getUnicode(item)) + regex = SENSITIVE_DATA_REGEX % re.sub(r"(\W)", r"\\\1", getUnicode(item)) while extractRegexResult(regex, retVal): value = extractRegexResult(regex, retVal) retVal = retVal.replace(value, '*' * len(value)) @@ -3777,7 +3776,7 @@ def randomizeParameterValue(value): value = re.sub(r"%[0-9a-fA-F]{2}", "", value) - for match in re.finditer('[A-Z]+', value): + for match in re.finditer(r"[A-Z]+", value): while True: original = match.group() candidate = randomStr(len(match.group())).upper() @@ -3786,7 +3785,7 @@ def randomizeParameterValue(value): retVal = retVal.replace(original, candidate) - for match in re.finditer('[a-z]+', value): + for match in re.finditer(r"[a-z]+", value): while True: original = match.group() candidate = randomStr(len(match.group())).lower() @@ -3795,7 +3794,7 @@ def randomizeParameterValue(value): retVal = retVal.replace(original, candidate) - for match in re.finditer('[0-9]+', value): + for match in re.finditer(r"[0-9]+", value): while True: original = match.group() candidate = str(randomInt(len(match.group()))) @@ -4034,7 +4033,7 @@ def getHostHeader(url): if url: retVal = urlparse.urlparse(url).netloc - if re.search("http(s)?://\[.+\]", url, re.I): + if re.search(r"http(s)?://\[.+\]", url, re.I): retVal = extractRegexResult("http(s)?://\[(?P.+)\]", url) elif any(retVal.endswith(':%d' % _) for _ in (80, 443)): retVal = retVal.split(':')[0] diff --git a/lib/core/option.py b/lib/core/option.py index 11ce1c76c..841f52437 100644 --- a/lib/core/option.py +++ b/lib/core/option.py @@ -434,7 +434,7 @@ def _setMultipleTargets(): files.sort() for reqFile in files: - if not re.search("([\d]+)\-request", reqFile): + if not re.search(r"([\d]+)\-request", reqFile): continue _feedTargetsDict(os.path.join(conf.logFile, reqFile), addedTargetUrls) @@ -666,7 +666,7 @@ def _setDBMSAuthentication(): debugMsg = "setting the DBMS authentication credentials" logger.debug(debugMsg) - match = re.search("^(.+?):(.*?)$", conf.dbmsCred) + match = re.search(r"^(.+?):(.*?)$", conf.dbmsCred) if not match: errMsg = "DBMS authentication credentials value must be in format " @@ -861,7 +861,7 @@ def _setDBMS(): logger.debug(debugMsg) conf.dbms = conf.dbms.lower() - regex = re.search("%s ([\d\.]+)" % ("(%s)" % "|".join([alias for alias in SUPPORTED_DBMS])), conf.dbms, re.I) + regex = re.search(r"%s ([\d\.]+)" % ("(%s)" % "|".join([alias for alias in SUPPORTED_DBMS])), conf.dbms, re.I) if regex: conf.dbms = regex.group(1) @@ -1148,7 +1148,7 @@ def _setHTTPHandlers(): raise SqlmapSyntaxException(errMsg) if conf.proxyCred: - _ = re.search("^(.*?):(.*?)$", conf.proxyCred) + _ = re.search(r"\A(.*?):(.*?)\Z", conf.proxyCred) if not _: errMsg = "proxy authentication credentials " errMsg += "value must be in format username:password" @@ -1256,7 +1256,7 @@ def _setSafeVisit(): errMsg = "invalid format of a safe request file" raise SqlmapSyntaxException, errMsg else: - if not re.search("^http[s]*://", conf.safeUrl): + if not re.search(r"\Ahttp[s]*://", conf.safeUrl): if ":443/" in conf.safeUrl: conf.safeUrl = "https://" + conf.safeUrl else: diff --git a/lib/core/settings.py b/lib/core/settings.py index f12522bb3..d6b22f04d 100644 --- a/lib/core/settings.py +++ b/lib/core/settings.py @@ -597,7 +597,7 @@ MAX_TOTAL_REDIRECTIONS = 10 MAX_DNS_LABEL = 63 # Alphabet used for prefix and suffix strings of name resolution requests in DNS technique (excluding hexadecimal chars for not mixing with inner content) -DNS_BOUNDARIES_ALPHABET = re.sub("[a-fA-F]", "", string.ascii_letters) +DNS_BOUNDARIES_ALPHABET = re.sub(r"[a-fA-F]", "", string.ascii_letters) # Alphabet used for heuristic checks HEURISTIC_CHECK_ALPHABET = ('"', '\'', ')', '(', ',', '.') diff --git a/lib/parse/handler.py b/lib/parse/handler.py index 790505fd9..08a8d46cd 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(r"\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/parse/html.py b/lib/parse/html.py index 226c1283a..019239309 100644 --- a/lib/parse/html.py +++ b/lib/parse/html.py @@ -43,7 +43,7 @@ class HTMLHandler(ContentHandler): elif name == "error": regexp = attrs.get("regexp") if regexp not in kb.cache.regex: - keywords = re.findall("\w+", re.sub(r"\\.", " ", regexp)) + keywords = re.findall(r"\w+", re.sub(r"\\.", " ", regexp)) keywords = sorted(keywords, key=len) kb.cache.regex[regexp] = keywords[-1].lower() diff --git a/lib/request/basic.py b/lib/request/basic.py index ab7cf8607..3b0776b6f 100644 --- a/lib/request/basic.py +++ b/lib/request/basic.py @@ -374,7 +374,7 @@ def processResponse(page, responseHeaders, status=None): continue conf.paramDict[PLACE.POST][name] = value - conf.parameters[PLACE.POST] = re.sub("(?i)(%s=)[^&]+" % re.escape(name), r"\g<1>%s" % re.escape(value), conf.parameters[PLACE.POST]) + conf.parameters[PLACE.POST] = re.sub(r"(?i)(%s=)[^&]+" % re.escape(name), r"\g<1>%s" % re.escape(value), conf.parameters[PLACE.POST]) if not kb.browserVerification and re.search(r"(?i)browser.?verification", page or ""): kb.browserVerification = True diff --git a/lib/request/connect.py b/lib/request/connect.py index 218ae2ebd..aadf435f2 100644 --- a/lib/request/connect.py +++ b/lib/request/connect.py @@ -319,8 +319,8 @@ class Connect(object): elif target: if conf.forceSSL and urlparse.urlparse(url).scheme != "https": - url = re.sub("(?i)\Ahttp:", "https:", url) - url = re.sub("(?i):80/", ":443/", url) + url = re.sub(r"(?i)\Ahttp:", "https:", url) + url = re.sub(r"(?i):80/", ":443/", url) if PLACE.GET in conf.parameters and not get: get = conf.parameters[PLACE.GET] @@ -681,7 +681,7 @@ class Connect(object): warnMsg = "there was an incomplete read error while retrieving data " warnMsg += "from the target URL" elif "Handshake status" in tbMsg: - status = re.search("Handshake status ([\d]{3})", tbMsg) + status = re.search(r"Handshake status ([\d]{3})", tbMsg) errMsg = "websocket handshake status %s" % status.group(1) if status else "unknown" raise SqlmapConnectionException(errMsg) else: @@ -738,12 +738,12 @@ class Connect(object): if conn and getattr(conn, "redurl", None): _ = urlparse.urlsplit(conn.redurl) _ = ("%s%s" % (_.path or "/", ("?%s" % _.query) if _.query else "")) - requestMsg = re.sub("(\n[A-Z]+ ).+?( HTTP/\d)", "\g<1>%s\g<2>" % getUnicode(_).replace("\\", "\\\\"), requestMsg, 1) + requestMsg = re.sub(r"(\n[A-Z]+ ).+?( HTTP/\d)", "\g<1>%s\g<2>" % getUnicode(_).replace("\\", "\\\\"), requestMsg, 1) if kb.resendPostOnRedirect is False: - requestMsg = re.sub("(\[#\d+\]:\n)POST ", "\g<1>GET ", requestMsg) - requestMsg = re.sub("(?i)Content-length: \d+\n", "", requestMsg) - requestMsg = re.sub("(?s)\n\n.+", "\n", requestMsg) + requestMsg = re.sub(r"(\[#\d+\]:\n)POST ", "\g<1>GET ", requestMsg) + requestMsg = re.sub(r"(?i)Content-length: \d+\n", "", requestMsg) + requestMsg = re.sub(r"(?s)\n\n.+", "\n", requestMsg) responseMsg += "[#%d] (%d %s):\r\n" % (threadData.lastRequestUID, conn.code, status) else: @@ -870,7 +870,7 @@ class Connect(object): singleTimeWarnMessage(warnMsg) if place in (PLACE.GET, PLACE.POST): _ = re.escape(PAYLOAD_DELIMITER) - match = re.search("(?P\w+)=%s(?P.+?)%s" % (_, _), value) + match = re.search(r"(?P\w+)=%s(?P.+?)%s" % (_, _), value) if match: payload = match.group("value") @@ -936,11 +936,11 @@ class Connect(object): if conf.csrfToken: def _adjustParameter(paramString, parameter, newValue): retVal = paramString - match = re.search("%s=[^&]*" % re.escape(parameter), paramString) + match = re.search(r"%s=[^&]*" % re.escape(parameter), paramString) if match: retVal = re.sub(re.escape(match.group(0)), "%s=%s" % (parameter, newValue), paramString) else: - match = re.search("(%s[\"']:[\"'])([^\"']+)" % re.escape(parameter), paramString) + match = re.search(r"(%s[\"']:[\"'])([^\"']+)" % re.escape(parameter), paramString) if match: retVal = re.sub(re.escape(match.group(0)), "%s%s" % (match.group(1), newValue), paramString) return retVal diff --git a/lib/request/dns.py b/lib/request/dns.py index eda86a9ac..257e32f7c 100644 --- a/lib/request/dns.py +++ b/lib/request/dns.py @@ -94,7 +94,7 @@ class DNSServer(object): with self._lock: for _ in self._requests: - if prefix is None and suffix is None or re.search("%s\..+\.%s" % (prefix, suffix), _, re.I): + if prefix is None and suffix is None or re.search(r"%s\..+\.%s" % (prefix, suffix), _, re.I): retVal = _ self._requests.remove(_) break diff --git a/lib/request/inject.py b/lib/request/inject.py index 9a2cd9d60..a9f50ad0a 100644 --- a/lib/request/inject.py +++ b/lib/request/inject.py @@ -81,9 +81,9 @@ def _goInference(payload, expression, charsetType=None, firstChar=None, lastChar timeBasedCompare = (kb.technique in (PAYLOAD.TECHNIQUE.TIME, PAYLOAD.TECHNIQUE.STACKED)) if not (timeBasedCompare and kb.dnsTest): - if (conf.eta or conf.threads > 1) and Backend.getIdentifiedDbms() and not re.search("(COUNT|LTRIM)\(", expression, re.I) and not (timeBasedCompare and not conf.forceThreads): + if (conf.eta or conf.threads > 1) and Backend.getIdentifiedDbms() and not re.search(r"(COUNT|LTRIM)\(", expression, re.I) and not (timeBasedCompare and not conf.forceThreads): - if field and re.search("\ASELECT\s+DISTINCT\((.+?)\)\s+FROM", expression, re.I): + if field and re.search(r"\ASELECT\s+DISTINCT\((.+?)\)\s+FROM", expression, re.I): expression = "SELECT %s FROM (%s)" % (field, expression) if Backend.getIdentifiedDbms() in (DBMS.MYSQL, DBMS.PGSQL): @@ -158,7 +158,7 @@ def _goInferenceProxy(expression, fromUser=False, batch=False, unpack=True, char _, _, _, _, _, expressionFieldsList, expressionFields, _ = agent.getFields(expression) - rdbRegExp = re.search("RDB\$GET_CONTEXT\([^)]+\)", expression, re.I) + rdbRegExp = re.search(r"RDB\$GET_CONTEXT\([^)]+\)", expression, re.I) if rdbRegExp and Backend.isDbms(DBMS.FIREBIRD): expressionFieldsList = [expressionFields] @@ -348,7 +348,7 @@ def getValue(expression, blind=True, union=True, error=True, time=True, fromUser kb.resumeValues = resumeValue for keyword in GET_VALUE_UPPERCASE_KEYWORDS: - expression = re.sub("(?i)(\A|\(|\)|\s)%s(\Z|\(|\)|\s)" % keyword, r"\g<1>%s\g<2>" % keyword, expression) + expression = re.sub(r"(?i)(\A|\(|\)|\s)%s(\Z|\(|\)|\s)" % keyword, r"\g<1>%s\g<2>" % keyword, expression) if suppressOutput is not None: pushValue(getCurrentThreadData().disableStdOut) diff --git a/lib/request/redirecthandler.py b/lib/request/redirecthandler.py index 8b7e5c7b3..c67114df0 100644 --- a/lib/request/redirecthandler.py +++ b/lib/request/redirecthandler.py @@ -129,7 +129,7 @@ class SmartRedirectHandler(urllib2.HTTPRedirectHandler): if HTTP_HEADER.COOKIE not in req.headers: req.headers[HTTP_HEADER.COOKIE] = _ else: - req.headers[HTTP_HEADER.COOKIE] = re.sub("%s{2,}" % delimiter, delimiter, ("%s%s%s" % (re.sub(r"\b%s=[^%s]*%s?" % (re.escape(_.split('=')[0]), delimiter, delimiter), "", req.headers[HTTP_HEADER.COOKIE]), delimiter, _)).strip(delimiter)) + req.headers[HTTP_HEADER.COOKIE] = re.sub(r"%s{2,}" % delimiter, delimiter, ("%s%s%s" % (re.sub(r"\b%s=[^%s]*%s?" % (re.escape(_.split('=')[0]), delimiter, delimiter), "", req.headers[HTTP_HEADER.COOKIE]), delimiter, _)).strip(delimiter)) try: result = urllib2.HTTPRedirectHandler.http_error_302(self, req, fp, code, msg, headers) except urllib2.HTTPError, e: diff --git a/lib/takeover/metasploit.py b/lib/takeover/metasploit.py index 7520c4bbf..5bdf676d0 100644 --- a/lib/takeover/metasploit.py +++ b/lib/takeover/metasploit.py @@ -576,7 +576,7 @@ class Metasploit: timeout = time.time() - start_time > METASPLOIT_SESSION_TIMEOUT if not initialized: - match = re.search("Meterpreter session ([\d]+) opened", out) + match = re.search(r"Meterpreter session ([\d]+) opened", out) if match: self._loadMetExtensions(proc, match.group(1)) @@ -622,7 +622,7 @@ class Metasploit: pollProcess(process) payloadStderr = process.communicate()[1] - match = re.search("(Total size:|Length:|succeeded with size|Final size of exe file:) ([\d]+)", payloadStderr) + match = re.search(r"(Total size:|Length:|succeeded with size|Final size of exe file:) ([\d]+)", payloadStderr) if match: payloadSize = int(match.group(2)) diff --git a/lib/takeover/web.py b/lib/takeover/web.py index 4575b762d..b1ba35bc0 100644 --- a/lib/takeover/web.py +++ b/lib/takeover/web.py @@ -80,7 +80,7 @@ class Web: page, _, _ = Request.getPage(url=cmdUrl, direct=True, silent=True, timeout=BACKDOOR_RUN_CMD_TIMEOUT) if page is not None: - output = re.search("
(.+?)
", page, re.I | re.S) + output = re.search(r"
(.+?)
", page, re.I | re.S) if output: output = output.group(1) diff --git a/lib/techniques/union/use.py b/lib/techniques/union/use.py index ff9989a0e..08e764248 100644 --- a/lib/techniques/union/use.py +++ b/lib/techniques/union/use.py @@ -226,7 +226,7 @@ def unionUse(expression, unpack=True, dump=False): if expressionFieldsList and len(expressionFieldsList) > 1 and "ORDER BY" in expression.upper(): # Removed ORDER BY clause because UNION does not play well with it - expression = re.sub("(?i)\s*ORDER BY\s+[\w,]+", "", expression) + expression = re.sub(r"(?i)\s*ORDER BY\s+[\w,]+", "", expression) debugMsg = "stripping ORDER BY clause from statement because " debugMsg += "it does not play well with UNION query SQL injection" singleTimeDebugMessage(debugMsg) diff --git a/plugins/dbms/access/fingerprint.py b/plugins/dbms/access/fingerprint.py index 27ebb5eef..d6feff18d 100644 --- a/plugins/dbms/access/fingerprint.py +++ b/plugins/dbms/access/fingerprint.py @@ -94,7 +94,7 @@ class Fingerprint(GenericFingerprint): if wasLastResponseDBMSError(): threadData = getCurrentThreadData() - match = re.search("Could not find file\s+'([^']+?)'", threadData.lastErrorPage[1]) + match = re.search(r"Could not find file\s+'([^']+?)'", threadData.lastErrorPage[1]) if match: retVal = match.group(1).rstrip("%s.mdb" % randStr) @@ -130,7 +130,7 @@ class Fingerprint(GenericFingerprint): if kb.bannerFp: banVer = kb.bannerFp["dbmsVersion"] - if re.search("-log$", kb.data.banner): + if re.search(r"-log$", kb.data.banner): banVer += ", logging enabled" banVer = Format.getDbms([banVer]) diff --git a/plugins/dbms/firebird/fingerprint.py b/plugins/dbms/firebird/fingerprint.py index 4e2d44e4a..68ed415de 100644 --- a/plugins/dbms/firebird/fingerprint.py +++ b/plugins/dbms/firebird/fingerprint.py @@ -52,7 +52,7 @@ class Fingerprint(GenericFingerprint): if kb.bannerFp: banVer = kb.bannerFp["dbmsVersion"] - if re.search("-log$", kb.data.banner): + if re.search(r"-log$", kb.data.banner): banVer += ", logging enabled" banVer = Format.getDbms([banVer]) diff --git a/plugins/dbms/hsqldb/fingerprint.py b/plugins/dbms/hsqldb/fingerprint.py index 07a487cda..e7afe0773 100644 --- a/plugins/dbms/hsqldb/fingerprint.py +++ b/plugins/dbms/hsqldb/fingerprint.py @@ -49,7 +49,7 @@ class Fingerprint(GenericFingerprint): if kb.bannerFp: banVer = kb.bannerFp["dbmsVersion"] if 'dbmsVersion' in kb.bannerFp else None - if re.search("-log$", kb.data.banner): + if re.search(r"-log$", kb.data.banner): banVer += ", logging enabled" banVer = Format.getDbms([banVer] if banVer else None) diff --git a/plugins/dbms/mysql/fingerprint.py b/plugins/dbms/mysql/fingerprint.py index 906790e28..d2d3b9884 100644 --- a/plugins/dbms/mysql/fingerprint.py +++ b/plugins/dbms/mysql/fingerprint.py @@ -125,7 +125,7 @@ class Fingerprint(GenericFingerprint): if kb.bannerFp: banVer = kb.bannerFp["dbmsVersion"] if "dbmsVersion" in kb.bannerFp else None - if banVer and re.search("-log$", kb.data.banner): + if banVer and re.search(r"-log$", kb.data.banner): banVer += ", logging enabled" banVer = Format.getDbms([banVer] if banVer else None) diff --git a/plugins/dbms/mysql/takeover.py b/plugins/dbms/mysql/takeover.py index b460b498d..00b3806d1 100644 --- a/plugins/dbms/mysql/takeover.py +++ b/plugins/dbms/mysql/takeover.py @@ -6,12 +6,12 @@ See the file 'LICENSE' for copying permission """ import os -import re from lib.core.agent import agent from lib.core.common import Backend from lib.core.common import decloakToTemp from lib.core.common import isStackingAvailable +from lib.core.common import isWindowsDriveLetterPath from lib.core.common import normalizePath from lib.core.common import ntToPosixSlashes from lib.core.common import randomStr @@ -49,7 +49,7 @@ class Takeover(GenericTakeover): # Reference: http://dev.mysql.com/doc/refman/5.1/en/server-options.html#option_mysqld_basedir self.__basedir = unArrayizeValue(inject.getValue("SELECT @@basedir")) - if re.search("^[\w]\:[\/\\\\]+", (self.__basedir or ""), re.I): + if isWindowsDriveLetterPath(self.__basedir or ""): Backend.setOs(OS.WINDOWS) else: Backend.setOs(OS.LINUX) diff --git a/plugins/dbms/oracle/fingerprint.py b/plugins/dbms/oracle/fingerprint.py index b4dfd2bc6..0a884e968 100644 --- a/plugins/dbms/oracle/fingerprint.py +++ b/plugins/dbms/oracle/fingerprint.py @@ -104,7 +104,7 @@ class Fingerprint(GenericFingerprint): # Reference: https://en.wikipedia.org/wiki/Oracle_Database for version in ("12c", "11g", "10g", "9i", "8i"): - number = int(re.search("([\d]+)", version).group(1)) + number = int(re.search(r"([\d]+)", version).group(1)) output = inject.checkBooleanExpression("%d=(SELECT SUBSTR((VERSION),1,%d) FROM SYS.PRODUCT_COMPONENT_VERSION WHERE ROWNUM=1)" % (number, 1 if number < 10 else 2)) if output: diff --git a/plugins/generic/users.py b/plugins/generic/users.py index b4b95cf77..746c55d96 100644 --- a/plugins/generic/users.py +++ b/plugins/generic/users.py @@ -165,7 +165,7 @@ class Users: if Backend.isDbms(DBMS.MYSQL): for user in users: - parsedUser = re.search("[\047]*(.*?)[\047]*\@", user) + parsedUser = re.search(r"['\"]?(.*?)['\"]?\@", user) if parsedUser: users[users.index(user)] = parsedUser.groups()[0] @@ -220,7 +220,7 @@ class Users: if Backend.isDbms(DBMS.MYSQL): for user in users: - parsedUser = re.search("[\047]*(.*?)[\047]*\@", user) + parsedUser = re.search(r"['\"]?(.*?)['\"]?\@", user) if parsedUser: users[users.index(user)] = parsedUser.groups()[0] @@ -349,7 +349,7 @@ class Users: if Backend.isDbms(DBMS.MYSQL): for user in users: - parsedUser = re.search("[\047]*(.*?)[\047]*\@", user) + parsedUser = re.search(r"['\"]?(.*?)['\"]?\@", user) if parsedUser: users[users.index(user)] = parsedUser.groups()[0] @@ -463,7 +463,7 @@ class Users: if Backend.isDbms(DBMS.MYSQL): for user in users: - parsedUser = re.search("[\047]*(.*?)[\047]*\@", user) + parsedUser = re.search(r"['\"]?(.*?)['\"]?\@", user) if parsedUser: users[users.index(user)] = parsedUser.groups()[0]