Пример #1
0
def update_payload(payload_id, enabled=None, jitter=None, interval=None, visible=None, expiration_date=None):
    payload = Payload.query.get(payload_id)
    if jitter:
        payload.Jitter = jitter
    if interval:
        payload.BeaconInterval = interval
    if expiration_date:
        payload.ExpirationDate = expiration_date
        expiration_date = payload.ExpirationDate.isoformat()
    if enabled is not None:
        payload.Enabled = enabled
    if visible is not None:
        payload.Visible = visible

    message = dict({
        "Id": payload_id,
        "Jitter": payload.Jitter,
        "BeaconInterval": payload.BeaconInterval,
        "ExpirationDate": expiration_date,
        "Enabled": payload.Enabled,
        "Visible": payload.Visible
    })

    log("payload.py:update_payload", "Sending: {0}".format(message))
    rabbit_producer.send_request("UpdatePayload", message)
    return dict({"Success": True, "Payload": payload_json(payload)})
Пример #2
0
def add_agent_checkin(agent_name, transport_id=None, source_ip=None, message=None):
    hmac = None
    iv = None
    msg = None
    if message:
        decoded_checkin = b64decode(message)
        checkin_dict = json.loads(decoded_checkin)
        hmac = checkin_dict["HMAC"]
        iv = checkin_dict["IV"]
        msg = checkin_dict["Message"]

    if not source_ip:
        source_ip = request.remote_addr

    if not transport_id:
        transport_id = 1

    checkin = {
        'AgentName': agent_name,
        'TransportId': transport_id,
        'SourceIp': source_ip,
        'HMAC': hmac,
        'IV': iv,
        'Message': msg
    }

    log("add_agent_task_response", "publishing?")
    rabbit_producer.send_request('NewAgentCheckin', checkin)
    return {
        'Success': True,
        'Result': checkin
    }
Пример #3
0
def new_console_message(agent_id, content):
    filenames = re.findall("(f2:files/[^\s]+)", content)
    display = content
    if len(filenames) > 0:
        for filename in filenames:
            name = filename.replace("f2:files/","")
            log("new_console_message", "getting bytes for file {0}".format(name))
            result = get_faction_file_bytes(name)
            if result['Success']:
                content = content.replace(filename, result['Message'])
            else:
                return dict({
                    'Success': False,
                    'Message': 'Could not find file: {0}'.format(filename)
                })
    console_message = {
        "AgentId": agent_id,
        "UserId": current_user.Id,
        "Content": content,
        "Display": display
    }

    log("add_message", "publishing message: {0}".format(console_message))
    rabbit_producer.send_request('NewConsoleMessage', console_message)
    return console_message
Пример #4
0
def create_error_message(message, details=None):
    error_message = dict({
        'Success': False,
        'Source': 'API',
        'Message': message,
        'Details': details
    })
    rabbit_producer.send_request("NewErrorMessage", error_message)
    return error_message
Пример #5
0
def update_agent(agent_id, agent_name=None, visible=None):
    agent = Agent.query.get(agent_id)
    if agent_name:
        agent.Name = agent_name

    if visible is not None:
        agent.Visible = visible

    message = dict({
        "Id": agent_id,
        "Name": agent.Name,
        "Visible": agent.Visible
    })
    log("update_agent", "sending message: {0}".format(message))
    rabbit_producer.send_request("UpdateAgent", message)
    return {"Success": True, "Result": agent_json(agent)}
Пример #6
0
def update_transport(transport_id, name=None, transport_type=None, guid=None, configuration=None, enabled=None, visible=None):
    transport = Transport.query.get(transport_id)

    # Only update what we're given. Probably a better way to do this..
    if name is None:
        name = transport.Name

    if transport_type is None:
        transport_type = transport.TransportType

    if guid is None:
        guid = transport.Guid

    if configuration is None:
        configuration = transport.Configuration

    if enabled is None:
        enabled = transport.Enabled

    if visible is None:
        visible = transport.Visible

    publish_message = {
        "Id": transport.Id,
        "Name": name,
        "TransportType": transport_type,
        "Guid": guid,
        "Configuration": configuration,
        "Enabled": enabled,
        "Visible": visible
    }

    message_id = rabbit_producer.send_request("UpdateTransport", publish_message, callback=True)
    # Wait for our response
    # TODO: Add actual timeout here.
    i = 0
    while rabbit_consumer.queue[message_id] is None and i < 15:
        log("transport:new_transport", "Waiting for {0} seconds".format(15 - i))
        sleep(1)
        i += 1

    # Return data
    message = rabbit_consumer.queue[message_id]

    if message:
        return json.loads(message)
    else:
        log("transport:update_transport", "Timed out.")
        return create_error_message("Timeout waiting for response from Core while updating transport. Resubmit your request.")
