Example #1
0
def scan_data(taskid):
    """
    Retrieve the data of a scan
    """
    json_data_message = list()
    json_errors_message = list()

    if taskid not in DataStore.tasks:
        logger.warning("[%s] Invalid task ID provided to scan_data()" % taskid)
        return jsonize({"success": False, "message": "Invalid task ID"})

    # Read all data from the IPC database for the taskid
    for status, content_type, value in DataStore.current_db.execute(
            "SELECT status, content_type, value FROM data WHERE taskid = ? ORDER BY id ASC",
            (taskid,)):
        json_data_message.append(
            {"status": status, "type": content_type, "value": dejsonize(value)})

    # Read all error messages from the IPC database
    for error in DataStore.current_db.execute(
            "SELECT error FROM errors WHERE taskid = ? ORDER BY id ASC",
            (taskid,)):
        json_errors_message.append(error)

    logger.debug("[%s] Retrieved scan data and error messages" % taskid)
    return jsonize({"success": True, "data": json_data_message, "error": json_errors_message})
Example #2
0
    def write(self, value, status=CONTENT_STATUS.IN_PROGRESS, content_type=None):
        if self.messagetype == "stdout":
            if content_type is None:
                content_type = 99

            output = conf.database_cursor.execute("SELECT id, value FROM data WHERE taskid = ? AND status = ? AND content_type = ? LIMIT 0,1",
                                                  (self.taskid, status, content_type))

            if status == CONTENT_STATUS.IN_PROGRESS:
                # Ignore all non-relevant messages
                if kb.partRun is None:
                    return

                if len(output) == 0:
                    conf.database_cursor.execute("INSERT INTO data VALUES(NULL, ?, ?, ?, ?)",
                                                 (self.taskid, status, content_type, jsonize(value)))
                else:
                    new_value = "%s%s" % (dejsonize(output[0][1]), value)
                    conf.database_cursor.execute("UPDATE data SET value = ? WHERE id = ?",
                                                 (jsonize(new_value), output[0][0]))
            else:
                if len(output) > 0:
                    conf.database_cursor.execute("DELETE FROM data WHERE taskid = ? AND status = %s AND content_type = ?" % CONTENT_STATUS.IN_PROGRESS,
                                                 (self.taskid, content_type))

                conf.database_cursor.execute("INSERT INTO data VALUES(NULL, ?, ?, ?, ?)",
                                             (self.taskid, status, content_type, jsonize(value)))
        else:
            conf.database_cursor.execute("INSERT INTO errors VALUES(NULL, ?, ?)",
                                         (self.taskid, str(value) if value else ""))
Example #3
0
    def write(self, value, status=CONTENT_STATUS.IN_PROGRESS, content_type=None):
        if self.messagetype == "stdout":
            if content_type is None:
                if kb.partRun is not None:
                    content_type = PART_RUN_CONTENT_TYPES.get(kb.partRun)
                else:
                    # Ignore all non-relevant messages
                    return

            output = conf.database_cursor.execute("SELECT id, status, value FROM data WHERE taskid = ? AND content_type = ?",
                                                  (self.taskid, content_type))

            #print >>sys.__stdout__, "output: %s\nvalue: %s\nstatus: %d\ncontent_type: %d\nkb.partRun: %s\n--------------" % (output, value, status, content_type, kb.partRun)

            # Delete partial output from IPC database if we have got a complete output
            if status == CONTENT_STATUS.COMPLETE:
                if len(output) > 0:
                    for index in xrange(0, len(output)):
                        conf.database_cursor.execute("DELETE FROM data WHERE id = ?", (output[index][0],))

                conf.database_cursor.execute("INSERT INTO data VALUES(NULL, ?, ?, ?, ?)", (self.taskid, status, content_type, jsonize(value)))
                if kb.partRun:
                    kb.partRun = None

            elif status == CONTENT_STATUS.IN_PROGRESS:
                if len(output) == 0:
                    conf.database_cursor.execute("INSERT INTO data VALUES(NULL, ?, ?, ?, ?)",
                                                 (self.taskid, status, content_type, jsonize(value)))
                else:
                    new_value = "%s%s" % (dejsonize(output[0][2]), value)
                    conf.database_cursor.execute("UPDATE data SET value = ? WHERE id = ?",
                                                 (jsonize(new_value), output[0][0]))
        else:
            conf.database_cursor.execute("INSERT INTO errors VALUES(NULL, ?, ?)",
                                         (self.taskid, str(value) if value else ""))
