If it works, don't touch. I touched

This commit is contained in:
Miroslav Stampar 2017-10-31 11:38:09 +01:00
parent 6bf84151e4
commit 66d37112d1
22 changed files with 66 additions and 67 deletions

View File

@ -20,11 +20,11 @@ def check(module):
print "CHECKING ", module 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: for line in pout:
if re.match("\AE:", line): if re.match(r"\AE:", line):
print line.strip() print line.strip()
if __RATING__ and "Your code has been rated at" in line: if __RATING__ and "Your code has been rated at" in line:
print line print line
score = re.findall("\d.\d\d", line)[0] score = re.findall(r"\d.\d\d", line)[0]
total += float(score) total += float(score)
count += 1 count += 1

View File

@ -138,7 +138,7 @@ class Agent(object):
value = origValue value = origValue
elif where == PAYLOAD.WHERE.NEGATIVE: elif where == PAYLOAD.WHERE.NEGATIVE:
if conf.invalidLogical: if conf.invalidLogical:
match = re.search(r'\A[^ ]+', newValue) match = re.search(r"\A[^ ]+", newValue)
newValue = newValue[len(match.group() if match else ""):] newValue = newValue[len(match.group() if match else ""):]
_ = randomInt(2) _ = randomInt(2)
value = "%s%s AND %s=%s" % (origValue, match.group() if match else "", _, _ + 1) 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): if fromTable and query.endswith(fromTable):
query = query[:-len(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: if topNumRegex:
topNum = topNumRegex.group(1) topNum = topNumRegex.group(1)
query = query[len("TOP %s " % topNum):] query = query[len("TOP %s " % topNum):]
unionQuery += "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: if intoRegExp:
intoRegExp = intoRegExp.group(1) intoRegExp = intoRegExp.group(1)
@ -810,7 +810,7 @@ class Agent(object):
stopLimit = None stopLimit = None
limitCond = True 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) limitRegExp = re.search(queries[Backend.getIdentifiedDbms()].limitregexp.query, expression, re.I)
@ -958,7 +958,7 @@ class Agent(object):
orderBy = limitedQuery[limitedQuery.index(" ORDER BY "):] orderBy = limitedQuery[limitedQuery.index(" ORDER BY "):]
limitedQuery = 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: for notDistinct in notDistincts:
limitedQuery = limitedQuery.replace("DISTINCT(%s)" % notDistinct, notDistinct) 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) limitedQuery = limitedQuery.replace(" (SELECT TOP %s" % startTopNums, " (SELECT TOP %d" % num)
forgeNotIn = False forgeNotIn = False
else: 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, "") limitedQuery = limitedQuery.replace("TOP %s " % topNum, "")
if forgeNotIn: if forgeNotIn:
@ -991,7 +991,7 @@ class Agent(object):
limitedQuery += "NOT IN (%s" % (limitStr % num) 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") limitedQuery += "%s %s ORDER BY %s) ORDER BY %s" % (self.nullAndCastField(uniqueField or field), fromFrom, uniqueField or "1", uniqueField or "1")
else: 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 field = match.group(1) if match else field
if " WHERE " in limitedQuery: if " WHERE " in limitedQuery:
@ -1071,7 +1071,7 @@ class Agent(object):
""" """
_ = re.escape(PAYLOAD_DELIMITER) _ = re.escape(PAYLOAD_DELIMITER)
return extractRegexResult("(?s)%s(?P<result>.*?)%s" % (_, _), value) return extractRegexResult(r"(?s)%s(?P<result>.*?)%s" % (_, _), value)
def replacePayload(self, value, payload): def replacePayload(self, value, payload):
""" """
@ -1079,7 +1079,7 @@ class Agent(object):
""" """
_ = re.escape(PAYLOAD_DELIMITER) _ = 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): def runAsDBMSUser(self, query):
if conf.dbmsCred and "Ad Hoc Distributed Queries" not in query: if conf.dbmsCred and "Ad Hoc Distributed Queries" not in query:

