Exemplo n.º 1
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()
Exemplo n.º 2
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()
Exemplo n.º 3
0
def __setVerbosity():
    """
    This function set the verbosity of sqlmap output messages.
    """

    if conf.verbose == None:
        conf.verbose = 1

    conf.verbose = int(conf.verbose)

    if conf.verbose == 1:
        logger.setLevel(logging.INFO)
    elif conf.verbose > 1 and conf.eta:
        conf.verbose = 1
        logger.setLevel(logging.INFO)
    elif conf.verbose == 2:
        logger.setLevel(logging.DEBUG)
    elif conf.verbose == 3:
        logger.setLevel(9)
    elif conf.verbose >= 4:
        logger.setLevel(8)
Exemplo n.º 4
0
def restAPIServe():
    # Increase default logging level to debug for RESTful API
    logger.setLevel(logging.DEBUG)

    # Enforce batch mode and disable coloring for RESTful API
    cmdLineOptions.batch = True
    cmdLineOptions.disableColoring = True

    # Setup RESTful API
    restAPISetup(port=cmdLineOptions.restApiPort or RESTAPI_SERVER_PORT)

    # Wrap logger stdout onto a custom file descriptor (LOGGER_OUTPUT)
    def emit(self, record):
        message = stdoutencode(FORMATTER.format(record))
        print >>LOGGER_OUTPUT, message.strip('\r')
    LOGGER_HANDLER.emit = types.MethodType(emit, LOGGER_HANDLER, type(LOGGER_HANDLER))

    # Wrap standard output onto a custom file descriptor
    sys.stdout = StringIO.StringIO()
    #sys.stderr = StringIO.StringIO()

    # Run RESTful API
    restAPIRun(port=cmdLineOptions.restApiPort or RESTAPI_SERVER_PORT)
Exemplo n.º 5
0
def set_verbosity():
	"""
	This function set the verbosity of apkscan output messages.
	"""

	if conf.verbose is None:
		conf.verbose = 1

	conf.verbose = int(conf.verbose)

	if conf.verbose == 0:
		logger.setLevel(logging.ERROR)
	elif conf.verbose == 1:
		logger.setLevel(logging.INFO)
	elif conf.verbose == 2:
		logger.setLevel(logging.DEBUG)
	elif conf.verbose == 3:
		logger.setLevel(CUSTOM_LOGGING.PAYLOAD)
	elif conf.verbose == 4:
		logger.setLevel(CUSTOM_LOGGING.TRAFFIC_OUT)
	elif conf.verbose >= 5:
		logger.setLevel(CUSTOM_LOGGING.TRAFFIC_IN)
Exemplo n.º 6
0
from sqlmap import modulePath
from lib.core.common import setPaths
from lib.core.data import paths
from lib.core.data import logger
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:
Exemplo n.º 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="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()
Exemplo n.º 8
0
def smokeTest():
    """
    Runs the basic smoke testing of a program
    """

    unisonRandom()

    content = open(paths.ERRORS_XML, "r").read()
    for regex in re.findall(r'<error regexp="(.+?)"/>', content):
        try:
            re.compile(regex)
        except re.error:
            errMsg = "smoke test failed at compiling '%s'" % regex
            logger.error(errMsg)
            return False

    retVal = True
    count, length = 0, 0

    for root, _, files in os.walk(paths.SQLMAP_ROOT_PATH):
        if any(_ in root for _ in ("thirdparty", "extra")):
            continue

        for filename in files:
            if os.path.splitext(filename)[1].lower(
            ) == ".py" and filename != "__init__.py":
                length += 1

    for root, _, files in os.walk(paths.SQLMAP_ROOT_PATH):
        if any(_ in root for _ in ("thirdparty", "extra")):
            continue

        for filename in files:
            if os.path.splitext(filename)[1].lower(
            ) == ".py" and filename not in ("__init__.py", "gui.py"):
                path = os.path.join(root, os.path.splitext(filename)[0])
                path = path.replace(paths.SQLMAP_ROOT_PATH, '.')
                path = path.replace(os.sep, '.').lstrip('.')
                try:
                    __import__(path)
                    module = sys.modules[path]
                except Exception as ex:
                    retVal = False
                    dataToStdout("\r")
                    errMsg = "smoke test failed at importing module '%s' (%s):\n%s" % (
                        path, os.path.join(root, filename), ex)
                    logger.error(errMsg)
                else:
                    logger.setLevel(logging.CRITICAL)
                    kb.smokeMode = True

                    (failure_count, _) = doctest.testmod(module)

                    kb.smokeMode = False
                    logger.setLevel(logging.INFO)

                    if failure_count > 0:
                        retVal = False

                count += 1
                status = '%d/%d (%d%%) ' % (count, length,
                                            round(100.0 * count / length))
                dataToStdout("\r[%s] [INFO] complete: %s" %
                             (time.strftime("%X"), status))

    def _(node):
        for __ in dir(node):
            if not __.startswith('_'):
                candidate = getattr(node, __)
                if isinstance(candidate, str):
                    if '\\' in candidate:
                        try:
                            re.compile(candidate)
                        except:
                            errMsg = "smoke test failed at compiling '%s'" % candidate
                            logger.error(errMsg)
                            raise
                else:
                    _(candidate)

    for dbms in queries:
        try:
            _(queries[dbms])
        except:
            retVal = False

    clearConsoleLine()
    if retVal:
        logger.info("smoke test final result: PASSED")
    else:
        logger.error("smoke test final result: FAILED")

    return retVal