Пример #7
0
def upload_payload(payload_id, build_token):
    log("payload:upload_payload", "Got id: {0} with token: {1}".format(str(payload_id), build_token))
    payload = Payload.query.get(payload_id)
    s = URLSafeSerializer(SECRET_KEY)
    token_value = s.loads(build_token)
    log("payload:upload_payload", "token value: {0}".format(token_value))
    if payload.Filename == None and payload.Name == token_value:
        log("payload:upload_payload", "filename is null and token matches")
        payload.Built = True
        file = request.files['file']
        payload.Filename = secure_filename(file.filename)
        log("payload:upload_payload", "filename set to: {0}".format(payload.Filename))
        try:
            savePath = os.path.join(payload_upload_dir, payload.Filename)
            log("payload:upload_payload", "saving file to: {0}".format(savePath))
            file.save(savePath)
            db.session.add(payload)
            db.session.commit()

            payload_message = dict({
                "Success": True,
                "Payload": payload_json(payload)
            })

            rabbit_producer.send_request('PayloadUpdated', payload_message)

            return dict({
                'Success': True,
                'Message': 'File saved as {0}'.format(payload.Filename)
            })
        except Exception as e:
            log("payload:upload_payload", "file save failed: {0}".format(str(e)))
            return create_error_message('Failed to save file: {0}'.format(str(e)))
    else:
        log("payload:upload_payload", "token check failed or payload already built")
        return create_error_message('Payload token invalid or payload already built')
Пример #8
0
def new_staging_message(payload_name,
                        staging_id,
                        transport_id,
                        message,
                        source_ip=None):
    log(
        "staging_message:new_staging_message",
        "Got staging request. PayloadName: {0} ID: {1}".format(
            payload_name, staging_id))

    response = get_staging_response(staging_id)
    if response['Success']:
        return response
    else:
        decoded_response = b64decode(message)
        response_dict = json.loads(decoded_response)
        response_dict["PayloadName"] = payload_name
        response_dict["TransportId"] = transport_id
        if source_ip == None:
            source_ip = request.remote_addr
        response_dict["SourceIp"] = source_ip

    log("staging_message:new_staging_message",
        "Publishing: {0}".format(response_dict))
    message_id = rabbit_producer.send_request('NewStagingMessage',
                                              response_dict,
                                              callback=True)

    # Wait for our response
    log("staging_message:new_staging_message", "Waiting for 10 seconds")
    i = 0
    while rabbit_consumer.queue[message_id] is None and i < 10:
        log("staging_message:new_staging_message",
            "Waiting for {0} seconds".format(10 - i))
        sleep(1)
        i += 1

    # Return data
    message = rabbit_consumer.queue[message_id]

    if message:
        log("staging_message", "Got response from Core: {0}".format(message))
        return json.loads(message)
    else:
        log("staging_message", "Timed out.")
        return "ERROR"
Пример #9
0
def new_transport(name):
    apiKey = new_api_key('transport', 1, current_user.Id)
    publish_message = dict({
        "Name": name,
        "ApiKeyId": apiKey["Id"],
        "UserId": current_user.Id
    })

    log("transport:new_transport", "Publishing: {0}".format(publish_message))
    message_id = rabbit_producer.send_request("NewTransport", publish_message, callback=True)

    # Wait for our response
    # TODO: Add actual timeout here.
    i = 0
    while i < 20:
        log("transport:new_transport", "Waiting for {0} seconds".format(20 - i))
        sleep(1)
        i += 1

        # Return data
        log("transport:new_transport", "queue: {}".format(rabbit_consumer.queue))
        message = rabbit_consumer.queue.get(message_id)
        if message:
            log("transport:new_transport", "Got response from Core: {0}".format(message))
            message_dict = json.loads(message)

            if 'Transport' in message_dict.keys():

                transport = Transport.query.get(message_dict['Transport']['Id'])
                return {
                    "Success": True,
                    "TransportId": transport.Id,
                    "ApiKey": {
                        "KeyName": apiKey["Name"],
                        "Secret": apiKey["Secret"]
                    },
                    "Transport": transport_json(transport)
                }
    log("transport:new_transport", "Timed out.")
    return create_error_message(
        "Timeout waiting for response from Core while creating new transport. Resubmit your request.")
