Exemple #1
0
def main():
    """
    REST-JSON API main function
    """

    # Set default logging level to debug
    logger.setLevel(logging.DEBUG)

    # Initialize path variable
    paths.SQLMAP_ROOT_PATH = modulePath()
    setPaths()

    # Parse command line options
    apiparser = optparse.OptionParser()
    apiparser.add_option("-s", "--server", help="Act as a REST-JSON API server", default=RESTAPI_DEFAULT_PORT, action="store_true")
    apiparser.add_option("-c", "--client", help="Act as a REST-JSON API client", default=RESTAPI_DEFAULT_PORT, action="store_true")
    apiparser.add_option("-H", "--host", help="Host of the REST-JSON API server", default=RESTAPI_DEFAULT_ADDRESS, action="store")
    apiparser.add_option("-p", "--port", help="Port of the the REST-JSON API server", default=RESTAPI_DEFAULT_PORT, type="int", action="store")
    apiparser.add_option("--adapter", help="Server (bottle) adapter to use (default %s)" % RESTAPI_DEFAULT_ADAPTER, default=RESTAPI_DEFAULT_ADAPTER, action="store")
    (args, _) = apiparser.parse_args()

    # Start the client or the server
    if args.server is True:
        server(args.host, args.port, adapter=args.adapter)
    elif args.client is True:
        client(args.host, args.port)
    else:
        apiparser.print_help()
Exemple #2
0
def main():
    try:
        paths['ROOT_PATH'] = os.path.dirname(
            os.path.dirname(os.path.realpath(__file__)))
        setPaths()
        parse_args()

        if IS_WIN:
            win_color_init()
        banner()

        if conf['DEBUG']:
            showDebugData()
        if conf['UPDATE']:
            update()

        load_payloads()

        if conf['ENGINE'] is 't':
            from lib.controller.threads import ThreadsEngine
            ThreadsEngine().run()
        elif conf['ENGINE'] is 'c':
            from lib.controller.coroutine import CoroutineEngine
            CoroutineEngine().run()
    except KeyboardInterrupt, e:
        logger.log(CUSTOM_LOGGING.ERROR, 'User quit!')
Exemple #3
0
 def start_button_clicked(self):
     if not conf.is_stop:
         return
     text = self.urlText.text()
     if text == "": return
     conf.is_stop = False
     row_index = self.tableWidget.rowCount()
     for i in range(row_index):
         self.tableWidget.removeRow(0)
     paths.ROOT_PATH = os.getcwd()
     setPaths()
     dicts = {
         'thread_num': 8,
         'target_input': text,
         'target_file': '',
         'load_config_file': True,
         'debug': False
     }
     cmdLineOptions.update(dicts)
     initOptions(cmdLineOptions)
     self.workThread = WorkThread()
     conf["thread"] = self.workThread
     self.workThread.start()
     self.workThread.stop.connect(self.stop_button_clicked)
     self.workThread.update.connect(self.update_table)
     self.workThread.update_status.connect(self.update_status_bar)
def main():
    """
    Main function of w9scan when running from command line.
    """
    checkEnvironment()  # 检测环境
    setPaths(modulePath())  # 为一些目录和文件设置了绝对路径

    parser = argparse.ArgumentParser(description="w9scan scanner")
    parser.add_argument("--update", help="update w9scan", action="store_true")
    parser.add_argument("--guide", help="w9scan to guide", action="store_true")
    parser.add_argument(
        "--banner", help="output the banner", action="store_true")
    parser.add_argument("-u", help="url")
    parser.add_argument("-p", "--plugin", help="plugins")
    parser.add_argument("-s", "--search", help="find infomation of plugin")
    parser.add_argument("--debug", help="output debug info",
                        action="store_true", default=False)
    args = parser.parse_args()

    if IS_WIN:
        winowsColorInit()
    Banner()

    try:
        configFileParser(os.path.join(paths.w9scan_ROOT_PATH, "config.conf"))
        initOption(args)
        pluginScan()
        webScan()

    except ToolkitMissingPrivileges, e:
        logger.error(e)
        systemQuit(EXIT_STATUS.ERROR_EXIT)
Exemple #5
0
def main():
    """
    REST-JSON API main function
    """

    # Set default logging level to debug
    logger.setLevel(logging.DEBUG)

    # Initialize paths
    setPaths(modulePath())

    # Parse command line options
    apiparser = optparse.OptionParser()
    apiparser.add_option("-s", "--server", help="Run as a REST-JSON API server", default=RESTAPI_DEFAULT_PORT, action="store_true")
    apiparser.add_option("-c", "--client", help="Run as a REST-JSON API client", default=RESTAPI_DEFAULT_PORT, action="store_true")
    apiparser.add_option("-H", "--host", help="Host of the REST-JSON API server (default \"%s\")" % RESTAPI_DEFAULT_ADDRESS, default=RESTAPI_DEFAULT_ADDRESS, action="store")
    apiparser.add_option("-p", "--port", help="Port of the the REST-JSON API server (default %d)" % RESTAPI_DEFAULT_PORT, default=RESTAPI_DEFAULT_PORT, type="int", action="store")
    apiparser.add_option("--adapter", help="Server (bottle) adapter to use (default \"%s\")" % RESTAPI_DEFAULT_ADAPTER, default=RESTAPI_DEFAULT_ADAPTER, action="store")
    apiparser.add_option("--username", help="Basic authentication username (optional)", action="store")
    apiparser.add_option("--password", help="Basic authentication password (optional)", action="store")
    (args, _) = apiparser.parse_args()

    # Start the client or the server
    if args.server is True:
        server(args.host, args.port, adapter=args.adapter, username=args.username, password=args.password)
    elif args.client is True:
        client(args.host, args.port, username=args.username, password=args.password)
    else:
        apiparser.print_help()
Exemple #6
0
def main():
    try:
        paths['ROOT_PATH'] = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
        setPaths()
        parse_args()

        if IS_WIN:
            win_color_init()
        banner()

        if conf['DEBUG']:
            showDebugData()
        if conf['UPDATE']:
            update()

        load_payloads()

        if conf['ENGINE'] is 't':
            from lib.controller.threads import ThreadsEngine
            ThreadsEngine().run()
        elif conf['ENGINE'] is 'c':
            from lib.controller.coroutine import CoroutineEngine
            CoroutineEngine().run()
    except KeyboardInterrupt, e:
        logger.log(CUSTOM_LOGGING.ERROR, 'User quit!')
Exemple #7
0
def main():
    """
    REST-JSON API main function
    """

    # Set default logging level to debug
    logger.setLevel(logging.DEBUG)

    # Initialize paths
    setPaths(modulePath())

    # Parse command line options
    apiparser = optparse.OptionParser()
    apiparser.add_option("-s", "--server", help="Act as a REST-JSON API server", default=RESTAPI_DEFAULT_PORT, action="store_true")
    apiparser.add_option("-c", "--client", help="Act as a REST-JSON API client", default=RESTAPI_DEFAULT_PORT, action="store_true")
    apiparser.add_option("-H", "--host", help="Host of the REST-JSON API server (default \"%s\")" % RESTAPI_DEFAULT_ADDRESS, default=RESTAPI_DEFAULT_ADDRESS, action="store")
    apiparser.add_option("-p", "--port", help="Port of the the REST-JSON API server (default %d)" % RESTAPI_DEFAULT_PORT, default=RESTAPI_DEFAULT_PORT, type="int", action="store")
    apiparser.add_option("--adapter", help="Server (bottle) adapter to use (default \"%s\")" % RESTAPI_DEFAULT_ADAPTER, default=RESTAPI_DEFAULT_ADAPTER, action="store")
    (args, _) = apiparser.parse_args()

    # Start the client or the server
    if args.server is True:
        server(args.host, args.port, adapter=args.adapter)
    elif args.client is True:
        client(args.host, args.port)
    else:
        apiparser.print_help()
Exemple #8
0
def main():
    """
    Main function of w9scan when running from command line.
    """
    try:
        checkEnvironment()  # 检测环境
        setPaths(modulePath())  # 为一些目录和文件设置了绝对路径
        banner()

        urlconfig.url = raw_input('Input url > ')
        urlconfig.url = makeurl(urlconfig.url)

        urlconfig.scanport = False
        input_scanport = raw_input('Need scan all ports ?(Y/N) (default N)> ')
        if input_scanport.lower() in ("y", "yes"):
            urlconfig.scanport = True

        urlconfig.threadNum = raw_input(
            'You need start number of thread(Recommendation number is 5) > ')
        urlconfig.threadNum = int(urlconfig.threadNum)

        e = Exploit_run(urlconfig.threadNum)
        print '[***] ScanStart Target:%s' % urlconfig.url
        e.load_modules("www", urlconfig.url)
        e.run()
        e.init_spider()
        s = crawler.SpiderMain(urlconfig.url)
        s.craw()
        logger.report()
    except KeyboardInterrupt:
        logger.critical("[***] User Interrupt")
        exit()
    except Exception as info:
        print "[xxx] MainError", info
        exit()
Exemple #9
0
def main():

    try:

        setEnvironment()
        setPaths()

        banner()
        cmdLineOptions.update(cmdLineParser().__dict__)
        initOptions(cmdLineOptions)

        init()

        run()

    except PyExpSyntaxException as ex:
        logger.error(ex)
        msg = "\n[*] Pyexp is shutting down at %s.\n\n" % time.strftime(
            "%H:%M:%S")
        dataToStdout(msg)
        raise SystemExit
    except PyExpSystemException as ex:
        logger.critical(ex)
        msg = "\n[*] Pyexp is shutting down at %s.\n\n" % time.strftime(
            "%H:%M:%S")
        dataToStdout(msg)
        raise SystemExit
