idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
27,400 | def http_method ( self , data ) : data = data . upper ( ) if data in [ 'DELETE' , 'GET' , 'POST' , 'PUT' ] : self . _http_method = data # set content type for commit methods (best guess) if self . _headers . get ( 'Content-Type' ) is None and data in [ 'POST' , 'PUT' ] : self . add_header ( 'Content-Type' , 'application/json' ) else : raise AttributeError ( 'Request Object Error: {} is not a valid HTTP method.' . format ( data ) ) | The HTTP method for this request . | 132 | 7 |
27,401 | 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 , data = self . _body , files = self . _files , headers = self . _headers , params = self . _payload , stream = stream , timeout = self . _timeout , ) except Exception as e : err = 'Failed making HTTP request ({}).' . format ( e ) raise RuntimeError ( err ) # self.tcex.log.info(u'URL ({}): {}'.format(self._http_method, response.url)) self . tcex . log . info ( u'Status Code: {}' . format ( response . status_code ) ) return response | Send the HTTP request via Python Requests modules . | 187 | 10 |
27,402 | def run ( self ) : # read inputs indent = int ( self . tcex . playbook . read ( self . args . indent ) ) json_data = self . tcex . playbook . read ( self . args . json_data ) # get the playbook variable type json_data_type = self . tcex . playbook . variable_type ( self . args . json_data ) # convert string input to dict if json_data_type in [ 'String' ] : json_data = json . loads ( json_data ) # generate the new "pretty" json (this will be used as an option variable) try : self . pretty_json = json . dumps ( json_data , indent = indent , sort_keys = self . args . sort_keys ) except Exception : self . tcex . exit ( 1 , 'Failed parsing JSON data.' ) # set the App exit message self . exit_message = 'JSON prettified.' | Run the App main logic . | 203 | 6 |
27,403 | def _parse_out_variable ( self ) : self . _out_variables = { } self . _out_variables_type = { } if self . tcex . default_args . tc_playbook_out_variables : variables = self . tcex . default_args . tc_playbook_out_variables . strip ( ) for o in variables . split ( ',' ) : # parse the variable to get individual parts parsed_key = self . parse_variable ( o ) variable_name = parsed_key [ 'name' ] variable_type = parsed_key [ 'type' ] # store the variables in dict by name (e.g. "status_code") self . _out_variables [ variable_name ] = { 'variable' : o } # store the variables in dict by name-type (e.g. "status_code-String") vt_key = '{}-{}' . format ( variable_name , variable_type ) self . _out_variables_type [ vt_key ] = { 'variable' : o } | Internal method to parse the tc_playbook_out_variable arg . | 240 | 15 |
27,404 | def _variable_pattern ( self ) : variable_pattern = r'#([A-Za-z]+)' # match literal (#App) at beginning of String variable_pattern += r':([\d]+)' # app id (:7979) variable_pattern += r':([A-Za-z0-9_\.\-\[\]]+)' # variable name (:variable_name) variable_pattern += r'!(StringArray|BinaryArray|KeyValueArray' # variable type (array) variable_pattern += r'|TCEntityArray|TCEnhancedEntityArray' # variable type (array) variable_pattern += r'|String|Binary|KeyValue|TCEntity|TCEnhancedEntity' # variable type variable_pattern += r'|(?:(?!String)(?!Binary)(?!KeyValue)' # non matching for custom variable_pattern += r'(?!TCEntity)(?!TCEnhancedEntity)' # non matching for custom variable_pattern += r'[A-Za-z0-9_-]+))' # variable type (custom) return variable_pattern | Regex pattern to match and parse a playbook variable . | 239 | 11 |
27,405 | def add_output ( self , key , value , variable_type ) : index = '{}-{}' . format ( key , variable_type ) self . output_data . setdefault ( index , { } ) if value is None : return if variable_type in [ 'String' , 'Binary' , 'KeyValue' , 'TCEntity' , 'TCEnhancedEntity' ] : self . output_data [ index ] = { 'key' : key , 'type' : variable_type , 'value' : value } elif variable_type in [ 'StringArray' , 'BinaryArray' , 'KeyValueArray' , 'TCEntityArray' , 'TCEnhancedEntityArray' , ] : self . output_data [ index ] . setdefault ( 'key' , key ) self . output_data [ index ] . setdefault ( 'type' , variable_type ) if isinstance ( value , list ) : self . output_data [ index ] . setdefault ( 'value' , [ ] ) . extend ( value ) else : self . output_data [ index ] . setdefault ( 'value' , [ ] ) . append ( value ) | Dynamically add output to output_data dictionary to be written to DB later . | 252 | 17 |
27,406 | def aot_blpop ( self ) : # pylint: disable=R1710 if self . tcex . default_args . tc_playbook_db_type == 'Redis' : res = None try : self . tcex . log . info ( 'Blocking for AOT message.' ) msg_data = self . db . blpop ( self . tcex . default_args . tc_action_channel , timeout = self . tcex . default_args . tc_terminate_seconds , ) if msg_data is None : self . tcex . exit ( 0 , 'AOT subscription timeout reached.' ) msg_data = json . loads ( msg_data [ 1 ] ) msg_type = msg_data . get ( 'type' , 'terminate' ) if msg_type == 'execute' : res = msg_data . get ( 'params' , { } ) elif msg_type == 'terminate' : self . tcex . exit ( 0 , 'Received AOT terminate message.' ) else : self . tcex . log . warn ( 'Unsupported AOT message type: ({}).' . format ( msg_type ) ) res = self . aot_blpop ( ) except Exception as e : self . tcex . exit ( 1 , 'Exception during AOT subscription ({}).' . format ( e ) ) return res | Subscribe to AOT action channel . | 305 | 7 |
27,407 | def aot_rpush ( self , exit_code ) : if self . tcex . default_args . tc_playbook_db_type == 'Redis' : try : self . db . rpush ( self . tcex . default_args . tc_exit_channel , exit_code ) except Exception as e : self . tcex . exit ( 1 , 'Exception during AOT exit push ({}).' . format ( e ) ) | Push message to AOT action channel . | 100 | 8 |
27,408 | def check_output_variable ( self , variable ) : match = False if variable in self . out_variables : match = True return match | Check to see if output variable was requested by downstream app . | 30 | 12 |
27,409 | 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)) parsed_key = self . parse_variable ( key . strip ( ) ) variable_type = parsed_key [ 'type' ] if variable_type in self . read_data_types : data = self . create_data_types [ variable_type ] ( key , value ) else : data = self . create_raw ( key , value ) return data | Create method of CRUD operation for working with KeyValue DB . | 158 | 13 |
27,410 | def create_data_types ( self ) : return { 'Binary' : self . create_binary , 'BinaryArray' : self . create_binary_array , 'KeyValue' : self . create_key_value , 'KeyValueArray' : self . create_key_value_array , 'String' : self . create_string , 'StringArray' : self . create_string_array , 'TCEntity' : self . create_tc_entity , 'TCEntityArray' : self . create_tc_entity_array , } | Map of standard playbook variable types to create method . | 119 | 10 |
27,411 | 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 requested v = self . out_variables_type . get ( key_type ) self . tcex . log . info ( u'Variable {} was requested by downstream app.' . format ( v . get ( 'variable' ) ) ) if value is not None : results = self . create ( v . get ( 'variable' ) , value ) else : self . tcex . log . info ( u'Variable {} has a none value and will not be written.' . format ( key ) ) elif self . out_variables . get ( key ) is not None and variable_type is None : # variable key has been requested v = self . out_variables . get ( key ) self . tcex . log . info ( u'Variable {} was requested by downstream app.' . format ( v . get ( 'variable' ) ) ) if value is not None : results = self . create ( v . get ( 'variable' ) , value ) else : self . tcex . log . info ( u'Variable {} has a none value and will not be written.' . format ( v . get ( 'variable' ) ) ) else : var_value = key if variable_type is not None : var_value = key_type self . tcex . log . info ( u'Variable {} was NOT requested by downstream app.' . format ( var_value ) ) return results | Wrapper for Create method of CRUD operation for working with KeyValue DB . | 377 | 16 |
27,412 | def db ( self ) : if self . _db is None : if self . tcex . default_args . tc_playbook_db_type == 'Redis' : from . tcex_redis import TcExRedis self . _db = TcExRedis ( self . tcex . default_args . tc_playbook_db_path , self . tcex . default_args . tc_playbook_db_port , self . tcex . default_args . tc_playbook_db_context , ) elif self . tcex . default_args . tc_playbook_db_type == 'TCKeyValueAPI' : from . tcex_key_value import TcExKeyValue self . _db = TcExKeyValue ( self . tcex ) else : err = u'Invalid DB Type: ({})' . format ( self . tcex . default_args . tc_playbook_db_type ) raise RuntimeError ( err ) return self . _db | Return the correct KV store for this execution . | 228 | 10 |
27,413 | 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 | Delete method of CRUD operation for all data types . | 54 | 11 |
27,414 | 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 ] : code = 1 self . tcex . exit ( code , msg ) | Playbook wrapper on TcEx exit method | 93 | 9 |
27,415 | 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 . group ( 0 ) , 'job_id' : var . group ( 2 ) , 'name' : var . group ( 3 ) , 'type' : var . group ( 4 ) , } return data | Method to parse an input or output variable . | 108 | 9 |
27,416 | def read ( self , key , array = False , embedded = True ) : self . tcex . log . debug ( 'read variable {}' . format ( key ) ) # if a non-variable value is passed it should be the default data = key if key is not None : key = key . strip ( ) key_type = self . variable_type ( key ) if re . match ( self . _variable_match , key ) : if key_type in self . read_data_types : # handle types with embedded variable if key_type in [ 'Binary' , 'BinaryArray' ] : data = self . read_data_types [ key_type ] ( key ) else : data = self . read_data_types [ key_type ] ( key , embedded ) else : data = self . read_raw ( key ) else : if key_type == 'String' : # replace "\s" with a space only for user input. # using '\\s' will prevent replacement. data = re . sub ( r'(?<!\\)\\s' , ' ' , data ) data = re . sub ( r'\\\\s' , '\\s' , data ) if embedded : # check for any embedded variables data = self . read_embedded ( data , key_type ) # return data as a list if array and not isinstance ( data , list ) : if data is not None : data = [ data ] else : # Adding none value to list breaks App logic. It's better to not request Array # and build array externally if None values are required. data = [ ] # self.tcex.log.debug(u'read data {}'.format(self.tcex.s(data))) return data | Read method of CRUD operation for working with KeyValue DB . | 375 | 13 |
27,417 | def read_data_types ( self ) : return { 'Binary' : self . read_binary , 'BinaryArray' : self . read_binary_array , 'KeyValue' : self . read_key_value , 'KeyValueArray' : self . read_key_value_array , 'String' : self . read_string , 'StringArray' : self . read_string_array , 'TCEntity' : self . read_tc_entity , 'TCEntityArray' : self . read_tc_entity_array , } | Map of standard playbook variable types to read method . | 119 | 10 |
27,418 | def read_embedded ( self , data , parent_var_type ) : if data is None : return data # iterate all matching variables for var in ( v . group ( 0 ) for v in re . finditer ( self . _variable_parse , str ( data ) ) ) : self . tcex . log . debug ( 'embedded variable: {}, parent_var_type: {}' . format ( var , parent_var_type ) ) key_type = self . variable_type ( var ) val = self . read ( var ) if val is None : val = '' elif key_type != 'String' : var = r'"?{}"?' . format ( var ) # replace quotes if they exist val = json . dumps ( val ) data = re . sub ( var , val , data ) return data | Read method for mixed variable type . | 178 | 7 |
27,419 | def variable_type ( self , variable ) : var_type = 'String' if variable is not None : variable = variable . strip ( ) # self.tcex.log.info(u'Variable {}'.format(variable)) if re . match ( self . _variable_match , variable ) : var_type = re . search ( self . _variable_parse , variable ) . group ( 4 ) return var_type | Get the Type from the variable string or default to String type . | 91 | 13 |
27,420 | 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_keyvalue_embedded, data) pass variables = [ ] for v in re . finditer ( self . _vars_keyvalue_embedded , data ) : variables . append ( v . group ( 0 ) ) for var in set ( variables ) : # recursion over set to handle duplicates # pull (#App:1441:embedded_string!String) from (": #App:1441:embedded_string!String) variable_string = re . search ( self . _variable_parse , var ) . group ( 0 ) # reformat to replace the correct instance only, handling the case where a variable # is embedded multiple times in the same key value array. data = data . replace ( var , '": "{}"' . format ( variable_string ) ) return data | Wrap keyvalue embedded variable in double quotes . | 249 | 10 |
27,421 | def write_output ( self ) : for data in self . output_data . values ( ) : self . create_output ( data . get ( 'key' ) , data . get ( 'value' ) , data . get ( 'type' ) ) | Write all stored output data to storage . | 54 | 8 |
27,422 | 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 = self . db . create ( key . strip ( ) , json . dumps ( base64 . b64encode ( bytes ( value ) ) . decode ( 'utf-8' ) ) ) except TypeError : # py3 # set encoding on string and convert to bytes as required for b64encode # decode bytes for json serialization as required for json dumps data = self . db . create ( key . strip ( ) , json . dumps ( base64 . b64encode ( bytes ( value , 'utf-8' ) ) . decode ( 'utf-8' ) ) ) else : self . tcex . log . warning ( u'The key or value field was None.' ) return data | Create method of CRUD operation for binary data . | 204 | 10 |
27,423 | 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 string data = base64 . b64decode ( data ) if decode : try : # if requested decode bytes to a string data = data . decode ( 'utf-8' ) except UnicodeDecodeError : # for data written an upstream java App data = data . decode ( 'latin-1' ) else : self . tcex . log . warning ( u'The key field was None.' ) return data | Read method of CRUD operation for binary data . | 159 | 10 |
27,424 | 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 # decode bytes for json serialization as required for json dumps value_encoded . append ( base64 . b64encode ( bytes ( v ) ) . decode ( 'utf-8' ) ) except TypeError : # py3 # set encoding on string and convert to bytes as required for b64encode # decode bytes for json serialization as required for json dumps value_encoded . append ( base64 . b64encode ( bytes ( v , 'utf-8' ) ) . decode ( 'utf-8' ) ) data = self . db . create ( key . strip ( ) , json . dumps ( value_encoded ) ) else : self . tcex . log . warning ( u'The key or value field was None.' ) return data | Create method of CRUD operation for binary array data . | 218 | 11 |
27,425 | def read_binary_array ( 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_decoded = [ ] for d in json . loads ( data , object_pairs_hook = OrderedDict ) : if b64decode : # if requested decode the base64 string dd = base64 . b64decode ( d ) if decode : # if requested decode bytes to a string try : dd = dd . decode ( 'utf-8' ) except UnicodeDecodeError : # for data written an upstream java App dd = dd . decode ( 'latin-1' ) data_decoded . append ( dd ) else : # for validation in tcrun it's easier to validate the base64 data data_decoded . append ( d ) data = data_decoded else : self . tcex . log . warning ( u'The key field was None.' ) return data | Read method of CRUD operation for binary array data . | 223 | 11 |
27,426 | def create_raw ( self , key , value ) : data = None if key is not None and value is not None : data = self . db . create ( key . strip ( ) , value ) else : self . tcex . log . warning ( u'The key or value field was None.' ) return data | Create method of CRUD operation for raw data . | 67 | 10 |
27,427 | def read_raw ( self , key ) : data = None if key is not None : data = self . db . read ( key . strip ( ) ) else : self . tcex . log . warning ( u'The key field was None.' ) return data | Read method of CRUD operation for raw data . | 56 | 10 |
27,428 | def create_string ( self , key , value ) : data = None if key is not None and value is not None : if isinstance ( value , ( bool , list , int , dict ) ) : # value = str(value) value = u'{}' . format ( value ) # data = self.db.create(key.strip(), str(json.dumps(value))) data = self . db . create ( key . strip ( ) , u'{}' . format ( json . dumps ( value ) ) ) else : self . tcex . log . warning ( u'The key or value field was None.' ) return data | Create method of CRUD operation for string data . | 139 | 10 |
27,429 | def read_string ( self , key , embedded = True ) : data = None if key is not None : key_type = self . variable_type ( key ) data = self . db . read ( key . strip ( ) ) if data is not None : # handle improperly saved string try : data = json . loads ( data ) if embedded : data = self . read_embedded ( data , key_type ) if data is not None : # reverted the previous change where data was encoded due to issues where # it broke the operator method in py3 (e.g. b'1' ne '1'). # data = str(data) data = u'{}' . format ( data ) except ValueError as e : err = u'Failed loading JSON data ({}). Error: ({})' . format ( data , e ) self . tcex . log . error ( err ) else : self . tcex . log . warning ( u'The key field was None.' ) return data | Read method of CRUD operation for string data . | 213 | 10 |
27,430 | def create_string_array ( self , key , value ) : data = None if key is not None and value is not None : if isinstance ( value , ( list ) ) : data = self . db . create ( key . strip ( ) , json . dumps ( value ) ) else : # used to save raw value with embedded variables data = self . db . create ( key . strip ( ) , value ) else : self . tcex . log . warning ( u'The key or value field was None.' ) return data | Create method of CRUD operation for string array data . | 112 | 11 |
27,431 | def read_string_array ( self , key , embedded = True ) : data = None if key is not None : key_type = self . variable_type ( key ) data = self . db . read ( key . strip ( ) ) if embedded : data = self . read_embedded ( data , key_type ) if data is not None : try : data = json . loads ( data , object_pairs_hook = OrderedDict ) except ValueError as e : err = u'Failed loading JSON data ({}). Error: ({})' . format ( data , e ) self . tcex . log . error ( err ) self . tcex . message_tc ( err ) self . tcex . exit ( 1 ) else : self . tcex . log . warning ( u'The key field was None.' ) return data | Read method of CRUD operation for string array data . | 184 | 11 |
27,432 | def create_tc_entity ( self , key , value ) : data = None if key is not None and value is not None : data = self . db . create ( key . strip ( ) , json . dumps ( value ) ) else : self . tcex . log . warning ( u'The key or value field was None.' ) return data | Create method of CRUD operation for TC entity data . | 74 | 11 |
27,433 | def entity_to_bulk ( entities , resource_type_parent ) : if not isinstance ( entities , list ) : entities = [ entities ] bulk_array = [ ] for e in entities : bulk = { 'type' : e . get ( 'type' ) , 'ownerName' : e . get ( 'ownerName' ) } if resource_type_parent in [ 'Group' , 'Task' , 'Victim' ] : bulk [ 'name' ] = e . get ( 'value' ) elif resource_type_parent in [ 'Indicator' ] : bulk [ 'confidence' ] = e . get ( 'confidence' ) bulk [ 'rating' ] = e . get ( 'rating' ) bulk [ 'summary' ] = e . get ( 'value' ) bulk_array . append ( bulk ) if len ( bulk_array ) == 1 : return bulk_array [ 0 ] return bulk_array | Convert Single TC Entity to Bulk format . | 200 | 9 |
27,434 | def indicator_arrays ( tc_entity_array ) : type_dict = { } for ea in tc_entity_array : type_dict . setdefault ( ea [ 'type' ] , [ ] ) . append ( ea [ 'value' ] ) return type_dict | Convert TCEntityArray to Indicator Type dictionary . | 62 | 13 |
27,435 | def json_to_bulk ( tc_data , value_fields , resource_type , resource_type_parent ) : if not isinstance ( tc_data , list ) : tc_data = [ tc_data ] bulk_array = [ ] for d in tc_data : # value values = [ ] for field in value_fields : if d . get ( field ) is not None : values . append ( d . get ( field ) ) del d [ field ] if resource_type_parent in [ 'Group' , 'Task' , 'Victim' ] : d [ 'name' ] = ' : ' . join ( values ) elif resource_type_parent in [ 'Indicator' ] : d [ 'summary' ] = ' : ' . join ( values ) if 'owner' in d : d [ 'ownerName' ] = d [ 'owner' ] [ 'name' ] del d [ 'owner' ] # type if d . get ( 'type' ) is None : d [ 'type' ] = resource_type bulk_array . append ( d ) return bulk_array | Convert ThreatConnect JSON response to a Bulk Format . | 237 | 11 |
27,436 | def json_to_entity ( tc_data , value_fields , resource_type , resource_type_parent ) : if not isinstance ( tc_data , list ) : tc_data = [ tc_data ] entity_array = [ ] for d in tc_data : entity = { 'id' : d . get ( 'id' ) , 'webLink' : d . get ( 'webLink' ) } # value values = [ ] if 'summary' in d : values . append ( d . get ( 'summary' ) ) else : for field in value_fields : if d . get ( field ) is not None : values . append ( d . get ( field ) ) entity [ 'value' ] = ' : ' . join ( values ) # type if d . get ( 'type' ) is not None : entity [ 'type' ] = d . get ( 'type' ) else : entity [ 'type' ] = resource_type if resource_type_parent in [ 'Indicator' ] : entity [ 'confidence' ] = d . get ( 'confidence' ) entity [ 'rating' ] = d . get ( 'rating' ) entity [ 'threatAssessConfidence' ] = d . get ( 'threatAssessConfidence' ) entity [ 'threatAssessRating' ] = d . get ( 'threatAssessRating' ) entity [ 'dateLastModified' ] = d . get ( 'lastModified' ) if resource_type_parent in [ 'Indicator' , 'Group' ] : if 'owner' in d : entity [ 'ownerName' ] = d [ 'owner' ] [ 'name' ] else : entity [ 'ownerName' ] = d . get ( 'ownerName' ) entity [ 'dateAdded' ] = d . get ( 'dateAdded' ) if resource_type_parent in [ 'Victim' ] : entity [ 'ownerName' ] = d . get ( 'org' ) entity_array . append ( entity ) return entity_array | Convert ThreatConnect JSON response to a TCEntityArray . | 435 | 14 |
27,437 | def any_to_datetime ( self , time_input , tz = None ) : # handle timestamp (e.g. 1510686617 or 1510686617.298753) dt_value = self . unix_time_to_datetime ( time_input , tz ) # handle ISO or other formatted date (e.g. 2017-11-08T16:52:42Z, # 2017-11-08T16:52:42.400306+00:00) if dt_value is None : dt_value = self . date_to_datetime ( time_input , tz ) # handle human readable relative time (e.g. 30 days ago, last friday) if dt_value is None : dt_value = self . human_date_to_datetime ( time_input , tz ) # if all attempt to convert fail raise an error if dt_value is None : raise RuntimeError ( 'Could not format input ({}) to datetime string.' . format ( time_input ) ) return dt_value | Return datetime object from multiple formats . | 238 | 8 |
27,438 | def date_to_datetime ( self , time_input , tz = None ) : dt = None try : # dt = parser.parse(time_input, fuzzy_with_tokens=True)[0] dt = parser . parse ( time_input ) # don't convert timezone if dt timezone already in the correct timezone if tz is not None and tz != dt . tzname ( ) : if dt . tzinfo is None : dt = self . _replace_timezone ( dt ) dt = dt . astimezone ( timezone ( tz ) ) except IndexError : pass except TypeError : pass except ValueError : pass return dt | Convert ISO 8601 and other date strings to datetime . datetime type . | 156 | 17 |
27,439 | def format_datetime ( self , time_input , tz = None , date_format = None ) : # handle timestamp (e.g. 1510686617 or 1510686617.298753) dt_value = self . any_to_datetime ( time_input , tz ) # format date if date_format == '%s' : dt_value = calendar . timegm ( dt_value . timetuple ( ) ) elif date_format : dt_value = dt_value . strftime ( date_format ) else : dt_value = dt_value . isoformat ( ) return dt_value | Return timestamp from multiple input formats . | 145 | 7 |
27,440 | def inflect ( self ) : if self . _inflect is None : import inflect self . _inflect = inflect . engine ( ) return self . _inflect | Return instance of inflect . | 37 | 6 |
27,441 | def write_temp_file ( self , content , filename = None , mode = 'w' ) : if filename is None : filename = str ( uuid . uuid4 ( ) ) fqpn = os . path . join ( self . tcex . default_args . tc_temp_path , filename ) with open ( fqpn , mode ) as fh : fh . write ( content ) return fqpn | Write content to a temporary file . | 92 | 7 |
27,442 | def timedelta ( self , time_input1 , time_input2 ) : time_input1 = self . any_to_datetime ( time_input1 ) time_input2 = self . any_to_datetime ( time_input2 ) diff = time_input1 - time_input2 # timedelta delta = relativedelta ( time_input1 , time_input2 ) # relativedelta # totals total_months = ( delta . years * 12 ) + delta . months total_weeks = ( delta . years * 52 ) + ( total_months * 4 ) + delta . weeks total_days = diff . days # handles leap days total_hours = ( total_days * 24 ) + delta . hours total_minutes = ( total_hours * 60 ) + delta . minutes total_seconds = ( total_minutes * 60 ) + delta . seconds total_microseconds = ( total_seconds * 1000 ) + delta . microseconds return { 'datetime_1' : time_input1 . isoformat ( ) , 'datetime_2' : time_input2 . isoformat ( ) , 'years' : delta . years , 'months' : delta . months , 'weeks' : delta . weeks , 'days' : delta . days , 'hours' : delta . hours , 'minutes' : delta . minutes , 'seconds' : delta . seconds , 'microseconds' : delta . microseconds , 'total_months' : total_months , 'total_weeks' : total_weeks , 'total_days' : total_days , 'total_hours' : total_hours , 'total_minutes' : total_minutes , 'total_seconds' : total_seconds , 'total_microseconds' : total_microseconds , } | Calculates time delta between two time expressions . | 386 | 10 |
27,443 | def event_date ( self , event_date ) : if not self . can_update ( ) : self . _tcex . handle_error ( 910 , [ self . type ] ) event_date = self . _utils . format_datetime ( event_date , date_format = '%Y-%m-%dT%H:%M:%SZ' ) self . _data [ 'eventDate' ] = event_date request = { 'eventDate' : event_date } return self . tc_requests . update ( self . api_type , self . api_sub_type , self . unique_id , request ) | Updates the event_date . | 143 | 7 |
27,444 | def add_asset ( self , asset , asset_name , asset_type ) : if not self . can_update ( ) : self . _tcex . handle_error ( 910 , [ self . type ] ) if asset == 'PHONE' : return self . tc_requests . add_victim_phone_asset ( self . unique_id , asset_name ) if asset == 'EMAIL' : return self . tc_requests . add_victim_email_asset ( self . unique_id , asset_name , asset_type ) if asset == 'NETWORK' : return self . tc_requests . add_victim_network_asset ( self . unique_id , asset_name , asset_type ) if asset == 'SOCIAL' : return self . tc_requests . add_victim_social_asset ( self . unique_id , asset_name , asset_type ) if asset == 'WEB' : return self . tc_requests . add_victim_web_asset ( self . unique_id , asset_name ) self . _tcex . handle_error ( 925 , [ 'asset_type' , 'add_asset' , 'asset_type' , 'asset_type' , asset_type ] ) return None | Adds a asset to the Victim | 292 | 6 |
27,445 | def update_asset ( self , asset , asset_id , asset_name , asset_type ) : if not self . can_update ( ) : self . _tcex . handle_error ( 910 , [ self . type ] ) if asset == 'PHONE' : return self . tc_requests . update_victim_phone_asset ( self . unique_id , asset_id , asset_name ) if asset == 'EMAIL' : return self . tc_requests . update_victim_email_asset ( self . unique_id , asset_id , asset_name , asset_type ) if asset == 'NETWORK' : return self . tc_requests . update_victim_network_asset ( self . unique_id , asset_id , asset_name , asset_type ) if asset == 'SOCIAL' : return self . tc_requests . update_victim_social_asset ( self . unique_id , asset_id , asset_name , asset_type ) if asset == 'WEB' : return self . tc_requests . update_victim_web_asset ( self . unique_id , asset_id , asset_name ) self . _tcex . handle_error ( 925 , [ 'asset_type' , 'update_asset' , 'asset_type' , 'asset_type' , asset_type ] ) return None | Update a asset of a Victim | 316 | 6 |
27,446 | 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 . victim_phone_asset ( self . api_type , self . api_sub_type , self . unique_id , asset_id , action = action ) if asset_type == 'EMAIL' : return self . tc_requests . victim_email_asset ( self . api_type , self . api_sub_type , self . unique_id , asset_id , action = action ) if asset_type == 'NETWORK' : return self . tc_requests . victim_network_asset ( self . api_type , self . api_sub_type , self . unique_id , asset_id , action = action ) if asset_type == 'SOCIAL' : return self . tc_requests . victim_social_asset ( self . api_type , self . api_sub_type , self . unique_id , asset_id , action = action ) if asset_type == 'WEB' : return self . tc_requests . victim_web_asset ( self . api_type , self . api_sub_type , self . unique_id , asset_id , action = action ) self . _tcex . handle_error ( 925 , [ 'asset_type' , 'asset' , 'asset_type' , 'asset_type' , asset_type ] ) return None | Gets a asset of a Victim | 364 | 7 |
27,447 | def assets ( self , asset_type = None ) : if not self . can_update ( ) : self . _tcex . handle_error ( 910 , [ self . type ] ) if not asset_type : for a in self . tc_requests . victim_assets ( self . api_type , self . api_sub_type , self . unique_id ) : yield a if asset_type == 'PHONE' : for a in self . tc_requests . victim_phone_assets ( self . api_type , self . api_sub_type , self . unique_id ) : yield a if asset_type == 'EMAIL' : for a in self . tc_requests . victim_email_assets ( self . api_type , self . api_sub_type , self . unique_id ) : yield a if asset_type == 'NETWORK' : for a in self . tc_requests . victim_network_assets ( self . api_type , self . api_sub_type , self . unique_id ) : yield a if asset_type == 'SOCIAL' : for a in self . tc_requests . victim_social_assets ( self . api_type , self . api_sub_type , self . unique_id ) : yield a if asset_type == 'WEB' : for a in self . tc_requests . victim_web_assets ( self . api_type , self . api_sub_type , self . unique_id ) : yield a self . _tcex . handle_error ( 925 , [ 'asset_type' , 'assets' , 'asset_type' , 'asset_type' , asset_type ] ) | Gets the assets of a Victim | 376 | 7 |
27,448 | def db_conn ( self ) : if self . _db_conn is None : try : self . _db_conn = sqlite3 . connect ( ':memory:' ) except sqlite3 . Error as e : self . handle_error ( e ) return self . _db_conn | Create a temporary in memory DB and return the connection . | 62 | 11 |
27,449 | def db_create_table ( self , table_name , columns ) : formatted_columns = '' for col in set ( columns ) : formatted_columns += '"{}" text, ' . format ( col . strip ( '"' ) . strip ( '\'' ) ) formatted_columns = formatted_columns . strip ( ', ' ) create_table_sql = 'CREATE TABLE IF NOT EXISTS {} ({});' . format ( table_name , formatted_columns ) try : cr = self . db_conn . cursor ( ) cr . execute ( create_table_sql ) except sqlite3 . Error as e : self . handle_error ( e ) | Create a temporary DB table . | 146 | 6 |
27,450 | def handle_error ( err , halt = True ) : print ( '{}{}{}' . format ( c . Style . BRIGHT , c . Fore . RED , err ) ) if halt : sys . exit ( 1 ) | Print errors message and optionally exit . | 48 | 7 |
27,451 | def install_json ( self ) : file_fqpn = os . path . join ( self . app_path , 'install.json' ) if self . _install_json is None : if os . path . isfile ( file_fqpn ) : try : with open ( file_fqpn , 'r' ) as fh : self . _install_json = json . load ( fh ) except ValueError as e : self . handle_error ( 'Failed to load "{}" file ({}).' . format ( file_fqpn , e ) ) else : self . handle_error ( 'File "{}" could not be found.' . format ( file_fqpn ) ) return self . _install_json | Return install . json contents . | 160 | 6 |
27,452 | def install_json_params ( self , ij = None ) : if self . _install_json_params is None or ij is not None : self . _install_json_params = { } # TODO: support for projects with multiple install.json files is not supported if ij is None : ij = self . install_json for p in ij . get ( 'params' ) or [ ] : self . _install_json_params . setdefault ( p . get ( 'name' ) , p ) return self . _install_json_params | Return install . json params in a dict with name param as key . | 122 | 14 |
27,453 | def install_json_output_variables ( self , ij = None ) : if self . _install_json_output_variables is None or ij is not None : self . _install_json_output_variables = { } # TODO: currently there is no support for projects with multiple install.json files. if ij is None : ij = self . install_json for p in ij . get ( 'playbook' , { } ) . get ( 'outputVariables' ) or [ ] : self . _install_json_output_variables . setdefault ( p . get ( 'name' ) , [ ] ) . append ( p ) return self . _install_json_output_variables | Return install . json output variables in a dict with name param as key . | 158 | 15 |
27,454 | def layout_json ( self ) : file_fqpn = os . path . join ( self . app_path , 'layout.json' ) if self . _layout_json is None : if os . path . isfile ( file_fqpn ) : try : with open ( file_fqpn , 'r' ) as fh : self . _layout_json = json . load ( fh ) except ValueError as e : self . handle_error ( 'Failed to load "{}" file ({}).' . format ( file_fqpn , e ) ) else : self . handle_error ( 'File "{}" could not be found.' . format ( file_fqpn ) ) return self . _layout_json | Return layout . json contents . | 160 | 6 |
27,455 | def layout_json_params ( self ) : if self . _layout_json_params is None : self . _layout_json_params = { } for i in self . layout_json . get ( 'inputs' , [ ] ) : for p in i . get ( 'parameters' , [ ] ) : self . _layout_json_params . setdefault ( p . get ( 'name' ) , p ) return self . _layout_json_params | Return layout . json params in a flattened dict with name param as key . | 101 | 15 |
27,456 | def layout_json_names ( self ) : if self . _layout_json_names is None : self . _layout_json_names = self . layout_json_params . keys ( ) return self . _layout_json_names | Return layout . json names . | 51 | 6 |
27,457 | def layout_json_outputs ( self ) : if self . _layout_json_outputs is None : self . _layout_json_outputs = { } for o in self . layout_json . get ( 'outputs' , [ ] ) : self . _layout_json_outputs . setdefault ( o . get ( 'name' ) , o ) return self . _layout_json_outputs | Return layout . json outputs in a flattened dict with name param as key . | 90 | 15 |
27,458 | def load_install_json ( self , filename = None ) : if filename is None : filename = 'install.json' file_fqpn = os . path . join ( self . app_path , filename ) install_json = None if os . path . isfile ( file_fqpn ) : try : with open ( file_fqpn , 'r' ) as fh : install_json = json . load ( fh ) except ValueError as e : self . handle_error ( 'Failed to load "{}" file ({}).' . format ( file_fqpn , e ) ) else : self . handle_error ( 'File "{}" could not be found.' . format ( file_fqpn ) ) return install_json | Return install . json data . | 163 | 6 |
27,459 | def redis ( self ) : if self . _redis is None : self . _redis = redis . StrictRedis ( host = self . args . redis_host , port = self . args . redis_port ) return self . _redis | Return instance of Redis . | 58 | 6 |
27,460 | def tcex_json ( self ) : file_fqpn = os . path . join ( self . app_path , 'tcex.json' ) if self . _tcex_json is None : if os . path . isfile ( file_fqpn ) : try : with open ( file_fqpn , 'r' ) as fh : self . _tcex_json = json . load ( fh ) except ValueError as e : self . handle_error ( 'Failed to load "{}" file ({}).' . format ( file_fqpn , e ) ) else : self . handle_error ( 'File "{}" could not be found.' . format ( file_fqpn ) ) return self . _tcex_json | Return tcex . json file contents . | 170 | 9 |
27,461 | def update_system_path ( ) : cwd = os . getcwd ( ) lib_dir = os . path . join ( os . getcwd ( ) , 'lib_' ) lib_latest = os . path . join ( os . getcwd ( ) , 'lib_latest' ) # insert the lib_latest directory into the system Path if no other lib directory found. This # entry will be bumped to index 1 after adding the current working directory. if not [ p for p in sys . path if lib_dir in p ] : sys . path . insert ( 0 , lib_latest ) # insert the current working directory into the system Path for the App, ensuring that it is # always the first entry in the list. try : sys . path . remove ( cwd ) except ValueError : pass sys . path . insert ( 0 , cwd ) | Update the system path to ensure project modules and dependencies can be found . | 184 | 14 |
27,462 | def _hmac_auth ( self ) : return TcExHmacAuth ( self . args . api_access_id , self . args . api_secret_key , self . tcex . log ) | Add ThreatConnect HMAC Auth to Session . | 46 | 9 |
27,463 | def _token_auth ( self ) : return TcExTokenAuth ( self , self . args . tc_token , self . args . tc_token_expires , self . args . tc_api_path , self . tcex . log , ) | Add ThreatConnect Token Auth to Session . | 56 | 8 |
27,464 | def request ( self , method , url , * * kwargs ) : if not url . startswith ( 'https' ) : url = '{}{}' . format ( self . args . tc_api_path , url ) return super ( TcExSession , self ) . request ( method , url , * * kwargs ) | Override request method disabling verify on token renewal if disabled on session . | 74 | 13 |
27,465 | def add_key_value ( self , key , value ) : key = self . _metadata_map . get ( key , key ) if key in [ 'dateAdded' , 'lastModified' ] : self . _indicator_data [ key ] = self . _utils . format_datetime ( value , date_format = '%Y-%m-%dT%H:%M:%SZ' ) elif key == 'confidence' : self . _indicator_data [ key ] = int ( value ) elif key == 'rating' : self . _indicator_data [ key ] = float ( value ) else : self . _indicator_data [ key ] = value | Add custom field to Indicator object . | 153 | 8 |
27,466 | def association ( self , group_xid ) : association = { 'groupXid' : group_xid } self . _indicator_data . setdefault ( 'associatedGroups' , [ ] ) . append ( association ) | Add association using xid value . | 50 | 7 |
27,467 | def attribute ( self , attr_type , attr_value , displayed = False , source = None , unique = True , formatter = None ) : attr = Attribute ( attr_type , attr_value , displayed , source , formatter ) if unique == 'Type' : for attribute_data in self . _attributes : if attribute_data . type == attr_type : attr = attribute_data break else : self . _attributes . append ( attr ) elif unique is True : for attribute_data in self . _attributes : if attribute_data . type == attr_type and attribute_data . value == attr . value : attr = attribute_data break else : self . _attributes . append ( attr ) elif unique is False : self . _attributes . append ( attr ) return attr | Return instance of Attribute | 186 | 5 |
27,468 | def data ( self ) : # add attributes if self . _attributes : self . _indicator_data [ 'attribute' ] = [ ] for attr in self . _attributes : if attr . valid : self . _indicator_data [ 'attribute' ] . append ( attr . data ) # add file actions if self . _file_actions : self . _indicator_data . setdefault ( 'fileAction' , { } ) self . _indicator_data [ 'fileAction' ] . setdefault ( 'children' , [ ] ) for action in self . _file_actions : self . _indicator_data [ 'fileAction' ] [ 'children' ] . append ( action . data ) # add file occurrences if self . _occurrences : self . _indicator_data . setdefault ( 'fileOccurrence' , [ ] ) for occurrence in self . _occurrences : self . _indicator_data [ 'fileOccurrence' ] . append ( occurrence . data ) # add security labels if self . _labels : self . _indicator_data [ 'securityLabel' ] = [ ] for label in self . _labels : self . _indicator_data [ 'securityLabel' ] . append ( label . data ) # add tags if self . _tags : self . _indicator_data [ 'tag' ] = [ ] for tag in self . _tags : if tag . valid : self . _indicator_data [ 'tag' ] . append ( tag . data ) return self . _indicator_data | Return Indicator data . | 340 | 5 |
27,469 | def last_modified ( self , last_modified ) : self . _indicator_data [ 'lastModified' ] = self . _utils . format_datetime ( last_modified , date_format = '%Y-%m-%dT%H:%M:%SZ' ) | Set Indicator lastModified . | 66 | 7 |
27,470 | def occurrence ( self , file_name = None , path = None , date = None ) : if self . _indicator_data . get ( 'type' ) != 'File' : # Indicator object has no logger to output warning return None occurrence_obj = FileOccurrence ( file_name , path , date ) self . _occurrences . append ( occurrence_obj ) return occurrence_obj | Add a file Occurrence . | 85 | 6 |
27,471 | def action ( self , relationship ) : action_obj = FileAction ( self . _indicator_data . get ( 'xid' ) , relationship ) self . _file_actions . append ( action_obj ) return action_obj | Add a File Action . | 50 | 5 |
27,472 | def data ( self ) : if self . _children : for child in self . _children : self . _action_data . setdefault ( 'children' , [ ] ) . append ( child . data ) return self . _action_data | Return File Occurrence data . | 51 | 6 |
27,473 | def action ( self , relationship ) : action_obj = FileAction ( self . xid , relationship ) self . _children . append ( action_obj ) | Add a nested File Action . | 33 | 6 |
27,474 | def date ( self , date ) : self . _occurrence_data [ 'date' ] = self . _utils . format_datetime ( date , date_format = '%Y-%m-%dT%H:%M:%SZ' ) | Set File Occurrence date . | 58 | 6 |
27,475 | def address ( self , ip , owner = None , * * kwargs ) : return Address ( self . tcex , ip , owner = owner , * * kwargs ) | Create the Address TI object . | 39 | 6 |
27,476 | def url ( self , url , owner = None , * * kwargs ) : return URL ( self . tcex , url , owner = owner , * * kwargs ) | Create the URL TI object . | 39 | 6 |
27,477 | def email_address ( self , address , owner = None , * * kwargs ) : return EmailAddress ( self . tcex , address , owner = owner , * * kwargs ) | Create the Email Address TI object . | 42 | 7 |
27,478 | def file ( self , owner = None , * * kwargs ) : return File ( self . tcex , owner = owner , * * kwargs ) | Create the File TI object . | 35 | 6 |
27,479 | def host ( self , hostname , owner = None , * * kwargs ) : return Host ( self . tcex , hostname , owner = owner , * * kwargs ) | Create the Host TI object . | 41 | 6 |
27,480 | def indicator ( self , indicator_type = None , owner = None , * * kwargs ) : if not indicator_type : return Indicator ( self . tcex , None , owner = owner , * * kwargs ) upper_indicator_type = indicator_type . upper ( ) indicator = None if upper_indicator_type == 'ADDRESS' : indicator = Address ( self . tcex , kwargs . pop ( 'ip' , None ) , owner = owner , * * kwargs ) elif upper_indicator_type == 'EMAILADDRESS' : indicator = EmailAddress ( self . tcex , kwargs . pop ( 'address' , None ) , owner = owner , * * kwargs ) elif upper_indicator_type == 'FILE' : indicator = File ( self . tcex , * * kwargs ) elif upper_indicator_type == 'HOST' : indicator = Host ( self . tcex , kwargs . pop ( 'hostname' , None ) , owner = owner , * * kwargs ) elif upper_indicator_type == 'URL' : indicator = URL ( self . tcex , kwargs . pop ( 'url' , None ) , owner = owner , * * kwargs ) else : try : if upper_indicator_type in self . _custom_indicator_classes . keys ( ) : custom_indicator_details = self . _custom_indicator_classes [ indicator_type ] value_fields = custom_indicator_details . get ( 'value_fields' ) c = getattr ( module , custom_indicator_details . get ( 'branch' ) ) if len ( value_fields ) == 1 : indicator = c ( value_fields [ 0 ] , owner = owner , * * kwargs ) elif len ( value_fields ) == 2 : indicator = c ( value_fields [ 0 ] , value_fields [ 1 ] , owner = owner , * * kwargs ) elif len ( value_fields ) == 3 : indicator = c ( value_fields [ 0 ] , value_fields [ 2 ] , owner = owner , * * kwargs ) except Exception : return None return indicator | Create the Indicator TI object . | 492 | 7 |
27,481 | def group ( self , group_type = None , owner = None , * * kwargs ) : group = None if not group_type : return Group ( self . tcex , None , None , owner = owner , * * kwargs ) name = kwargs . pop ( 'name' , None ) group_type = group_type . upper ( ) if group_type == 'ADVERSARY' : group = Adversary ( self . tcex , name , owner = owner , * * kwargs ) if group_type == 'CAMPAIGN' : group = Campaign ( self . tcex , name , owner = owner , * * kwargs ) if group_type == 'DOCUMENT' : group = Document ( self . tcex , name , kwargs . pop ( 'file_name' , None ) , owner = owner , * * kwargs ) if group_type == 'EVENT' : group = Event ( self . tcex , name , owner = owner , * * kwargs ) if group_type == 'EMAIL' : group = Email ( self . tcex , name , kwargs . pop ( 'to' , None ) , kwargs . pop ( 'from_addr' , None ) , kwargs . pop ( 'subject' , None ) , kwargs . pop ( 'body' , None ) , kwargs . pop ( 'header' , None ) , owner = owner , * * kwargs ) if group_type == 'INCIDENT' : group = Incident ( self . tcex , name , owner = owner , * * kwargs ) if group_type == 'INTRUSION SET' : group = IntrusionSet ( self . tcex , name , owner = owner , * * kwargs ) if group_type == 'REPORT' : group = Report ( self . tcex , name , owner = owner , * * kwargs ) if group_type == 'SIGNATURE' : group = Signature ( self . tcex , name , kwargs . pop ( 'file_name' , None ) , kwargs . pop ( 'file_type' , None ) , kwargs . pop ( 'file_text' , None ) , owner = owner , * * kwargs ) if group_type == 'THREAT' : group = Threat ( self . tcex , name , owner = owner , * * kwargs ) if group_type == 'TASK' : group = Task ( self . tcex , name , kwargs . pop ( 'status' , 'Not Started' ) , kwargs . pop ( 'due_date' , None ) , kwargs . pop ( 'reminder_date' , None ) , kwargs . pop ( 'escalation_date' , None ) , owner = owner , * * kwargs ) return group | Create the Group TI object . | 637 | 6 |
27,482 | def adversary ( self , name , owner = None , * * kwargs ) : return Adversary ( self . tcex , name , owner = owner , * * kwargs ) | Create the Adversary TI object . | 41 | 8 |
27,483 | def campaign ( self , name , owner = None , * * kwargs ) : return Campaign ( self . tcex , name , owner = owner , * * kwargs ) | Create the Campaign TI object . | 39 | 6 |
27,484 | def document ( self , name , file_name , owner = None , * * kwargs ) : return Document ( self . tcex , name , file_name , owner = owner , * * kwargs ) | Create the Document TI object . | 47 | 6 |
27,485 | def event ( self , name , owner = None , * * kwargs ) : return Event ( self . tcex , name , owner = owner , * * kwargs ) | Create the Event TI object . | 39 | 6 |
27,486 | def email ( self , name , to , from_addr , subject , body , header , owner = None , * * kwargs ) : return Email ( self . tcex , name , to , from_addr , subject , body , header , owner = owner , * * kwargs ) | Create the Email TI object . | 63 | 6 |
27,487 | def incident ( self , name , owner = None , * * kwargs ) : return Incident ( self . tcex , name , owner = owner , * * kwargs ) | Create the Incident TI object . | 39 | 6 |
27,488 | def intrusion_sets ( self , name , owner = None , * * kwargs ) : return IntrusionSet ( self . tcex , name , owner = owner , * * kwargs ) | Create the Intrustion Set TI object . | 44 | 9 |
27,489 | def report ( self , name , owner = None , * * kwargs ) : return Report ( self . tcex , name , owner = owner , * * kwargs ) | Create the Report TI object . | 39 | 6 |
27,490 | def signature ( self , name , file_name , file_type , file_content , owner = None , * * kwargs ) : return Signature ( self . tcex , name , file_name , file_type , file_content , owner = owner , * * kwargs ) | Create the Signature TI object . | 63 | 6 |
27,491 | def threat ( self , name , owner = None , * * kwargs ) : return Threat ( self . tcex , name , owner = owner , * * kwargs ) | Create the Threat TI object . | 39 | 6 |
27,492 | def victim ( self , name , owner = None , * * kwargs ) : return Victim ( self . tcex , name , owner = owner , * * kwargs ) | Create the Victim TI object . | 39 | 6 |
27,493 | def format ( self , record ) : return { 'timestamp' : int ( float ( record . created or time . time ( ) ) * 1000 ) , 'message' : record . msg or '' , 'level' : record . levelname or 'DEBUG' , } | Format log record for ThreatConnect API . | 57 | 8 |
27,494 | def emit ( self , record ) : self . entries . append ( self . format ( record ) ) if len ( self . entries ) > self . flush_limit and not self . session . auth . renewing : self . log_to_api ( ) self . entries = [ ] | Emit the log record . | 60 | 6 |
27,495 | def log_to_api ( self ) : if self . entries : try : headers = { 'Content-Type' : 'application/json' } self . session . post ( '/v2/logs/app' , headers = headers , json = self . entries ) # self.entries = [] # clear entries except Exception : # best effort on api logging pass | Best effort API logger . | 78 | 5 |
27,496 | def class_factory ( name , base_class , class_dict ) : def __init__ ( self , tcex ) : base_class . __init__ ( self , tcex ) for k , v in class_dict . items ( ) : setattr ( self , k , v ) newclass = type ( str ( name ) , ( base_class , ) , { '__init__' : __init__ } ) return newclass | Internal method for dynamically building Custom Indicator classes . | 97 | 10 |
27,497 | def _apply_filters ( self ) : # apply filters filters = [ ] for f in self . _filters : filters . append ( '{}{}{}' . format ( f [ 'name' ] , f [ 'operator' ] , f [ 'value' ] ) ) self . tcex . log . debug ( u'filters: {}' . format ( filters ) ) if filters : self . _request . add_payload ( 'filters' , ',' . join ( filters ) ) | Apply any filters added to the resource . | 110 | 8 |
27,498 | def _request_process_json ( self , response ) : data = [ ] try : if self . _api_branch == 'bulk' : response_data = self . _request_bulk ( response ) else : response_data = response . json ( ) if self . _request_entity is None : data = response_data status = 'Success' elif self . _api_branch == 'bulk' : data , status = self . _request_process_json_bulk ( response_data ) elif response_data . get ( 'data' ) is None : data , status = self . _request_process_json_status ( response_data ) elif response_data . get ( 'status' ) == 'Success' : data , status = self . _request_process_json_standard ( response_data ) # setup pagination if self . _result_count is None : self . _result_count = response_data . get ( 'data' , { } ) . get ( 'resultCount' ) else : self . tcex . log . error ( 'Failed Request: {}' . format ( response . text ) ) status = 'Failure' except KeyError as e : # TODO: Remove try/except block status = 'Failure' msg = u'Error: Invalid key {}. [{}] ' . format ( e , self . request_entity ) self . tcex . log . error ( msg ) except ValueError as e : # TODO: Remove try/except block status = 'Failure' msg = u'Error: ({})' . format ( e ) self . tcex . log . error ( msg ) return data , status | Handle response data of type JSON | 365 | 6 |
27,499 | def _request_process_json_bulk ( self , response_data ) : status = 'Failure' data = response_data . get ( self . request_entity , [ ] ) if data : status = 'Success' return data , status | Handle bulk JSON response | 52 | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.