sqlmap/sqlmap.py

234 lines
6.9 KiB
Python
Raw Normal View History

#!/usr/bin/env python
2008-10-15 19:38:22 +04:00
"""
2016-01-06 02:06:12 +03:00
Copyright (c) 2006-2016 sqlmap developers (http://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
"""
2013-02-06 13:28:17 +04:00
import bdb
2013-05-29 12:20:43 +04:00
import inspect
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
2013-02-06 13:28:17 +04:00
import time
import traceback
import warnings
2016-02-13 23:28:02 +03:00
sys.dont_write_bytecode = True
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:32:19 +04:00
from lib.utils import versioncheck # this has to be the first non-standard import
2013-02-06 13:28:17 +04:00
from lib.controller.controller import start
from lib.core.common import banner
2014-10-27 02:37:46 +03:00
from lib.core.common import createGithubIssue
2013-02-06 13:28:17 +04:00
from lib.core.common import dataToStdout
from lib.core.common import getSafeExString
2013-02-06 13:28:17 +04:00
from lib.core.common import getUnicode
from lib.core.common import maskSensitiveData
2013-02-06 13:28:17 +04: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.data import logger
from lib.core.data import paths
from lib.core.common import unhandledExceptionMessage
from lib.core.exception import SqlmapBaseException
2014-09-16 16:12:43 +04:00
from lib.core.exception import SqlmapShellQuitException
2013-02-06 13:28:17 +04:00
from lib.core.exception import SqlmapSilentQuitException
from lib.core.exception import SqlmapUserQuitException
from lib.core.option import initOptions
from lib.core.option import init
from lib.core.profiling import profile
from lib.core.settings import LEGAL_DISCLAIMER
from lib.core.testing import smokeTest
from lib.core.testing import liveTest
from lib.parse.cmdline import cmdLineParser
from lib.utils.api import setRestAPILog
from lib.utils.api import StdDbOut
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)
2015-08-04 11:28:43 +03:00
return getUnicode(os.path.dirname(os.path.realpath(_)), encoding=sys.getfilesystemencoding())
2013-02-06 13:28:17 +04:00
def main():
"""
Main function of sqlmap when running from command line.
"""
try:
paths.SQLMAP_ROOT_PATH = modulePath()
2015-08-04 12:10:15 +03:00
try:
os.path.isdir(paths.SQLMAP_ROOT_PATH)
except UnicodeEncodeError:
errMsg = "your system does not properly handle non-ASCII paths. "
errMsg += "Please move the sqlmap's directory to the other location"
logger.error(errMsg)
2015-10-12 11:05:49 +03:00
raise SystemExit
2015-08-04 12:10:15 +03:00
2013-02-06 13:28:17 +04:00
setPaths()
# Store original command line options for possible later restoration
cmdLineOptions.update(cmdLineParser().__dict__)
initOptions(cmdLineOptions)
if hasattr(conf, "api"):
# 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()
banner()
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()
if conf.profile:
profile()
elif conf.smokeTest:
smokeTest()
elif conf.liveTest:
liveTest()
else:
start()
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()
2014-10-28 16:08:06 +03:00
2015-12-28 13:39:46 +03:00
try:
if any(_ in excMsg for _ in ("No space left", "Disk quota exceeded")):
errMsg = "no space left on output device"
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
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)
logger.critical(errMsg)
kb.stickyLevel = logging.CRITICAL
dataToStdout(excMsg)
createGithubIssue(errMsg, excMsg)
except KeyboardInterrupt:
pass
2013-02-06 13:28:17 +04:00
finally:
kb.threadContinue = False
kb.threadException = True
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)
2016-01-11 01:27:32 +03:00
if kb.get("tempDir"):
shutil.rmtree(kb.tempDir, ignore_errors=True)
2013-02-06 13:28:17 +04:00
if conf.get("hashDB"):
try:
conf.hashDB.flush(True)
except KeyboardInterrupt:
pass
2014-09-16 16:12:43 +04:00
if cmdLineOptions.get("sqlmapShell"):
cmdLineOptions.clear()
conf.clear()
kb.clear()
main()
2013-02-06 13:28:17 +04:00
if hasattr(conf, "api"):
try:
conf.database_cursor.disconnect()
except KeyboardInterrupt:
pass
if conf.get("dumper"):
conf.dumper.flush()
2013-02-06 13:28:17 +04:00
# Reference: http://stackoverflow.com/questions/1635080/terminate-a-multi-thread-python-program
if conf.get("threads", 0) > 1 or conf.get("dnsServer"):
os._exit(0)
if __name__ == "__main__":
2008-10-15 19:38:22 +04:00
main()