Exemple #10
0
def main():
    """
    REST-JSON API main function
    """

    # Set default logging level to debug
    logger.setLevel(logging.DEBUG)

    # Initialize path variable
    paths.SQLMAP_ROOT_PATH = modulePath()
    setPaths()

    # Parse command line options
    apiparser = optparse.OptionParser()
    apiparser.add_option("-s", "--server", help="Act as a REST-JSON API server", default=RESTAPI_DEFAULT_PORT, action="store_true")
    apiparser.add_option("-c", "--client", help="Act as a REST-JSON API client", default=RESTAPI_DEFAULT_PORT, action="store_true")
    apiparser.add_option("-H", "--host", help="Host of the REST-JSON API server", default=RESTAPI_DEFAULT_ADDRESS, action="store")
    apiparser.add_option("-p", "--port", help="Port of the the REST-JSON API server", default=RESTAPI_DEFAULT_PORT, type="int", action="store")
    (args, _) = apiparser.parse_args()

    # Start the client or the server
    if args.server is True:
        server(args.host, args.port)
    elif args.client is True:
        client(args.host, args.port)
    else:
        apiparser.print_help()
Exemple #11
0
def main(taskID, target, thread_num, load_config_file):
    """
    main fuction of dirmap 
    """

    # set paths of project
    paths.ROOT_PATH = os.path.dirname(os.path.abspath(__file__))
    setPaths()

    scan_param = {
        'thread_num': thread_num,
        'target_input': target,  # single or range or mask
        'target_file': '',
        'load_config_file': load_config_file,
        'debug': False
    }
    # received command >> cmdLineOptions
    cmdLineOptions.update(scan_param)

    # loader script,target,working way(threads? gevent?),output_file from cmdLineOptions
    # and send it to conf
    initOptions(cmdLineOptions)  # 扫描中的全部参数放到conf中
    # run!
    run()
    print(result)
    _ = MongoDB()
    _.add_web_dir(taskID, result)
    return result
Exemple #12
0
def main():
    """
	Main function of cloudspider when running from command line
	"""
    paths.ROOT_PATH = modulePath()
    setPaths()
    banner()
    initServer()
Exemple #13
0
def main():
    paths.ZEROSCAN_ROOT_PATH = modulePath()
    setPaths()
    kb.unloadedList = {}
    initializeKb()
    initializeExp()
    zs = baseConsole()
    zs.cmdloop()
Exemple #14
0
def main():
    paths.ZEROSCAN_ROOT_PATH = modulePath()
    setPaths()
    kb.unloadedList = {}
    initializeKb()
    initializeExp()
    zs = baseConsole()
    zs.cmdloop()
Exemple #15
0
def main():
	try:
		logger.log(CUSTOM_LOGGING.INFO,'Start the initialization work ...')

		# Set program path
		logger.log(CUSTOM_LOGGING.SUCCESS,'Start setting program path ...')
		setPaths()

		# Parse command line parameters
		logger.log(CUSTOM_LOGGING.INFO,'Start parsing parameters ...')
		args=parseArgs()

		# Adjust color output
		logger.log(CUSTOM_LOGGING.INFO,'Start adjusting color output ...')
		initWinStdout()

		# Output banner information
		logger.log(CUSTOM_LOGGING.INFO,'Start printing banner ...')
		printBanner()
		
		# Print banner information
		logger.log(CUSTOM_LOGGING.INFO,'Start initial configuration ...')
		initConfig(args)

		# Load concurrent target
		logger.log(CUSTOM_LOGGING.INFO,'Start to initialize the concurrent target ...')
		loadTarget()

		# Load modules (preprocessing and processing)
		logger.log(CUSTOM_LOGGING.INFO,'Start to initialize the concurrent module ...')
		loadModule()

		# So far, all initialization work of the program is completed
		logger.log(CUSTOM_LOGGING.INFO,'So far, Initialization work has been completed')

		# Run concurrency engine
		logger.log(CUSTOM_LOGGING.INFO,'Start running the concurrent engine ...')
		runEngine()

		# End of program
		logger.log(CUSTOM_LOGGING.INFO,'End of program.')
		sys.exit(0)

	except KeyboardInterrupt as e:
		# If the KeyboardInterrupt exception occurs during the program, it means that the user has pressed ctrl+c, that is, the user voluntarily exits
		logger.error('User Quit')
		sys.exit(0)

	except Exception as e:
		# If other exceptions occur in the program, print the exception traceback message
		errMsg=traceback.format_exc()
		logger.error('An exception has occurred in the MyCT.\n Exception : \n%s'%errMsg)
		logger.error('The program exits unexpectedly.')
		sys.exit(-1)
Exemple #16
0
def main():
    """
    REST-JSON API 主函数
    """

    # 将默认日志记录级别设置为debug
    logger.setLevel(logging.DEBUG)

    # 初始化路径
    setPaths(modulePath())

    # 解析命令行选项
    apiparser = optparse.OptionParser()
    apiparser.add_option("-s",
                         "--server",
                         help=u"作为REST-JSON API服务器",
                         default=RESTAPI_DEFAULT_PORT,
                         action="store_true")
    apiparser.add_option("-c",
                         "--client",
                         help=u"作为REST-JSON API客户端",
                         default=RESTAPI_DEFAULT_PORT,
                         action="store_true")
    apiparser.add_option("-H",
                         "--host",
                         help="REST-JSON API服务器主机地址(默认为 \"%s\")" %
                         RESTAPI_DEFAULT_ADDRESS,
                         default=RESTAPI_DEFAULT_ADDRESS,
                         action="store")
    apiparser.add_option("-p",
                         "--port",
                         help="REST-JSON服务器端口(默认为 %d)" % RESTAPI_DEFAULT_PORT,
                         default=RESTAPI_DEFAULT_PORT,
                         type="int",
                         action="store")
    apiparser.add_option("--adapter",
                         help="要使用的服务器适配器(默认为 \"%s\")" %
                         RESTAPI_DEFAULT_ADAPTER,
                         default=RESTAPI_DEFAULT_ADAPTER,
                         action="store")
    (args, _) = apiparser.parse_args()
    """
    adapter(适配器)定义为将一个类的接口变换成客户端所期待的一种接口,
    从而使原本因接口不匹配而无法在一起工作的两个类能够在一起工作。
    """

    # 启动客户端或服务器
    if args.server is True:
        server(args.host, args.port, adapter=args.adapter)
    elif args.client is True:
        client(args.host, args.port)
    else:
        apiparser.print_help()
Exemple #17
0
def main():
    """
    Main function of sqlmap when running from command line.
    """

    try:
        paths.SQLMAP_ROOT_PATH = modulePath()
        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()

        dataToStdout("[!] legal disclaimer: %s\n\n" % LEGAL_DISCLAIMER,
                     forceOutput=True)
        dataToStdout("[*] starting at %s\n\n" % time.strftime("%X"),
                     forceOutput=True)

        if ".sqlmap" in paths.SQLMAP_OUTPUT_PATH:
            warnMsg = "using '%s' as the output directory" % paths.SQLMAP_OUTPUT_PATH
            logger.warn(warnMsg)

        init()

        if conf.profile:
            profile()
        elif conf.smokeTest:
            smokeTest()
        elif conf.liveTest:
            liveTest()
        else:
            start()

    except SqlmapUserQuitException:
        errMsg = "user quit"
        logger.error(errMsg)

    except (SqlmapSilentQuitException, bdb.BdbQuit):
        pass

    except SqlmapBaseException, ex:
        errMsg = getUnicode(ex.message)
        logger.critical(errMsg)
        sys.exit(1)
Exemple #18
0
def main():
    """
    Main function of sqlmap when running from command line.
    """

    try:
        paths.SQLMAP_ROOT_PATH = modulePath()
        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()

        dataToStdout("[!] legal disclaimer: %s\n\n" % LEGAL_DISCLAIMER, forceOutput=True)
        dataToStdout("[*] starting at %s\n\n" % time.strftime("%X"), forceOutput=True)

        if ".sqlmap" in paths.SQLMAP_OUTPUT_PATH:
            warnMsg = "using '%s' as the output directory" % paths.SQLMAP_OUTPUT_PATH
            logger.warn(warnMsg)

        init()

        if conf.profile:
            profile()
        elif conf.smokeTest:
            smokeTest()
        elif conf.liveTest:
            liveTest()
        else:
            start()

    except SqlmapUserQuitException:
        errMsg = "user quit"
        logger.error(errMsg)

    except (SqlmapSilentQuitException, bdb.BdbQuit):
        pass

    except SqlmapBaseException, ex:
        errMsg = getUnicode(ex.message)
        logger.critical(errMsg)
        sys.exit(1)
Exemple #19
0
def main():  #main 定义
    """
    Main function of sqlmap when running from command line.#主要功能的sqlmap从命令行运行时
        """

    try:
        paths.SQLMAP_ROOT_PATH = modulePath()  #注释:设置各个路径
        setPaths()  #进入lib/core/commin.py下的setpaths函数

        # Store original command line options for possible later restoration。 #存储原始命令行选项可能晚些时候恢复
        cmdLineOptions.update(cmdLineParser().__dict__)
        initOptions(
            cmdLineOptions)  #initOption 函数  lib/core/option.py 设置conf,KB,参数

        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()

        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()  # thirdparty/gprof2dot/gprof2dot.py
        elif conf.smokeTest:
            smokeTest()  #lib/core/testing.py
        elif conf.liveTest:
            liveTest()  #lib/core/testing.py
        else:
            start()  #在 controller.py

    except SqlmapUserQuitException:
        errMsg = "user quit"
        logger.error(errMsg)

    except (SqlmapSilentQuitException, bdb.BdbQuit):
        pass

    except SqlmapBaseException, ex:
        errMsg = getUnicode(ex.message)
        logger.critical(errMsg)
        sys.exit(1)