Example #4
0
def scan_log_limited(taskid, start, end):
    """
    Retrieve a subset of log messages
    """
    json_log_messages = list()

    if taskid not in DataStore.tasks:
        logger.warning("[%s] Invalid task ID provided to scan_log_limited()" % taskid)
        return jsonize({"success": False, "message": "Invalid task ID"})

    if not start.isdigit() or not end.isdigit() or end < start:
        logger.warning("[%s] Invalid start or end value provided to scan_log_limited()" % taskid)
        return jsonize({"success": False, "message": "Invalid start or end value, must be digits"})

    start = max(1, int(start))
    end = max(1, int(end))

    # Read a subset of log messages from the IPC database
    for time_, level, message in DataStore.current_db.execute(
            ("SELECT time, level, message FROM logs WHERE "
             "taskid = ? AND id >= ? AND id <= ? ORDER BY id ASC"),
            (taskid, start, end)):
        json_log_messages.append({"time": time_, "level": level, "message": message})

    logger.debug("[%s] Retrieved scan log messages subset" % taskid)
    return jsonize({"success": True, "log": json_log_messages})
Example #5
0
def option_list(taskid):
    """
    List options for a certain task ID
    """
    if taskid not in DataStore.tasks:
        logger.warning("[%s] Invalid task ID provided to option_list()" % taskid)
        return jsonize({"success": False, "message": "Invalid task ID"})

    logger.debug("[%s] Listed task options" % taskid)
    return jsonize({"success": True, "options": DataStore.tasks[taskid].get_options()})
Example #6
0
def task_list(taskid):
    """
    List task pull
    """
    if is_admin(taskid):
        logger.debug("[%s] Listed task pool" % taskid)
        tasks = list(DataStore.tasks)
        return jsonize({"success": True, "tasks": tasks, "tasks_num": len(tasks)})
    else:
        logger.warning("[%s] Unauthorized call to task_list()" % taskid)
        return jsonize({"success": False, "message": "Unauthorized"})
Example #7
0
def task_flush(taskid):
    """
    Flush task spool (delete all tasks)
    """
    if is_admin(taskid):
        DataStore.tasks = dict()
        logger.debug("[%s] Flushed task pool" % taskid)
        return jsonize({"success": True})
    else:
        logger.warning("[%s] Unauthorized call to task_flush()" % taskid)
        return jsonize({"success": False, "message": "Unauthorized"})
Example #8
0
def task_delete(taskid):
    """
    Delete own task ID
    """
    if taskid in DataStore.tasks:
        DataStore.tasks.pop(taskid)

        logger.debug("[%s] Deleted task" % taskid)
        return jsonize({"success": True})
    else:
        logger.warning("[%s] Invalid task ID provided to task_delete()" % taskid)
        return jsonize({"success": False, "message": "Invalid task ID"})
Example #9
0
def scan_kill(taskid):
    """
    Kill a scan
    """
    if taskid not in DataStore.tasks:
        logger.warning("[%s] Invalid task ID provided to scan_kill()" % taskid)
        return jsonize({"success": False, "message": "Invalid task ID"})

    DataStore.tasks[taskid].engine_kill()

    logger.debug("[%s] Killed scan" % taskid)
    return jsonize({"success": True})
Example #10
0
def option_set(taskid):
    """
    Set an option (command line switch) for a certain task ID
    """
    if taskid not in DataStore.tasks:
        logger.warning("[%s] Invalid task ID provided to option_set()" % taskid)
        return jsonize({"success": False, "message": "Invalid task ID"})

    for option, value in request.json.items():
        DataStore.tasks[taskid].set_option(option, value)

    logger.debug("[%s] Requested to set options" % taskid)
    return jsonize({"success": True})
Example #11
0
def option_get(taskid):
    """
    Get the value of an option (command line switch) for a certain task ID
    """
    if taskid not in tasks:
        abort(500, "Invalid task ID")

    option = request.json.get("option", "")

    if option in tasks[taskid]:
        return jsonize({option: tasks[taskid].get_option(option)})
    else:
        return jsonize({option: None})
Example #12
0
def task_delete(taskid):
    """
    Delete an existing task
    """
    if taskid in DataStore.tasks:
        DataStore.tasks.pop(taskid)

        logger.debug("(%s) Deleted task" % taskid)
        return jsonize({"success": True})
    else:
        response.status = 404
        logger.warning("[%s] Non-existing task ID provided to task_delete()" % taskid)
        return jsonize({"success": False, "message": "Non-existing task ID"})