Exemplo n.º 9
0
def fileExists(pathFile):
    retVal = []

    message = "which common files file do you want to use?\n"
    message += "[1] default '%s' (press Enter)\n" % pathFile
    message += "[2] custom"
    choice = readInput(message, default='1')

    if choice == '2':
        message = "what's the custom common files file location?\n"
        pathFile = readInput(message) or pathFile

    infoMsg = "checking files existence using items from '%s'" % pathFile
    logger.info(infoMsg)

    paths = getFileItems(pathFile, unique=True)

    kb.bruteMode = True

    try:
        conf.dbmsHandler.readFile(randomStr())
    except SqlmapNoneDataException:
        pass
    except:
        kb.bruteMode = False
        raise

    threadData = getCurrentThreadData()
    threadData.shared.count = 0
    threadData.shared.limit = len(paths)
    threadData.shared.files = []

    def fileExistsThread():
        threadData = getCurrentThreadData()

        while kb.threadContinue:
            kb.locks.count.acquire()
            if threadData.shared.count < threadData.shared.limit:
                path = ntToPosixSlashes(paths[threadData.shared.count])
                threadData.shared.count += 1
                kb.locks.count.release()
            else:
                kb.locks.count.release()
                break

            try:
                result = unArrayizeValue(conf.dbmsHandler.readFile(path))
            except SqlmapNoneDataException:
                result = None

            kb.locks.io.acquire()

            if not isNoneValue(result):
                threadData.shared.files.append(result)

                if not conf.api:
                    clearConsoleLine(True)
                    infoMsg = "[%s] [INFO] retrieved: '%s'\n" % (
                        time.strftime("%X"), path)
                    dataToStdout(infoMsg, True)

            if conf.verbose in (1, 2):
                status = '%d/%d items (%d%%)' % (
                    threadData.shared.count, threadData.shared.limit,
                    round(100.0 * threadData.shared.count /
                          threadData.shared.limit))
                dataToStdout(
                    "\r[%s] [INFO] tried %s" % (time.strftime("%X"), status),
                    True)

            kb.locks.io.release()

    try:
        pushValue(logger.getEffectiveLevel())
        logger.setLevel(logging.CRITICAL)

        runThreads(conf.threads, fileExistsThread, threadChoice=True)
    except KeyboardInterrupt:
        warnMsg = "user aborted during file existence "
        warnMsg += "check. ramusql will display partial output"
        logger.warn(warnMsg)
    finally:
        kb.bruteMode = False
        logger.setLevel(popValue())

    clearConsoleLine(True)
    dataToStdout("\n")

    if not threadData.shared.files:
        warnMsg = "no file(s) found"
        logger.warn(warnMsg)
    else:
        retVal = threadData.shared.files

    return retVal