View File

@ -1208,7 +1208,7 @@ def cleanQuery(query):
for sqlStatements in SQL_STATEMENTS.values(): for sqlStatements in SQL_STATEMENTS.values():
for sqlStatement in sqlStatements: 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: if queryMatch and "sys_exec" not in query:
retVal = retVal.replace(queryMatch.group(1), sqlStatement.upper()) retVal = retVal.replace(queryMatch.group(1), sqlStatement.upper())
@ -1387,13 +1387,12 @@ def parseTargetUrl():
originalUrl = conf.url 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 = "IPv6 addressing is not supported "
errMsg += "on this platform" errMsg += "on this platform"
raise SqlmapGenericException(errMsg) raise SqlmapGenericException(errMsg)
if not re.search("^http[s]*://", conf.url, re.I) and \ if not re.search(r"^http[s]*://", conf.url, re.I) and not re.search(r"^ws[s]*://", conf.url, re.I):
not re.search("^ws[s]*://", conf.url, re.I):
if ":443/" in conf.url: if ":443/" in conf.url:
conf.url = "https://" + conf.url conf.url = "https://" + conf.url
else: else:
@ -1410,7 +1409,7 @@ def parseTargetUrl():
errMsg += "in the hostname part" errMsg += "in the hostname part"
raise SqlmapGenericException(errMsg) 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<port>\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<port>\d+))?", urlSplit.netloc).group("port")))
conf.scheme = (urlSplit.scheme.strip().lower() or "http") if not conf.forceSSL else "https" conf.scheme = (urlSplit.scheme.strip().lower() or "http") if not conf.forceSSL else "https"
conf.path = urlSplit.path.strip() conf.path = urlSplit.path.strip()
@ -1426,7 +1425,7 @@ def parseTargetUrl():
except UnicodeError: except UnicodeError:
_ = None _ = 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 errMsg = "invalid target URL ('%s')" % originalUrl
raise SqlmapSyntaxException(errMsg) raise SqlmapSyntaxException(errMsg)
@ -1559,7 +1558,7 @@ def parseUnionPage(page):
data = BigArray() data = BigArray()
keys = set() 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) entry = match.group(1)
if kb.chars.start in entry: if kb.chars.start in entry:
@ -1885,7 +1884,7 @@ def isWindowsDriveLetterPath(filepath):
False False
""" """
return re.search("\A[\w]\:", filepath) is not None return re.search(r"\A[\w]\:", filepath) is not None
def posixToNtSlashes(filepath): def posixToNtSlashes(filepath):
""" """
@ -2579,7 +2578,7 @@ def urlencode(value, safe="%&=-_", convall=False, limit=False, spaceplus=False):
# encoded (when not representing URL encoded char) # encoded (when not representing URL encoded char)
# except in cases when tampering scripts are used # except in cases when tampering scripts are used
if all('%' in _ for _ in (safe, value)) and not kb.tamperFunctions: 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: while True:
result = urllib.quote(utf8encode(value), safe) result = urllib.quote(utf8encode(value), safe)
@ -3277,7 +3276,7 @@ def unhandledExceptionMessage():
errMsg += "sqlmap version: %s\n" % VERSION_STRING[VERSION_STRING.find('/') + 1:] errMsg += "sqlmap version: %s\n" % VERSION_STRING[VERSION_STRING.find('/') + 1:]
errMsg += "Python version: %s\n" % PYVERSION errMsg += "Python version: %s\n" % PYVERSION
errMsg += "Operating system: %s\n" % PLATFORM 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 += "Technique: %s\n" % (enumValueToNameLookup(PAYLOAD.TECHNIQUE, kb.technique) if kb.get("technique") else ("DIRECT" if conf.get("direct") else None))
errMsg += "Back-end DBMS:" errMsg += "Back-end DBMS:"
@ -3376,7 +3375,7 @@ def maskSensitiveData(msg):
retVal = getUnicode(msg) retVal = getUnicode(msg)
for item in filter(None, (conf.get(_) for _ in SENSITIVE_OPTIONS)): 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): while extractRegexResult(regex, retVal):
value = extractRegexResult(regex, retVal) value = extractRegexResult(regex, retVal)
retVal = retVal.replace(value, '*' * len(value)) retVal = retVal.replace(value, '*' * len(value))
@ -3777,7 +3776,7 @@ def randomizeParameterValue(value):
value = re.sub(r"%[0-9a-fA-F]{2}", "", 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: while True:
original = match.group() original = match.group()
candidate = randomStr(len(match.group())).upper() candidate = randomStr(len(match.group())).upper()
@ -3786,7 +3785,7 @@ def randomizeParameterValue(value):
retVal = retVal.replace(original, candidate) retVal = retVal.replace(original, candidate)
for match in re.finditer('[a-z]+', value): for match in re.finditer(r"[a-z]+", value):
while True: while True:
original = match.group() original = match.group()
candidate = randomStr(len(match.group())).lower() candidate = randomStr(len(match.group())).lower()
@ -3795,7 +3794,7 @@ def randomizeParameterValue(value):
retVal = retVal.replace(original, candidate) retVal = retVal.replace(original, candidate)
for match in re.finditer('[0-9]+', value): for match in re.finditer(r"[0-9]+", value):
while True: while True:
original = match.group() original = match.group()
candidate = str(randomInt(len(match.group()))) candidate = str(randomInt(len(match.group())))
@ -4034,7 +4033,7 @@ def getHostHeader(url):
if url: if url:
retVal = urlparse.urlparse(url).netloc 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<result>.+)\]", url) retVal = extractRegexResult("http(s)?://\[(?P<result>.+)\]", url)
elif any(retVal.endswith(':%d' % _) for _ in (80, 443)): elif any(retVal.endswith(':%d' % _) for _ in (80, 443)):
retVal = retVal.split(':')[0] retVal = retVal.split(':')[0]