Example #13
0
def scan_kill(taskid):
    """
    Kill a scan
    """

    if (taskid not in DataStore.tasks or DataStore.tasks[taskid].engine_process() is None or DataStore.tasks[taskid].engine_has_terminated()):
        logger.warning("[%s] Invalid task ID provided to scan_kill()" % taskid)
        return jsonize({"success": False, "message": "Invalid task ID"})

    DataStore.tasks[taskid].engine_kill()

    logger.debug("(%s) Killed scan" % taskid)
    return jsonize({"success": True})
Example #14
0
def scan_status(taskid):
    """
    Returns status of a scan
    """
    if taskid not in DataStore.tasks:
        logger.warning("[%s] Invalid task ID provided to scan_status()" % taskid)
        return jsonize({"success": False, "message": "Invalid task ID"})

    if DataStore.tasks[taskid].engine_process() is None:
        status = "not running"
    else:
        status = "terminated" if DataStore.tasks[taskid].engine_has_terminated() is True else "running"

    logger.debug("[%s] Retrieved scan status" % taskid)
    return jsonize({"success": True, "status": status, "returncode": DataStore.tasks[taskid].engine_get_returncode()})
Example #15
0
def option_get(taskid):
    """
    Get the value of an option (command line switch) for a certain task ID
    """
    if taskid not in DataStore.tasks:
        logger.warning("[%s] Invalid task ID provided to option_get()" % taskid)
        return jsonize({"success": False, "message": "Invalid task ID"})

    option = request.json.get("option", "")

    if option in DataStore.tasks[taskid].options:
        logger.debug("[%s] Retrieved value for option %s" % (taskid, option))
        return jsonize({"success": True, option: DataStore.tasks[taskid].get_option(option)})
    else:
        logger.debug("[%s] Requested value for unknown option %s" % (taskid, option))
        return jsonize({"success": False, "message": "Unknown option", option: "not set"})
Example #16
0
def scan_log(taskid):
    """
    Retrieve the log messages
    """
    json_log_messages = list()

    if taskid not in DataStore.tasks:
        logger.warning("[%s] Invalid task ID provided to scan_log()" % taskid)
        return jsonize({"success": False, "message": "Invalid task ID"})

    # Read all log messages from the IPC database
    for time_, level, message in DataStore.current_db.execute("SELECT time, level, message FROM logs WHERE taskid = ? ORDER BY id ASC", (taskid,)):
        json_log_messages.append({"time": time_, "level": level, "message": message})

    logger.debug("[%s] Retrieved scan log messages" % taskid)
    return jsonize({"success": True, "log": json_log_messages})
Example #17
0
def scan_log_limited(taskid, start, end):
    """
    Retrieve a subset of log messages
    """
    global procs

    json_log_messages = {}

    if taskid not in tasks:
        abort(500, "Invalid task ID")

    # Temporary "protection" against SQL injection FTW ;)
    if not start.isdigit() or not end.isdigit() or end <= start:
        abort(500, "Invalid start or end value, must be digits")

    start = max(1, int(start))
    end = max(1, int(end))

    # Read a subset of log messages from the temporary I/O database
    procs[taskid].ipc_database_cursor.execute("SELECT id, time, level, message FROM logs WHERE id >= %d AND id <= %d" % (start, end))
    db_log_messages = procs[taskid].ipc_database_cursor.fetchall()

    for (id_, time_, level, message) in db_log_messages:
        json_log_messages[id_] = {"time": time_, "level": level, "message": message}

    return jsonize({"log": json_log_messages})
Example #18
0
def scan_output(taskid):
    """
    Read the standard output of sqlmap core execution
    """
    global procs
    global tasks

    json_stdout_message = []
    json_stderr_message = []

    if taskid not in tasks:
        abort(500, "Invalid task ID")

    # Read all stdout messages from the temporary I/O database
    procs[taskid].ipc_database_cursor.execute("SELECT message FROM stdout")
    db_stdout_messages = procs[taskid].ipc_database_cursor.fetchall()

    for message in db_stdout_messages:
        json_stdout_message.append(message)

    # Read all stderr messages from the temporary I/O database
    procs[taskid].ipc_database_cursor.execute("SELECT message FROM stderr")
    db_stderr_messages = procs[taskid].ipc_database_cursor.fetchall()

    for message in db_stderr_messages:
        json_stderr_message.append(message)

    return jsonize({"stdout": json_stdout_message, "stderr": json_stderr_message})
