Beispiel #1
0
    def save(self):
        """Saves artifact. 

        Sets the arifacts id. Sets the ``id`` attribute of the artifact to the new artifact id returned from phantom.
        
        Raises:
            Exception: Raises exception if artifact fails to save.
        
        Returns:
            dict: Returns a dict indicating if the artifact was saved and the new id. ``{'id': id_number, 'created', True_or_False}``
        """
        response = ph_base._send_request('/rest/artifact',
                                         'post',
                                         payload=json.dumps(
                                             self.render_dictionary()),
                                         content_type='application/json')

        if response.get(ph_consts.ARTIFACT_FAILED_KEY) and response[
                ph_consts.
                ARTIFACT_FAILED_MESSAGE_KEY] != ph_consts.ARTIFACT_EXISTING_ID:
            raise Exception(response[ph_consts.ARTIFACT_FAILED_MESSAGE_KEY])

        self.id = response[ph_consts.ARTIFACT_NEW_ID] if response.get(
            ph_consts.ARTIFACT_NEW_ID) else response[
                ph_consts.ARTIFACT_EXISTING_ID]

        artifact_results = {'id': self.id, 'created': ('id' in response)}

        return artifact_results
Beispiel #2
0
    def get_list(cls, list_name, id=None):
        """Get list data.
        
        Args:
            list_name (string): Name of phantom list to get
            id (int): Defaults to None. Id of phantom list.
        
        Raises:
            Exception: Exception if list is not found.
        
        Returns:
            ph_list: Returns found list.
        """

        retrieved_list = None

        response = ph_base._send_request(
            '/rest/decided_list/' + (list_name if list_name else str(id)) +
            '?_output_format=JSON', 'get')

        if 'failed' in response:
            if 'item not found' not in response['message']:
                raise Exception('Error reading from list - ' + list_name +
                                '. Error: ' + response['message'])
        else:
            retrieved_list = ph_list(response['name'],
                                     content=response['content'],
                                     id=response['id'])

        return retrieved_list
Beispiel #3
0
    def cancel_playbook(cls, playbook_run_id):
        """Cancels action.

        This should be used if you want to cancel an action for which
        you already know the ``playbook_run_id``.
        
        Args:
            playbook_run_id (int): id of running playbook.

        Raises:
            Exception: Raises exception if action fails to be cancelled.
        
        Returns:
            bool: True if action cancelled.

        Example:
            Cancel the playbook::

                ph_action.cancel_playbook(111) # cancels playbook
        """

        response = ph_base._send_request('/request/playbook_run/' +
                                         str(playbook_run_id),
                                         'post',
                                         payload=json.dumps({'cancel': True}))

        if ph_consts.PLAYBOOK_CANCEL_FAILED_KEY in response:
            raise Exception(response[ph_consts.PLAYBOOK_FAILED_MESSAGE_KEY])

        return True
Beispiel #4
0
    def save(self):
        """Saves container. 

        Sets the container's id. If container already exists, just sets id of object.
        
        Raises:
            Exception: Raises exception if container fails to save.
        
        Returns:
            dict: Returns a dict indicating if the container was saved and the new id. ``{'id': id_number, 'created', True_or_False}``
        """

        response = ph_base._send_request('/rest/container',
                                         'post',
                                         payload=json.dumps(
                                             self.render_dictionary()),
                                         content_type='application/json')

        if response.get(
                ph_consts.CONTAINER_FAILED_KEY
        ) and ph_consts.CONTAINER_DUPLICATE_MESSAGE not in response[
                ph_consts.CONTAINER_FAILED_MESSAGE_KEY]:
            raise Exception(str(
                response))  #response[ph_consts.CONTAINER_FAILED_MESSAGE_KEY])

        self.id = response[ph_consts.CONTAINER_NEW_ID] if response.get(
            ph_consts.CONTAINER_NEW_ID) else response[
                ph_consts.CONTAINER_EXISTING_ID]

        container_results = {
            'id': self.id,
            'created': (ph_consts.CONTAINER_NEW_ID in response)
        }

        return container_results
Beispiel #5
0
    def get_list_csv(cls, list_name, row_separator='%0A', field_separator=','):
        """Get list csv
        
        Args:
            list_name (string): name of list

        Keyword Args:
            row_separator (string): separator for rows - defaults to %0A
            field_separator (string): separator for fields defaults to ,
        
        Raises:
            Exception: [description]
        """

        retreived_csv = None

        response = ph_base._send_request(
            '/rest/decided_list/' + list_name +
            '/formatted_content?_output_format=csv&_rs=' + row_separator +
            '&_fs=' + field_separator, 'get')

        if 'failed' in response:
            if 'item not found' not in response['message']:
                raise Exception('Error reading from list - ' + list_name +
                                '. Error: ' + response['message'])
        else:
            retrieved_csv = response

        return retrieved_csv