View File

@ -434,7 +434,7 @@ def _setMultipleTargets():
files.sort() files.sort()
for reqFile in files: for reqFile in files:
if not re.search("([\d]+)\-request", reqFile): if not re.search(r"([\d]+)\-request", reqFile):
continue continue
_feedTargetsDict(os.path.join(conf.logFile, reqFile), addedTargetUrls) _feedTargetsDict(os.path.join(conf.logFile, reqFile), addedTargetUrls)
@ -666,7 +666,7 @@ def _setDBMSAuthentication():
debugMsg = "setting the DBMS authentication credentials" debugMsg = "setting the DBMS authentication credentials"
logger.debug(debugMsg) logger.debug(debugMsg)
match = re.search("^(.+?):(.*?)$", conf.dbmsCred) match = re.search(r"^(.+?):(.*?)$", conf.dbmsCred)
if not match: if not match:
errMsg = "DBMS authentication credentials value must be in format " errMsg = "DBMS authentication credentials value must be in format "
@ -861,7 +861,7 @@ def _setDBMS():
logger.debug(debugMsg) logger.debug(debugMsg)
conf.dbms = conf.dbms.lower() 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: if regex:
conf.dbms = regex.group(1) conf.dbms = regex.group(1)
@ -1148,7 +1148,7 @@ def _setHTTPHandlers():
raise SqlmapSyntaxException(errMsg) raise SqlmapSyntaxException(errMsg)
if conf.proxyCred: if conf.proxyCred:
_ = re.search("^(.*?):(.*?)$", conf.proxyCred) _ = re.search(r"\A(.*?):(.*?)\Z", conf.proxyCred)
if not _: if not _:
errMsg = "proxy authentication credentials " errMsg = "proxy authentication credentials "
errMsg += "value must be in format username:password" errMsg += "value must be in format username:password"
@ -1256,7 +1256,7 @@ def _setSafeVisit():
errMsg = "invalid format of a safe request file" errMsg = "invalid format of a safe request file"
raise SqlmapSyntaxException, errMsg raise SqlmapSyntaxException, errMsg
else: else:
if not re.search("^http[s]*://", conf.safeUrl): if not re.search(r"\Ahttp[s]*://", conf.safeUrl):
if ":443/" in conf.safeUrl: if ":443/" in conf.safeUrl:
conf.safeUrl = "https://" + conf.safeUrl conf.safeUrl = "https://" + conf.safeUrl
else: else:

View File

@ -597,7 +597,7 @@ MAX_TOTAL_REDIRECTIONS = 10
MAX_DNS_LABEL = 63 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) # 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 # Alphabet used for heuristic checks
HEURISTIC_CHECK_ALPHABET = ('"', '\'', ')', '(', ',', '.') HEURISTIC_CHECK_ALPHABET = ('"', '\'', ')', '(', ',', '.')

View File

@ -44,7 +44,7 @@ class FingerprintHandler(ContentHandler):
def startElement(self, name, attrs): def startElement(self, name, attrs):
if name == "regexp": if name == "regexp":
self._regexp = sanitizeStr(attrs.get("value")) 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 _: if _ and _.group(0).lower() in self._banner.lower() or not _:
self._match = re.search(self._regexp, self._banner, re.I | re.M) self._match = re.search(self._regexp, self._banner, re.I | re.M)

View File

@ -43,7 +43,7 @@ class HTMLHandler(ContentHandler):
elif name == "error": elif name == "error":
regexp = attrs.get("regexp") regexp = attrs.get("regexp")
if regexp not in kb.cache.regex: 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) keywords = sorted(keywords, key=len)
kb.cache.regex[regexp] = keywords[-1].lower() kb.cache.regex[regexp] = keywords[-1].lower()

View File

@ -374,7 +374,7 @@ def processResponse(page, responseHeaders, status=None):
continue continue
conf.paramDict[PLACE.POST][name] = value 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 ""): if not kb.browserVerification and re.search(r"(?i)browser.?verification", page or ""):
kb.browserVerification = True kb.browserVerification = True

View File