Example #19
0
def task_new():
    """
    Create new task ID
    """
    global procs
    global tasks

    taskid = hexencode(os.urandom(16))
    tasks[taskid] = init_options()
    procs[taskid] = AttribDict()

    _, ipc_database_filepath = tempfile.mkstemp(prefix="sqlmapipc-", text=False)

    # Initiate the temporary database for asynchronous I/O with the
    # sqlmap engine
    procs[taskid].ipc_database_connection = sqlite3.connect(ipc_database_filepath, timeout=1, isolation_level=None)
    procs[taskid].ipc_database_cursor = procs[taskid].ipc_database_connection.cursor()
    procs[taskid].ipc_database_cursor.execute("CREATE TABLE logs(id INTEGER PRIMARY KEY AUTOINCREMENT, time TEXT, level TEXT, message TEXT)")
    procs[taskid].ipc_database_cursor.execute("CREATE TABLE stdout(id INTEGER PRIMARY KEY AUTOINCREMENT, time TEXT, message TEXT)")
    procs[taskid].ipc_database_cursor.execute("CREATE TABLE stderr(id INTEGER PRIMARY KEY AUTOINCREMENT, time TEXT, message TEXT)")

    # Set the temporary database to use for asynchronous I/O communication
    tasks[taskid].ipc_database = ipc_database_filepath

    return jsonize({"taskid": taskid})
Example #20
0
File: api.py Project: charl1/sqlmap
def scan_start(taskid):
    """
    Launch a scan
    """
    global tasks
    global procs
    global pipes

    if taskid not in tasks:
        abort(500, "Invalid task ID")

    # Initialize sqlmap engine's options with user's provided options
    # within the JSON request
    for key, value in request.json.items():
        tasks[taskid][key] = value

    # Overwrite output directory (oDir) value to a temporary directory
    tasks[taskid].oDir = tempfile.mkdtemp(prefix="sqlmap-")

    # Launch sqlmap engine in a separate thread
    logger.debug("starting a scan for task ID %s" % taskid)

    pipes[taskid] = os.pipe()

    # Provide sqlmap engine with the writable pipe for logging
    tasks[taskid]["fdLog"] = pipes[taskid][1]

    # Launch sqlmap engine
    procs[taskid] = execute("python sqlmap.py --pickled-options %s" % base64pickle(tasks[taskid]), shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=False)

    return jsonize({"success": True})
Example #21
0
def option_list(taskid):
    """
    List options for a certain task ID
    """
    if taskid not in tasks:
        abort(500, "Invalid task ID")

    return jsonize({"options": tasks[taskid].get_options()})
Example #22
0
def scan_log(taskid):
    """
    Retrieve the log messages
    """

    json_log_messages = list()

    if taskid not in DataStore.tasks:
        logger.warning("[%s] Invalid task ID provided to scan_log()" % taskid)
        return jsonize({"success": False, "message": "Invalid task ID"})

    # Read all log messages from the IPC database
    for time_, level, message in DataStore.current_db.execute("SELECT time, level, message FROM logs WHERE taskid = ? ORDER BY id ASC", (taskid,)):
        json_log_messages.append({"time": time_, "level": level, "message": message})

    logger.debug("(%s) Retrieved scan log messages" % taskid)
    return jsonize({"success": True, "log": json_log_messages})
Example #23
0
def scan_start(taskid):
    """
    Launch a scan
    """
    if taskid not in DataStore.tasks:
        logger.warning("[%s] Invalid task ID provided to scan_start()" % taskid)
        return jsonize({"success": False, "message": "Invalid task ID"})

    # Initialize sqlmap engine's options with user's provided options, if any
    for option, value in request.json.items():
        DataStore.tasks[taskid].set_option(option, value)

    # Launch sqlmap engine in a separate process
    DataStore.tasks[taskid].engine_start()

    logger.debug("[%s] Started scan" % taskid)
    return jsonize({"success": True, "engineid": DataStore.tasks[taskid].engine_get_id()})