Пример #10
0
def new_error_message(source, message):
    error_message = dict({"Source": source, "Message": message})
    rabbit_producer.send_request("NewErrorMessage", error_message)

    return dict({'Success': True, 'ErrorMessage': error_message})
Пример #11
0
def new_payload(description,
                agent_type,
                transport_id,
                agent_transport_id,
                operating_system,
                architecture,
                version,
                format,
                agent_type_configuration,
                jitter,
                interval,
                debug,
                expiration_date=None):

    log("payload:new_payload", "Got request")
    log("payload:new_payload", "Details - Jitter: {0}, Interval: {1}, AgentType: {2}, ExpirationDate: {3}".format(jitter, interval, agent_type, expiration_date))

    if expiration_date != None:
        try:
            expiration_date = dateparser.parse(expiration_date).isoformat()
        except:
            error_message = create_error_message("Could not convert {0} to a DateTime object".format(expiration_date))
            return error_message

    if jitter is None:
        jitter_float = None
    else:
        try:
            jitter_float = float(jitter)
        except:
            error_message = create_error_message("Jitter is in invalid format. Expected 0.0 to 1.0. Got {0}".format(jitter))
            return error_message

    error_at = None
    expected = None

    if not isinstance(transport_id, int):
        error_at = "TransportId"
        expected = "Expected an Integer."

    if not isinstance(agent_transport_id, int):
        error_at = "AgentTransportId"
        expected = "Expected an Integer."

    if not isinstance(interval, int):
        error_at = "BeaconInterval"
        expected = "Expected an Integer."

    if jitter_float is not None and 1.0 < jitter_float < 0.0:
        error_at = "Jitter"
        expected = "Expected 0.0 to 1.0."

    if error_at is not None:
        error_message = create_error_message("Error processing {0}. {1}".format(error_at, expected))
        return error_message


    payload_name = token_urlsafe(8)
    s = URLSafeSerializer(SECRET_KEY)
    build_token = s.dumps(payload_name)

    publish_message = dict({
        "Name": payload_name,
        "Description": description,
        "BuildToken": build_token,
        "AgentTypeId": agent_type,
        "AgentTransportTypeId": agent_transport_id,
        "TransportId": transport_id,
        "OperatingSystemId": operating_system,
        "ArchitectureId": architecture,
        "VersionId": version,
        "FormatId": format,
        "AgentTypeConfigurationId": agent_type_configuration,
        "Jitter": "{0:0.1f}".format(jitter_float),
        "BeaconInterval": interval,
        "ExpirationDate": expiration_date,
        "Debug": debug
    })

    log("payload:new_payload", "Publishing: {0}".format(publish_message))
    message_id = rabbit_producer.send_request("NewPayload", publish_message, callback=True)

    # Wait for our response
    # TODO: Add actual timeout here.
    i = 0
    while rabbit_consumer.queue[message_id] is None and i < 15:
        log("payload:new_payload", "Waiting for {0} seconds".format(15 - i))
        sleep(1)
        i += 1

    # Return data
    message = rabbit_consumer.queue[message_id]

    if message:
        log("payload:new_payload", "Got response from Build Server: {0}".format(message))
        message_dict = json.loads(message)
        if message_dict.get('Source'):
            log("payload:new_payload", "Its an error..")
            return message_dict
        else:
            payload = Payload.query.get(message_dict['Id'])
            return {
                "Success": True,
                "Result": payload_json(payload)
            }
    log("payload:new_payload", "Timed out.")
    return create_error_message("Timeout waiting for response from Core while processing new payload")