@ -319,8 +319,8 @@ class Connect(object):
elif target: elif target:
if conf.forceSSL and urlparse.urlparse(url).scheme != "https": if conf.forceSSL and urlparse.urlparse(url).scheme != "https":
url = re.sub("(?i)\Ahttp:", "https:", url) url = re.sub(r"(?i)\Ahttp:", "https:", url)
url = re.sub("(?i):80/", ":443/", url) url = re.sub(r"(?i):80/", ":443/", url)
if PLACE.GET in conf.parameters and not get: if PLACE.GET in conf.parameters and not get:
get = conf.parameters[PLACE.GET] get = conf.parameters[PLACE.GET]
@ -681,7 +681,7 @@ class Connect(object):
warnMsg = "there was an incomplete read error while retrieving data " warnMsg = "there was an incomplete read error while retrieving data "
warnMsg += "from the target URL" warnMsg += "from the target URL"
elif "Handshake status" in tbMsg: 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" errMsg = "websocket handshake status %s" % status.group(1) if status else "unknown"
raise SqlmapConnectionException(errMsg) raise SqlmapConnectionException(errMsg)
else: else:
@ -738,12 +738,12 @@ class Connect(object):
if conn and getattr(conn, "redurl", None): if conn and getattr(conn, "redurl", None):
_ = urlparse.urlsplit(conn.redurl) _ = urlparse.urlsplit(conn.redurl)
_ = ("%s%s" % (_.path or "/", ("?%s" % _.query) if _.query else "")) _ = ("%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: if kb.resendPostOnRedirect is False:
requestMsg = re.sub("(\[#\d+\]:\n)POST ", "\g<1>GET ", requestMsg) requestMsg = re.sub(r"(\[#\d+\]:\n)POST ", "\g<1>GET ", requestMsg)
requestMsg = re.sub("(?i)Content-length: \d+\n", "", requestMsg) requestMsg = re.sub(r"(?i)Content-length: \d+\n", "", requestMsg)
requestMsg = re.sub("(?s)\n\n.+", "\n", requestMsg) requestMsg = re.sub(r"(?s)\n\n.+", "\n", requestMsg)
responseMsg += "[#%d] (%d %s):\r\n" % (threadData.lastRequestUID, conn.code, status) responseMsg += "[#%d] (%d %s):\r\n" % (threadData.lastRequestUID, conn.code, status)
else: else:
@ -870,7 +870,7 @@ class Connect(object):
singleTimeWarnMessage(warnMsg) singleTimeWarnMessage(warnMsg)
if place in (PLACE.GET, PLACE.POST): if place in (PLACE.GET, PLACE.POST):
_ = re.escape(PAYLOAD_DELIMITER) _ = re.escape(PAYLOAD_DELIMITER)
match = re.search("(?P<name>\w+)=%s(?P<value>.+?)%s" % (_, _), value) match = re.search(r"(?P<name>\w+)=%s(?P<value>.+?)%s" % (_, _), value)
if match: if match:
payload = match.group("value") payload = match.group("value")
@ -936,11 +936,11 @@ class Connect(object):
if conf.csrfToken: if conf.csrfToken:
def _adjustParameter(paramString, parameter, newValue): def _adjustParameter(paramString, parameter, newValue):
retVal = paramString retVal = paramString
match = re.search("%s=[^&]*" % re.escape(parameter), paramString) match = re.search(r"%s=[^&]*" % re.escape(parameter), paramString)
if match: if match:
retVal = re.sub(re.escape(match.group(0)), "%s=%s" % (parameter, newValue), paramString) retVal = re.sub(re.escape(match.group(0)), "%s=%s" % (parameter, newValue), paramString)
else: else:
match = re.search("(%s[\"']:[\"'])([^\"']+)" % re.escape(parameter), paramString) match = re.search(r"(%s[\"']:[\"'])([^\"']+)" % re.escape(parameter), paramString)
if match: if match:
retVal = re.sub(re.escape(match.group(0)), "%s%s" % (match.group(1), newValue), paramString) retVal = re.sub(re.escape(match.group(0)), "%s%s" % (match.group(1), newValue), paramString)
return retVal return retVal

View File

@ -94,7 +94,7 @@ class DNSServer(object):
with self._lock: with self._lock:
for _ in self._requests: 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 = _ retVal = _
self._requests.remove(_) self._requests.remove(_)
break break

View File

@ -81,9 +81,9 @@ def _goInference(payload, expression, charsetType=None, firstChar=None, lastChar
timeBasedCompare = (kb.technique in (PAYLOAD.TECHNIQUE.TIME, PAYLOAD.TECHNIQUE.STACKED)) timeBasedCompare = (kb.technique in (PAYLOAD.TECHNIQUE.TIME, PAYLOAD.TECHNIQUE.STACKED))
if not (timeBasedCompare and kb.dnsTest): 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) expression = "SELECT %s FROM (%s)" % (field, expression)
if Backend.getIdentifiedDbms() in (DBMS.MYSQL, DBMS.PGSQL): 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) _, _, _, _, _, 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): if rdbRegExp and Backend.isDbms(DBMS.FIREBIRD):
expressionFieldsList = [expressionFields] expressionFieldsList = [expressionFields]
@ -348,7 +348,7 @@ def getValue(expression, blind=True, union=True, error=True, time=True, fromUser
kb.resumeValues = resumeValue kb.resumeValues = resumeValue
for keyword in GET_VALUE_UPPERCASE_KEYWORDS: 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: if suppressOutput is not None:
pushValue(getCurrentThreadData().disableStdOut) pushValue(getCurrentThreadData().disableStdOut)

View File

@ -129,7 +129,7 @@ class SmartRedirectHandler(urllib2.HTTPRedirectHandler):
if HTTP_HEADER.COOKIE not in req.headers: if HTTP_HEADER.COOKIE not in req.headers:
req.headers[HTTP_HEADER.COOKIE] = _ req.headers[HTTP_HEADER.COOKIE] = _
else: 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: try:
result = urllib2.HTTPRedirectHandler.http_error_302(self, req, fp, code, msg, headers) result = urllib2.HTTPRedirectHandler.http_error_302(self, req, fp, code, msg, headers)
except urllib2.HTTPError, e: except urllib2.HTTPError, e:

View File

@ -576,7 +576,7 @@ class Metasploit:
timeout = time.time() - start_time > METASPLOIT_SESSION_TIMEOUT timeout = time.time() - start_time > METASPLOIT_SESSION_TIMEOUT
if not initialized: if not initialized:
match = re.search("Meterpreter session ([\d]+) opened", out) match = re.search(r"Meterpreter session ([\d]+) opened", out)
if match: if match:
self._loadMetExtensions(proc, match.group(1)) self._loadMetExtensions(proc, match.group(1))
@ -622,7 +622,7 @@ class Metasploit:
pollProcess(process) pollProcess(process)
payloadStderr = process.communicate()[1] 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: if match:
payloadSize = int(match.group(2)) payloadSize = int(match.group(2))

View File

@ -80,7 +80,7 @@ class Web:
page, _, _ = Request.getPage(url=cmdUrl, direct=True, silent=True, timeout=BACKDOOR_RUN_CMD_TIMEOUT) page, _, _ = Request.getPage(url=cmdUrl, direct=True, silent=True, timeout=BACKDOOR_RUN_CMD_TIMEOUT)
if page is not None: if page is not None:
output = re.search("<pre>(.+?)</pre>", page, re.I | re.S) output = re.search(r"<pre>(.+?)</pre>", page, re.I | re.S)
if output: if output:
output = output.group(1) output = output.group(1)

View File

@ -226,7 +226,7 @@ def unionUse(expression, unpack=True, dump=False):
if expressionFieldsList and len(expressionFieldsList) > 1 and "ORDER BY" in expression.upper(): if expressionFieldsList and len(expressionFieldsList) > 1 and "ORDER BY" in expression.upper():
# Removed ORDER BY clause because UNION does not play well with it # 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 = "stripping ORDER BY clause from statement because "
debugMsg += "it does not play well with UNION query SQL injection" debugMsg += "it does not play well with UNION query SQL injection"
singleTimeDebugMessage(debugMsg) singleTimeDebugMessage(debugMsg)

View File

@ -94,7 +94,7 @@ class Fingerprint(GenericFingerprint):
if wasLastResponseDBMSError(): if wasLastResponseDBMSError():
threadData = getCurrentThreadData() 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: if match:
retVal = match.group(1).rstrip("%s.mdb" % randStr) retVal = match.group(1).rstrip("%s.mdb" % randStr)
@ -130,7 +130,7 @@ class Fingerprint(GenericFingerprint):
if kb.bannerFp: if kb.bannerFp:
banVer = kb.bannerFp["dbmsVersion"] banVer = kb.bannerFp["dbmsVersion"]
if re.search("-log$", kb.data.banner): if re.search(r"-log$", kb.data.banner):
banVer += ", logging enabled" banVer += ", logging enabled"
banVer = Format.getDbms([banVer]) banVer = Format.getDbms([banVer])

View File

@ -52,7 +52,7 @@ class Fingerprint(GenericFingerprint):
if kb.bannerFp: if kb.bannerFp:
banVer = kb.bannerFp["dbmsVersion"] banVer = kb.bannerFp["dbmsVersion"]
if re.search("-log$", kb.data.banner): if re.search(r"-log$", kb.data.banner):
banVer += ", logging enabled" banVer += ", logging enabled"
banVer = Format.getDbms([banVer]) banVer = Format.getDbms([banVer])

View File

@ -49,7 +49,7 @@ class Fingerprint(GenericFingerprint):
if kb.bannerFp: if kb.bannerFp:
banVer = kb.bannerFp["dbmsVersion"] if 'dbmsVersion' in kb.bannerFp else None 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 += ", logging enabled"
banVer = Format.getDbms([banVer] if banVer else None) banVer = Format.getDbms([banVer] if banVer else None)

View File

@ -125,7 +125,7 @@ class Fingerprint(GenericFingerprint):
if kb.bannerFp: if kb.bannerFp:
banVer = kb.bannerFp["dbmsVersion"] if "dbmsVersion" in kb.bannerFp else None 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 += ", logging enabled"
banVer = Format.getDbms([banVer] if banVer else None) banVer = Format.getDbms([banVer] if banVer else None)

View File

@ -6,12 +6,12 @@ See the file 'LICENSE' for copying permission
""" """
import os import os
import re
from lib.core.agent import agent from lib.core.agent import agent
from lib.core.common import Backend from lib.core.common import Backend
from lib.core.common import decloakToTemp from lib.core.common import decloakToTemp
from lib.core.common import isStackingAvailable from lib.core.common import isStackingAvailable
from lib.core.common import isWindowsDriveLetterPath
from lib.core.common import normalizePath from lib.core.common import normalizePath
from lib.core.common import ntToPosixSlashes from lib.core.common import ntToPosixSlashes
from lib.core.common import randomStr 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 # Reference: http://dev.mysql.com/doc/refman/5.1/en/server-options.html#option_mysqld_basedir
self.__basedir = unArrayizeValue(inject.getValue("SELECT @@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) Backend.setOs(OS.WINDOWS)
else: else:
Backend.setOs(OS.LINUX) Backend.setOs(OS.LINUX)

View File

@ -104,7 +104,7 @@ class Fingerprint(GenericFingerprint):
# Reference: https://en.wikipedia.org/wiki/Oracle_Database # Reference: https://en.wikipedia.org/wiki/Oracle_Database
for version in ("12c", "11g", "10g", "9i", "8i"): 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)) 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: if output:

View File

@ -165,7 +165,7 @@ class Users:
if Backend.isDbms(DBMS.MYSQL): if Backend.isDbms(DBMS.MYSQL):
for user in users: for user in users:
parsedUser = re.search("[\047]*(.*?)[\047]*\@", user) parsedUser = re.search(r"['\"]?(.*?)['\"]?\@", user)
if parsedUser: if parsedUser:
users[users.index(user)] = parsedUser.groups()[0] users[users.index(user)] = parsedUser.groups()[0]
@ -220,7 +220,7 @@ class Users:
if Backend.isDbms(DBMS.MYSQL): if Backend.isDbms(DBMS.MYSQL):
for user in users: for user in users:
parsedUser = re.search("[\047]*(.*?)[\047]*\@", user) parsedUser = re.search(r"['\"]?(.*?)['\"]?\@", user)
if parsedUser: if parsedUser:
users[users.index(user)] = parsedUser.groups()[0] users[users.index(user)] = parsedUser.groups()[0]
@ -349,7 +349,7 @@ class Users:
if Backend.isDbms(DBMS.MYSQL): if Backend.isDbms(DBMS.MYSQL):
for user in users: for user in users:
parsedUser = re.search("[\047]*(.*?)[\047]*\@", user) parsedUser = re.search(r"['\"]?(.*?)['\"]?\@", user)
if parsedUser: if parsedUser:
users[users.index(user)] = parsedUser.groups()[0] users[users.index(user)] = parsedUser.groups()[0]
@ -463,7 +463,7 @@ class Users:
if Backend.isDbms(DBMS.MYSQL): if Backend.isDbms(DBMS.MYSQL):
for user in users: for user in users:
parsedUser = re.search("[\047]*(.*?)[\047]*\@", user) parsedUser = re.search(r"['\"]?(.*?)['\"]?\@", user)
if parsedUser: if parsedUser:
users[users.index(user)] = parsedUser.groups()[0] users[users.index(user)] = parsedUser.groups()[0]