Example #24
0
    def write(self,
              value,
              status=CONTENT_STATUS.IN_PROGRESS,
              content_type=None):
        if self.messagetype == "stdout":
            if content_type is None:
                if kb.partRun is not None:
                    content_type = PART_RUN_CONTENT_TYPES.get(kb.partRun)
                else:
                    # Ignore all non-relevant messages
                    return

            output = conf.database_cursor.execute(
                "SELECT id, status, value FROM data WHERE taskid = ? AND content_type = ?",
                (self.taskid, content_type))

            #print >>sys.__stdout__, "output: %s\nvalue: %s\nstatus: %d\ncontent_type: %d\nkb.partRun: %s\n--------------" % (output, value, status, content_type, kb.partRun)

            # Delete partial output from IPC database if we have got a complete output
            if status == CONTENT_STATUS.COMPLETE:
                if len(output) > 0:
                    for index in xrange(0, len(output)):
                        conf.database_cursor.execute(
                            "DELETE FROM data WHERE id = ?",
                            (output[index][0], ))

                conf.database_cursor.execute(
                    "INSERT INTO data VALUES(NULL, ?, ?, ?, ?)",
                    (self.taskid, status, content_type, jsonize(value)))
                if kb.partRun:
                    kb.partRun = None

            elif status == CONTENT_STATUS.IN_PROGRESS:
                if len(output) == 0:
                    conf.database_cursor.execute(
                        "INSERT INTO data VALUES(NULL, ?, ?, ?, ?)",
                        (self.taskid, status, content_type, jsonize(value)))
                else:
                    new_value = "%s%s" % (dejsonize(output[0][2]), value)
                    conf.database_cursor.execute(
                        "UPDATE data SET value = ? WHERE id = ?",
                        (jsonize(new_value), output[0][0]))
        else:
            conf.database_cursor.execute(
                "INSERT INTO errors VALUES(NULL, ?, ?)",
                (self.taskid, str(value) if value else ""))
def task_list(taskid):
    """
    List all active tasks
    """
    if is_admin(taskid):
        return jsonize({"tasks": tasks})
    else:
        abort(401)
Example #26
0
def option_list(taskid):
    """
    List options for a certain task ID
    """
    if taskid not in tasks:
        abort(500, "Invalid task ID")

    return jsonize(tasks[taskid].get_options())
Example #27
0
def version(token=None):
    """
    Fetch server version
    """

    logger.debug("Fetched version (%s)" %
                 ("admin" if is_admin(token) else request.remote_addr))
    return jsonize({"success": True, "version": VERSION_STRING.split('/')[-1]})
Example #28
0
def scan_start(taskid):
    """
    Launch a scan
    """
    if taskid not in DataStore.tasks:
        logger.warning("[%s] Invalid task ID provided to scan_start()" % taskid)
        return jsonize({"success": False, "message": "Invalid task ID"})

    # Initialize sqlmap engine's options with user's provided options, if any
    for option, value in request.json.items():
        DataStore.tasks[taskid].set_option(option, value)

    # Launch sqlmap engine in a separate process
    DataStore.tasks[taskid].engine_start()

    logger.debug("[%s] Started scan" % taskid)
    return jsonize({"success": True, "engineid": DataStore.tasks[taskid].engine_get_id()})
Example #29
0
def task_list(taskid):
    """
    List all active tasks
    """
    if is_admin(taskid):
        return jsonize({"tasks": tasks})
    else:
        abort(401)
Example #30
0
def task_list(taskid):
    """
    List task pull
    """
    if is_admin(taskid):
        logger.debug("Listed task pull")
        return jsonize({"tasks": tasks, "tasks_num": len(tasks)})
    else:
        abort(401)
def task_destroy(taskid):
    """
    Destroy own task ID
    """
    if taskid in tasks and not is_admin(taskid):
        tasks.pop(taskid)
        return jsonize({"success": True})
    else:
        abort(500, "Invalid task ID")
Example #32
0
def option_set(taskid):
    """
    Set value of option(s) for a certain task ID
    """

    if taskid not in DataStore.tasks:
        logger.warning("[%s] Invalid task ID provided to option_set()" % taskid)
        return jsonize({"success": False, "message": "Invalid task ID"})

    if request.json is None:
        logger.warning("[%s] Invalid JSON options provided to option_set()" % taskid)
        return jsonize({"success": False, "message": "Invalid JSON options"})

    for option, value in request.json.items():
        DataStore.tasks[taskid].set_option(option, value)

    logger.debug("(%s) Requested to set options" % taskid)
    return jsonize({"success": True})
Example #33
0
def task_new():
    """
    Create new task ID
    """
    taskid = hexencode(os.urandom(8))
    DataStore.tasks[taskid] = Task(taskid)

    logger.debug("Created new task: '%s'" % taskid)
    return jsonize({"success": True, "taskid": taskid})
Example #34
0
def option_set(taskid):
    """
    Set value of option(s) for a certain task ID
    """

    if taskid not in DataStore.tasks:
        logger.warning("[%s] Invalid task ID provided to option_set()" % taskid)
        return jsonize({"success": False, "message": "Invalid task ID"})

    if request.json is None:
        logger.warning("[%s] Invalid JSON options provided to option_set()" % taskid)
        return jsonize({"success": False, "message": "Invalid JSON options"})

    for option, value in request.json.items():
        DataStore.tasks[taskid].set_option(option, value)

    logger.debug("(%s) Requested to set options" % taskid)
    return jsonize({"success": True})