Beispiel #6
0
    def add_container_comment(cls, container_id, comment):
        """Used to add a comment to container.
        
        Args:
            container_id (int): id of container
            comment (string): comment to be saved
        
        Returns:
            dict: returns id of new comment and whether comment save succesfully (see ``save()`` for example)

        Example:
            Adding a comment to a container for which I already know the container id::

                ph_container.add_container_comment(1069, 'this is a comment')

        Notes:
            Use this if you have not created a container with ``save()`` and you already know a container id.
        """

        container_json = {'container_id': container_id, 'comment': comment}

        response = ph_base._send_request('/rest/container_comment',
                                         'POST',
                                         payload=json.dumps(container_json),
                                         content_type='application/json')

        return cls._format_container_results(response, 'comment', container_id)
Beispiel #7
0
    def update_role(cls, role_id, remove_users=[], add_users=[], update_permissions=None):
        """Update role

        Keyword Args:
            role_id (int): id of role
            add_users (list): list of user ids to add to role
            remove_users (list): list of users to remove from role.
            update_permission (list): dictionary of new permissions

        Notes:
            Use this for existing roles which you already know the ids of.
        """

        update_json = {
            'add_users': add_users,
            'remove_users': remove_users,
        }

        if update_permissions and ph_base._exists_in_data_set('permission object', ph_consts.ROLE_PERMISSIONS, [permission['name'] for permission in update_permissions]):
            update_json['update_permissions'] = update_permissions

        response = ph_base._send_request(
            '/rest/role/' + str(role_id),
            'post',
            payload=json.dumps(update_json),
            content_type='application/json'
        )

        return response
Beispiel #8
0
    def cancel_action(cls, action_id):
        """Cancels action.

        This should be used if you want to cancel an action for which
        you already know the ``action_id``.
        
        Args:
            action_id (int): id of running action.

        Raises:
            Exception: Raises exception if action fails to be cancelled.

        Returns:
            bool: True if action cancelled.

        Example:
            Cancel the action::

                ph_action.cancel_action(444) # cancels action
        """
        response = ph_base._send_request('/request/action_run/' +
                                         str(action_id),
                                         'post',
                                         payload=json.dumps({'cancel': True}))

        if ph_consts.ACTION_CANCEL_FAILED_KEY in response:
            raise Exception(response[ph_consts.ACTION_FAILED_MESSAGE_KEY])

        return True
Beispiel #9
0
    def get_action_results(cls, action_id):

        response = ph_base._send_request(
            '/rest/app_run?include_expensive=True&_filter_action_run_id=' +
            str(action_id), 'get')

        return (response)
Beispiel #10
0
    def delete_user(cls, user_id):
        """Delete an existing user

        Delete an existing user

        Args:
            user_id (int): id of the user

        Returns:
            dict: returns delete user response json

        Example:
            Delete a user with user id of 15::

                ph_user.delete_user(15)

        Notes:
            This should be used if you have not run ``save()`` but already know the user id
        """
        response = ph_base._send_request(
            '/rest/ph_user/' + str(user_id),
            'delete'
        )

        return response
Beispiel #11
0
    def save(self):
        """Saves user
        
        Sets user_id after successful save

        Raises:
            Exception: Exception if error saving user
        
        Returns:
            int: id of newly saved user
        """

        response = ph_base._send_request(
            '/rest/ph_user',
            'post',
            payload=json.dumps(self.render_dictionary()),
            content_type='application/json'
        )

        if ph_consts.USER_SUCCESS_KEY not in response:
            raise Exception(str(response)) #response[ph_consts.USER_FAILED_MESSAGE_KEY])
        
        self.user_id = response[ph_consts.USER_NEW_ID]

        return self.user_id
Beispiel #12
0
    def save(self):
        """Saves asset.
        
        Raises:
            Exception: Exception raised if issue saving asset.
        
        Returns:
            int: Returns asset id of newly saved asset.
        """

        response = ph_base._send_request('/rest/asset',
                                         'post',
                                         payload=json.dumps(
                                             self.render_dictionary()),
                                         content_type='application/json')

        if not response.get(ph_consts.ASSET_NEW_ID):
            message = response[
                ph_consts.ASSET_FAILED_MESSAGE_KEY] if response.get(
                    ph_consts.ASSET_FAILED_MESSAGE_KEY
                ) else 'Error creating asset.'
            raise Exception(message)

        self.asset_id = response['id']

        return response['id']
