sqlmap/sqlmap.py

384 lines
13 KiB
Python
Raw Normal View History

#!/usr/bin/env python
2008-10-15 19:38:22 +04:00
"""
2018-01-02 02:48:10 +03:00
Copyright (c) 2006-2018 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
"""
2016-03-12 21:28:28 +03:00
import sys
sys.dont_write_bytecode = True
try:
__import__("lib.utils.versioncheck") # this has to be the first non-standard import
except ImportError:
exit("[!] wrong installation detected (missing modules). Visit 'https://github.com/sqlmapproject/sqlmap/#installation' for further details")
2016-03-12 21:28:28 +03:00
2013-02-06 13:28:17 +04:00
import bdb
2016-05-06 11:23:57 +03:00
import distutils
import glob
2013-05-29 12:20:43 +04:00
import inspect
2017-07-03 17:55:24 +03:00
import json
2013-04-19 12:14:28 +04:00
import logging
2013-02-06 13:28:17 +04:00
import os
2014-10-28 16:08:06 +03:00
import re
2015-01-13 12:33:51 +03:00
import shutil
2008-10-15 19:38:22 +04:00
import sys
2016-02-15 02:00:37 +03:00
import thread
2016-05-16 16:37:49 +03:00
import threading
2013-02-06 13:28:17 +04:00
import time
import traceback
import warnings
2013-02-06 13:28:17 +04:00
warnings.filterwarnings(action="ignore", message=".*was already imported", category=UserWarning)
warnings.filterwarnings(action="ignore", category=DeprecationWarning)
2008-10-15 19:38:22 +04:00
2013-02-06 13:28:17 +04:00
from lib.core.data import logger
2016-05-10 10:19:59 +03:00
try:
from lib.core.common import banner
from lib.core.common import checkIntegrity
2016-05-10 10:19:59 +03:00
from lib.core.common import createGithubIssue
from lib.core.common import dataToStdout
from lib.core.common import getSafeExString
from lib.core.common import getUnicode
from lib.core.common import maskSensitiveData
2017-07-03 17:55:24 +03:00
from lib.core.common import openFile
2016-05-10 10:19:59 +03:00
from lib.core.common import setPaths
from lib.core.common import weAreFrozen
from lib.core.data import cmdLineOptions
from lib.core.data import conf
from lib.core.data import kb
from lib.core.common import unhandledExceptionMessage
from lib.core.common import MKSTEMP_PREFIX
2016-05-10 10:19:59 +03:00
from lib.core.exception import SqlmapBaseException
from lib.core.exception import SqlmapShellQuitException
from lib.core.exception import SqlmapSilentQuitException
from lib.core.exception import SqlmapUserQuitException
from lib.core.option import initOptions
from lib.core.option import init
2016-06-18 02:21:57 +03:00
from lib.core.settings import GIT_PAGE
2016-05-10 10:19:59 +03:00
from lib.core.settings import IS_WIN
from lib.core.settings import LEGAL_DISCLAIMER
from lib.core.settings import THREAD_FINALIZATION_TIMEOUT
2016-06-19 18:44:47 +03:00
from lib.core.settings import UNICODE_ENCODING
2016-05-10 10:19:59 +03:00
from lib.core.settings import VERSION
from lib.parse.cmdline import cmdLineParser
except KeyboardInterrupt:
errMsg = "user aborted"
logger.error(errMsg)
raise SystemExit
2013-02-06 13:28:17 +04:00
def modulePath():
"""
This will get us the program's directory, even if we are frozen
using py2exe
"""
2013-05-29 12:20:43 +04:00
try:
_ = sys.executable if weAreFrozen() else __file__
except NameError:
_ = inspect.getsourcefile(modulePath)
2016-06-19 18:44:47 +03:00
return getUnicode(os.path.dirname(os.path.realpath(_)), encoding=sys.getfilesystemencoding() or UNICODE_ENCODING)
2013-02-06 13:28:17 +04:00
2016-05-06 11:23:57 +03:00
def checkEnvironment():
try:
2016-08-02 01:17:59 +03:00
os.path.isdir(modulePath())
2016-05-06 11:23:57 +03:00
except UnicodeEncodeError:
errMsg = "your system does not properly handle non-ASCII paths. "
errMsg += "Please move the sqlmap's directory to the other location"
logger.critical(errMsg)
raise SystemExit
if distutils.version.LooseVersion(VERSION) < distutils.version.LooseVersion("1.0"):
2016-05-06 11:23:57 +03:00
errMsg = "your runtime environment (e.g. PYTHONPATH) is "
errMsg += "broken. Please make sure that you are not running "
errMsg += "newer versions of sqlmap with runtime scripts for older "
errMsg += "versions"
logger.critical(errMsg)
raise SystemExit
2016-09-04 04:09:28 +03:00
# Patch for pip (import) environment
2016-09-04 02:33:52 +03:00
if "sqlmap.sqlmap" in sys.modules:
2016-09-04 04:09:28 +03:00
for _ in ("cmdLineOptions", "conf", "kb"):
globals()[_] = getattr(sys.modules["lib.core.data"], _)
for _ in ("SqlmapBaseException", "SqlmapShellQuitException", "SqlmapSilentQuitException", "SqlmapUserQuitException"):
globals()[_] = getattr(sys.modules["lib.core.exception"], _)
2016-09-04 02:33:52 +03:00
2013-02-06 13:28:17 +04:00
def main():
"""
Main function of sqlmap when running from command line.
"""
try:
2016-05-06 11:23:57 +03:00
checkEnvironment()
2016-08-02 01:17:59 +03:00
setPaths(modulePath())
2016-04-19 14:45:49 +03:00
banner()
2013-02-06 13:28:17 +04:00
# Store original command line options for possible later restoration
cmdLineOptions.update(cmdLineParser().__dict__)
initOptions(cmdLineOptions)
2017-04-10 20:21:22 +03:00
if conf.get("api"):
2016-09-28 15:48:33 +03:00
# heavy imports
from lib.utils.api import StdDbOut
from lib.utils.api import setRestAPILog
2013-02-06 13:28:17 +04:00
# Overwrite system standard output and standard error to write
# to an IPC database
sys.stdout = StdDbOut(conf.taskid, messagetype="stdout")
sys.stderr = StdDbOut(conf.taskid, messagetype="stderr")
setRestAPILog()
2014-09-16 18:28:38 +04:00
conf.showTime = True
2013-02-06 13:28:17 +04:00
dataToStdout("[!] legal disclaimer: %s\n\n" % LEGAL_DISCLAIMER, forceOutput=True)
dataToStdout("[*] starting at %s\n\n" % time.strftime("%X"), forceOutput=True)
init()
2017-12-04 17:40:59 +03:00
if not conf.updateAll:
# Postponed imports (faster start)
if conf.profile:
from lib.core.profiling import profile
profile()
elif conf.smokeTest:
from lib.core.testing import smokeTest
smokeTest()
elif conf.liveTest:
from lib.core.testing import liveTest
liveTest()
else:
from lib.controller.controller import start
try:
start()
except thread.error as ex:
if "can't start new thread" in getSafeExString(ex):
errMsg = "unable to start new threads. Please check OS (u)limits"
logger.critical(errMsg)
raise SystemExit
else:
raise
2013-02-06 13:28:17 +04:00
except SqlmapUserQuitException:
errMsg = "user quit"
2015-12-28 13:39:46 +03:00
try:
logger.error(errMsg)
except KeyboardInterrupt:
pass
2013-02-06 13:28:17 +04:00
except (SqlmapSilentQuitException, bdb.BdbQuit):
pass
2014-09-16 16:12:43 +04:00
except SqlmapShellQuitException:
cmdLineOptions.sqlmapShell = False
except SqlmapBaseException as ex:
errMsg = getSafeExString(ex)
2015-12-28 13:39:46 +03:00
try:
logger.critical(errMsg)
except KeyboardInterrupt:
pass
2015-10-12 11:05:49 +03:00
raise SystemExit
2013-02-06 13:28:17 +04:00
except KeyboardInterrupt:
print
2015-12-28 13:39:46 +03:00
2013-02-06 13:28:17 +04:00
errMsg = "user aborted"
2015-12-28 13:39:46 +03:00
try:
logger.error(errMsg)
except KeyboardInterrupt:
pass
2013-02-06 13:28:17 +04:00
except EOFError:
print
errMsg = "exit"
2015-12-28 13:39:46 +03:00
try:
logger.error(errMsg)
except KeyboardInterrupt:
pass
2013-02-06 13:28:17 +04:00
except SystemExit:
pass
except:
print
errMsg = unhandledExceptionMessage()
2014-10-27 02:37:46 +03:00
excMsg = traceback.format_exc()
2017-04-11 11:01:37 +03:00
valid = checkIntegrity()
2014-10-28 16:08:06 +03:00
2015-12-28 13:39:46 +03:00
try:
2017-04-11 11:01:37 +03:00
if valid is False:
2016-09-02 16:55:33 +03:00
errMsg = "code integrity check failed (turning off automatic issue creation). "
errMsg += "You should retrieve the latest development version from official GitHub "
errMsg += "repository at '%s'" % GIT_PAGE
logger.critical(errMsg)
print
2016-07-29 16:30:59 +03:00
dataToStdout(excMsg)
raise SystemExit
2016-08-15 19:35:04 +03:00
2017-07-28 01:00:09 +03:00
elif any(_ in excMsg for _ in ("tamper/", "waf/")):
2016-11-02 14:04:21 +03:00
logger.critical(errMsg)
print
dataToStdout(excMsg)
raise SystemExit
2016-09-02 16:52:07 +03:00
elif "MemoryError" in excMsg:
errMsg = "memory exhaustion detected"
logger.error(errMsg)
raise SystemExit
elif any(_ in excMsg for _ in ("No space left", "Disk quota exceeded")):
2015-12-28 13:39:46 +03:00
errMsg = "no space left on output device"
logger.error(errMsg)
raise SystemExit
2016-07-04 10:12:30 +03:00
elif all(_ in excMsg for _ in ("No such file", "_'", "self.get_prog_name()")):
2016-06-18 02:21:57 +03:00
errMsg = "corrupted installation detected ('%s'). " % excMsg.strip().split('\n')[-1]
errMsg += "You should retrieve the latest development version from official GitHub "
errMsg += "repository at '%s'" % GIT_PAGE
logger.error(errMsg)
raise SystemExit
2016-06-13 15:50:44 +03:00
elif "Read-only file system" in excMsg:
errMsg = "output device is mounted as read-only"
logger.error(errMsg)
raise SystemExit
2016-08-15 19:35:04 +03:00
elif "OperationalError: disk I/O error" in excMsg:
errMsg = "I/O error on output device"
logger.error(errMsg)
raise SystemExit
2017-10-10 12:04:17 +03:00
elif "Violation of BIDI" in excMsg:
errMsg = "invalid URL (violation of Bidi IDNA rule - RFC 5893)"
logger.error(errMsg)
raise SystemExit
2016-03-14 19:21:35 +03:00
elif "_mkstemp_inner" in excMsg:
errMsg = "there has been a problem while accessing temporary files"
logger.error(errMsg)
raise SystemExit
2017-11-10 02:44:33 +03:00
elif all(_ in excMsg for _ in ("twophase", "sqlalchemy")):
2017-11-10 02:41:03 +03:00
errMsg = "please update the 'sqlalchemy' package"
errMsg += "(Reference: https://github.com/apache/incubator-superset/issues/3447)"
logger.error(errMsg)
raise SystemExit
2016-05-09 14:13:02 +03:00
elif "can't start new thread" in excMsg:
errMsg = "there has been a problem while creating new thread instance. "
errMsg += "Please make sure that you are not running too many processes"
if not IS_WIN:
errMsg += " (or increase the 'ulimit -u' value)"
logger.error(errMsg)
raise SystemExit
2017-05-26 17:08:30 +03:00
elif "'DictObject' object has no attribute '" in excMsg and all(_ in errMsg for _ in ("(fingerprinted)", "(identified)")):
2017-05-02 00:21:12 +03:00
errMsg = "there has been a problem in enumeration. "
errMsg += "Because of a considerable chance of false-positive case "
errMsg += "you are advised to rerun with switch '--flush-session'"
logger.error(errMsg)
raise SystemExit
2016-01-20 11:33:05 +03:00
elif all(_ in excMsg for _ in ("pymysql", "configparser")):
errMsg = "wrong initialization of pymsql detected (using Python3 dependencies)"
logger.error(errMsg)
raise SystemExit
2015-12-28 13:39:46 +03:00
elif "bad marshal data (unknown type code)" in excMsg:
match = re.search(r"\s*(.+)\s+ValueError", excMsg)
errMsg = "one of your .pyc files are corrupted%s" % (" ('%s')" % match.group(1) if match else "")
errMsg += ". Please delete .pyc files on your system to fix the problem"
logger.error(errMsg)
raise SystemExit
2016-03-23 12:33:32 +03:00
elif "valueStack.pop" in excMsg and kb.get("dumpKeyboardInterrupt"):
raise SystemExit
2017-07-11 15:48:22 +03:00
elif any(_ in excMsg for _ in ("Broken pipe",)):
raise SystemExit
2015-12-28 13:39:46 +03:00
for match in re.finditer(r'File "(.+?)", line', excMsg):
file_ = match.group(1)
file_ = os.path.relpath(file_, os.path.dirname(__file__))
file_ = file_.replace("\\", '/')
file_ = re.sub(r"\.\./", '/', file_).lstrip('/')
excMsg = excMsg.replace(match.group(1), file_)
errMsg = maskSensitiveData(errMsg)
excMsg = maskSensitiveData(excMsg)
2017-04-11 11:01:37 +03:00
if conf.get("api") or not valid:
logger.critical("%s\n%s" % (errMsg, excMsg))
else:
logger.critical(errMsg)
kb.stickyLevel = logging.CRITICAL
dataToStdout(excMsg)
createGithubIssue(errMsg, excMsg)
2015-12-28 13:39:46 +03:00
except KeyboardInterrupt:
pass
2013-02-06 13:28:17 +04:00
finally:
kb.threadContinue = False
2016-01-11 02:03:22 +03:00
if conf.get("showTime"):
dataToStdout("\n[*] shutting down at %s\n\n" % time.strftime("%X"), forceOutput=True)
kb.threadException = True
2016-01-11 01:27:32 +03:00
if kb.get("tempDir"):
2016-07-13 15:09:33 +03:00
for prefix in (MKSTEMP_PREFIX.IPC, MKSTEMP_PREFIX.TESTING, MKSTEMP_PREFIX.COOKIE_JAR, MKSTEMP_PREFIX.BIG_ARRAY):
for filepath in glob.glob(os.path.join(kb.tempDir, "%s*" % prefix)):
try:
os.remove(filepath)
except OSError:
pass
if not filter(None, (filepath for filepath in glob.glob(os.path.join(kb.tempDir, '*')) if not any(filepath.endswith(_) for _ in ('.lock', '.exe', '_')))):
shutil.rmtree(kb.tempDir, ignore_errors=True)
2016-01-11 01:27:32 +03:00
2013-02-06 13:28:17 +04:00
if conf.get("hashDB"):
try:
conf.hashDB.flush(True)
except KeyboardInterrupt:
pass
2017-07-05 14:35:02 +03:00
if conf.get("harFile"):
2017-07-03 17:55:24 +03:00
with openFile(conf.harFile, "w+b") as f:
2017-07-05 15:07:21 +03:00
json.dump(conf.httpCollector.obtain(), fp=f, indent=4, separators=(',', ': '))
2017-07-03 17:55:24 +03:00
2014-09-16 16:12:43 +04:00
if cmdLineOptions.get("sqlmapShell"):
cmdLineOptions.clear()
conf.clear()
kb.clear()
main()
2017-04-10 20:21:22 +03:00
if conf.get("api"):
2013-02-06 13:28:17 +04:00
try:
2016-08-08 17:08:16 +03:00
conf.databaseCursor.disconnect()
2013-02-06 13:28:17 +04:00
except KeyboardInterrupt:
pass
if conf.get("dumper"):
conf.dumper.flush()
# short delay for thread finalization
try:
_ = time.time()
while threading.activeCount() > 1 and (time.time() - _) > THREAD_FINALIZATION_TIMEOUT:
time.sleep(0.01)
except KeyboardInterrupt:
pass
2016-08-08 17:08:16 +03:00
finally:
# Reference: http://stackoverflow.com/questions/1635080/terminate-a-multi-thread-python-program
if threading.activeCount() > 1:
os._exit(0)
2013-02-06 13:28:17 +04:00
if __name__ == "__main__":
2008-10-15 19:38:22 +04:00
main()