Exemple #20
0
def main():
    """
    REST-JSON API main function
    """

    # Set default logging level to debug
    logger.setLevel(logging.DEBUG)

    # Initialize paths
    setPaths(modulePath())

    server(RESTAPI_DEFAULT_ADDRESS,
           RESTAPI_DEFAULT_PORT,
           adapter=RESTAPI_DEFAULT_ADAPTER)
Exemple #21
0
def main():
    """
    Main function of sheep when running from command line.
    :return:
    """
    try:
        paths.SHEEP_ROOT_PATH = modulePath()
        setPaths()
        mainC = mainCmd()
        mainC.cmdloop()
    except KeyboardInterrupt:
        systemQuit(EXIT_STATUS.USER_QUIT)
    except Exception:
        systemQuit(EXIT_STATUS.ERROR_EXIT)
Exemple #22
0
def main():
    """
    Main function of POC-T when running from command line.
    """
    try:
        paths.ROOT_PATH = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
        try:
            os.path.isdir(paths.ROOT_PATH)
        except UnicodeEncodeError:
            errMsg = "your system does not properly handle non-ASCII paths. "
            errMsg += "Please move the project root directory to another location"
            logger.error(errMsg)
            raise SystemExit
        setPaths()

        cmdLineOptions.update(cmdLineParser().__dict__)
        initOptions(cmdLineOptions)

        if IS_WIN:
            winowsColorInit()
        banner()

        loadModule()
        loadPayloads()

        run()

        if conf.OPEN_BROWSER:
            openBrowser()

        systemQuit(EXIT_STATUS.SYSETM_EXIT)

    except ToolkitMissingPrivileges as e:
        logger.error(e)
        systemQuit(EXIT_STATUS.ERROR_EXIT)

    except ToolkitSystemException as e:
        logger.error(e)
        systemQuit(EXIT_STATUS.ERROR_EXIT)

    except ToolkitUserQuitException:
        systemQuit(EXIT_STATUS.USER_QUIT)
    except KeyboardInterrupt:
        systemQuit(EXIT_STATUS.USER_QUIT)

    except Exception:
        print(traceback.format_exc())
        logger.warning('It seems like you reached a unhandled exception, please report it to author\'s mail:<*****@*****.**>.')
Exemple #23
0
def main():
    try:
        paths.ROOT_PATH = modulePath()
        setPaths()
        setConfAttribute()
        banner()
        print '[*] starting at %s\n' % time.strftime("%X")
    except KeyboardInterrupt:
        print
        err_msg = 'User Aborted!'
    except EOFError:
        print
        err_msg = 'Exit!'
    except SystemExit:
        pass
    finally:
        print '[*] shutdown at %s\n' % time.strftime("%X")
Exemple #24
0
def main(debug=False):
    try:
        checkSystemEnvironment()
        setPaths(modulePath())
        if not debug: cmdLineParse()
        loadRules()
        scan()

    except PhcatSystemNotSupportException:
        pass
    except PhcatCmdParserErrorException:
        pass
    except PhcatCoroutineErrorException:
        pass
    except KeyboardInterrupt:
        logger.warn("Keyboard interrupt")
        exit()
Exemple #25
0
def main():
    """"
    Main function of AWIScan when running from command line.
    """

    banner()

    # Set paths of project.
    CONF.ROOT_PATH = os.getcwd()
    setPaths()

    # received command >> parse_args
    base_targets, level = parse_args()
    initOptions(level)

    run(base_targets)
    logger.info("[AWIScan] All target is end")
Exemple #26
0
    def test_paths_setPaths(self):
        self.assertEqual({}, paths)
        paths.SQLMAP_ROOT_PATH = modulePath()
#        self.assertEqual({'SQLMAP_ROOT_PATH': u'/home/k/Develop/sqlmap'}, paths)
        setPaths()
        self.maxDiff = None
        # self.assertDictContainsSubset({'COMMON_COLUMNS': u'/home/k/Develop/sqlmap/txt/common-columns.txt',
        #                                 'COMMON_OUTPUTS': u'/home/k/Develop/sqlmap/txt/common-outputs.txt',
        #                                 'COMMON_TABLES': u'/home/k/Develop/sqlmap/txt/common-tables.txt',
        #                                 'ERRORS_XML': u'/home/k/Develop/sqlmap/xml/errors.xml',
        #                                 'GENERIC_XML': u'/home/k/Develop/sqlmap/xml/banner/generic.xml',
        #                                 'INJECTIONS_XML': u'/home/k/Develop/sqlmap/xml/injections.xml',
        #                                 'LIVE_TESTS_XML': u'/home/k/Develop/sqlmap/xml/livetests.xml',
        #                                 'MSSQL_XML': u'/home/k/Develop/sqlmap/xml/banner/mssql.xml',
        #                                 'MYSQL_XML': u'/home/k/Develop/sqlmap/xml/banner/mysql.xml',
        #                                 'ORACLE_XML': u'/home/k/Develop/sqlmap/xml/banner/oracle.xml',
        #                                 'OS_SHELL_HISTORY': '/home/k/.sqlmap/os.hst',
        #                                 'PAYLOADS_XML': u'/home/k/Develop/sqlmap/xml/payloads.xml',
        #                                 'PGSQL_XML': u'/home/k/Develop/sqlmap/xml/banner/postgresql.xml',
        #                                 'QUERIES_XML': u'/home/k/Develop/sqlmap/xml/queries.xml',
        #                                 'SMALL_DICT': u'/home/k/Develop/sqlmap/txt/smalldict.txt',
        #                                 #'SQLMAP_CONFIG': u'/home/k/Develop/sqlmap/sqlmap-dieD.conf',
        #                                 'SQLMAP_DUMP_PATH': u'/home/k/.sqlmap/output/%s/dump',
        #                                 'SQLMAP_EXTRAS_PATH': u'/home/k/Develop/sqlmap/extra',
        #                                 'SQLMAP_FILES_PATH': u'/home/k/.sqlmap/output/%s/files',
        #                                 'SQLMAP_OUTPUT_PATH': u'/home/k/.sqlmap/output',
        #                                 'SQLMAP_PROCS_PATH': u'/home/k/Develop/sqlmap/procs',
        #                                 'SQLMAP_ROOT_PATH': u'/home/k/Develop/sqlmap',
        #                                 'SQLMAP_SHELL_HISTORY': '/home/k/.sqlmap/sqlmap.hst',
        #                                 'SQLMAP_SHELL_PATH': u'/home/k/Develop/sqlmap/shell',
        #                                 'SQLMAP_TAMPER_PATH': u'/home/k/Develop/sqlmap/tamper',
        #                                 'SQLMAP_TXT_PATH': u'/home/k/Develop/sqlmap/txt',
        #                                 'SQLMAP_UDF_PATH': u'/home/k/Develop/sqlmap/udf',
        #                                 'SQLMAP_WAF_PATH': u'/home/k/Develop/sqlmap/waf',
        #                                 'SQLMAP_XML_BANNER_PATH': u'/home/k/Develop/sqlmap/xml/banner',
        #                                 'SQLMAP_XML_PATH': u'/home/k/Develop/sqlmap/xml',
        #                                 'SQL_KEYWORDS': u'/home/k/Develop/sqlmap/txt/keywords.txt',
        #                                 'SQL_SHELL_HISTORY': '/home/k/.sqlmap/sql.hst',
        #                                 'USER_AGENTS': u'/home/k/Develop/sqlmap/txt/user-agents.txt',
        #                                 'WORDLIST': u'/home/k/Develop/sqlmap/txt/wordlist.zip'}, paths)
        #self.assertEqual(u'/home/k/Develop/sqlmap/sqlmap-YplE.conf', paths.SQLMAP_CONFIG)
        import os
        profileOutputFile = os.path.join(paths.SQLMAP_OUTPUT_PATH, "sqlmap_profile.raw")
        # self.assertEqual(u'/home/k/.sqlmap/output/sqlmap_profile.raw', profileOutputFile)
        paths.SQLMAP_FILES_PATH = os.path.join(paths.SQLMAP_OUTPUT_PATH, "%s", "files")
Exemple #27
0
def main():
    """
    Main function of w9scan when running from command line.
    """
    try:
        checkEnvironment()  # 检测环境
        setPaths(modulePath())  # 为一些目录和文件设置了绝对路径
        banner()
        Test_Url = raw_input('Input url > ')
        Test_Url = Test_Url.strip()
        #Test_Url = "https://blog.hacking8.com/"
        e = Exploit_run(Test_Url)
        print '[***] ScanStart Target:%s' % Test_Url
        e.load_modules("www", Test_Url)
        logger.report()
    except KeyboardInterrupt:
        logger.critical("[***] UserInterrupt")
        exit()
Exemple #28
0
def main():
    """
    Main function of w9scan when running from command line.
    """
    try:
        checkEnvironment() # 检测环境
        setPaths(modulePath()) # 为一些目录和文件设置了绝对路径
        banner()
        Test_Url = raw_input('Input url > ')
        Test_Url = Test_Url.strip()
        #Test_Url = "https://blog.hacking8.com/"
        e = Exploit_run(Test_Url)
        print '[***] ScanStart Target:%s' % Test_Url
        e.load_modules("www",Test_Url)
        logger.report()
    except KeyboardInterrupt:
        logger.critical("[***] UserInterrupt")
        exit()