Exemplo n.º 10
0
def smokeTest():
    """
    Runs the basic smoke testing of a program
    """

    dirtyPatchRandom()

    retVal = True
    count, length = 0, 0

    for root, _, files in os.walk(paths.SQLMAP_ROOT_PATH):
        if any(_ in root for _ in ("thirdparty", "extra")):
            continue

        for filename in files:
            if os.path.splitext(filename)[1].lower(
            ) == ".py" and filename != "__init__.py":
                length += 1

    for root, _, files in os.walk(paths.SQLMAP_ROOT_PATH):
        if any(_ in root for _ in ("thirdparty", "extra")):
            continue

        for filename in files:
            if os.path.splitext(filename)[1].lower(
            ) == ".py" and filename != "__init__.py":
                path = os.path.join(root, os.path.splitext(filename)[0])
                path = path.replace(paths.SQLMAP_ROOT_PATH, '.')
                path = path.replace(os.sep, '.').lstrip('.')
                try:
                    __import__(path)
                    module = sys.modules[path]
                except Exception as ex:
                    retVal = False
                    dataToStdout("\r")
                    errMsg = "smoke test failed at importing module '%s' (%s):\n%s" % (
                        path, os.path.join(root, filename), ex)
                    logger.error(errMsg)
                else:
                    logger.setLevel(logging.CRITICAL)
                    kb.smokeMode = True

                    (failure_count, test_count) = doctest.testmod(module)

                    kb.smokeMode = False
                    logger.setLevel(logging.INFO)

                    if failure_count > 0:
                        retVal = False

                count += 1
                status = '%d/%d (%d%%) ' % (count, length,
                                            round(100.0 * count / length))
                dataToStdout("\r[%s] [INFO] complete: %s" %
                             (time.strftime("%X"), status))

    clearConsoleLine()
    if retVal:
        logger.info("smoke test final result: PASSED")
    else:
        logger.error("smoke test final result: FAILED")

    return retVal
Exemplo n.º 11
0
from sqlmap import modulePath
from lib.core.common import setPaths
from lib.core.data import paths
from lib.core.data import logger
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",
Exemplo n.º 12
0
def fileExists(pathFile):
    retVal = []
    paths = getFileItems(pathFile, unique=True)

    kb.bruteMode = True

    try:
        conf.dbmsHandler.readFile(randomStr())
    except SqlmapNoneDataException:
        pass
    except:
        kb.bruteMode = False
        raise

    threadData = getCurrentThreadData()
    threadData.shared.count = 0
    threadData.shared.limit = len(paths)
    threadData.shared.value = []

    def fileExistsThread():
        threadData = getCurrentThreadData()

        while kb.threadContinue:
            kb.locks.count.acquire()
            if threadData.shared.count < threadData.shared.limit:
                path = paths[threadData.shared.count]
                threadData.shared.count += 1
                kb.locks.count.release()
            else:
                kb.locks.count.release()
                break

            try:
                result = unArrayizeValue(conf.dbmsHandler.readFile(path))
            except SqlmapNoneDataException:
                result = None

            kb.locks.io.acquire()

            if not isNoneValue(result):
                threadData.shared.value.append(result)

                if conf.verbose in (1, 2) and not conf.api:
                    clearConsoleLine(True)
                    infoMsg = "[%s] [INFO] retrieved: '%s'\n" % (
                        time.strftime("%X"), path)
                    dataToStdout(infoMsg, True)

            if conf.verbose in (1, 2):
                status = '%d/%d items (%d%%)' % (
                    threadData.shared.count, threadData.shared.limit,
                    round(100.0 * threadData.shared.count /
                          threadData.shared.limit))
                dataToStdout(
                    "\r[%s] [INFO] tried %s" % (time.strftime("%X"), status),
                    True)

            kb.locks.io.release()

    try:
        pushValue(logger.getEffectiveLevel())
        logger.setLevel(logging.CRITICAL)

        runThreads(conf.threads, fileExistsThread, threadChoice=True)
    except KeyboardInterrupt:
        warnMsg = "user aborted during file existence "
        warnMsg += "check. sqlmap will display partial output"
        logger.warn(warnMsg)
    finally:
        kb.bruteMode = False
        logger.setLevel(popValue())

    clearConsoleLine(True)
    dataToStdout("\n")

    if not threadData.shared.value:
        warnMsg = "no file(s) found"
        logger.warn(warnMsg)
    else:
        retVal = threadData.shared.value

    return retVal