Beispiel #13
0
    def save(self):
        """Saves the phase. 
        
        Raises:
            Exception: Raises exception if save is attempted without saving template id.
            Exception: Raises exception if phase failed to save.
        
        Returns:
            bool: Returns True if phase successfully saved.

        Note:
            This should only be used if you are saving phases to existing case templates.
            If you are creating an entirely new case template. Use the ``add_phase()`` method
            of ``ph_case`` to add this phase to that case, and the call ``save()`` on the case.
        """

        if self.template_id is None:
            raise Exception(
                'Phase can only be saved if template ID is set to existing ' +
                'case template id.')

        response = ph_base._send_request('/rest/workflow_phase_template',
                                         'post',
                                         payload=json.dumps(
                                             self.render_dictionary()),
                                         content_type='application/json')

        if ph_consts.PHASE_SUCCESS_KEY not in response:
            raise Exception('Error trying to save phase - ' + self.name +
                            '. ' +
                            response[ph_consts.PHASE_FAILED_MESSAGE_KEY])
        elif ph_consts.PHASE_NEW_ID in response:
            self.id = response[ph_consts.PHASE_NEW_ID]

        return True
Beispiel #14
0
    def update_task(cls, task_id, task_json):
        response = ph_base._send_request('/rest/workflow_task_template/' +
                                         str(task_id),
                                         'post',
                                         payload=json.dumps(task_json),
                                         content_type='application/json')

        return response
Beispiel #15
0
    def save(self, overwrite=True):
        """Saves list to phantom

        Keyword Args:
            overwrite (bool): Defaults to True. If true will overrite existing list data.
        
        Raises:
            Exception: [description]
            Exception: [description]
        
        Returns:
            [type]: [description]
        """

        list_exists = self._list_exists()
        if not overwrite and list_exists:
            raise Exception('Cannot create list - ' + self.name +
                            ' - because it already exists.')
        else:
            if list_exists:
                response = ph_base._send_request(
                    '/rest/decided_list/' + self.name,
                    'post',
                    payload=json.dumps(self.format_list_json()),
                    content_type='application/json')
            else:
                if not list_exists:
                    response = ph_base._send_request(
                        '/rest/decided_list',
                        'post',
                        payload=json.dumps(self.format_list_json()),
                        content_type='application/json')

        if ph_consts.LIST_SUCCESS_KEY not in response:
            raise Exception('Error saving list with name - ' + self.name +
                            '. ' + response[ph_consts.LIST_FAILED_MESSAGE_KEY])
        elif ph_consts.LIST_NEW_ID in response:
            self.id = response[ph_consts.LIST_NEW_ID]

        return True
Beispiel #16
0
    def pin_to_container_hud(cls,
                             container_id,
                             message,
                             pin_data,
                             playbook_id=None,
                             pin_type='data',
                             pin_style=''):
        """Pin an item to the container HUD.
        
        Args:
            container_id (int): id of container
            message (string): message associated with this pin
            pin_data (string): data that is actually pinned
        
        Keyword Args:
            playbook_id ([type]): Defaults to None. Id of playbook associated with this HUD pin
            pin_type (string): Type of pin to create (determins how it is displayed. Defaults to data. Other options are card_small, card_medium, card_large.
            pin_style (string): Color of pin when using the card types. (white, purple, or red)
        
        Returns:
            dict: returns id of new note and whether comment save succesfully (see ``save()`` for example)
        
        Example:
            Pinning a purple card to the container hud for which I already know the container id::

                ph_container.pin_to_container_hud(1052, 'test message 2', '55', pin_type='card_large', pin_style='purple')

        Notes:
            Use this if you have not created a container with ``save()`` and you already know a container id.
        """

        pin_json = {
            'container_id': container_id,
            'message': message,
            'data': pin_data
        }

        if playbook_id:
            pin_json['playbook_id'] = playbook_id
        if pin_type and ph_base._exists_in_data_set(
                'pin type', ph_consts.CONTAINER_PIN_TYPE, pin_type):
            pin_json['pin_type'] = pin_type
        if pin_style and ph_base._exists_in_data_set(
                'pin style', ph_consts.CONTAINER_PIN_STYLE, pin_style):
            pin_json['pin_style'] = pin_style

        response = ph_base._send_request('/rest/container_pin',
                                         'post',
                                         payload=json.dumps(pin_json),
                                         content_type='application/json')

        return cls._format_container_results(response, 'hud pin', container_id)