Exemple #29
0
def main():
    """
    Main function of w9scan when running from command line.
    """
    try:
        checkEnvironment()  # 检测环境
        setPaths(modulePath())  # 为一些目录和文件设置了绝对路径
        banner()

        urlconfig.url = raw_input('Input url > ')
        urlconfig.url = makeurl(urlconfig.url)

        urlconfig.scanport = False
        input_scanport = raw_input('Need scan all ports ?(Y/N) (default N)> ')
        if input_scanport.lower() in ("y", "yes"):
            urlconfig.scanport = True

        urlconfig.threadNum = raw_input(
            'You need start number of thread(Recommendation number is 5) > ')
        urlconfig.threadNum = int(urlconfig.threadNum)

        startTime = time.clock()
        e = Exploit_run(urlconfig.threadNum)
        print '[***] ScanStart Target:%s' % urlconfig.url
        e.load_modules("www", urlconfig.url)
        e.run()
        e.init_spider()
        s = crawler.SpiderMain(urlconfig.url)
        time.sleep(0.5)
        s.craw()
        endTime = time.clock()
        urlconfig.runningTime = endTime - startTime
        e.report()

    except KeyboardInterrupt:
        logger.critical("[***] User Interrupt")
        exit()
    except Exception as info:
        print "[xxx] MainError:", Exception, " :", info
        errinfo = Get_lineNumber_fileName()
        data = e.buildHtml.getData()
        aax = "error:%s urlconfig:%s date:%s" % (errinfo, str(urlconfig), data)
        createIssueForBlog(aax)
        exit()
Exemple #30
0
def main():
    """
    Main function of sqlmap when running from command line.
    """

    try:
        paths.SQLMAP_ROOT_PATH = modulePath()
        setPaths()

        # Store original command line options for possible later restoration
        cmdLineOptions.update(cmdLineParser().__dict__)
        init(cmdLineOptions)

        if hasattr(conf, "ipc_database"):
            # Overwrite system standard output and standard error to write
            # to a temporary I/O database
            sys.stdout = StdDbOut(type_="stdout")
            sys.stderr = StdDbOut(type_="stderr")

        banner()

        dataToStdout("[!] legal disclaimer: %s\n\n" % LEGAL_DISCLAIMER, forceOutput=True)
        dataToStdout("[*] starting at %s\n\n" % time.strftime("%X"), forceOutput=True)

        if conf.profile:
            profile()
        elif conf.smokeTest:
            smokeTest()
        elif conf.liveTest:
            liveTest()
        else:
            start()

    except SqlmapUserQuitException:
        errMsg = "user quit"
        logger.error(errMsg)

    except (SqlmapSilentQuitException, bdb.BdbQuit):
        pass

    except SqlmapBaseException, e:
        e = getUnicode(e)
        logger.critical(e)
        sys.exit(1)
Exemple #31
0
def main():
    try:
        paths.ROOT_PATH = os.path.dirname(
            os.path.dirname(os.path.realpath(__file__)))
        #得到当前py文件所在文件夹上一个文件夹目录赋值给paths.ROOT_PATH,也就是Sepia的根目录
        try:
            os.path.isdir(paths.ROOT_PATH)  #此处判断path.ROOT_PATH得到的路径编码是否正常
        except UnicodeEncodeError:  #出现编码错误就退出
            errMsg = "Your system does not properly handle non-ASCII paths. "
            errMsg += "Please move the project root directory to another location"
            logger.error(errMsg)
            raise SystemExit
        setPaths()  #设置Sepia的文件路径和目录
        banner()  #打印Sepia的logo
        '''
        print "########以下为paths字典#########"
        print paths
        '''
        #存储原始命令行选项,以备恢复
        '''
        print "########以下为原始命令行参数#########"
        print cmdLineParser().__dict__
        '''
        #cmdLineParser().__dict__获得命令行参数数据字典并赋值给cmdLineOptions字典对象
        cmdLineOptions.update(cmdLineParser().__dict__)
        initOptions(cmdLineOptions)
        '''
        print "########以下为cmdLineOption字典#########"
        print cmdLineOptions
        '''

        if IS_WIN:  #如果是Windows使用Colorama插件并初始化
            winowsColorInit()

        loadModule()  #加载poc脚本
        loadPayloads()  #配置扫描模式

        run()  #开始扫描

        systemQuit(EXIT_STATUS.SYSETM_EXIT)

    except ToolkitMissingPrivileges, e:
        logger.error(e)
        systemQuit(EXIT_STATUS.ERROR_EXIT)
Exemple #32
0
def pcsInit(PCS_OPTIONS=None):
    try:
        paths.POCSUITE_ROOT_PATH = modulePath()

        setPaths()

        banner()
        argsDict = PCS_OPTIONS or parseCmdOptions()

        cmdLineOptions.update(argsDict)
        initOptions(cmdLineOptions)
        conf.showTime = True

        dataToStdout("[!] legal disclaimer: %s\n\n" % LEGAL_DISCLAIMER)
        dataToStdout("[*] starting at %s\n\n" % time.strftime("%X"))

        init()
        start()

    except PocsuiteUserQuitException:
        errMsg = "user quit"
        logger.log(CUSTOM_LOGGING.ERROR, errMsg)

    except KeyboardInterrupt:
        print
        errMsg = "user aborted"
        logger.log(CUSTOM_LOGGING.ERROR, errMsg)

    except EOFError:
        print
        errMsg = "exit"
        logger.log(CUSTOM_LOGGING.ERROR, errMsg)

    except SystemExit:
        pass

    except Exception, ex:
        print
        print ex
        #errMsg = unhandledExceptionMessage()
        #logger.log(CUSTOM_LOGGING.WARNING, errMsg)
        excMsg = traceback.format_exc()
        dataToStdout(excMsg)
Exemple #33
0
def main():
    """
    Main function of POC-T when running from command line.
    """
    try:
        paths.ROOT_PATH = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
        try:
            os.path.isdir(paths.ROOT_PATH)
        except UnicodeEncodeError:
            errMsg = "your system does not properly handle non-ASCII paths. "
            errMsg += "Please move the project root directory to another location"
            logger.error(errMsg)
            raise SystemExit
        setPaths()

        cmdLineOptions.update(cmdLineParser().__dict__)
        initOptions(cmdLineOptions)

        if IS_WIN:
            winowsColorInit()
        banner()

        if conf.DEBUG:
            showDebugData()

        loadModule()
        loadPayloads()

        if conf.ENGINE is 't':
            from lib.controller.threads import ThreadsEngine
            ThreadsEngine().run()
        elif conf.ENGINE is 'c':
            from lib.controller.coroutine import CoroutineEngine
            CoroutineEngine().run()

        if conf.OPEN_BROWSER:
            openBrowser()

        systemQuit(EXIT_STATUS.SYSETM_EXIT)

    except ToolkitMissingPrivileges, e:
        logger.error(e)
        systemQuit(EXIT_STATUS.ERROR_EXIT)
Exemple #34
0
def pcsInit(PCS_OPTIONS=None):
    try:
        paths.POCSUITE_ROOT_PATH = modulePath()

        setPaths()

        banner()
        argsDict = PCS_OPTIONS or parseCmdOptions()

        cmdLineOptions.update(argsDict)
        initOptions(cmdLineOptions)
        conf.showTime = True

        dataToStdout("[!] legal disclaimer: %s\n\n" % LEGAL_DISCLAIMER)
        dataToStdout("[*] starting at %s\n\n" % time.strftime("%X"))

        init()
        start()

    except PocsuiteUserQuitException:
        errMsg = "user quit"
        logger.log(CUSTOM_LOGGING.ERROR, errMsg)

    except KeyboardInterrupt:
        print
        errMsg = "user aborted"
        logger.log(CUSTOM_LOGGING.ERROR, errMsg)

    except EOFError:
        print
        errMsg = "exit"
        logger.log(CUSTOM_LOGGING.ERROR, errMsg)

    except SystemExit:
        pass

    except Exception, ex:
        print
        print ex
        #errMsg = unhandledExceptionMessage()
        #logger.log(CUSTOM_LOGGING.WARNING, errMsg)
        excMsg = traceback.format_exc()
        dataToStdout(excMsg)
Exemple #35
0
def main():
    """
    Main function of sqlmap when running from command line.
    """

    try:
        paths.SQLMAP_ROOT_PATH = modulePath()
        setPaths()
        banner()

        dataToStdout("[!] legal disclaimer: %s\n\n" % LEGAL_DISCLAIMER,
                     forceOutput=True)
        dataToStdout("[*] starting at %s\n\n" % time.strftime("%X"),
                     forceOutput=True)

        # Store original command line options for possible later restoration
        cmdLineOptions.update(cmdLineParser().__dict__)

        if cmdLineOptions.xmlRpc:
            server = XMLRPCServer()
            server.serve()
        else:
            init(cmdLineOptions)

            if conf.profile:
                profile()
            elif conf.smokeTest:
                smokeTest()
            elif conf.liveTest:
                liveTest()
            else:
                start()

    except SqlmapUserQuitException:
        errMsg = "user quit"
        logger.error(errMsg)

    except (SqlmapSilentQuitException, bdb.BdbQuit):
        pass

    except exceptionsTuple, e:
        e = getUnicode(e)
        logger.critical(e)
Exemple #36
0
def main():
    """
    Main function of POC-T when running from command line.
    """
    try:
        paths['ROOT_PATH'] = os.path.dirname(
            os.path.dirname(os.path.realpath(__file__)))
        try:
            os.path.isdir(paths['ROOT_PATH'])
        except UnicodeEncodeError:
            errMsg = "your system does not properly handle non-ASCII paths. "
            errMsg += "Please move the project root directory to another location"
            logger.error(errMsg)
            raise SystemExit
        setPaths()

        parseArgs()

        if IS_WIN:
            winowsColorInit()
        banner()

        if conf['DEBUG']:
            showDebugData()

        loadModule()
        loadPayloads()

        if conf['ENGINE'] is 't':
            from lib.controller.threads import ThreadsEngine
            ThreadsEngine().run()
        elif conf['ENGINE'] is 'c':
            from lib.controller.coroutine import CoroutineEngine
            CoroutineEngine().run()

        if conf['OPEN_BROWSER']:
            openBrowser()

        systemQuit(EXIT_STATUS.SYSETM_EXIT)

    except KeyboardInterrupt, e:
        systemQuit(EXIT_STATUS.USER_QUIT)
