def lookup_epo_unique_identifiers(
            dxl_client, response_timeout=Client._DEFAULT_RESPONSE_TIMEOUT):
        """
        Returns a ``set`` containing the unique identifiers for the ePO servers that are currently
        exposed to the DXL fabric

        :param dxl_client: The DXL client with which to perform the request
        :param response_timeout: (optional) The maximum amount of time to wait for a response
        :return: A ``set`` containing the unique identifiers for the ePO servers that are currently
            exposed to the DXL fabric.
        """
        res = EpoClient._sync_request(
            dxl_client, Request("/mcafee/service/dxl/svcregistry/query"),
            response_timeout, {"serviceType": EpoClient.DXL_SERVICE_TYPE})
        res_dict = MessageUtils.json_to_dict(res)

        ret_ids = set()
        if "services" in res_dict:
            for service in res_dict["services"].values():
                if "requestChannels" in service:
                    channels = service['requestChannels']
                    for channel in channels:
                        if channel.startswith(EpoClient.DXL_REQUEST_PREFIX):
                            ret_ids.add(
                                channel[len(EpoClient.DXL_REQUEST_PREFIX):])
        return ret_ids
Beispiel #2
0
    def help(self, output_format=OutputFormat.VERBOSE):
        # pylint: disable=line-too-long
        """
        Returns the list of remote commands that are supported by the ePO server this client is
        communicating with.

        **Example Usage**

            .. code-block:: python

                # Display the help
                print(epo_client.help())

        **Example Response**

            .. parsed-literal::

                ComputerMgmt.createAgentDeploymentUrlCmd deployPath groupId urlName
                agentVersionNumber agentHotFix [edit] [ahId] [fallBackAhId] - Create Agent
                Deployment URL Command
                ComputerMgmt.createCustomInstallPackageCmd deployPath [ahId] [fallBackAhId] -
                Create Custom Install Package Command
                ComputerMgmt.createDefaultAgentDeploymentUrlCmd tenantId - Create Default
                Non-Editable Agent Deployment URL Command
                ComputerMgmt.createTagGroup parentTagGroupId newTagGroupName - Create a new
                subgroup under an existing tag group.
                ComputerMgmt.deleteTag tagIds [forceDelete] - Delete one or more tags.

                ...

        :param output_format: (optional) The output format for ePO to use when
            returning the response. The list of `output formats` can be found
            in the :class:`OutputFormat` constants class. If the command is
            processed by the ePO-hosted `DXL Commands` service, this parameter
            can only be set to :const:`OutputFormat.VERBOSE` or
            :const:`OutputFormat.JSON`.
        :raise Exception: If an unsupported `output format` is specified. This
            exception is raised if the command is to be sent to an ePO-hosted
            `DXL Commands` service and an `output format` of anything other
            than :const:`OutputFormat.VERBOSE` or :const:`OutputFormat.JSON`
            is specified.
        :return: The result of the remote command execution
        """
        res = self.run_command(
            "core.help",
            output_format=OutputFormat.JSON \
                if output_format == OutputFormat.VERBOSE else output_format)
        if output_format == OutputFormat.VERBOSE:
            res_list = MessageUtils.json_to_dict(res)
            res = os.linesep.join(res_list)
        return res
Beispiel #3
0
    def test_runcommand(self):
        with BaseClientTest.create_client(max_retries=0) as dxl_client:
            # Set up client, and register mock service
            epo_client = EpoClient(dxl_client,
                                   epo_unique_id=LOCAL_TEST_SERVER_NAME +
                                   str(DEFAULT_EPO_SERVER_ID))
            dxl_client.connect()

            with MockEpoServer(dxl_client):
                res = epo_client.run_command(
                    "system.find", {"searchText": SYSTEM_FIND_CMD_NAME},
                    output_format=OutputFormat.JSON)

                # Load find result into dictionary
                res_list = MessageUtils.json_to_dict(res)

                self.assertEqual(res_list, SYSTEM_FIND_PAYLOAD)

            dxl_client.disconnect()