Example #35
0
def task_destroy(taskid):
    """
    Destroy own task ID
    """
    if taskid in tasks and not is_admin(taskid):
        tasks.pop(taskid)
        return jsonize({"success": True})
    else:
        abort(500, "Invalid task ID")
Example #36
0
 def write(self, value, status=None, content_type=None):
     if self.messagetype == "stdout":
         #conf.database_cursor.execute("INSERT INTO data VALUES(NULL, ?, ?, ?, ?)",
         #                             (self.taskid, status, content_type, base64pickle(value)))
         conf.database_cursor.execute("INSERT INTO data VALUES(NULL, ?, ?, ?, ?)",
                                      (self.taskid, status, content_type, jsonize(value)))
     else:
         conf.database_cursor.execute("INSERT INTO errors VALUES(NULL, ?, ?)",
                                      (self.taskid, str(value) if value else ""))
Example #37
0
def task_list(taskid):
    """
    List task pull
    """
    if is_admin(taskid):
        logger.debug("Listed task pull")
        return jsonize({"tasks": tasks, "tasks_num": len(tasks)})
    else:
        abort(401)
Example #38
0
    def write(self,
              value,
              status=CONTENT_STATUS.IN_PROGRESS,
              content_type=None):
        if self.messagetype == "stdout":
            if content_type is None:
                if kb.partRun is not None:
                    content_type = PART_RUN_CONTENT_TYPES.get(kb.partRun)
                else:
                    # 忽略所有不相关的消息
                    return

            output = conf.databaseCursor.execute(
                "SELECT id, status, value FROM data WHERE taskid = ? AND content_type = ?",
                (self.taskid, content_type))

            # 如果得到完整的输出,则从IPC数据库中删除部分输出
            if status == CONTENT_STATUS.COMPLETE:
                if len(output) > 0:
                    for index in xrange(len(output)):
                        conf.databaseCursor.execute(
                            "DELETE FROM data WHERE id = ?",
                            (output[index][0], ))

                conf.databaseCursor.execute(
                    "INSERT INTO data VALUES(NULL, ?, ?, ?, ?)",
                    (self.taskid, status, content_type, jsonize(value)))
                if kb.partRun:
                    kb.partRun = None

            elif status == CONTENT_STATUS.IN_PROGRESS:
                if len(output) == 0:
                    conf.databaseCursor.execute(
                        "INSERT INTO data VALUES(NULL, ?, ?, ?, ?)",
                        (self.taskid, status, content_type, jsonize(value)))
                else:
                    new_value = "%s%s" % (dejsonize(output[0][2]), value)
                    conf.databaseCursor.execute(
                        "UPDATE data SET value = ? WHERE id = ?",
                        (jsonize(new_value), output[0][0]))
        else:
            conf.databaseCursor.execute(
                "INSERT INTO errors VALUES(NULL, ?, ?)",
                (self.taskid, str(value) if value else ""))
def status(taskid):
    """
    Verify the status of the API as well as the core
    """

    if is_admin(taskid):
        tasks_num = len(tasks)
        return jsonize({"tasks": tasks_num})
    else:
        abort(401)
Example #40
0
def scan_kill(taskid):
    """
    Kill a scan
    """
    global tasks

    if taskid not in tasks:
        abort(500, "Invalid task ID")

    return jsonize({"success": tasks[taskid].engine_kill()})
Example #41
0
def status(taskid):
    """
    Verify the status of the API as well as the core
    """

    if is_admin(taskid):
        tasks_num = len(tasks)
        return jsonize({"tasks": tasks_num})
    else:
        abort(401)
def task_new():
    """
    Create new task ID
    """
    global tasks

    taskid = hexencode(os.urandom(16))
    tasks[taskid] = init_options()

    return jsonize({"taskid": taskid})
Example #43
0
def scan_status(taskid):
    """
    Returns status of a scan
    """
    if taskid not in DataStore.tasks:
        logger.warning("[%s] Invalid task ID provided to scan_status()" % taskid)
        return jsonize({"success": False, "message": "Invalid task ID"})

    if DataStore.tasks[taskid].engine_process() is None:
        status = "not running"
    else:
        status = "terminated" if DataStore.tasks[taskid].engine_has_terminated() is True else "running"

    logger.debug("[%s] Retrieved scan status" % taskid)
    return jsonize({
        "success": True,
        "status": status,
        "returncode": DataStore.tasks[taskid].engine_get_returncode()
    })