Exemple #37
0
Fichier : cli.py Projet : 52M/POC-T
def main():
    paths['ROOT_PATH'] = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
    setPaths()
    parse_args()

    print "[*]loading payloads..."
    load_payloads()
    print "total:", th['queue'].qsize()

    if DEBUG:
        debug()
        raw_input('press any key to continue')

    print "[*]testing with " + str(th["THREADS_NUM"]) + " threads..."
    if conf['ENGINE'] is 't':
        from lib.controller.threads import ThreadsEngine
        ThreadsEngine().run()
    elif conf['ENGINE'] is 'c':
        from lib.controller.coroutine import CoroutineEngine
        CoroutineEngine().run()
Exemple #38
0
def main():
    """
    Main function of sqlmap when running from command line.
    """

    try:
        paths.SQLMAP_ROOT_PATH = modulePath()
        setPaths()
        banner()

        dataToStdout("[!] legal disclaimer: %s\n\n" % LEGAL_DISCLAIMER, forceOutput=True)
        dataToStdout("[*] starting at %s\n\n" % time.strftime("%X"), forceOutput=True)

        # Store original command line options for possible later restoration
        cmdLineOptions.update(cmdLineParser().__dict__)

        if cmdLineOptions.restApi:
            restAPIServe()
        else:
            init(cmdLineOptions)

            if conf.profile:
                profile()
            elif conf.smokeTest:
                smokeTest()
            elif conf.liveTest:
                liveTest()
            else:
                start()

    except SqlmapUserQuitException:
        errMsg = "user quit"
        logger.error(errMsg)

    except (SqlmapSilentQuitException, bdb.BdbQuit):
        pass

    except exceptionsTuple, e:
        e = getUnicode(e)
        logger.critical(e)
        sys.exit(1)
Exemple #39
0
def main():
    """
    Main function of POC-T when running from command line.
    """
    try:
        paths['ROOT_PATH'] = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
        try:
            os.path.isdir(paths['ROOT_PATH'])
        except UnicodeEncodeError:
            errMsg = "your system does not properly handle non-ASCII paths. "
            errMsg += "Please move the project root directory to another location"
            logger.error(errMsg)
            raise SystemExit
        setPaths()

        parseArgs()

        if IS_WIN:
            winowsColorInit()
        banner()

        if conf['DEBUG']:
            showDebugData()

        loadModule()
        loadPayloads()

        if conf['ENGINE'] is 't':
            from lib.controller.threads import ThreadsEngine
            ThreadsEngine().run()
        elif conf['ENGINE'] is 'c':
            from lib.controller.coroutine import CoroutineEngine
            CoroutineEngine().run()

        if conf['OPEN_BROWSER']:
            openBrowser()

        systemQuit(EXIT_STATUS.SYSETM_EXIT)

    except KeyboardInterrupt, e:
        systemQuit(EXIT_STATUS.USER_QUIT)
Exemple #40
0
def main():
    """
    Main function of sqlmap when running from command line.
    """

    paths.SQLMAP_ROOT_PATH = modulePath()
    setPaths()

    banner()
    cmdLineOptions = cmdLineParser()

    print "[*] starting at: %s\n" % time.strftime("%X")

    try:
        init(cmdLineOptions)

        if conf.start:
            start()

    except exceptionsTuple, e:
        logger.error(e)
Exemple #41
0
def main():
    """
    Main function of sqlmap when running from command line.
    """

    paths.SQLMAP_ROOT_PATH = modulePath()
    setPaths()

    banner()
    cmdLineOptions = cmdLineParser()

    print "[*] starting at: %s\n" % time.strftime("%X")

    try:
        init(cmdLineOptions)

        if conf.start:
            start()

    except exceptionsTuple, e:
        logger.error(e)
Exemple #42
0
def main():
    #主函数

    checkEnvironment()  #检测环境
    setPaths(modulePath())  #初始化一些绝对路径,参数为根目录

    #参数设置
    args = parser()

    if IS_WIN == 'win32':  #win 初始化
        winowsColorInit()
    #Banner()

    try:
        configFileParser(os.path.join(paths.Ajatar_ROOT_PATH,
                                      "config.conf"))  #配置文件参数处理
        initOption(args)  #初始化参数
        #pluginScan() #插件函数
        webScan()  #扫描函数
    except Exception as e:
        raise e
Exemple #43
0
def main():
    paths['ROOT_PATH'] = os.path.dirname(
        os.path.dirname(os.path.realpath(__file__)))
    setPaths()
    parse_args()

    print "[*]loading payloads..."
    load_payloads()
    print "total:", th['queue'].qsize()

    if DEBUG:
        debug()
        raw_input('press any key to continue')

    print "[*]testing with " + str(th["THREADS_NUM"]) + " threads..."
    if conf['ENGINE'] is 't':
        from lib.controller.threads import ThreadsEngine
        ThreadsEngine().run()
    elif conf['ENGINE'] is 'c':
        from lib.controller.coroutine import CoroutineEngine
        CoroutineEngine().run()
Exemple #44
0
def main():
    """
    main fuction of dirmap 
    """

    # anyway output thr banner information
    banner()

    # set paths of project
    paths.ROOT_PATH = os.getcwd()
    setPaths()

    # received command >> cmdLineOptions
    cmdLineOptions.update(cmdLineParser().__dict__)

    # loader script,target,working way(threads? gevent?),output_file from cmdLineOptions
    # and send it to conf
    initOptions(cmdLineOptions)

    # run!
    run()
Exemple #45
0
def main():
    """
    Main function of POC-T when running from command line.
    """
    try:
        paths['ROOT_PATH'] = os.path.dirname(
            os.path.dirname(os.path.realpath(__file__)))
        try:
            os.path.isdir(paths['ROOT_PATH'])
        except UnicodeEncodeError:
            errMsg = "your system does not properly handle non-ASCII paths. "
            errMsg += "Please move the project root directory to another location"
            logger.error(errMsg)
            raise SystemExit

        setPaths()
        parse_args()

        if IS_WIN:
            win_color_init()
        banner()

        if conf['DEBUG']:
            showDebugData()
        if conf['UPDATE']:
            update()

        load_payloads()

        if conf['ENGINE'] is 't':
            from lib.controller.threads import ThreadsEngine
            ThreadsEngine().run()
        elif conf['ENGINE'] is 'c':
            from lib.controller.coroutine import CoroutineEngine
            CoroutineEngine().run()

        sysquit(0)

    except KeyboardInterrupt, e:
        sysquit(1)
Exemple #46
0
def main():
    """
    Main function of sqlmap when running from command line.
    """

    paths.SQLMAP_ROOT_PATH = modulePath()
    setPaths()
    banner()

    # Store original command line options for possible later restoration
    cmdLineOptions.update(cmdLineParser().__dict__)

    dataToStdout("[*] starting at: %s\n\n" % time.strftime("%X"), forceOutput=True)

    try:
        init(cmdLineOptions)
        if conf.profile:
            profile()
        elif conf.smokeTest:
            smokeTest()
        elif conf.liveTest:
            liveTest()
        else:
            start()

    except sqlmapUserQuitException:
        errMsg = "user quit"
        logger.error(errMsg)
        closeDumper(False, errMsg)

    except sqlmapSilentQuitException:
        closeDumper(False)

    except exceptionsTuple, e:
        e = getUnicode(e)
        logger.critical(e)
        closeDumper(False, e)
Exemple #47
0
def main():
    """
    Main function of sqlmap when running from command line.
    """

    try:
        checkEnvironment()

        setPaths()
        banner()

        # 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()

        conf.showTime = True
        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:
            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

    except SqlmapUserQuitException:
        errMsg = "user quit"
        try:
            logger.error(errMsg)
        except KeyboardInterrupt:
            pass

    except (SqlmapSilentQuitException, bdb.BdbQuit):
        pass

    except SqlmapShellQuitException:
        cmdLineOptions.sqlmapShell = False

    except SqlmapBaseException as ex:
        errMsg = getSafeExString(ex)
        try:
            logger.critical(errMsg)
        except KeyboardInterrupt:
            pass
        raise SystemExit

    except KeyboardInterrupt:
        print

        errMsg = "user aborted"
        try:
            logger.error(errMsg)
        except KeyboardInterrupt:
            pass

    except EOFError:
        print
        errMsg = "exit"

        try:
            logger.error(errMsg)
        except KeyboardInterrupt:
            pass

    except SystemExit:
        pass

    except:
        print
        errMsg = unhandledExceptionMessage()
        excMsg = traceback.format_exc()

        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

            elif "_mkstemp_inner" in excMsg:
                errMsg = "there has been a problem while accessing temporary files"
                logger.error(errMsg)
                raise SystemExit

            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

            elif all(_ in excMsg for _ in ("pymysql", "configparser")):
                errMsg = "wrong initialization of pymsql detected (using Python3 dependencies)"
                logger.error(errMsg)
                raise SystemExit

            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

            elif "valueStack.pop" in excMsg and kb.get("dumpKeyboardInterrupt"):
                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)

            if hasattr(conf, "api"):
                logger.critical("%s\n%s" % (errMsg, excMsg))
            else:
                logger.critical(errMsg)
                kb.stickyLevel = logging.CRITICAL
                dataToStdout(excMsg)
                createGithubIssue(errMsg, excMsg)

        except KeyboardInterrupt:
            pass

    finally:
        kb.threadContinue = False
        kb.threadException = True

        if conf.get("showTime"):
            dataToStdout("\n[*] shutting down at %s\n\n" % time.strftime("%X"), forceOutput=True)

        if kb.get("tempDir"):
            shutil.rmtree(kb.tempDir, ignore_errors=True)

        if conf.get("hashDB"):
            try:
                conf.hashDB.flush(True)
            except KeyboardInterrupt:
                pass

        if cmdLineOptions.get("sqlmapShell"):
            cmdLineOptions.clear()
            conf.clear()
            kb.clear()
            main()

        if hasattr(conf, "api"):
            try:
                conf.database_cursor.disconnect()
            except KeyboardInterrupt:
                pass

        if conf.get("dumper"):
            conf.dumper.flush()

        if threading.activeCount() > 1:
            logger.debug("short delay for thread finalization")
            try:
                time.sleep(0.5)
            except KeyboardInterrupt:
                pass

        # 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)