Beispiel #17
0
    def get_action_status(cls, action_id):
        """Returns status of action.

        This should be used if you want to get the status of an action for which
        you already know the ``action_id``.
        
        Args:
            action_id (int): id of running action.

        Example:
            Get action status::

                ph_action.get_action_status(444) # returns action status
        """

        response = ph_base._send_request('/rest/action_run/' + str(action_id),
                                         'get')

        return (response)
Beispiel #18
0
    def save(self):
        """Saves the new role

        Sets role_id upon successful save
        
        Raises:
            Exception: Exception if fails to save role
        
        Example:
            Creating a new role an saving it::
            
                role = ph_role(
                    'Test Role',
                    'Testing role creation',
                    permissions=[
                        {
                            'name': 'containers',
                            'view': True,
                            'edit': False,
                            'delete': True
                        }
                    ]
                )

                role.save()

        Returns:
            int: id of new role. 
        """

        response = ph_base._send_request(
            '/rest/role',
            'post',
            payload=json.dumps(self.render_dictionary()),
            content_type='application/json'
        )

        if ph_consts.ROLE_SUCCESS_KEY not in response:
            raise Exception(response[ph_consts.ROLE_FAILED_MESSAGE_KEY])
        
        self.role_id = response[ph_consts.ROLE_NEW_ID]

        return self.role_id
Beispiel #19
0
    def get_playbook_status(cls, playbook_run_id):
        """Gets the status of a playbook.
        
        Args:
            playbook_run_id (int): Playbook run id from a running playbook or running playbook.
        
        Returns:
            dict: Returns playbook status.

        Example:
            Get playbook status::

                ph_playbook.get_playbook_status(111)
        """

        response = ph_base._send_request(
            '/rest/playbook_run/' + str(playbook_run_id), 'get')

        return response
Beispiel #20
0
    def save(self):
        if self.phase_id is None:
            raise Exception(
                'Tasks can only be saved if phase ID is set to existing ' +
                'phase id.')

        response = ph_base._send_request('/rest/workflow_task_template',
                                         'post',
                                         payload=json.dumps(
                                             self.render_dictionary()),
                                         content_type='application/json')

        if ph_consts.TASK_SUCCESS_KEY not in response:
            raise Exception('Error trying to save task - ' + self.name + '. ' +
                            response[ph_consts.TASK_FAILED_MESSAGE_KEY])
        elif ph_consts.TASK_NEW_ID in response:
            self.id = response[ph_consts.TASK_NEW_ID]

        return True
Beispiel #21
0
    def add_container_note(cls,
                           container_id,
                           note_title,
                           note_content,
                           phase_id=None):
        """Add a note to a container
        
        Args:
            container_id (int): id of container
            note_title (string): title of note
            note_content (string): content of note

        Keyword Args:
            phase_id (string): Defaults to None. Phase to which this note belongs.
        
        Returns:
            dict: returns id of new note and whether comment save succesfully (see ``save()`` for example)

        Example:
            Saving a note to a container for which I already know the container id::

                ph_container.add_container_note(1052,'test note2', 'test note 2 title', 'test contents 2')

        Notes:
            Use this if you have not created a container with ``save()`` and you already know a container id.
        """

        container_json = {
            'container_id': container_id,
            'title': note_title,
            'content': note_content,
        }

        if phase_id:
            container_json['phase_id'] = phase_id

        response = ph_base._send_request('/rest/container_note',
                                         'post',
                                         payload=json.dumps(container_json),
                                         content_type='application/json')

        return cls._format_container_results(response, 'note', container_id)
Beispiel #22
0
    def save(self):
        """Saves case template
        
        Raises:
            Exception: Raises exception if case failed to be saved.
        
        Returns:
            int: Returns case template id of newly saved case template.
        """

        response = ph_base._send_request('/rest/workflow_template',
                                         'post',
                                         payload=json.dumps(
                                             self.render_dictionary()),
                                         content_type='application/json')

        if ph_consts.CASE_SUCCESS_KEY not in response:
            raise Exception('Error saving case - ' + self.name + '. ' +
                            response[ph_consts.CASE_FAILED_MESSAGE_KEY])
        elif ph_consts.CASE_NEW_ID in response:
            self.id = response[ph_consts.CASE_NEW_ID]

        return True