Beispiel #4
0
    def _query_service_registry(dxl_client, response_timeout, service_type):
        """
        Queries the broker service registry for services.

        :param dxl_client: The DXL client with which to perform the request.
        :param response_timeout: The maximum amount of time to wait for a
            response.
        :param service_type: The service type to return data for.
        :return: A ``list`` containing info for each registered service whose
            ``service_type`` matches the ``service_type`` parameter passed
            into this method.
        """
        res = EpoClient._decode_response(
            EpoClient._sync_request(
                dxl_client,
                Request("/mcafee/service/dxl/svcregistry/query"),
                response_timeout,
                {"serviceType": service_type}))
        res_dict = MessageUtils.json_to_dict(res)
        return res_dict["services"].values() if "services" in res_dict else []
    def test_run_command(self):
        with self.create_client(max_retries=0) as dxl_client:
            dxl_client.connect()

            for use_commands_service in [True, False]:
                with MockEpoServer(dxl_client,
                                   use_commands_service=use_commands_service):
                    epo_client = EpoClient(
                        dxl_client,
                        epo_unique_id=LOCAL_TEST_SERVER_NAME +
                        str(DEFAULT_EPO_SERVER_ID))

                    # Run it twice to validate the command vs. remote
                    # service failover logic for request topics
                    for _ in range(2):
                        res = epo_client.run_command(
                            "system.find",
                            {"searchText": SYSTEM_FIND_OSTYPE_LINUX},
                            output_format=OutputFormat.JSON)

                        res_list = MessageUtils.json_to_dict(res)

                        self.assertEqual(res_list, SYSTEM_FIND_PAYLOAD)
# Create the client
with DxlClient(config) as dxl_client:

    # Connect to the fabric
    dxl_client.connect()

    logger.info("Connected to DXL fabric.")

    # Create client wrapper
    client = OpenC2Client(dxl_client)

    # Custom Actuator (VirusTotal)
    @openc2.v10.CustomActuator(
        "x-virustotal",
        [("resource", stix2.properties.StringProperty(required=True))])
    class VirusTotalActuator(object):
        pass

    # Send the command and receive the response
    cmd = openc2.v10.Command(
        action="query",
        target=openc2.v10.Properties(properties=["url-report"]),
        actuator=VirusTotalActuator(resource=URL))
    response = client.send_command('/openc2-virustotal/service/api', cmd)
    response_dict = MessageUtils.json_to_dict(response.serialize())

    # Print out the response (convert dictionary to JSON for pretty printing)
    print("Response:\n{0}".format(
        MessageUtils.dict_to_json(response_dict, pretty_print=True)))
logging.getLogger().setLevel(logging.ERROR)
logger = logging.getLogger(__name__)

# Create DXL configuration from file
config = DxlClientConfig.create_dxl_config_from_file(CONFIG_FILE)

# The ePO unique identifier
EPO_UNIQUE_ID = None

# The search text
SEARCH_TEXT = "<specify-find-search-text>"

# Create the client
with DxlClient(config) as client:

    # Connect to the fabric
    client.connect()

    # Create the ePO client
    epo_client = EpoClient(client, EPO_UNIQUE_ID)

    # Run the system find command
    res = epo_client.run_command("system.find", {"searchText": SEARCH_TEXT},
                                 output_format=OutputFormat.JSON)

    # Load find result into dictionary
    res_dict = MessageUtils.json_to_dict(res)

    # Display the results
    print(MessageUtils.dict_to_json(res_dict, pretty_print=True))
Beispiel #8
0
    # Connect to the fabric
    dxl_client.connect()

    logger.info("Connected to DXL fabric.")

    # Create client wrapper
    client = DomainToolsApiClient(dxl_client)

    # Invoke 'account_information' method on service, in default (dict) output
    # format
    resp_dict = client.account_information()

    # Print out the response
    print("Response in default output format:\n{0}".format(
        MessageUtils.dict_to_json(resp_dict, pretty_print=True)))

    # Invoke 'account_information' method on service, in 'json' output
    resp_json = client.account_information(out_format="json")

    # Print out the response
    print("Response in json output format:\n{0}".format(
        MessageUtils.dict_to_json(MessageUtils.json_to_dict(resp_json),
                                  pretty_print=True)))

    # Invoke 'account_information' method on service, in 'xml' output
    resp_xml = client.account_information(out_format="xml")

    # Print out the response
    print("Response in xml output format:\n{}".format(resp_xml))