Example #44
0
def task_new():
    """
    Create a new task
    """
    taskid = hexencode(os.urandom(8))
    remote_addr = request.remote_addr

    DataStore.tasks[taskid] = Task(taskid, remote_addr)

    logger.debug("Created new task: '%s'" % taskid)
    return jsonize({"success": True, "taskid": taskid})
Example #45
0
def scan_start(taskid):
    """
    启动扫描
    """
    if taskid not in DataStore.tasks:
        logger.warning(u"[%s] 提供给scan_start()的任务ID无效" % taskid)
        return jsonize({"success": False, "message": u"任务ID无效"})

    # 使用用户提供的选项(如果有)初始化sqlmap引擎选项
    for option, value in request.json.items():
        DataStore.tasks[taskid].set_option(option, value)

    # 在单独的进程中启动sqlmap引擎
    DataStore.tasks[taskid].engine_start()

    logger.debug(u"[%s] 开始扫描" % taskid)
    return jsonize({
        "success": True,
        "engineid": DataStore.tasks[taskid].engine_get_id()
    })
Example #46
0
def task_new():
    """
    Create new task ID
    """
    global tasks

    taskid = hexencode(os.urandom(8))
    tasks[taskid] = Task(taskid)

    logger.debug("Created new task ID: %s" % taskid)
    return jsonize({"taskid": taskid})
Example #47
0
def task_delete(taskid):
    """
    Delete own task ID
    """
    if taskid in tasks:
        tasks[taskid].clean_filesystem()
        tasks.pop(taskid)

        logger.debug("Deleted task ID: %s" % taskid)
        return jsonize({"success": True})
    else:
        abort(500, "Invalid task ID")
Example #48
0
def option_get(taskid):
    """
    Get value of option(s) for a certain task ID
    """
    if taskid not in DataStore.tasks:
        logger.warning("[%s] Invalid task ID provided to option_get()" % taskid)
        return jsonize({"success": False, "message": "Invalid task ID"})

    options = request.json or []
    results = {}

    for option in options:
        if option in DataStore.tasks[taskid].options:
            results[option] = DataStore.tasks[taskid].options[option]
        else:
            logger.debug("(%s) Requested value for unknown option '%s'" % (taskid, option))
            return jsonize({"success": False, "message": "Unknown option '%s'" % option})

    logger.debug("(%s) Retrieved values for option(s) '%s'" % (taskid, ",".join(options)))

    return jsonize({"success": True, "options": results})
Example #49
0
def task_list(token=None):
    """
    Pull task list
    """
    tasks = {}

    for key in DataStore.tasks:
        if is_admin(token) or DataStore.tasks[key].remote_addr == request.remote_addr:
            tasks[key] = dejsonize(scan_status(key))["status"]

    logger.debug("(%s) Listed task pool (%s)" % (token, "admin" if is_admin(token) else request.remote_addr))
    return jsonize({"success": True, "tasks": tasks, "tasks_num": len(tasks)})
Example #50
0
def task_flush(token=None):
    """
    Flush task spool (delete all tasks)
    """

    for key in list(DataStore.tasks):
        if is_admin(token) or DataStore.tasks[key].remote_addr == request.remote_addr:
            DataStore.tasks[key].engine_kill()
            del DataStore.tasks[key]

    logger.debug("(%s) Flushed task pool (%s)" % (token, "admin" if is_admin(token) else request.remote_addr))
    return jsonize({"success": True})
Example #51
0
def scan_data(taskid):
    """
    Retrieve the data of a scan
    """

    json_data_message = list()
    json_errors_message = list()

    if taskid not in DataStore.tasks:
        logger.warning("[%s] Invalid task ID provided to scan_data()" % taskid)
        return jsonize({"success": False, "message": "Invalid task ID"})

    # Read all data from the IPC database for the taskid
    for status, content_type, value in DataStore.current_db.execute("SELECT status, content_type, value FROM data WHERE taskid = ? ORDER BY id ASC", (taskid,)):
        json_data_message.append({"status": status, "type": content_type, "value": dejsonize(value)})

    # Read all error messages from the IPC database
    for error in DataStore.current_db.execute("SELECT error FROM errors WHERE taskid = ? ORDER BY id ASC", (taskid,)):
        json_errors_message.append(error)

    logger.debug("(%s) Retrieved scan data and error messages" % taskid)
    return jsonize({"success": True, "data": json_data_message, "error": json_errors_message})