Beispiel #23
0
    def update_user(cls, user_id, remove_roles=[], add_roles=[]):
        """Update an existing user

        Remove or add roles

        Args:
            user_id (int): id of the user

        Keyword Args:
            remove_roles (list): list of role ids to remove
            add_roles (list): list of role ids to add

        Returns:
            dict: returns update user response json

        Example:
            Update a user with user id of 15::

                ph_user.update_user(user_id=15, remove_roles=[4])

        Notes:
            This should be used if you have not run ``save()`` but already know the user id
        """

        update_json = {
            'add_roles': add_roles,
            'remove_roles': remove_roles
        }

        response = ph_base._send_request(
            '/rest/ph_user/' + str(user_id),
            'post',
            payload=json.dumps(update_json),
            content_type='application/json'
        )

        return response
Beispiel #24
0
    def run(self):
        """Runs the playbook

        After ``run()`` is called, the playbook_run_id attribute is set.
        
        Raises:
            Exception: Raises Exception if playbook fails to run.
        
        Returns:
            [dict]: Returns the response dictionary from the playbook run.
        """

        response = ph_base._send_request('/rest/playbook_run',
                                         'post',
                                         payload=json.dumps(
                                             self.render_dictionary()),
                                         content_type='application/json')

        if ph_consts.PLAYBOOK_RUN_ID not in response:
            raise Exception(response[ph_consts.PLAYBOOK_FAILED_MESSAGE_KEY])

        self.playbook_run_id = response[ph_consts.PLAYBOOK_RUN_ID]

        return response
Beispiel #25
0
    def run(self):
        """Used to run a phantom action.

        After ``run()`` is called the action_id is set on the object.
        
        Raises:
            Exception: If action fails, exception is raised.
        
        Returns:
            [int]: Returns the action run id of the phanton action.
        """

        response = ph_base._send_request('/rest/action_run',
                                         'post',
                                         payload=json.dumps(
                                             self.render_dictionary()),
                                         content_type='application/json')

        if not (response.get(ph_consts.ACTION_SUCCESS_KEY)):
            raise Exception(response[ph_consts.ACTION_FAILED_MESSAGE_KEY])

        self.action_id = response[ph_consts.ACTION_RUN_ID]

        return response
Beispiel #26
0
    def update_list(self,
                    append_data=None,
                    delete_rows=None,
                    update_rows=None):
        """Update an existing list

        Keyword Args:
            append_data (list): Data to append ``[[col1, col2, col3], [col1, col2, col3]]``
            delete_rows (list): List of rows to delete
            update_rows (dict): Dict where keys are row numbers and values are column data in list format.
        
        Raises:
            Exception: Exception if you try to append data,  but the columns in your data don't match the number of columns in the list
            Exception: Exception if you try to delete row that doesn't exist
            Exception: Exception if you try to update a row that doesn't exist or there is a mismatch in column count.
            Exception: Exception if updating the list fails.
        
        Returns:
            bool: True if successfully saved.
        """

        if self.content:
            if append_data and len(self.content[0]) != len(append_data[0]):
                raise Exception(
                    'The data you are trying to add to the list - ' +
                    self.name + ' - does not ' +
                    'have the same number of columns as the list. Append Data Columns - '
                    + str(len(append_data[0])) + ' vs List Data Columns - ' +
                    str(len(self.content[0])))
            if delete_rows and any(
                [row_num > len(self.content) - 1 for row_num in delete_rows]):
                raise Exception(
                    'You are trying to delete a row_number that does not exists in the list - '
                    + self.name + '.')
            if (update_rows and (any([
                    int(row_num) > len(self.content) - 1
                    for row_num in update_rows.keys()
            ]) or any([
                    len(row_data) != len(self.content[0])
                    for row_data in update_rows.values()
            ]))):
                raise Exception(
                    'The data in the rows you are trying to update do no have the same number '
                    + 'of columns as the list - ' + self.name +
                    ' - that you are trying to ' +
                    'update. List Data Columns - ' + str(len(self.content[0])))

        update_json = {}
        if append_data:
            update_json['append_rows'] = append_data
        if delete_rows:
            update_json['delete_rows'] = delete_rows
        if update_rows:
            update_json['update_rows'] = update_rows

        response = ph_base._send_request('/rest/decided_list/' + self.name,
                                         'POST',
                                         payload=json.dumps(update_json),
                                         content_type='application/json')

        if (ph_consts.LIST_SUCCESS_KEY not in response):
            raise Exception('Error updating list with name - ' + self.name +
                            '. ' + response[ph_consts.LIST_FAILED_MESSAGE_KEY])

        return True
Beispiel #27
0
    def delete_case(cls, case_id):
        response = ph_base._send_request(
            '/rest/workflow_template/' + str(case_id), 'delete')

        return response