Exemple #48
0
def main():
    """
    Main function of sqlmap when running from command line.
    """

    try:
        checkEnvironment()
        setPaths(modulePath())
        banner()

        # Store original command line options for possible later restoration
        cmdLineOptions.update(cmdLineParser().__dict__)
        initOptions(cmdLineOptions)

        if conf.get("api"):
            # heavy imports
            from lib.utils.api import StdDbOut
            from lib.utils.api import setRestAPILog

            # 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()

        conf.showTime = True
        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:
            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

    except SqlmapUserQuitException:
        errMsg = "user quit"
        try:
            logger.error(errMsg)
        except KeyboardInterrupt:
            pass

    except (SqlmapSilentQuitException, bdb.BdbQuit):
        pass

    except SqlmapShellQuitException:
        cmdLineOptions.sqlmapShell = False

    except SqlmapBaseException as ex:
        errMsg = getSafeExString(ex)
        try:
            logger.critical(errMsg)
        except KeyboardInterrupt:
            pass
        raise SystemExit

    except KeyboardInterrupt:
        print

        errMsg = "user aborted"
        try:
            logger.error(errMsg)
        except KeyboardInterrupt:
            pass

    except EOFError:
        print
        errMsg = "exit"

        try:
            logger.error(errMsg)
        except KeyboardInterrupt:
            pass

    except SystemExit:
        pass

    except:
        print
        errMsg = unhandledExceptionMessage()
        excMsg = traceback.format_exc()
        valid = checkIntegrity()

        try:
            if valid is False:
                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
                dataToStdout(excMsg)
                raise SystemExit

            elif any(_ in excMsg for _ in ("tamper/", "waf/")):
                logger.critical(errMsg)
                print
                dataToStdout(excMsg)
                raise SystemExit

            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")):
                errMsg = "no space left on output device"
                logger.error(errMsg)
                raise SystemExit

            elif all(_ in excMsg for _ in ("No such file", "_'", "self.get_prog_name()")):
                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

            elif "Read-only file system" in excMsg:
                errMsg = "output device is mounted as read-only"
                logger.error(errMsg)
                raise SystemExit

            elif "OperationalError: disk I/O error" in excMsg:
                errMsg = "I/O error on output device"
                logger.error(errMsg)
                raise SystemExit

            elif "_mkstemp_inner" in excMsg:
                errMsg = "there has been a problem while accessing temporary files"
                logger.error(errMsg)
                raise SystemExit

            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

            elif "'DictObject' object has no attribute '" in excMsg and all(_ in errMsg for _ in ("(fingerprinted)", "(identified)")):
                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

            elif all(_ in excMsg for _ in ("pymysql", "configparser")):
                errMsg = "wrong initialization of pymsql detected (using Python3 dependencies)"
                logger.error(errMsg)
                raise SystemExit

            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

            elif "valueStack.pop" in excMsg and kb.get("dumpKeyboardInterrupt"):
                raise SystemExit

            elif any(_ in excMsg for _ in ("Broken pipe",)):
                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)

            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)

        except KeyboardInterrupt:
            pass

    finally:
        kb.threadContinue = False

        if conf.get("showTime"):
            dataToStdout("\n[*] shutting down at %s\n\n" % time.strftime("%X"), forceOutput=True)

        kb.threadException = True

        if kb.get("tempDir"):
            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)

        if conf.get("hashDB"):
            try:
                conf.hashDB.flush(True)
            except KeyboardInterrupt:
                pass

        if conf.get("harFile"):
            with openFile(conf.harFile, "w+b") as f:
                json.dump(conf.httpCollector.obtain(), fp=f, indent=4, separators=(',', ': '))

        if cmdLineOptions.get("sqlmapShell"):
            cmdLineOptions.clear()
            conf.clear()
            kb.clear()
            main()

        if conf.get("api"):
            try:
                conf.databaseCursor.disconnect()
            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
        finally:
            # Reference: http://stackoverflow.com/questions/1635080/terminate-a-multi-thread-python-program
            if threading.activeCount() > 1:
                os._exit(0)
Exemple #49
0
def main():
    """
    Main function of sqlmap when running from command line.
    """

    try:
        dirtyPatches()
        checkEnvironment()
        setPaths(modulePath())
        banner()

        # Store original command line options for possible later restoration
        cmdLineOptions.update(cmdLineParser().__dict__)
        initOptions(cmdLineOptions)

        if checkPipedInput():
            conf.batch = True

        if conf.get("api"):
            # heavy imports
            from lib.utils.api import StdDbOut
            from lib.utils.api import setRestAPILog

            # 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()

        conf.showTime = True
        dataToStdout("[!] legal disclaimer: %s\n\n" % LEGAL_DISCLAIMER, forceOutput=True)
        dataToStdout("[*] starting @ %s\n\n" % time.strftime("%X /%Y-%m-%d/"), forceOutput=True)

        init()

        if not conf.updateAll:
            # Postponed imports (faster start)
            if conf.smokeTest:
                from lib.core.testing import smokeTest
                os._exitcode = 1 - (smokeTest() or 0)
            elif conf.vulnTest:
                from lib.core.testing import vulnTest
                os._exitcode = 1 - (vulnTest() or 0)
            elif conf.liveTest:
                from lib.core.testing import liveTest
                os._exitcode = 1 - (liveTest() or 0)
            else:
                from lib.controller.controller import start
                if conf.profile and PY2:
                    from lib.core.profiling import profile
                    globals()["start"] = start
                    profile()
                else:
                    try:
                        start()
                    except Exception as ex:
                        os._exitcode = 1

                        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

    except SqlmapUserQuitException:
        if not conf.batch:
            errMsg = "user quit"
            logger.error(errMsg)

    except (SqlmapSilentQuitException, bdb.BdbQuit):
        pass

    except SqlmapShellQuitException:
        cmdLineOptions.sqlmapShell = False

    except SqlmapBaseException as ex:
        errMsg = getSafeExString(ex)
        logger.critical(errMsg)

        raise SystemExit

    except KeyboardInterrupt:
        print()

    except EOFError:
        print()

        errMsg = "exit"
        logger.error(errMsg)

    except SystemExit:
        pass

    except:
        print()
        errMsg = unhandledExceptionMessage()
        excMsg = traceback.format_exc()
        valid = checkIntegrity()

        if valid is False:
            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()
            dataToStdout(excMsg)
            raise SystemExit

        elif any(_ in excMsg for _ in ("tamper/", "waf/")):
            logger.critical(errMsg)
            print()
            dataToStdout(excMsg)
            raise SystemExit

        elif any(_ in excMsg for _ in ("ImportError", "Can't find file for module")):
            errMsg = "invalid runtime environment ('%s')" % excMsg.split("Error: ")[-1].strip()
            logger.critical(errMsg)
            raise SystemExit

        elif any(_ in excMsg for _ in ("MemoryError", "Cannot allocate memory")):
            errMsg = "memory exhaustion detected"
            logger.critical(errMsg)
            raise SystemExit

        elif any(_ in excMsg for _ in ("No space left", "Disk quota exceeded", "Disk full while accessing")):
            errMsg = "no space left on output device"
            logger.critical(errMsg)
            raise SystemExit

        elif any(_ in excMsg for _ in ("The paging file is too small",)):
            errMsg = "no space left for paging file"
            logger.critical(errMsg)
            raise SystemExit

        elif all(_ in excMsg for _ in ("No such file", "_'", "self.get_prog_name()")):
            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.critical(errMsg)
            raise SystemExit

        elif "Read-only file system" in excMsg:
            errMsg = "output device is mounted as read-only"
            logger.critical(errMsg)
            raise SystemExit

        elif "OperationalError: disk I/O error" in excMsg:
            errMsg = "I/O error on output device"
            logger.critical(errMsg)
            raise SystemExit

        elif "Violation of BIDI" in excMsg:
            errMsg = "invalid URL (violation of Bidi IDNA rule - RFC 5893)"
            logger.critical(errMsg)
            raise SystemExit

        elif "_mkstemp_inner" in excMsg:
            errMsg = "there has been a problem while accessing temporary files"
            logger.critical(errMsg)
            raise SystemExit

        elif all(_ in excMsg for _ in ("twophase", "sqlalchemy")):
            errMsg = "please update the 'sqlalchemy' package (>= 1.1.11) "
            errMsg += "(Reference: https://qiita.com/tkprof/items/7d7b2d00df9c5f16fffe)"
            logger.critical(errMsg)
            raise SystemExit

        elif all(_ in excMsg for _ in ("scramble_caching_sha2", "TypeError")):
            errMsg = "please downgrade the 'PyMySQL' package (=< 0.8.1) "
            errMsg += "(Reference: https://github.com/PyMySQL/PyMySQL/issues/700)"
            logger.critical(errMsg)
            raise SystemExit

        elif "must be pinned buffer, not bytearray" in excMsg:
            errMsg = "error occurred at Python interpreter which "
            errMsg += "is fixed in 2.7.x. Please update accordingly "
            errMsg += "(Reference: https://bugs.python.org/issue8104)"
            logger.critical(errMsg)
            raise SystemExit

        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.critical(errMsg)
            raise SystemExit

        elif "'DictObject' object has no attribute '" in excMsg and all(_ in errMsg for _ in ("(fingerprinted)", "(identified)")):
            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.critical(errMsg)
            raise SystemExit

        elif all(_ in excMsg for _ in ("pymysql", "configparser")):
            errMsg = "wrong initialization of pymsql detected (using Python3 dependencies)"
            logger.critical(errMsg)
            raise SystemExit

        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.critical(errMsg)
            raise SystemExit

        elif kb.get("dumpKeyboardInterrupt"):
            raise SystemExit

        elif any(_ in excMsg for _ in ("Broken pipe",)):
            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("\\", '/')
            if "../" in file_:
                file_ = re.sub(r"(\.\./)+", '/', file_)
            else:
                file_ = file_.lstrip('/')
            file_ = re.sub(r"/{2,}", '/', file_)
            excMsg = excMsg.replace(match.group(1), file_)

        errMsg = maskSensitiveData(errMsg)
        excMsg = maskSensitiveData(excMsg)

        if conf.get("api") or not valid:
            logger.critical("%s\n%s" % (errMsg, excMsg))
        else:
            logger.critical(errMsg)
            dataToStdout("%s\n" % setColor(excMsg.strip(), level=logging.CRITICAL))
            createGithubIssue(errMsg, excMsg)

    finally:
        kb.threadContinue = False

        _ = getDaysFromLastUpdate()
        if _ > LAST_UPDATE_NAGGING_DAYS:
            warnMsg = "you haven't updated sqlmap for more than %d days!!!" % _
            logger.warn(warnMsg)

        if conf.get("showTime"):
            dataToStdout("\n[*] ending @ %s\n\n" % time.strftime("%X /%Y-%m-%d/"), forceOutput=True)

        kb.threadException = True

        if kb.get("tempDir"):
            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 filterNone(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)

        if conf.get("hashDB"):
            conf.hashDB.flush(True)

        if conf.get("harFile"):
            with openFile(conf.harFile, "w+b") as f:
                json.dump(conf.httpCollector.obtain(), fp=f, indent=4, separators=(',', ': '))

        if conf.get("api"):
            conf.databaseCursor.disconnect()

        if conf.get("dumper"):
            conf.dumper.flush()

        # short delay for thread finalization
        _ = time.time()
        while threading.activeCount() > 1 and (time.time() - _) > THREAD_FINALIZATION_TIMEOUT:
            time.sleep(0.01)

        if cmdLineOptions.get("sqlmapShell"):
            cmdLineOptions.clear()
            conf.clear()
            kb.clear()
            conf.disableBanner = True
            main()