def scan_delete(taskid):
    """
    Delete a scan and corresponding temporary output directory
    """
    global tasks

    if taskid not in tasks:
        abort(500, "Invalid task ID")

    if "oDir" in tasks[taskid] and tasks[taskid].oDir is not None:
        shutil.rmtree(tasks[taskid].oDir)

    return jsonize({"success": True})
Example #53
0
def scan_log(taskid):
    """
    检索日志消息
    """
    json_log_messages = list()

    if taskid not in DataStore.tasks:
        logger.warning(u"提供给scan_log()的任务ID[%s]无效" % taskid)
        return jsonize({"success": False, "message": "任务ID无效"})

    # Read all log messages from the IPC database
    for time_, level, message in DataStore.current_db.execute(
            "SELECT time, level, message FROM logs WHERE taskid = ? ORDER BY id ASC",
        (taskid, )):
        json_log_messages.append({
            "time": time_,
            "level": level,
            "message": message
        })

    logger.debug(u" 检索扫描[%s]的日志消息" % taskid)
    return jsonize({"success": True, "log": json_log_messages})
Example #54
0
File: api.py Project: zensec/sqlmap
def download(taskid, target, filename):
    """
    Download a certain file from the file system
    """
    if taskid not in DataStore.tasks:
        logger.warning("[%s] Invalid task ID provided to download()" % taskid)
        return jsonize({"success": False, "message": "Invalid task ID"})

    path = os.path.abspath(os.path.join(paths.SQLMAP_OUTPUT_PATH, target, filename))
    # Prevent file path traversal
    if not path.startswith(paths.SQLMAP_OUTPUT_PATH):
        logger.warning("[%s] Forbidden path (%s)" % (taskid, target))
        return jsonize({"success": False, "message": "Forbidden path"})

    if os.path.isfile(path):
        logger.debug("[%s] Retrieved content of file %s" % (taskid, target))
        with open(path, 'rb') as inf:
            file_content = inf.read()
        return jsonize({"success": True, "file": file_content.encode("base64")})
    else:
        logger.warning("[%s] File does not exist %s" % (taskid, target))
        return jsonize({"success": False, "message": "File does not exist"})
Example #55
0
def option_set(taskid):
    """
    Set an option (command line switch) for a certain task ID
    """
    global tasks

    if taskid not in tasks:
        abort(500, "Invalid task ID")

    for option, value in request.json.items():
        tasks[taskid].set_option(option, value)

    return jsonize({"success": True})
Example #56
0
def scan_kill(taskid):
    """
    Kill a scan
    """
    global tasks

    if taskid not in tasks:
        abort(500, "Invalid task ID")

    tasks[taskid].engine_kill()

    logger.debug("Killed scan for task ID %s" % taskid)
    return jsonize({"success": True})
Example #57
0
def _client(url, options=None):
    logger.debug("Calling %s" % url)
    try:
        data = None
        if options is not None:
            data = jsonize(options)
        req = urllib2.Request(url, data, {"Content-Type": "application/json"})
        response = urllib2.urlopen(req)
        text = response.read()
    except:
        if options:
            logger.error("Failed to load and parse %s" % url)
        raise
    return text
Example #58
0
def option_get(taskid):
    """
    获取某个任务ID的选项(命令行开关)的值
    """
    if taskid not in DataStore.tasks:
        logger.warning(u"[%s] 提供给option_get()的任务ID无效" % taskid)
        return jsonize({"success": False, "message": u"任务ID无效"})

    option = request.json.get("option", "")

    if option in DataStore.tasks[taskid].options:
        logger.debug(u"[%s] 检索选项%s的值" % (taskid, option))
        return jsonize({
            "success": True,
            option: DataStore.tasks[taskid].get_option(option)
        })
    else:
        logger.debug(u"[%s] 未知选项%s的请求值" % (taskid, option))
        return jsonize({
            "success": False,
            "message": "Unknown option",
            option: "not set"
        })
Example #59
0
def scan_status(taskid):
    """
    返回扫描的状态
    """
    if taskid not in DataStore.tasks:
        logger.warning(u"[%s] 提供给scan_status()的任务ID无效" % taskid)
        return jsonize({"success": False, "message": u"任务ID无效"})

    if DataStore.tasks[taskid].engine_process() is None:
        status = "not running"
    else:
        status = "terminated" if DataStore.tasks[taskid].engine_has_terminated(
        ) is True else "running"

    logger.debug(u"[%s] 检索扫描状态" % taskid)
    return jsonize({
        "success":
        True,
        "status":
        status,
        "returncode":
        DataStore.tasks[taskid].engine_get_returncode()
    })