sqlmap/lib/core/testing.py

326 lines
10 KiB
Python
Raw Normal View History

#!/usr/bin/env python
2010-09-15 17:28:56 +04:00
"""
2014-01-13 21:24:49 +04:00
Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/)
2010-10-15 03:18:29 +04:00
See the file 'doc/COPYING' for copying permission
2010-09-15 17:28:56 +04:00
"""
2012-12-20 13:37:20 +04:00
import codecs
2010-09-27 17:26:46 +04:00
import doctest
2010-09-15 17:28:56 +04:00
import os
2010-09-26 18:02:13 +04:00
import re
import shutil
2010-09-15 17:28:56 +04:00
import sys
2010-09-26 18:02:13 +04:00
import tempfile
2010-09-26 14:47:04 +04:00
import time
import traceback
2010-09-15 17:28:56 +04:00
2012-12-11 15:02:06 +04:00
from extra.beep.beep import beep
2010-09-26 18:02:13 +04:00
from lib.controller.controller import start
2010-11-24 00:00:42 +03:00
from lib.core.common import clearConsoleLine
2010-09-26 14:47:04 +04:00
from lib.core.common import dataToStdout
2012-12-20 13:37:20 +04:00
from lib.core.common import getUnicode
from lib.core.common import randomStr
2010-10-07 02:43:04 +04:00
from lib.core.common import readXmlFile
2010-09-15 17:28:56 +04:00
from lib.core.data import conf
from lib.core.data import logger
from lib.core.data import paths
from lib.core.exception import SqlmapBaseException
2013-01-22 15:25:01 +04:00
from lib.core.exception import SqlmapNotVulnerableException
from lib.core.log import LOGGER_HANDLER
2010-09-26 18:02:13 +04:00
from lib.core.option import init
2013-01-29 20:23:30 +04:00
from lib.core.option import initOptions
from lib.core.option import setVerbosity
2010-09-27 17:26:46 +04:00
from lib.core.optiondict import optDict
2012-12-20 13:37:20 +04:00
from lib.core.settings import UNICODE_ENCODING
2010-09-26 18:02:13 +04:00
from lib.parse.cmdline import cmdLineParser
2010-09-15 17:28:56 +04:00
2014-01-13 21:24:49 +04:00
class Failures(object):
failedItems = None
failedParseOn = None
failedTraceBack = None
2010-09-15 17:28:56 +04:00
def smokeTest():
"""
Runs the basic smoke testing of a program
2010-09-15 17:28:56 +04:00
"""
2010-09-15 17:28:56 +04:00
retVal = True
2010-09-26 14:47:04 +04:00
count, length = 0, 0
2011-06-16 16:12:30 +04:00
for root, _, files in os.walk(paths.SQLMAP_ROOT_PATH):
2012-12-03 20:20:18 +04:00
if any(_ in root for _ in ("thirdparty", "extra")):
2011-06-16 16:12:30 +04:00
continue
for ifile in files:
2010-09-26 14:47:04 +04:00
length += 1
2010-09-15 17:28:56 +04:00
for root, _, files in os.walk(paths.SQLMAP_ROOT_PATH):
2012-12-03 20:20:18 +04:00
if any(_ in root for _ in ("thirdparty", "extra")):
2011-06-16 16:12:30 +04:00
continue
for ifile in files:
2012-12-06 17:15:44 +04:00
if os.path.splitext(ifile)[1].lower() == ".py" and ifile != "__init__.py":
path = os.path.join(root, os.path.splitext(ifile)[0])
2010-09-15 17:28:56 +04:00
path = path.replace(paths.SQLMAP_ROOT_PATH, '.')
path = path.replace(os.sep, '.').lstrip('.')
try:
__import__(path)
module = sys.modules[path]
except Exception, msg:
retVal = False
2010-09-26 14:47:04 +04:00
dataToStdout("\r")
2011-06-18 15:26:17 +04:00
errMsg = "smoke test failed at importing module '%s' (%s):\n%s" % (path, os.path.join(root, ifile), msg)
2010-09-15 17:28:56 +04:00
logger.error(errMsg)
else:
# Run doc tests
# Reference: http://docs.python.org/library/doctest.html
(failure_count, test_count) = doctest.testmod(module)
if failure_count > 0:
retVal = False
2010-09-26 14:47:04 +04:00
count += 1
2013-01-09 19:10:26 +04:00
status = '%d/%d (%d%%) ' % (count, length, round(100.0 * count / length))
2012-12-06 17:15:44 +04:00
dataToStdout("\r[%s] [INFO] complete: %s" % (time.strftime("%X"), status))
2010-09-26 14:47:04 +04:00
2010-11-24 00:00:42 +03:00
clearConsoleLine()
2010-09-15 17:28:56 +04:00
if retVal:
logger.info("smoke test final result: PASSED")
2010-09-15 17:28:56 +04:00
else:
logger.error("smoke test final result: FAILED")
2010-09-15 17:28:56 +04:00
return retVal
2010-09-15 17:32:42 +04:00
2010-09-27 17:26:46 +04:00
def adjustValueType(tagName, value):
for family in optDict.keys():
for name, type_ in optDict[family].items():
if type(type_) == tuple:
type_ = type_[0]
if tagName == name:
if type_ == "boolean":
value = (value == "True")
elif type_ == "integer":
value = int(value)
elif type_ == "float":
value = float(value)
break
return value
2010-09-15 17:32:42 +04:00
def liveTest():
"""
Runs the test of a program against the live testing environment
2010-09-15 17:32:42 +04:00
"""
2010-09-26 18:56:55 +04:00
retVal = True
count = 0
global_ = {}
vars_ = {}
2010-10-07 02:43:04 +04:00
livetests = readXmlFile(paths.LIVE_TESTS_XML)
length = len(livetests.getElementsByTagName("case"))
element = livetests.getElementsByTagName("global")
if element:
for item in element:
2010-09-26 18:02:13 +04:00
for child in item.childNodes:
if child.nodeType == child.ELEMENT_NODE and child.hasAttribute("value"):
2010-09-27 17:26:46 +04:00
global_[child.tagName] = adjustValueType(child.tagName, child.getAttribute("value"))
element = livetests.getElementsByTagName("vars")
if element:
for item in element:
for child in item.childNodes:
if child.nodeType == child.ELEMENT_NODE and child.hasAttribute("value"):
var = child.getAttribute("value")
vars_[child.tagName] = randomStr(6) if var == "random" else var
2010-09-26 18:02:13 +04:00
for case in livetests.getElementsByTagName("case"):
2013-01-30 14:32:56 +04:00
parse_from_console_output = False
count += 1
name = None
parse = []
switches = dict(global_)
value = ""
vulnerable = True
2013-01-21 21:10:56 +04:00
result = None
if case.hasAttribute("name"):
name = case.getAttribute("name")
2010-09-26 18:02:13 +04:00
if conf.runCase and ((conf.runCase.isdigit() and conf.runCase != count) or not re.search(conf.runCase, name, re.DOTALL)):
continue
2010-09-26 18:02:13 +04:00
if case.getElementsByTagName("switches"):
for child in case.getElementsByTagName("switches")[0].childNodes:
if child.nodeType == child.ELEMENT_NODE and child.hasAttribute("value"):
2010-09-27 17:26:46 +04:00
value = replaceVars(child.getAttribute("value"), vars_)
switches[child.tagName] = adjustValueType(child.tagName, value)
2010-09-26 18:02:13 +04:00
if case.getElementsByTagName("parse"):
for item in case.getElementsByTagName("parse")[0].getElementsByTagName("item"):
2010-09-26 18:02:13 +04:00
if item.hasAttribute("value"):
value = replaceVars(item.getAttribute("value"), vars_)
if item.hasAttribute("console_output"):
2013-01-30 14:32:56 +04:00
parse_from_console_output = bool(item.getAttribute("console_output"))
2013-01-30 14:32:56 +04:00
parse.append((value, parse_from_console_output))
2010-09-26 18:02:13 +04:00
conf.verbose = global_.get("verbose", 1)
setVerbosity()
msg = "running live test case: %s (%d/%d)" % (name, count, length)
logger.info(msg)
initCase(switches, count)
test_case_fd = codecs.open(os.path.join(paths.SQLMAP_OUTPUT_PATH, "test_case"), "wb", UNICODE_ENCODING)
2013-01-19 21:11:16 +04:00
test_case_fd.write("%s\n" % name)
2013-02-03 19:39:07 +04:00
try:
result = runCase(parse)
except SqlmapNotVulnerableException:
vulnerable = False
finally:
conf.verbose = global_.get("verbose", 1)
setVerbosity()
2013-02-03 19:39:07 +04:00
2013-01-21 21:10:56 +04:00
if result is True:
logger.info("test passed")
cleanCase()
else:
2014-01-13 21:24:49 +04:00
errMsg = "test failed"
2013-01-18 17:02:35 +04:00
2014-01-13 21:24:49 +04:00
if Failures.failedItems:
errMsg += " at parsing items:\n"
errMsg += "\n".join("\t%s" % i for i in Failures.failedItems)
2013-01-18 17:02:35 +04:00
2014-01-13 21:24:49 +04:00
errMsg += " - scan folder: %s" % paths.SQLMAP_OUTPUT_PATH
errMsg += " - traceback: %s" % bool(Failures.failedTraceBack)
2013-01-18 17:02:35 +04:00
if not vulnerable:
2013-01-18 17:02:35 +04:00
errMsg += " - SQL injection not detected"
logger.error(errMsg)
2013-01-19 21:11:16 +04:00
test_case_fd.write("%s\n" % errMsg)
2013-01-18 17:02:35 +04:00
2014-01-13 21:24:49 +04:00
if Failures.failedParseOn:
2013-01-18 17:02:35 +04:00
console_output_fd = codecs.open(os.path.join(paths.SQLMAP_OUTPUT_PATH, "console_output"), "wb", UNICODE_ENCODING)
2014-01-13 21:24:49 +04:00
console_output_fd.write(Failures.failedParseOn)
console_output_fd.close()
2014-01-13 21:24:49 +04:00
if Failures.failedTraceBack:
2013-01-18 17:02:35 +04:00
traceback_fd = codecs.open(os.path.join(paths.SQLMAP_OUTPUT_PATH, "traceback"), "wb", UNICODE_ENCODING)
2014-01-13 21:24:49 +04:00
traceback_fd.write(Failures.failedTraceBack)
2013-01-18 17:02:35 +04:00
traceback_fd.close()
beep()
if conf.stopFail is True:
return retVal
test_case_fd.close()
2013-01-18 17:02:35 +04:00
retVal &= bool(result)
dataToStdout("\n")
2010-09-26 18:56:55 +04:00
if retVal:
logger.info("live test final result: PASSED")
2010-09-26 18:56:55 +04:00
else:
logger.error("live test final result: FAILED")
2010-09-26 18:56:55 +04:00
return retVal
2010-09-26 18:02:13 +04:00
def initCase(switches, count):
2014-01-13 21:24:49 +04:00
Failures.failedItems = []
Failures.failedParseOn = None
Failures.failedTraceBack = None
paths.SQLMAP_OUTPUT_PATH = tempfile.mkdtemp(prefix="sqlmaptest-%d-" % count)
2011-04-30 17:20:05 +04:00
paths.SQLMAP_DUMP_PATH = os.path.join(paths.SQLMAP_OUTPUT_PATH, "%s", "dump")
paths.SQLMAP_FILES_PATH = os.path.join(paths.SQLMAP_OUTPUT_PATH, "%s", "files")
logger.debug("using output directory '%s' for this test case" % paths.SQLMAP_OUTPUT_PATH)
LOGGER_HANDLER.stream = sys.stdout = tempfile.SpooledTemporaryFile(max_size=0, mode="w+b", prefix="sqlmapstdout-")
2010-09-26 18:02:13 +04:00
cmdLineOptions = cmdLineParser()
if switches:
for key, value in switches.items():
2010-09-27 17:26:46 +04:00
if key in cmdLineOptions.__dict__:
cmdLineOptions.__dict__[key] = value
2013-01-29 20:23:30 +04:00
initOptions(cmdLineOptions, True)
init()
2010-09-26 18:56:55 +04:00
def cleanCase():
shutil.rmtree(paths.SQLMAP_OUTPUT_PATH, True)
2010-09-26 18:02:13 +04:00
2013-02-03 19:39:07 +04:00
def runCase(parse):
2012-12-19 18:34:34 +04:00
retVal = True
handled_exception = None
unhandled_exception = None
result = False
console = ""
try:
result = start()
except KeyboardInterrupt:
2013-01-26 19:33:09 +04:00
pass
except SqlmapBaseException, e:
handled_exception = e
2012-12-19 18:34:34 +04:00
except Exception, e:
unhandled_exception = e
finally:
sys.stdout.seek(0)
console = sys.stdout.read()
2012-12-19 18:34:34 +04:00
LOGGER_HANDLER.stream = sys.stdout = sys.__stdout__
if unhandled_exception:
2014-01-13 21:24:49 +04:00
Failures.failedTraceBack = "unhandled exception: %s" % str(traceback.format_exc())
2013-01-18 17:02:35 +04:00
retVal = None
elif handled_exception:
2014-01-13 21:24:49 +04:00
Failures.failedTraceBack = "handled exception: %s" % str(traceback.format_exc())
2013-01-18 17:02:35 +04:00
retVal = None
elif result is False: # this means no SQL injection has been detected - if None, ignore
2010-09-26 18:56:55 +04:00
retVal = False
console = getUnicode(console, system=True)
if parse and retVal:
2012-12-20 13:37:20 +04:00
with codecs.open(conf.dumper.getOutputFile(), "rb", UNICODE_ENCODING) as f:
content = f.read()
2012-12-19 17:47:17 +04:00
2013-01-30 14:32:56 +04:00
for item, parse_from_console_output in parse:
parse_on = console if parse_from_console_output else content
if item.startswith("r'") and item.endswith("'"):
if not re.search(item[2:-1], parse_on, re.DOTALL):
2013-01-18 17:02:35 +04:00
retVal = None
2014-01-13 21:24:49 +04:00
Failures.failedItems.append(item)
#break
2012-12-20 13:37:20 +04:00
elif item not in parse_on:
2013-01-18 17:02:35 +04:00
retVal = None
2014-01-13 21:24:49 +04:00
Failures.failedItems.append(item)
#break
2010-09-26 18:56:55 +04:00
2014-01-13 21:24:49 +04:00
if Failures.failedItems:
Failures.failedParseOn = console
elif retVal is False:
2014-01-13 21:24:49 +04:00
Failures.failedParseOn = console
2010-09-26 18:56:55 +04:00
return retVal
2010-09-26 18:02:13 +04:00
def replaceVars(item, vars_):
2010-09-26 18:02:13 +04:00
retVal = item
2012-12-19 18:25:29 +04:00
if item and vars_:
for var in re.findall("\$\{([^}]+)\}", item):
if var in vars_:
retVal = retVal.replace("${%s}" % var, vars_[var])
2012-12-19 18:25:29 +04:00
2012-12-06 17:15:44 +04:00
return retVal