Exemple #50
0
def main():
    """
    Main function of sqlmap when running from command line.
    """

    try:
        paths.SQLMAP_ROOT_PATH = modulePath()

        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)
            raise SystemExit

        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()

        conf.showTime = True
        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"
        logger.error(errMsg)

    except (SqlmapSilentQuitException, bdb.BdbQuit):
        pass

    except SqlmapShellQuitException:
        cmdLineOptions.sqlmapShell = False

    except SqlmapBaseException as ex:
        errMsg = getSafeExString(ex)
        logger.critical(errMsg)
        raise SystemExit

    except KeyboardInterrupt:
        print
        errMsg = "user aborted"
        logger.error(errMsg)

    except EOFError:
        print
        errMsg = "exit"
        logger.error(errMsg)

    except SystemExit:
        pass

    except:
        print
        errMsg = unhandledExceptionMessage()
        excMsg = traceback.format_exc()

        if any(_ in excMsg for _ in ("No space left", "Disk quota exceeded")):
            errMsg = "no space left on output device"
            logger.error(errMsg)
            raise SystemExit

        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)

    finally:
        if conf.get("showTime"):
            dataToStdout("\n[*] shutting down at %s\n\n" % time.strftime("%X"), forceOutput=True)

        if kb.get("tempDir"):
            shutil.rmtree(kb.tempDir, ignore_errors=True)

        kb.threadContinue = False
        kb.threadException = True

        if conf.get("hashDB"):
            try:
                conf.hashDB.flush(True)
            except KeyboardInterrupt:
                pass

        if cmdLineOptions.get("sqlmapShell"):
            cmdLineOptions.clear()
            conf.clear()
            kb.clear()
            main()

        if hasattr(conf, "api"):
            try:
                conf.database_cursor.disconnect()
            except KeyboardInterrupt:
                pass

        if conf.get("dumper"):
            conf.dumper.flush()

        # 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)
Exemple #51
0
def main():
    """
    Main function of sqlmap when running from command line.
    """

    try:
        paths.SQLMAP_ROOT_PATH = modulePath()
        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()

        conf.showTime = True
        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"
        logger.error(errMsg)

    except (SqlmapSilentQuitException, bdb.BdbQuit):
        pass

    except SqlmapShellQuitException:
        cmdLineOptions.sqlmapShell = False

    except SqlmapBaseException as ex:
        errMsg = getUnicode(ex.message)
        logger.critical(errMsg)
        sys.exit(1)

    except KeyboardInterrupt:
        print
        errMsg = "user aborted"
        logger.error(errMsg)

    except EOFError:
        print
        errMsg = "exit"
        logger.error(errMsg)

    except SystemExit:
        pass

    except:
        print
        errMsg = unhandledExceptionMessage()
        excMsg = traceback.format_exc()

        for match in re.finditer(r'File "(.+?)", line', excMsg):
            file = match.group(1).replace('\\', "/")
            file = file[file.find("sqlmap"):].replace("sqlmap/", "", 1)
            excMsg = excMsg.replace(match.group(1), file)

        logger.critical(errMsg)
        kb.stickyLevel = logging.CRITICAL
        dataToStdout(excMsg)
        createGithubIssue(errMsg, excMsg)

    finally:
        if conf.get("showTime"):
            dataToStdout("\n[*] shutting down at %s\n\n" % time.strftime("%X"), forceOutput=True)

        kb.threadContinue = False
        kb.threadException = True

        if conf.get("hashDB"):
            try:
                conf.hashDB.flush(True)
            except KeyboardInterrupt:
                pass

        if cmdLineOptions.get("sqlmapShell"):
            cmdLineOptions.clear()
            conf.clear()
            kb.clear()
            main()

        if hasattr(conf, "api"):
            try:
                conf.database_cursor.disconnect()
            except KeyboardInterrupt:
                pass

        if conf.get("dumper"):
            conf.dumper.flush()

        # 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)
Exemple #52
0
def main():
    """
    Main function of sqlmap when running from command line.
    http://python.usyiyi.cn/
    http://blog.csdn.net/pipisorry/article/details/39909057/
    python异常类型:http://www.cnblogs.com/zhangpengshou/p/3565087.html
    """

    try:
        checkEnvironment()  # 检查系统环境

        setPaths()          # 设置路径
        banner()            # 打印sqlmap标识信息

        '''
        cmdLineParser()解析命令行参数
        '''
        # Store original command line options for possible later restoration
        cmdLineOptions.update(cmdLineParser().__dict__)
        initOptions(cmdLineOptions)

        if hasattr(conf, "api"):  # hasattr用于确定一个对象是否具有某一个属性
            '''
            语法:
            hasattr(object,name)->bool
            判断object中是否有name属性,返回一个布尔值,如果有name属性,则返回为True,否则返回为False
            '''
            # 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()

        conf.showTime = True
        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()    # sqlmap程序运行时的环境信息
        elif conf.smokeTest:
            smokeTest()  # 冒烟测试
        elif conf.liveTest:
            liveTest()   # 存活测试
        else:
            try:
                start()   # 检测开始的地方,start()函数位于controller.py中
            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

    except SqlmapUserQuitException:
        errMsg = "user quit"
        try:
            logger.error(errMsg)
            '''
            os._exit() 直接退出 Python 解释器,其后的代码都不执行。
            sys.exit() 引发一个 SystemExit 异常,没有捕获这个异常,会直接退出;捕获这个异常可以做一些额外的清理工作。
            exit() 跟 C 语言等其他语言的 exit() 应该是一样的。

            Python退出程序的方式有两种:os._exit(), sys.exit()
            1)os._exit() 直接退出 Python程序,其后的代码也不会继续执行。
            2)sys.exit() 引发一个 SystemExit异常,若没有捕获这个异常,Python解释器会直接退出;捕获这个异常可以做一些额外的清理工作。0为正常退出,其他数值(1-127)为不正常,可抛异常事件供捕获。
            3) exit() 跟 C 语言等其他语言的 exit() 应该是一样的。
            os._exit() 调用 C 语言的 _exit() 函数。
            __builtin__.exit 是一个 Quitter 对象,这个对象的 __call__ 方法会抛出一个 SystemExit 异常。
            一般来说
            os._exit() 用于在线程中退出
            sys.exit() 用于在主线程中退出。
            '''
        except KeyboardInterrupt:  # Ctrl+C被按下
            pass

    except (SqlmapSilentQuitException, bdb.BdbQuit):
        pass

    except SqlmapShellQuitException:
        cmdLineOptions.sqlmapShell = False

    except SqlmapBaseException as ex:
        errMsg = getSafeExString(ex)
        try:
            logger.critical(errMsg)
        except KeyboardInterrupt:  # Ctrl+C被按下
            pass
        raise SystemExit

    except KeyboardInterrupt:  # Ctrl+C被按下
        print

        errMsg = "user aborted"
        try:
            logger.error(errMsg)
        except KeyboardInterrupt:  # Ctrl+C被按下
            pass

    except EOFError:  # 遇到文件末尾引发的异常
        print
        errMsg = "exit"

        try:
            logger.error(errMsg)
        except KeyboardInterrupt:  # Ctrl+C被按下
            pass

    except SystemExit:
        pass

    except:
        print
        errMsg = unhandledExceptionMessage()
        excMsg = traceback.format_exc()

        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

            elif "_mkstemp_inner" in excMsg:
                errMsg = "there has been a problem while accessing temporary files"
                logger.error(errMsg)
                raise SystemExit

            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

            elif all(_ in excMsg for _ in ("pymysql", "configparser")):
                errMsg = "wrong initialization of pymsql detected (using Python3 dependencies)"
                logger.error(errMsg)
                raise SystemExit

            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

            elif "valueStack.pop" in excMsg and kb.get("dumpKeyboardInterrupt"):
                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)

            if hasattr(conf, "api"):
                logger.critical("%s\n%s" % (errMsg, excMsg))
            else:
                logger.critical(errMsg)
                kb.stickyLevel = logging.CRITICAL
                dataToStdout(excMsg)
                createGithubIssue(errMsg, excMsg)

        except KeyboardInterrupt:  # Ctrl+C被按下
            pass

    finally:
        kb.threadContinue = False
        kb.threadException = True

        if conf.get("showTime"):
            dataToStdout("\n[*] shutting down at %s\n\n" % time.strftime("%X"), forceOutput=True)

        '''
        返回所有匹配的文件路径列表。例如,
        >>> import glob
        >>> print glob.glob(r'*.py')
        ['sqlmap.py', 'sqlmapapi.py']
        >>> print glob.glob(r'*.py');
        ['sqlmap.py', 'sqlmapapi.py']
        >>> print glob.glob(r'E:\SQLMap\*.py')
        ['E:\\SQLMap\\sqlmap.py', 'E:\\SQLMap\\sqlmapapi.py']
        >>>
        '''
        if kb.get("tempDir"):  #kb是一个字典
                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)

        if conf.get("hashDB"):   #conf是一个字典
            try:
                conf.hashDB.flush(True)
            except KeyboardInterrupt:  # Ctrl+C被按下
                pass

        if cmdLineOptions.get("sqlmapShell"):
            cmdLineOptions.clear()
            conf.clear()
            kb.clear()
            main()

        if hasattr(conf, "api"):
            try:
                conf.database_cursor.disconnect()
            except KeyboardInterrupt:  # Ctrl+C被按下
                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:  # Ctrl+C被按下
            pass

        # Reference: http://stackoverflow.com/questions/1635080/terminate-a-multi-thread-python-program
        if threading.activeCount() > 1:
            os._exit(0)
