docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Run the App on local system. Args: commands (dict): A dictionary of the CLI commands. Returns: int: The exit code of the subprocess command.
def run_local(self, commands): process = subprocess.Popen( commands.get('cli_command'), shell=self.shell, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) out, err = process.communicate() # dis...
541,773
Run App in Docker Container. Args: commands (dict): A dictionary of the CLI commands. Returns: int: The exit code of the subprocess command.
def run_docker(self, commands): try: import docker except ImportError: print( '{}{}Could not import docker module (try "pip install docker").'.format( c.Style.BRIGHT, c.Fore.RED ) ) sys.exit(1) ...
541,774
Handle the exit code for the current run. Args: err (str): One or more lines of errors messages.
def run_display_app_errors(self, err): if err is not None and err: for e_ in err.decode('utf-8').split('\n'): print('{}{}{}'.format(c.Style.BRIGHT, c.Fore.RED, e_)) self.log.error('[tcrun] App error: {}'.format(e_))
541,775
Print any App output. Args: out (str): One or more lines of output messages.
def run_display_app_output(self, out): if not self.profile.get('quiet') and not self.args.quiet: print('App Output:') for o in out.decode('utf-8').split('\n'): print(' {}{}{}'.format(c.Style.BRIGHT, c.Fore.CYAN, o)) self.log.debug('[tcrun] App ou...
541,776
Print profile name with programMain. Args: program_main (str): The executable name.
def run_display_profile(self, program_main): install_json = self.profile.get('install_json') output = 'Profile: ' output += '{}{}{}{} '.format( c.Style.BRIGHT, c.Fore.CYAN, self.profile.get('profile_name'), c.Style.RESET_ALL ) output += '[{}{}{}{}'.format( ...
541,778
Handle the exit code for the current run. Args: returncode (int): The return exit code. Raises: RuntimeError: Raise on invalid exit code if halt_on_fail is True. Returns: bool: True if exit code is a valid exit code, else False.
def run_exit_code(self, returncode): exit_status = False self.log.info('[run] Exit Code {}'.format(returncode)) self.reports.increment_total() # increment report execution total valid_exit_codes = self.profile.get('exit_codes', [0]) self.reports.exit_code(returncode) ...
541,779
Validate the program main file exists. Args: program_main (str): The executable name.
def run_validate_program_main(self, program_main): program_language = self.profile.get('install_json').get('programLanguage', 'python').lower() if program_language == 'python' and not os.path.isfile('{}.py'.format(program_main)): print( '{}{}Could not find program ma...
541,780
Stage data in Redis. Args: variable (str): The Redis variable name. data (dict|list|str): The data to store in Redis.
def stage_redis(self, variable, data): if isinstance(data, int): data = str(data) # handle binary if variable.endswith('Binary'): try: data = base64.b64decode(data) except binascii.Error: msg = 'The Binary staging data ...
541,783
Add an attribute to a resource. Args: attribute_type (str): The attribute type (e.g., Description). attribute_value (str): The attribute value. resource (obj): An instance of tcex resource class.
def stage_tc_create_attribute(self, attribute_type, attribute_value, resource): attribute_data = {'type': str(attribute_type), 'value': str(attribute_value)} # handle default description and source if attribute_type in ['Description', 'Source']: attribute_data['displayed'] =...
541,785
Add a security label to a resource. Args: label (str): The security label (must exit in ThreatConnect). resource (obj): An instance of tcex resource class.
def stage_tc_create_security_label(self, label, resource): sl_resource = resource.security_labels(label) sl_resource.http_method = 'POST' sl_response = sl_resource.request() if sl_response.get('status') != 'Success': self.log.warning( '[tcex] Failed a...
541,786
Add a tag to a resource. Args: tag (str): The tag to be added to the resource. resource (obj): An instance of tcex resource class.
def stage_tc_create_tag(self, tag, resource): tag_resource = resource.tags(self.tcex.safetag(tag)) tag_resource.http_method = 'POST' t_response = tag_resource.request() if t_response.get('status') != 'Success': self.log.warning( '[tcex] Failed adding ...
541,787
Add an attribute to a resource. Args: entity1 (str): A Redis variable containing a TCEntity. entity2 (str): A Redis variable containing a TCEntity.
def stage_tc_associations(self, entity1, entity2): # resource 1 entity1 = self.tcex.playbook.read(entity1) entity1_id = entity1.get('id') entity1_owner = entity1.get('ownerName') entity1_type = entity1.get('type') if entity1.get('type') in self.tcex.indicator_typ...
541,788
Stage data in ThreatConnect Platform using batch API. Args: owner (str): The ThreatConnect owner to submit batch job. staging_data (dict): A dict of ThreatConnect batch data.
def stage_tc_batch(self, owner, staging_data): batch = self.tcex.batch(owner) for group in staging_data.get('group') or []: # add to redis variable = group.pop('variable', None) path = group.pop('path', None) data = self.path_data(group, path) ...
541,789
Create an xid for a batch job. Args: xid_type (str): [description] xid_value (str): [description] owner (str): [description] Returns: [type]: [description]
def stage_tc_batch_xid(xid_type, xid_value, owner): xid_string = '{}-{}-{}'.format(xid_type, xid_value, owner) hash_object = hashlib.sha256(xid_string.encode('utf-8')) return hash_object.hexdigest()
541,790
Convert JSON data to TCEntity. Args: indicator_data (str): [description] Returns: [type]: [description]
def stage_tc_indicator_entity(self, indicator_data): path = '@.{value: summary, ' path += 'type: type, ' path += 'ownerName: ownerName, ' path += 'confidence: confidence || `0`, ' path += 'rating: rating || `0`}' return self.path_data(indicator_data, path)
541,791
Validate data in Redis. Args: db_data (str): The data store in Redis. user_data (str): The user provided data. oper (str): The comparison operator. Returns: bool: True if the data passed validation.
def validate_redis(self, db_data, user_data, oper): passed = True # convert any int to string since playbooks don't support int values if isinstance(db_data, int): db_data = str(db_data) if isinstance(user_data, int): user_data = str(user_data) #...
541,793
Format the validation log output to be easier to read. Args: passed (bool): The results of the validation test. db_data (str): The data store in Redis. user_data (str): The user provided data. oper (str): The comparison operator. Raises: Runt...
def validate_log_output(self, passed, db_data, user_data, oper): truncate = self.args.truncate if db_data is not None and passed: if isinstance(db_data, (string_types)) and len(db_data) > truncate: db_data = db_data[:truncate] elif isinstance(db_data, (li...
541,794
Add CLI Arg formatted specifically for Python. Args: key (string): The CLI Args key (e.g., --name). value (string): The CLI Args value (e.g., bob). mask (boolean, default:False): Indicates whether no mask value.
def _add_arg_python(self, key, value=None, mask=False): self._data[key] = value if not value: # both false boolean values (flags) and empty values should not be added. pass elif value is True: # true boolean values are flags and should not contain a v...
541,796
Add CLI Arg formatted specifically for Java. Args: key (string): The CLI Args key (e.g., --name). value (string): The CLI Args value (e.g., bob). mask (boolean, default:False): Indicates whether no mask value.
def _add_arg_java(self, key, value, mask=False): if isinstance(value, bool): value = int(value) self._data[key] = value self._args.append('{}{}={}'.format('-D', key, value)) self._args_quoted.append(self.quote('{}{}={}'.format('-D', key, value))) if mask: ...
541,797
Add CLI Arg for the correct language. Args: key (string): The CLI Args key (e.g., --name). value (string): The CLI Args value (e.g., bob). mask (boolean, default:False): Indicates whether no mask value.
def _add_arg(self, key, value, mask=False): if self.lang == 'python': self._add_arg_python(key, value, mask) elif self.lang == 'java': self._add_arg_java(key, value, mask)
541,798
Add CLI Arg to lists value. Args: key (string): The CLI Args key (e.g., --name). value (string): The CLI Args value (e.g., bob).
def add(self, key, value): if isinstance(value, list): # TODO: support env vars in list w/masked values for val in value: self._add_arg_python(key, val) elif isinstance(value, dict): err = 'Dictionary types are not currently supported for fiel...
541,799
Load provided CLI Args. Args: args (dict): Dictionary of args in key/value format.
def load(self, profile_args): for key, value in profile_args.items(): self.add(key, value)
541,801
Initialize Class Properties. Args: group_type (str): The ThreatConnect define Group type. name (str): The name for this Group. xid (str, kwargs): The external id for this Group.
def __init__(self, group_type, name, **kwargs): self._utils = TcExUtils() self._name = name self._type = group_type self._group_data = {'name': name, 'type': group_type} # process all kwargs and update metadata field names for arg, value in kwargs.items(): ...
541,810
Add a file for Document and Report types. Example:: document = tcex.batch.group('Document', 'My Document') document.add_file('my_file.txt', 'my contents') Args: filename (str): The name of the file. file_content (bytes|method|str): The contents of the f...
def add_file(self, filename, file_content): self._group_data['fileName'] = filename self._file_content = file_content
541,811
Add custom field to Group object. .. note:: The key must be the exact name required by the batch schema. Example:: document = tcex.batch.group('Document', 'My Document') document.add_key_value('fileName', 'something.pdf') Args: key (str): The field key to ...
def add_key_value(self, key, value): key = self._metadata_map.get(key, key) if key in ['dateAdded', 'eventDate', 'firstSeen', 'publishDate']: self._group_data[key] = self._utils.format_datetime( value, date_format='%Y-%m-%dT%H:%M:%SZ' ) elif key =...
541,812
Return instance of SecurityLabel. .. note:: The provided security label will be create if it doesn't exist. If the security label already exists nothing will be changed. Args: name (str): The value for this security label. description (str): A description for this s...
def security_label(self, name, description=None, color=None): label = SecurityLabel(name, description, color) for label_data in self._labels: if label_data.name == name: label = label_data break else: self._labels.append(label) ...
541,816
Return instance of Tag. Args: name (str): The value for this tag. formatter (method, optional): A method that take a tag value and returns a formatted tag. Returns: obj: An instance of Tag.
def tag(self, name, formatter=None): tag = Tag(name, formatter) for tag_data in self._tags: if tag_data.name == name: tag = tag_data break else: self._tags.append(tag) return tag
541,817
Sets the unique_id provided a json response. Args: json_response:
def _set_unique_id(self, json_response): self.unique_id = ( json_response.get('md5') or json_response.get('sha1') or json_response.get('sha256') or '' )
541,831
Converts the value and adds it as a data field. Args: key: value:
def add_key_value(self, key, value): key = self._metadata_map.get(key, key) if key in ['dateAdded', 'lastModified']: self._data[key] = self._utils.format_datetime(value, date_format='%Y-%m-%dT%H:%M:%SZ') elif key == 'confidence': self._data[key] = int(value) ...
541,834
Updates the Indicators rating Args: value:
def rating(self, value): if not self.can_update(): self._tcex.handle_error(910, [self.type]) request_data = {'rating': value} return self.tc_requests.update( self.api_type, self.api_sub_type, self.unique_id, request_data, owner=self.owner )
541,835
Adds a Indicator Observation Args: count: date_observed:
def add_observers(self, count, date_observed): if not self.can_update(): self._tcex.handle_error(910, [self.type]) data = { 'count': count, 'dataObserved': self._utils.format_datetime( date_observed, date_format='%Y-%m-%dT%H:%M:%SZ' ...
541,836
Gets the indicators deleted. Args: params: filters: deleted_since: Date since its been deleted
def deleted(self, deleted_since, filters=None, params=None): return self.tc_requests.deleted( self.api_type, self.api_sub_type, deleted_since, owner=self.owner, filters=filters, params=params, )
541,837
Constructs the summary given va1, va2, val3 Args: val1: val2: val3: Returns:
def build_summary(val1=None, val2=None, val3=None): summary = [] if val1 is not None: summary.append(val1) if val2 is not None: summary.append(val2) if val3 is not None: summary.append(val3) if not summary: return None ...
541,838
Updates the security labels name. Args: name:
def name(self, name): self._data['name'] = name request = self._base_request request['name'] = name return self._tc_requests.update(request, owner=self.owner)
541,841
Updates the security labels color. Args: color:
def color(self, color): self._data['color'] = color request = self._base_request request['color'] = color return self._tc_requests.update(request, owner=self.owner)
541,842
Updates the security labels description. Args: description:
def description(self, description): self._data['description'] = description request = self._base_request request['description'] = description return self._tc_requests.update(request, owner=self.owner)
541,843
Updates the security labels date_added Args: date_added: Converted to %Y-%m-%dT%H:%M:%SZ date format
def date_added(self, date_added): date_added = self._utils.format_datetime(date_added, date_format='%Y-%m-%dT%H:%M:%SZ') self._data['dateAdded'] = date_added request = self._base_request request['dateAdded'] = date_added return self._tc_requests.update(request, owner=se...
541,844
Updates the campaign with the new first_seen date. Args: first_seen: The first_seen date. Converted to %Y-%m-%dT%H:%M:%SZ date format Returns:
def first_seen(self, first_seen): if not self.can_update(): self._tcex.handle_error(910, [self.type]) first_seen = self._utils.format_datetime(first_seen, date_format='%Y-%m-%dT%H:%M:%SZ') self._data['firstSeen'] = first_seen request = {'firstSeen': first_seen} ...
541,845
Initialize the Class properties. Args: tcex (obj): An instance of TcEx object.
def __init__(self, tcex): self._tcex = tcex self._is_organization = False self._notification_type = None self._recipients = None self._priority = 'Low'
541,848
Set vars for the passed in data. Used for org notification. .. code-block:: javascript { "notificationType": notification_type, "priority": priority "isOrganization": true } Args: notification_type (str): The notifica...
def org(self, notification_type, priority='Low'): self._notification_type = notification_type self._recipients = None self._priority = priority self._is_organization = True
541,850
Send our message Args: message (str): The message to be sent. Returns: requests.models.Response: The response from the request.
def send(self, message): body = { 'notificationType': self._notification_type, 'priority': self._priority, 'isOrganization': self._is_organization, 'message': message, } if self._recipients: body['recipients'] = self._recipien...
541,851
Add an asset to the adversary Args: asset_type: (str) Either PHONE, HANDLER, or URL asset_name: (str) the value for the asset Returns:
def add_asset(self, asset_type, asset_name): if not self.can_update(): self._tcex.handle_error(910, [self.type]) if asset_type == 'PHONE': return self.tc_requests.add_adversary_phone_asset( self.api_type, self.api_sub_type, self.unique_id, asset_name ...
541,852
Gets the asset with the provided id Args: asset_id: The id of the asset to be retrieved asset_type: (str) Either PHONE, HANDLER, or URL action: Returns:
def asset(self, asset_id, asset_type, action='GET'): if not self.can_update(): self._tcex.handle_error(910, [self.type]) if asset_type == 'PHONE': return self.tc_requests.adversary_phone_asset( self.api_type, self.api_sub_type, self.unique_id, asset_id, ...
541,853
Retrieves all of the assets of a given asset_type Args: asset_type: (str) Either None, PHONE, HANDLER, or URL Returns:
def assets(self, asset_type=None): if not self.can_update(): self._tcex.handle_error(910, [self.type]) if not asset_type: return self.tc_requests.adversary_assets( self.api_type, self.api_sub_type, self.unique_id ) if asset_type == 'P...
541,854
Delete the asset with the provided asset_id. Args: asset_id: The id of the asset. asset_type: The asset type. Returns:
def delete_asset(self, asset_id, asset_type): return self.asset(asset_id, asset_type=asset_type, action='DELETE')
541,855
Initialize Class properties. Args: _args (namespace): The argparser args Namespace.
def __init__(self, _args): super(TcExLib, self).__init__(_args) # properties self.latest_version = None self.lib_directory = 'lib_{}.{}.{}'.format( sys.version_info.major, sys.version_info.minor, sys.version_info.micro ) self.requirements_file = 'req...
541,856
Build the pip command for installing dependencies. Args: python_executable (str): The fully qualified path of the Python executable. lib_dir_fq (str): The fully qualified path of the lib directory. Returns: list: The Python pip command with all required args.
def _build_command(self, python_executable, lib_dir_fq, proxy_enabled): exe_command = [ os.path.expanduser(python_executable), '-m', 'pip', 'install', '-r', self.requirements_file, '--ignore-installed', '--q...
541,857
Initialize Class Properties. Args: tcex (obj): An instance of TcEx object. owner (str): The ThreatConnect owner for Batch action. action (str, default:Create): Action for the batch job ['Create', 'Delete']. attribute_write_type (str, default:Replace): Write type ...
def __init__( self, tcex, owner, action=None, attribute_write_type=None, halt_on_error=True, playbook_triggers_enabled=None, ): self.tcex = tcex self._action = action or 'Create' self._attribute_write_type = attribute_write_typ...
541,863
Dynamically generate custom Indicator methods. Args: name (str): The name of the method. custom_class (object): The class to add. value_count (int): The number of value parameters to support.
def _gen_indicator_method(self, name, custom_class, value_count): method_name = name.replace(' ', '_').lower() # Add Method for each Custom Indicator class def method_1(value1, xid, **kwargs): # pylint: disable=W0641 indicator_obj = custom_class(value1, xid, *...
541,865
Return previously stored group or new group. Args: group_data (dict|obj): An Group dict or instance of Group object. Returns: dict|obj: The new Group dict/object or the previously stored dict/object.
def _group(self, group_data): if isinstance(group_data, dict): # get xid from dict xid = group_data.get('xid') else: # get xid from object xid = group_data.xid if self.groups.get(xid) is not None: # return existing group from ...
541,866
Return previously stored indicator or new indicator. Args: indicator_data (dict|obj): An Indicator dict or instance of Indicator object. Returns: dict|obj: The new Indicator dict/object or the previously stored dict/object.
def _indicator(self, indicator_data): if isinstance(indicator_data, dict): # get xid from dict xid = indicator_data.get('xid') else: # get xid from object xid = indicator_data.xid if self.indicators.get(xid) is not None: # ret...
541,867
Add Adversary data to Batch object. Args: name (str): The name for this Group. date_added (str, kwargs): The date timestamp the Indicator was created. xid (str, kwargs): The external id for this Group. Returns: obj: An instance of Adversary.
def adversary(self, name, **kwargs): group_obj = Adversary(name, **kwargs) return self._group(group_obj)
541,870
Add Campaign data to Batch object. Args: name (str): The name for this Group. date_added (str, kwargs): The date timestamp the Indicator was created. first_seen (str, kwargs): The first seen datetime expression for this Group. xid (str, kwargs): The external id f...
def campaign(self, name, **kwargs): group_obj = Campaign(name, **kwargs) return self._group(group_obj)
541,872
Return group dict array following all associations. Args: xid (str): The xid of the group to retrieve associations. Returns: list: A list of group dicts.
def data_group_association(self, xid): groups = [] group_data = None # get group data from one of the arrays if self.groups.get(xid) is not None: group_data = self.groups.get(xid) del self.groups[xid] elif self.groups_shelf.get(xid) is not None: ...
541,876
Return dict representation of group data. Args: group_data (dict|obj): The group data dict or object. Returns: dict: The group data in dict format.
def data_group_type(self, group_data): if isinstance(group_data, dict): # process file content file_content = group_data.pop('fileContent', None) if file_content is not None: self._files[group_data.get('xid')] = { 'fileContent': fi...
541,877
Process Group data. Args: groups (list): The list of groups to process. Returns: list: A list of groups including associations
def data_groups(self, groups, entity_count): data = [] # process group objects for xid in groups.keys(): # get association from group data assoc_group_data = self.data_group_association(xid) data += assoc_group_data entity_count += len(ass...
541,878
Add Event data to Batch object. Args: name (str): The name for this Group. date_added (str, kwargs): The date timestamp the Indicator was created. event_date (str, kwargs): The event datetime expression for this Group. status (str, kwargs): The status for this Gr...
def event(self, name, **kwargs): group_obj = Event(name, **kwargs) return self._group(group_obj)
541,885
Generate xid from provided identifiers. .. Important:: If no identifier is provided a unique xid will be returned, but it will not be reproducible. If a list of identifiers are provided they must be in the same order to generate a reproducible xid. Args...
def generate_xid(identifier=None): if identifier is None: identifier = str(uuid.uuid4()) elif isinstance(identifier, list): identifier = '-'.join([str(i) for i in identifier]) identifier = hashlib.sha256(identifier.encode('utf-8')).hexdigest() return ...
541,887
Add Group data to Batch object. Args: group_type (str): The ThreatConnect define Group type. name (str): The name for this Group. date_added (str, kwargs): The date timestamp the Indicator was created. xid (str, kwargs): The external id for this Group. R...
def group(self, group_type, name, **kwargs): group_obj = Group(group_type, name, **kwargs) return self._group(group_obj)
541,888
Add Incident data to Batch object. Args: name (str): The name for this Group. date_added (str, kwargs): The date timestamp the Indicator was created. event_date (str, kwargs): The event datetime expression for this Group. status (str, kwargs): The status for this...
def incident(self, name, **kwargs): group_obj = Incident(name, **kwargs) return self._group(group_obj)
541,892
Add Intrusion Set data to Batch object. Args: name (str): The name for this Group. date_added (str, kwargs): The date timestamp the Indicator was created. xid (str, kwargs): The external id for this Group. Returns: obj: An instance of IntrusionSet.
def intrusion_set(self, name, **kwargs): group_obj = IntrusionSet(name, **kwargs) return self._group(group_obj)
541,896
Save group|indicator dict or object to shelve. Best effort to save group/indicator data to disk. If for any reason the save fails the data will still be accessible from list in memory. Args: resource (dict|obj): The Group or Indicator dict or object.
def save(self, resource): resource_type = None xid = None if isinstance(resource, dict): resource_type = resource.get('type') xid = resource.get('xid') else: resource_type = resource.type xid = resource.xid if resource_typ...
541,901
Submit Batch request to ThreatConnect API. Args: batch_id (string): The batch id of the current job.
def submit_data(self, batch_id, halt_on_error=True): # check global setting for override if self.halt_on_batch_error is not None: halt_on_error = self.halt_on_batch_error content = self.data # store the length of the batch data to use for poll interval calculations ...
541,909
Submit Files for Documents and Reports to ThreatConnect API. Critical Errors * There is insufficient document storage allocated to this account. Args: halt_on_error (bool, default:True): If True any exception will raise an error. Returns: dict: The upload stat...
def submit_files(self, halt_on_error=True): # check global setting for override if self.halt_on_file_error is not None: halt_on_error = self.halt_on_file_error upload_status = [] for xid, content_data in self._files.items(): del self._files[xid] # win o...
541,910
Add Threat data to Batch object Args: name (str): The name for this Group. date_added (str, kwargs): The date timestamp the Indicator was created. xid (str, kwargs): The external id for this Group. Returns: obj: An instance of Threat.
def threat(self, name, **kwargs): group_obj = Threat(name, **kwargs) return self._group(group_obj)
541,913
Initialize Class Properties. Args: tcex: main_type: api_type: sub_type: api_entity:
def __init__(self, tcex, main_type, api_type, sub_type, api_entity, owner): self._tcex = tcex self._data = {} self._owner = owner self._type = main_type self._api_sub_type = sub_type self._api_type = api_type self._unique_id = None self._api_enti...
541,918
Gets the Indicator/Group/Victim or Security Labels Args: filters: owner: params: parameters to pass in to get the objects Yields: A Indicator/Group/Victim json
def many(self, filters=None, params=None): for i in self.tc_requests.many( self.api_type, self.api_sub_type, self.api_entity, owner=self.owner, filters=filters, params=params, ): yield i
541,922
Gets the Indicator/Group/Victim or Security Labels Args: filters: owner: result_limit: result_start: params: parameters to pass in to get the objects Returns:
def request(self, result_limit, result_start, filters=None, params=None): return self.tc_requests.request( self.api_type, self.api_sub_type, result_limit, result_start, owner=self.owner, filters=filters, params=params, ...
541,923
Adds a tag to a Indicator/Group/Victim/Security Label Args: params: action: name: The name of the tag
def tag(self, name, action='ADD', params=None): if not name: self._tcex.handle_error(925, ['name', 'tag', 'name', 'name', name]) if not self.can_update(): self._tcex.handle_error(910, [self.type]) if action in ['GET', 'ADD', 'DELETE']: return self.t...
541,924
Gets a tag from a Indicator/Group/Victim/Security Label Args: name: The name of the tag params:
def get_tag(self, name, params=None): return self.tag(name, action='GET', params=params)
541,925
Adds a Security Label to a Indicator/Group or Victim Args: params: label: The name of the Security Label action:
def label(self, label, action='ADD', params=None): if params is None: params = {} if not label: self._tcex.handle_error(925, ['label', 'Security Label', 'label', 'label', label]) if not self.can_update(): self._tcex.handle_error(910, [self.type]) ...
541,927
Gets a security label from a Indicator/Group/Victim Args: label: The name of the Security Label params:
def get_label(self, label, params=None): return self.label(label, action='GET', params=params)
541,928
Gets the indicator association from a Indicator/Group/Victim Args: indicator_type: api_entity: api_branch: params: Returns:
def indicator_associations_types( self, indicator_type, api_entity=None, api_branch=None, params=None ): if params is None: params = {} if not self.can_update(): self._tcex.handle_error(910, [self.type]) target = self._tcex.ti.indicator(indicator_typ...
541,932
Gets the group association from a Indicator/Group/Victim Args: group_type: api_entity: api_branch: params: Returns:
def group_associations_types(self, group_type, api_entity=None, api_branch=None, params=None): if params is None: params = {} if not self.can_update(): self._tcex.handle_error(910, [self.type]) target = self._tcex.ti.group(group_type) for gat in self.tc...
541,933
Deletes a association from a Indicator/Group/Victim Args: target: api_type: api_sub_type: unique_id: Returns:
def delete_association(self, target, api_type=None, api_sub_type=None, unique_id=None): api_type = api_type or target.api_type api_sub_type = api_sub_type or target.api_sub_type unique_id = unique_id or target.unique_id if not self.can_update(): self._tcex.handle_err...
541,934
Gets the attribute from a Group/Indicator or Victim Args: action: params: attribute_id: Returns: attribute json
def attribute(self, attribute_id, action='GET', params=None): if params is None: params = {} if not self.can_update(): self._tcex.handle_error(910, [self.type]) if action == 'GET': return self.tc_requests.get_attribute( self.api_type,...
541,936
Adds a attribute to a Group/Indicator or Victim Args: attribute_type: attribute_value: Returns: attribute json
def add_attribute(self, attribute_type, attribute_value): if not self.can_update(): self._tcex.handle_error(910, [self.type]) return self.tc_requests.add_attribute( self.api_type, self.api_sub_type, self.unique_id, attribute_type, ...
541,937
Gets a security labels from a attribute Args: attribute_id: label: action: params: Returns: Security label json
def attribute_label(self, attribute_id, label, action='GET', params=None): if params is None: params = {} if not self.can_update(): self._tcex.handle_error(910, [self.type]) if action == 'GET': return self.tc_requests.get_attribute_label( ...
541,939
Adds a security labels to a attribute Args: attribute_id: label: Returns: A response json
def add_attribute_label(self, attribute_id, label): if not self.can_update(): self._tcex.handle_error(910, [self.type]) return self.tc_requests.add_attribute_label( self.api_type, self.api_sub_type, self.unique_id, attribute_id, label, owner=self.owner )
541,940
Initialize Class properties. Args: _args (namespace): The argparser args Namespace.
def __init__(self, _args): super(TcExPackage, self).__init__(_args) # properties self.features = ['aotExecutionEnabled', 'secureParams'] # properties self._app_packages = [] self.package_data = {'errors': [], 'updates': [], 'bundle': [], 'package': []} ...
541,941
Write install.json file. Args: install_json (dict): The contents of the install.json file. Returns: dict, bool: The contents of the install.json file and boolean value that is True if an update was made.
def _update_install_json(self, install_json): updated = False # Update features install_json.setdefault('features', []) for feature in self.features: if feature not in install_json.get('features'): install_json['features'].append(feature) ...
541,942
Write install.json file. Some projects have bundles App with multiple install.json files. Typically these files are prefixed with the App name (e.g., MyApp.install.json). Args: filename (str): The install.json file name. install_json (dict): The contents of the install...
def _write_install_json(self, filename, install_json): # TODO: why check if it exists? if os.path.isfile(filename): with open(filename, 'w') as fh: json.dump(install_json, fh, indent=4, sort_keys=True) else: err = 'Could not write file: {}.'.forma...
541,943
Bundle multiple Job or Playbook Apps into a single zip file. Args: bundle_name (str): The output name of the bundle zip file.
def bundle(self, bundle_name): if self.args.bundle or self.tcex_json.get('package', {}).get('bundle', False): if self.tcex_json.get('package', {}).get('bundle_packages') is not None: for bundle in self.tcex_json.get('package', {}).get('bundle_packages') or []: ...
541,944
Bundle multiple Job or Playbook Apps (.tcx files) into a single zip file. Args: bundle_name (str): The output name of the bundle zip file. bundle_apps (list): A list of Apps to include in the bundle.
def bundle_apps(self, bundle_name, bundle_apps): bundle_file = os.path.join( self.app_path, self.args.outdir, '{}-bundle.zip'.format(bundle_name) ) z = zipfile.ZipFile(bundle_file, 'w') for app in bundle_apps: # update package data self.packag...
541,945
Zip the App with tcex extension. Args: app_path (str): The path of the current project. app_name (str): The name of the App. tmp_path (str): The temp output path for the zip.
def zip_file(self, app_path, app_name, tmp_path): # zip build directory zip_file = os.path.join(app_path, self.args.outdir, app_name) zip_file_zip = '{}.zip'.format(zip_file) zip_file_tcx = '{}.tcx'.format(zip_file) shutil.make_archive(zip_file, 'zip', tmp_path, app_name...
541,949
Add a key value pair to payload for this request. Args: key (str): The payload key. val (str): The payload value. append (bool, default:False): Indicate whether the value should be appended or overwritten.
def add_payload(self, key, val, append=False): if append: self._payload.setdefault(key, []).append(val) else: self._payload[key] = val
541,956
Send the HTTP request via Python Requests modules. This method will send the request to the remote endpoint. It will try to handle temporary communications issues by retrying the request automatically. Args: stream (bool): Boolean to enable stream download. Returns: ...
def send(self, stream=False): # # api request (gracefully handle temporary communications issues with the API) # try: response = self.session.request( self._http_method, self._url, auth=self._basic_auth, ...
541,958
Initialize Class Properties. Args: name (str): The name for this Group. subject (str): The subject for this Email. header (str): The header for this Email. body (str): The body for this Email. date_added (str, kwargs): The date timestamp the Indicator...
def __init__(self, tcex, name, to, from_addr, subject, body, header, owner=None, **kwargs): super(Email, self).__init__(tcex, 'emails', name, owner, **kwargs) self.api_entity = 'email' self._data['to'] = to or kwargs.get('to') self._data['from'] = from_addr or kwargs.get('from_a...
541,960
Initialize the Class properties. Args: tcex (object): Instance of TcEx.
def __init__(self, tcex): self.tcex = tcex self._db = None self._out_variables = None self._out_variables_type = None self.output_data = {} # match full variable self._variable_match = re.compile(r'^{}$'.format(self._variable_pattern)) # capture ...
541,966
Check to see if output variable was requested by downstream app. Using the auto generated dictionary of output variables check to see if provided variable was requested by downstream app. Args: variable (string): The variable name, not the full variable. Returns: ...
def check_output_variable(self, variable): match = False if variable in self.out_variables: match = True return match
541,972
Create method of CRUD operation for working with KeyValue DB. This method will automatically determine the variable type and call the appropriate method to write the data. If a non standard type is provided the data will be written as RAW data. Args: key (string): The vari...
def create(self, key, value): data = None if key is not None: key = key.strip() self.tcex.log.debug(u'create variable {}'.format(key)) # bcs - only for debugging or binary might cause issues # self.tcex.log.debug(u'variable value: {}'.format(value...
541,973
Wrapper for Create method of CRUD operation for working with KeyValue DB. This method will automatically check to see if provided variable was requested by a downstream app and if so create the data in the KeyValue DB. Args: key (string): The variable to write to the DB. ...
def create_output(self, key, value, variable_type=None): results = None if key is not None: key = key.strip() key_type = '{}-{}'.format(key, variable_type) if self.out_variables_type.get(key_type) is not None: # variable key-type has been requ...
541,975
Delete method of CRUD operation for all data types. Args: key (string): The variable to write to the DB. Returns: (string): Result of DB write.
def delete(self, key): data = None if key is not None: data = self.db.delete(key.strip()) else: self.tcex.log.warning(u'The key field was None.') return data
541,977
Playbook wrapper on TcEx exit method Playbooks do not support partial failures so we change the exit method from 3 to 1 and call it a partial success instead. Args: code (Optional [integer]): The exit code value for the app.
def exit(self, code=None, msg=None): if code is None: code = self.tcex.exit_code if code == 3: self.tcex.log.info(u'Changing exit code from 3 to 0.') code = 0 # playbooks doesn't support partial failure elif code not in [0, 1]: ...
541,978
Method to parse an input or output variable. **Example Variable**:: #App:1234:output!String Args: variable (string): The variable name to parse. Returns: (dictionary): Result of parsed string.
def parse_variable(self, variable): data = None if variable is not None: variable = variable.strip() if re.match(self._variable_match, variable): var = re.search(self._variable_parse, variable) data = { 'root': var.grou...
541,979
Alias for read method that will read any type (e.g., String, KeyValue) and always return array. Args: key (string): The variable to read from the DB. embedded (boolean): Resolve embedded variables. Returns: (any): Results retrieved from DB
def read_array(self, key, embedded=True): return self.read(key, True, embedded)
541,981
Wrap keyvalue embedded variable in double quotes. Args: data (string): The data with embedded variables. Returns: (string): Results retrieved from DB
def wrap_embedded_keyvalue(self, data): if data is not None: try: data = u'{}'.format(data) # variables = re.findall(self._vars_keyvalue_embedded, u'{}'.format(data)) except UnicodeEncodeError: # variables = re.findall(self._vars_k...
541,985
Create method of CRUD operation for binary data. Args: key (string): The variable to write to the DB. value (any): The data to write to the DB. Returns: (string): Result of DB write.
def create_binary(self, key, value): data = None if key is not None and value is not None: try: # py2 # convert to bytes as required for b64encode # decode bytes for json serialization as required for json dumps data = ...
541,987
Read method of CRUD operation for binary data. Args: key (string): The variable to read from the DB. b64decode (bool): If true the data will be base64 decoded. decode (bool): If true the data will be decoded to a String. Returns: (bytes|string): Results ...
def read_binary(self, key, b64decode=True, decode=False): data = None if key is not None: data = self.db.read(key.strip()) if data is not None: data = json.loads(data) if b64decode: # if requested decode the base64 stri...
541,988
Create method of CRUD operation for binary array data. Args: key (string): The variable to write to the DB. value (any): The data to write to the DB. Returns: (string): Result of DB write.
def create_binary_array(self, key, value): data = None if key is not None and value is not None: value_encoded = [] for v in value: try: # py2 # convert to bytes as required for b64encode # decod...
541,989