Exemple #53
0
def main():
    """
    Main function of sqlmap when running from command line.
    """
    GLOBALSS.init()
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    port = int(sys.argv[1])
    s.bind(("localhost", port))
    print(port)
    s.listen(1)
    while True:
        conn, addr = s.accept()
        GLOBALSS.myList.append(conn)
    	while len(GLOBALSS.myList) > 0:
            try:
                paths.SQLMAP_ROOT_PATH = modulePath()
        
                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)
                    raise SystemExit
        
                setPaths()
                parser_result = cmdLineParser()
                # Store original command line options for possible later restoration
                if parser_result == False:
                    break
                cmdLineOptions.update(parser_result.__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()
        
                conf.showTime = True
                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"
                logger.error(errMsg)
        
            except (SqlmapSilentQuitException, bdb.BdbQuit):
                pass
        
            except SqlmapShellQuitException:
                cmdLineOptions.sqlmapShell = False
        
            except SqlmapBaseException as ex:
                errMsg = getSafeExString(ex)
                logger.critical(errMsg)
                raise SystemExit
        
            except KeyboardInterrupt:
                print
                errMsg = "user aborted"
                logger.error(errMsg)
        
            except EOFError:
                print
                errMsg = "exit"
                logger.error(errMsg)
        
            except SystemExit:
                pass
        
            except:
                print
                errMsg = unhandledExceptionMessage()
                excMsg = traceback.format_exc()
                print(errMsg)
                print(excMsg)
        
                if "No space left" in excMsg:
                    errMsg = "no space left on output device"
                    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)
        
            finally:
                if conf.get("showTime"):
                    dataToStdout("\n[*] shutting down at %s\n\n" % time.strftime("%X"), forceOutput=True)
        
                if kb.get("tempDir"):
                    shutil.rmtree(kb.tempDir, ignore_errors=True)
        
                kb.threadContinue = False
                kb.threadException = True
        
                if conf.get("hashDB"):
                    try:
                        conf.hashDB.flush(True)
                    except KeyboardInterrupt:
                        pass
        
                if cmdLineOptions.get("sqlmapShell"):
                    cmdLineOptions.clear()
                    conf.clear()
                    kb.clear()
                    main()
        
                if hasattr(conf, "api"):
                    try:
                        conf.database_cursor.disconnect()
                    except KeyboardInterrupt:
                        pass
        
                if conf.get("dumper"):
                    conf.dumper.flush()
        
                # 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)
Exemple #54
0
from lib.utils.api import client
from lib.utils.api import server

RESTAPI_SERVER_HOST = "127.0.0.1"
RESTAPI_SERVER_PORT = 8775

if __name__ == "__main__":
    """
    REST-JSON API main function
    """
    # Set default logging level to debug
    logger.setLevel(logging.DEBUG)

    # Initialize path variable
    paths.SQLMAP_ROOT_PATH = modulePath()
    setPaths()

    # Parse command line options
    apiparser = optparse.OptionParser()
    apiparser.add_option("-s", "--server", help="Act as a REST-JSON API server", default=RESTAPI_SERVER_PORT, action="store_true")
    apiparser.add_option("-c", "--client", help="Act as a REST-JSON API client", default=RESTAPI_SERVER_PORT, action="store_true")
    apiparser.add_option("-H", "--host", help="Host of the REST-JSON API server", default=RESTAPI_SERVER_HOST, action="store")
    apiparser.add_option("-p", "--port", help="Port of the the REST-JSON API server", default=RESTAPI_SERVER_PORT, type="int", action="store")
    (args, _) = apiparser.parse_args()

    # Start the client or the server
    if args.server is True:
        server(args.host, args.port)
    elif args.client is True:
        client(args.host, args.port)
    else:
Exemple #55
0
def main():
    """
    Main function of sqlmap when running from command line.
    """

    try:
        paths.SQLMAP_ROOT_PATH = modulePath()
        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()

        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"
        logger.error(errMsg)

    except (SqlmapSilentQuitException, bdb.BdbQuit):
        pass

    except SqlmapBaseException as e:
        e = getUnicode(e)
        logger.critical(e)
        sys.exit(1)

    except KeyboardInterrupt:
        print
        errMsg = "user aborted"
        logger.error(errMsg)

    except EOFError:
        print
        errMsg = "exit"
        logger.error(errMsg)

    except SystemExit:
        pass

    except:
        print
        errMsg = unhandledExceptionMessage()
        logger.critical(errMsg)
        traceback.print_exc()

    finally:
        dataToStdout("\n[*] shutting down at %s\n\n" % time.strftime("%X"), forceOutput=True)

        kb.threadContinue = False
        kb.threadException = True

        if conf.get("hashDB"):
            try:
                conf.hashDB.flush(True)
            except KeyboardInterrupt:
                pass

        if hasattr(conf, "api"):
            try:
                conf.database_cursor.disconnect()
            except KeyboardInterrupt:
                pass

        # 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)
Exemple #56
0
def main():
    """
    Main function of injection when running from command line.
    """

    try:
        # paths.SQLMAP_ROOT_PATH = modulePath()#Get current path of sqlmap.py
        paths.INJECTION_ROOT_PATH= modulePath()#Get current path of sqlmap.py
        setPaths()

        # Store original command line options for possible later restoration
        cmdLineOptions.update(cmdLineParser().__dict__)

        """
        ###Get the options from cmdline command
        print "-----------------------------------------------------------------"
        print "---------------------  cmdLineOptions ---------------------------"
        print cmdLineOptions
        print "----------------------------------------------------------------"
        for i in cmdLineOptions.keys() :
            print i,"---------",cmdLineOptions[i]
        print "-----------------------------------------------------------------"
        """

        initOptions(cmdLineOptions)
        # print "----------------------------------"
        # print kb.chars

        banner()
        #Show the banner of the software

        conf.showTime = True
        dataToStdout("[!] legal disclaimer: %s\n\n" % LEGAL_DISCLAIMER, forceOutput=True)
        dataToStdout("[*] starting at %s\n\n" % time.strftime("%X"), forceOutput=True)

        init()
        #According to the input parameters, set the configure of the software

        start()

    except SqlmapUserQuitException:
        errMsg = "user quit"
        logger.error(errMsg)

    except (SqlmapSilentQuitException, bdb.BdbQuit):
        pass

    except SqlmapShellQuitException:
        cmdLineOptions.sqlmapShell = False

    except SqlmapBaseException as ex:
        errMsg = getUnicode(ex.message)
        logger.critical(errMsg)
        sys.exit(1)

    except KeyboardInterrupt:
        print
        errMsg = "user aborted"
        logger.error(errMsg)

    except EOFError:
        print
        errMsg = "exit"
        logger.error(errMsg)

    except SystemExit:
        pass

    except:
        print
        errMsg = unhandledExceptionMessage()
        excMsg = traceback.format_exc()

        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)

    finally:
        if conf.get("showTime"):
            dataToStdout("\n[*] shutting down at %s\n\n" % time.strftime("%X"), forceOutput=True)

        kb.threadContinue = False
        kb.threadException = True

        # 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)