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,500
def _request_process_json_standard ( self , response_data ) : data = response_data . get ( 'data' , { } ) . get ( self . request_entity , [ ] ) status = response_data . get ( 'status' , 'Failure' ) return data , status
Handle JSON response
64
3
27,501
def _request_process_octet ( response ) : status = 'Failure' # Handle document download data = response . content if data : status = 'Success' return data , status
Handle Document download .
38
4
27,502
def _request_process_text ( response ) : status = 'Failure' # Handle document download data = response . content if data : status = 'Success' return data , status
Handle Signature download .
37
4
27,503
def add_filter ( self , name , operator , value ) : self . _filters . append ( { 'name' : name , 'operator' : operator , 'value' : value } )
Add ThreatConnect API Filter for this resource request .
42
10
27,504
def association_custom ( self , association_name , association_resource = None ) : resource = self . copy ( ) association_api_branch = self . tcex . indicator_associations_types_data . get ( association_name , { } ) . get ( 'apiBranch' ) if association_api_branch is None : self . tcex . handle_error ( 305 , [ association_name ] ) # handle URL difference between Custom Associations and File Actions custom_type = 'associations' file_action = self . tcex . utils . to_bool ( self . tcex . indicator_associations_types_data . get ( association_name , { } ) . get ( 'fileAction' ) ) if file_action : custom_type = 'actions' resource . _request_entity = 'indicator' if association_resource is not None : resource . _request_uri = '{}/{}/{}/{}' . format ( resource . _request_uri , custom_type , association_api_branch , association_resource . request_uri , ) else : resource . _request_uri = '{}/{}/{}/indicators' . format ( resource . _request_uri , custom_type , association_api_branch ) return resource
Custom Indicator association for this resource with resource value .
291
11
27,505
def association_pivot ( self , association_resource ) : resource = self . copy ( ) resource . _request_uri = '{}/{}' . format ( association_resource . request_uri , resource . _request_uri ) return resource
Pivot point on association for this resource .
54
9
27,506
def associations ( self , association_resource ) : resource = self . copy ( ) resource . _request_entity = association_resource . api_entity resource . _request_uri = '{}/{}' . format ( resource . _request_uri , association_resource . request_uri ) return resource
Retrieve Association for this resource of the type in association_resource .
65
14
27,507
def attributes ( self , resource_id = None ) : resource = self . copy ( ) resource . _request_entity = 'attribute' resource . _request_uri = '{}/attributes' . format ( resource . _request_uri ) if resource_id is not None : resource . _request_uri = '{}/{}' . format ( resource . _request_uri , resource_id ) return resource
Attribute endpoint for this resource with optional attribute id .
91
10
27,508
def copy_reset ( self ) : # Reset settings self . _filters = [ ] self . _filter_or = False self . _paginate = True self . _paginate_count = 0 self . _result_count = None self . _result_limit = 500 self . _result_start = 0
Reset values after instance has been copied
69
8
27,509
def copy ( self ) : resource = copy . copy ( self ) # workaround for bytes/str issue in Py3 with copy of instance # TypeError: a bytes-like object is required, not 'str' (ssl.py) resource . _request = self . tcex . request ( self . tcex . session ) # reset properties of resource resource . copy_reset ( ) # Preserve settings resource . http_method = self . http_method if self . _request . payload . get ( 'owner' ) is not None : resource . owner = self . _request . payload . get ( 'owner' ) # future bcs - these should not need to be reset. correct? # resource._request_entity = self._api_entity # resource._request_uri = self._api_uri return resource
Return a clean copy of this instance .
173
8
27,510
def group_pivot ( self , group_resource ) : resource = self . copy ( ) resource . _request_uri = '{}/{}' . format ( group_resource . request_uri , resource . _request_uri ) return resource
Pivot point on groups for this resource .
54
9
27,511
def http_method ( self , data ) : data = data . upper ( ) if data in [ 'DELETE' , 'GET' , 'POST' , 'PUT' ] : self . _request . http_method = data self . _http_method = data
The HTTP Method for this resource request .
58
8
27,512
def indicator_pivot ( self , indicator_resource ) : resource = self . copy ( ) resource . _request_uri = '{}/{}' . format ( indicator_resource . request_uri , resource . _request_uri ) return resource
Pivot point on indicators for this resource .
54
9
27,513
def owner ( self , data ) : if data is not None : self . _request . add_payload ( 'owner' , data ) else : self . tcex . log . warn ( u'Provided owner was invalid. ({})' . format ( data ) )
The Owner payload value for this resource request .
59
9
27,514
def paginate ( self ) : self . tcex . log . warning ( u'Using deprecated method (paginate).' ) resources = [ ] self . _request . add_payload ( 'resultStart' , self . _result_start ) self . _request . add_payload ( 'resultLimit' , self . _result_limit ) results = self . request ( ) response = results . get ( 'response' ) if results . get ( 'status' ) == 'Success' : data = response . json ( ) [ 'data' ] resources = data [ self . request_entity ] # set results count returned by first API call if data . get ( 'resultCount' ) is not None : self . _result_count = data . get ( 'resultCount' ) # self._result_start = self._result_limit self . tcex . log . debug ( u'Result Count: {}' . format ( self . _result_count ) ) while True : if len ( resources ) >= self . _result_count : break self . _result_start += self . _result_limit self . _request . add_payload ( 'resultStart' , self . _result_start ) results = self . request ( ) resources . extend ( results [ 'data' ] ) self . tcex . log . debug ( u'Resource Count: {}' . format ( len ( resources ) ) ) return resources
Paginate results from ThreatConnect API
307
8
27,515
def request ( self ) : # self._request.authorization_method(self._authorization_method) self . _request . url = '{}/v2/{}' . format ( self . tcex . default_args . tc_api_path , self . _request_uri ) self . _apply_filters ( ) self . tcex . log . debug ( u'Resource URL: ({})' . format ( self . _request . url ) ) response = self . _request . send ( stream = self . _stream ) data , status = self . _request_process ( response ) # # bcs - to reset or not to reset? # self._request.body = None # # self._request.reset_headers() # # self._request.reset_payload() # self._request_uri = self._api_uri # self._request_entity = self._api_entity return { 'data' : data , 'response' : response , 'status' : status }
Send the request to the API .
218
7
27,516
def security_label_pivot ( self , security_label_resource ) : resource = self . copy ( ) resource . _request_uri = '{}/{}' . format ( security_label_resource . request_uri , resource . _request_uri ) return resource
Pivot point on security labels for this resource .
60
10
27,517
def security_labels ( self , resource_id = None ) : resource = self . copy ( ) resource . _request_entity = 'securityLabel' resource . _request_uri = '{}/securityLabels' . format ( resource . _request_uri ) if resource_id is not None : resource . _request_uri = '{}/{}' . format ( resource . _request_uri , resource_id ) return resource
Security Label endpoint for this resource with optional label name .
96
11
27,518
def tag_pivot ( self , tag_resource ) : resource = self . copy ( ) resource . _request_uri = '{}/{}' . format ( tag_resource . request_uri , resource . _request_uri ) return resource
Pivot point on tags for this resource .
54
9
27,519
def tags ( self , resource_id = None ) : resource = self . copy ( ) resource . _request_entity = 'tag' resource . _request_uri = '{}/tags' . format ( resource . _request_uri ) if resource_id is not None : resource . _request_uri = '{}/{}' . format ( resource . _request_uri , self . tcex . safetag ( resource_id ) ) return resource
Tag endpoint for this resource with optional tag name .
101
10
27,520
def task_pivot ( self , task_resource ) : resource = self . copy ( ) resource . _request_uri = '{}/{}' . format ( task_resource . request_uri , resource . _request_uri ) return resource
Pivot point on Tasks for this resource .
54
10
27,521
def victim_assets ( self , asset_type = None , asset_id = None ) : type_entity_map = { 'emailAddresses' : 'victimEmailAddress' , 'networkAccounts' : 'victimNetworkAccount' , 'phoneNumbers' : 'victimPhone' , 'socialNetworks' : 'victimSocialNetwork' , 'webSites' : 'victimWebSite' , } resource = self . copy ( ) resource . _request_entity = 'victimAsset' resource . _request_uri = '{}/victimAssets' . format ( resource . _request_uri ) if asset_type is not None : resource . _request_entity = type_entity_map . get ( asset_type , 'victimAsset' ) resource . _request_uri = '{}/{}' . format ( resource . _request_uri , asset_type ) if asset_id is not None : resource . _request_uri = '{}/{}' . format ( resource . _request_uri , asset_id ) return resource
Victim Asset endpoint for this resource with optional asset type .
235
12
27,522
def indicators ( self , indicator_data ) : # indicator_list = [] for indicator_field in self . value_fields : if indicator_field == 'summary' : indicators = self . tcex . expand_indicators ( indicator_data . get ( 'summary' ) ) if indicator_data . get ( 'type' ) == 'File' : hash_patterns = { 'md5' : re . compile ( r'^([a-fA-F\d]{32})$' ) , 'sha1' : re . compile ( r'^([a-fA-F\d]{40})$' ) , 'sha256' : re . compile ( r'^([a-fA-F\d]{64})$' ) , } for i in indicators : if not i : continue i = i . strip ( ) # clean up badly formatted summary string i_type = None if hash_patterns [ 'md5' ] . match ( i ) : i_type = 'md5' elif hash_patterns [ 'sha1' ] . match ( i ) : i_type = 'sha1' elif hash_patterns [ 'sha256' ] . match ( i ) : i_type = 'sha256' else : msg = u'Cannot determine hash type: "{}"' . format ( indicator_data . get ( 'summary' ) ) self . tcex . log . warning ( msg ) data = { 'type' : i_type , 'value' : i } yield data else : resource = getattr ( self . tcex . resources , self . tcex . safe_rt ( indicator_data . get ( 'type' ) ) ) ( self . tcex ) values = resource . value_fields index = 0 for i in indicators : if i is None : continue i = i . strip ( ) # clean up badly formatted summary string # TODO: remove workaround for bug in indicatorTypes API endpoint if len ( values ) - 1 < index : break data = { 'type' : values [ index ] , 'value' : i } index += 1 yield data else : if indicator_data . get ( indicator_field ) is not None : yield { 'type' : indicator_field , 'value' : indicator_data . get ( indicator_field ) }
Generator for indicator values .
504
6
27,523
def observed ( self , date_observed = None ) : if self . name != 'Indicator' : self . tcex . log . warning ( u'Observed endpoint only available for "indicator" endpoint.' ) else : self . _request_uri = '{}/observed' . format ( self . _request_uri ) if date_observed is not None : self . _request . add_payload ( 'dateObserved' , date_observed )
Retrieve indicator observations count for top 10
104
8
27,524
def csv ( self , ondemand = False ) : self . _request_uri = '{}/{}' . format ( self . _api_uri , 'csv' ) self . _stream = True if ondemand : self . _request . add_payload ( 'runNow' , True )
Update request URI to return CSV data .
67
8
27,525
def json ( self , ondemand = False ) : self . _request_entity = 'indicator' self . _request_uri = '{}/{}' . format ( self . _api_uri , 'json' ) self . _stream = True if ondemand : self . _request . add_payload ( 'runNow' , True )
Update request URI to return JSON data .
77
8
27,526
def indicator_body ( indicators ) : hash_patterns = { 'md5' : re . compile ( r'^([a-fA-F\d]{32})$' ) , 'sha1' : re . compile ( r'^([a-fA-F\d]{40})$' ) , 'sha256' : re . compile ( r'^([a-fA-F\d]{64})$' ) , } body = { } for indicator in indicators : if indicator is None : continue if hash_patterns [ 'md5' ] . match ( indicator ) : body [ 'md5' ] = indicator elif hash_patterns [ 'sha1' ] . match ( indicator ) : body [ 'sha1' ] = indicator elif hash_patterns [ 'sha256' ] . match ( indicator ) : body [ 'sha256' ] = indicator return body
Generate the appropriate dictionary content for POST of an File indicator
199
12
27,527
def occurrence ( self , indicator = None ) : self . _request_entity = 'fileOccurrence' self . _request_uri = '{}/fileOccurrences' . format ( self . _request_uri ) if indicator is not None : self . _request_uri = '{}/{}/fileOccurrences' . format ( self . _api_uri , indicator )
Update the URI to retrieve file occurrences for the provided indicator .
85
12
27,528
def resolution ( self , indicator = None ) : self . _request_entity = 'dnsResolution' self . _request_uri = '{}/dnsResolutions' . format ( self . _request_uri ) if indicator is not None : self . _request_uri = '{}/{}/dnsResolutions' . format ( self . _api_uri , indicator )
Update the URI to retrieve host resolutions for the provided indicator .
86
12
27,529
def group_id ( self , resource_id ) : if self . _name != 'group' : self . _request_uri = '{}/{}' . format ( self . _api_uri , resource_id )
Update the request URI to include the Group ID for specific group retrieval .
50
14
27,530
def pdf ( self , resource_id ) : self . resource_id ( str ( resource_id ) ) self . _request_uri = '{}/pdf' . format ( self . _request_uri )
Update the request URI to get the pdf for this resource .
46
12
27,531
def download ( self , resource_id ) : self . resource_id ( str ( resource_id ) ) self . _request_uri = '{}/download' . format ( self . _request_uri )
Update the request URI to download the document for this resource .
46
12
27,532
def upload ( self , resource_id , data ) : self . body = data self . content_type = 'application/octet-stream' self . resource_id ( str ( resource_id ) ) self . _request_uri = '{}/upload' . format ( self . _request_uri )
Update the request URI to upload the a document to this resource .
67
13
27,533
def data ( self , resource_value , return_value = False ) : if return_value : self . _request_entity = None self . _request . add_payload ( 'returnValue' , True ) self . _request_uri = '{}/{}/data' . format ( self . _request_uri , resource_value )
Alias for metric_name method
76
6
27,534
def tag ( self , resource_id ) : self . _request_uri = '{}/{}' . format ( self . _request_uri , self . tcex . safetag ( resource_id ) )
Update the request URI to include the Tag for specific retrieval .
49
12
27,535
def assignees ( self , assignee = None , resource_id = None ) : if resource_id is not None : self . resource_id ( resource_id ) self . _request_uri = '{}/assignees' . format ( self . _request_uri ) if assignee is not None : self . _request_uri = '{}/{}' . format ( self . _request_uri , assignee )
Add an assignee to a Task
95
7
27,536
def escalatees ( self , escalatee = None , resource_id = None ) : if resource_id is not None : self . resource_id ( resource_id ) self . _request_uri = '{}/escalatees' . format ( self . _request_uri ) if escalatee is not None : self . _request_uri = '{}/{}' . format ( self . _request_uri , escalatee )
Add an escalatee to a Task
95
7
27,537
def _request ( self , domain , type_name , search_command , db_method , body = None ) : headers = { 'Content-Type' : 'application/json' , 'DB-Method' : db_method } search_command = self . _clean_datastore_path ( search_command ) url = '/v2/exchange/db/{}/{}/{}' . format ( domain , type_name , search_command ) r = self . tcex . session . post ( url , data = body , headers = headers , params = self . _params ) data = [ ] status = 'Failed' if not r . ok or 'application/json' not in r . headers . get ( 'content-type' , '' ) : self . tcex . handle_error ( 350 , [ r . status_code , r . text ] ) data = r . json ( ) status = 'Success' return { 'data' : data , 'response' : r , 'status' : status }
Make the API request for a Data Store CRUD operation
225
11
27,538
def create ( self , domain , type_name , search_command , body ) : return self . _request ( domain , type_name , search_command , 'POST' , body )
Create entry in ThreatConnect Data Store
40
7
27,539
def delete ( self , domain , type_name , search_command ) : return self . _request ( domain , type_name , search_command , 'DELETE' , None )
Delete entry in ThreatConnect Data Store
40
7
27,540
def read ( self , domain , type_name , search_command , body = None ) : return self . _request ( domain , type_name , search_command , 'GET' , body )
Read entry in ThreatConnect Data Store
42
7
27,541
def update ( self , domain , type_name , search_command , body ) : return self . _request ( domain , type_name , search_command , 'PUT' , body )
Update entry in ThreatConnect Data Store
40
7
27,542
def file_content ( self , file_content , update_if_exists = True ) : if not self . can_update ( ) : self . _tcex . handle_error ( 910 , [ self . type ] ) self . _data [ 'fileContent' ] = file_content return self . tc_requests . upload ( self . api_type , self . api_sub_type , self . unique_id , file_content , update_if_exists = update_if_exists , )
Updates the file content .
114
6
27,543
def file_name ( self , file_name ) : if not self . can_update ( ) : self . _tcex . handle_error ( 910 , [ self . type ] ) self . _data [ 'fileName' ] = file_name request = { 'fileName' : file_name } return self . tc_requests . update ( self . api_type , self . api_sub_type , self . unique_id , request )
Updates the file_name .
100
7
27,544
def malware ( self , malware , password , file_name ) : if not self . can_update ( ) : self . _tcex . handle_error ( 910 , [ self . type ] ) self . _data [ 'malware' ] = malware self . _data [ 'password' ] = password self . _data [ 'fileName' ] = file_name request = { 'malware' : malware , 'password' : password , 'fileName' : file_name } return self . tc_requests . update ( self . api_type , self . api_sub_type , self . unique_id , request )
Uploads to malware vault .
138
6
27,545
def check_imports ( self ) : modules = [ ] for filename in sorted ( os . listdir ( self . app_path ) ) : if not filename . endswith ( '.py' ) : continue fq_path = os . path . join ( self . app_path , filename ) with open ( fq_path , 'rb' ) as f : # TODO: fix this code_lines = deque ( [ ( f . read ( ) , 1 ) ] ) while code_lines : m_status = True code , lineno = code_lines . popleft ( ) # pylint: disable=W0612 try : parsed_code = ast . parse ( code ) for node in ast . walk ( parsed_code ) : if isinstance ( node , ast . Import ) : for n in node . names : m = n . name . split ( '.' ) [ 0 ] if self . check_import_stdlib ( m ) : # stdlib module, not need to proceed continue m_status = self . check_imported ( m ) modules . append ( { 'file' : filename , 'module' : m , 'status' : m_status } ) elif isinstance ( node , ast . ImportFrom ) : m = node . module . split ( '.' ) [ 0 ] if self . check_import_stdlib ( m ) : # stdlib module, not need to proceed continue m_status = self . check_imported ( m ) modules . append ( { 'file' : filename , 'module' : m , 'status' : m_status } ) else : continue except SyntaxError : pass for module_data in modules : status = True if not module_data . get ( 'status' ) : status = False # update validation data errors self . validation_data [ 'errors' ] . append ( 'Module validation failed for {} (module "{}" could not be imported).' . format ( module_data . get ( 'file' ) , module_data . get ( 'module' ) ) ) # update validation data for module self . validation_data [ 'moduleImports' ] . append ( { 'filename' : module_data . get ( 'file' ) , 'module' : module_data . get ( 'module' ) , 'status' : status , } )
Check the projects top level directory for missing imports .
500
10
27,546
def check_import_stdlib ( module ) : if ( module in stdlib_list ( '2.7' ) # pylint: disable=R0916 or module in stdlib_list ( '3.4' ) or module in stdlib_list ( '3.5' ) or module in stdlib_list ( '3.6' ) or module in stdlib_list ( '3.7' ) or module in [ 'app' , 'args' , 'playbook_app' ] ) : return True return False
Check if module is in Python stdlib .
117
9
27,547
def check_install_json ( self ) : if self . install_json_schema is None : return contents = os . listdir ( self . app_path ) if self . args . install_json is not None : contents = [ self . args . install_json ] for install_json in sorted ( contents ) : # skip files that are not install.json files if 'install.json' not in install_json : continue error = None status = True try : # loading explicitly here to keep all error catching in this file with open ( install_json ) as fh : data = json . loads ( fh . read ( ) ) validate ( data , self . install_json_schema ) except SchemaError as e : status = False error = e except ValidationError as e : status = False error = e . message except ValueError : # any JSON decode error will be caught during syntax validation return if error : # update validation data errors self . validation_data [ 'errors' ] . append ( 'Schema validation failed for {} ({}).' . format ( install_json , error ) ) # update validation data for module self . validation_data [ 'schema' ] . append ( { 'filename' : install_json , 'status' : status } )
Check all install . json files for valid schema .
271
10
27,548
def check_layout_json ( self ) : # the install.json files can't be validates if the schema file is not present layout_json_file = 'layout.json' if self . layout_json_schema is None or not os . path . isfile ( layout_json_file ) : return error = None status = True try : # loading explicitly here to keep all error catching in this file with open ( layout_json_file ) as fh : data = json . loads ( fh . read ( ) ) validate ( data , self . layout_json_schema ) except SchemaError as e : status = False error = e except ValidationError as e : status = False error = e . message except ValueError : # any JSON decode error will be caught during syntax validation return # update validation data for module self . validation_data [ 'schema' ] . append ( { 'filename' : layout_json_file , 'status' : status } ) if error : # update validation data errors self . validation_data [ 'errors' ] . append ( 'Schema validation failed for {} ({}).' . format ( layout_json_file , error ) ) else : self . check_layout_params ( )
Check all layout . json files for valid schema .
263
10
27,549
def check_layout_params ( self ) : ij_input_names = [ ] ij_output_names = [ ] if os . path . isfile ( 'install.json' ) : try : with open ( 'install.json' ) as fh : ij = json . loads ( fh . read ( ) ) for p in ij . get ( 'params' , [ ] ) : ij_input_names . append ( p . get ( 'name' ) ) for o in ij . get ( 'playbook' , { } ) . get ( 'outputVariables' , [ ] ) : ij_output_names . append ( o . get ( 'name' ) ) except Exception : # checking parameters isn't possible if install.json can't be parsed return if 'sqlite3' in sys . modules : # create temporary inputs tables self . db_create_table ( self . input_table , ij_input_names ) # inputs status = True for i in self . layout_json . get ( 'inputs' , [ ] ) : for p in i . get ( 'parameters' ) : if p . get ( 'name' ) not in ij_input_names : # update validation data errors self . validation_data [ 'errors' ] . append ( 'Layouts input.parameters[].name validations failed ("{}" is defined in ' 'layout.json, but not found in install.json).' . format ( p . get ( 'name' ) ) ) status = False if 'sqlite3' in sys . modules : if p . get ( 'display' ) : display_query = 'SELECT * FROM {} WHERE {}' . format ( self . input_table , p . get ( 'display' ) ) try : self . db_conn . execute ( display_query . replace ( '"' , '' ) ) except sqlite3 . Error : self . validation_data [ 'errors' ] . append ( 'Layouts input.parameters[].display validations failed ("{}" query ' 'is an invalid statement).' . format ( p . get ( 'display' ) ) ) status = False # update validation data for module self . validation_data [ 'layouts' ] . append ( { 'params' : 'inputs' , 'status' : status } ) # outputs status = True for o in self . layout_json . get ( 'outputs' , [ ] ) : if o . get ( 'name' ) not in ij_output_names : # update validation data errors self . validation_data [ 'errors' ] . append ( 'Layouts output validations failed ({} is defined in layout.json, but not ' 'found in install.json).' . format ( o . get ( 'name' ) ) ) status = False if 'sqlite3' in sys . modules : if o . get ( 'display' ) : display_query = 'SELECT * FROM {} WHERE {}' . format ( self . input_table , o . get ( 'display' ) ) try : self . db_conn . execute ( display_query . replace ( '"' , '' ) ) except sqlite3 . Error : self . validation_data [ 'errors' ] . append ( 'Layouts outputs.display validations failed ("{}" query is ' 'an invalid statement).' . format ( o . get ( 'display' ) ) ) status = False # update validation data for module self . validation_data [ 'layouts' ] . append ( { 'params' : 'outputs' , 'status' : status } )
Check that the layout . json is consistent with install . json .
774
13
27,550
def check_syntax ( self , app_path = None ) : app_path = app_path or '.' for filename in sorted ( os . listdir ( app_path ) ) : error = None status = True if filename . endswith ( '.py' ) : try : with open ( filename , 'rb' ) as f : ast . parse ( f . read ( ) , filename = filename ) except SyntaxError : status = False # cleanup output e = [ ] for line in traceback . format_exc ( ) . split ( '\n' ) [ - 5 : - 2 ] : e . append ( line . strip ( ) ) error = ' ' . join ( e ) elif filename . endswith ( '.json' ) : try : with open ( filename , 'r' ) as fh : json . load ( fh ) except ValueError as e : status = False error = e else : # skip unsupported file types continue if error : # update validation data errors self . validation_data [ 'errors' ] . append ( 'Syntax validation failed for {} ({}).' . format ( filename , error ) ) # store status for this file self . validation_data [ 'fileSyntax' ] . append ( { 'filename' : filename , 'status' : status } )
Run syntax on each . py and . json file .
278
11
27,551
def install_json_schema ( self ) : if self . _install_json_schema is None and self . install_json_schema_file is not None : # remove old schema file if os . path . isfile ( 'tcex_json_schema.json' ) : # this file is now part of tcex. os . remove ( 'tcex_json_schema.json' ) if os . path . isfile ( self . install_json_schema_file ) : with open ( self . install_json_schema_file ) as fh : self . _install_json_schema = json . load ( fh ) return self . _install_json_schema
Load install . json schema file .
158
7
27,552
def interactive ( self ) : while True : line = sys . stdin . readline ( ) . strip ( ) if line == 'quit' : sys . exit ( ) elif line == 'validate' : self . check_syntax ( ) self . check_imports ( ) self . check_install_json ( ) self . check_layout_json ( ) self . print_json ( ) # reset validation_data self . validation_data = self . _validation_data
Run in interactive mode .
104
5
27,553
def layout_json_schema ( self ) : if self . _layout_json_schema is None and self . layout_json_schema_file is not None : if os . path . isfile ( self . layout_json_schema_file ) : with open ( self . layout_json_schema_file ) as fh : self . _layout_json_schema = json . load ( fh ) return self . _layout_json_schema
Load layout . json schema file .
103
7
27,554
def print_results ( self ) : # Validating Syntax if self . validation_data . get ( 'fileSyntax' ) : print ( '\n{}{}Validated File Syntax:' . format ( c . Style . BRIGHT , c . Fore . BLUE ) ) print ( '{}{!s:<60}{!s:<25}' . format ( c . Style . BRIGHT , 'File:' , 'Status:' ) ) for f in self . validation_data . get ( 'fileSyntax' ) : status_color = self . status_color ( f . get ( 'status' ) ) status_value = self . status_value ( f . get ( 'status' ) ) print ( '{!s:<60}{}{!s:<25}' . format ( f . get ( 'filename' ) , status_color , status_value ) ) # Validating Imports if self . validation_data . get ( 'moduleImports' ) : print ( '\n{}{}Validated Imports:' . format ( c . Style . BRIGHT , c . Fore . BLUE ) ) print ( '{}{!s:<30}{!s:<30}{!s:<25}' . format ( c . Style . BRIGHT , 'File:' , 'Module:' , 'Status:' ) ) for f in self . validation_data . get ( 'moduleImports' ) : status_color = self . status_color ( f . get ( 'status' ) ) status_value = self . status_value ( f . get ( 'status' ) ) print ( '{!s:<30}{}{!s:<30}{}{!s:<25}' . format ( f . get ( 'filename' ) , c . Fore . WHITE , f . get ( 'module' ) , status_color , status_value ) ) # Validating Schema if self . validation_data . get ( 'schema' ) : print ( '\n{}{}Validated Schema:' . format ( c . Style . BRIGHT , c . Fore . BLUE ) ) print ( '{}{!s:<60}{!s:<25}' . format ( c . Style . BRIGHT , 'File:' , 'Status:' ) ) for f in self . validation_data . get ( 'schema' ) : status_color = self . status_color ( f . get ( 'status' ) ) status_value = self . status_value ( f . get ( 'status' ) ) print ( '{!s:<60}{}{!s:<25}' . format ( f . get ( 'filename' ) , status_color , status_value ) ) # Validating Layouts if self . validation_data . get ( 'layouts' ) : print ( '\n{}{}Validated Layouts:' . format ( c . Style . BRIGHT , c . Fore . BLUE ) ) print ( '{}{!s:<60}{!s:<25}' . format ( c . Style . BRIGHT , 'Params:' , 'Status:' ) ) for f in self . validation_data . get ( 'layouts' ) : status_color = self . status_color ( f . get ( 'status' ) ) status_value = self . status_value ( f . get ( 'status' ) ) print ( '{!s:<60}{}{!s:<25}' . format ( f . get ( 'params' ) , status_color , status_value ) ) if self . validation_data . get ( 'errors' ) : print ( '\n' ) # separate errors from normal output for error in self . validation_data . get ( 'errors' ) : # print all errors print ( '* {}{}' . format ( c . Fore . RED , error ) ) # ignore exit code if not self . args . ignore_validation : self . exit_code = 1
Print results .
863
3
27,555
def status_color ( status ) : status_color = c . Fore . GREEN if not status : status_color = c . Fore . RED return status_color
Return the appropriate status color .
34
6
27,556
def _dt_to_epoch ( dt ) : try : epoch = dt . timestamp ( ) except AttributeError : # py2 epoch = ( dt - datetime ( 1970 , 1 , 1 ) ) . total_seconds ( ) return epoch
Convert datetime to epoch seconds .
55
8
27,557
def get ( self , rid , data_callback = None , raise_on_error = True ) : cached_data = None ds_data = self . ds . get ( rid , raise_on_error = False ) if ds_data is not None : expired = True if ds_data . get ( 'found' ) is True : if self . ttl < int ( ds_data . get ( '_source' , { } ) . get ( 'cache-date' , 0 ) ) : cached_data = ds_data . get ( '_source' , { } ) . get ( 'cache-data' ) expired = False self . tcex . log . debug ( 'Using cached data for ({}).' . format ( rid ) ) else : self . tcex . log . debug ( 'Cached data is expired for ({}).' . format ( rid ) ) if expired or ds_data . get ( 'found' ) is False : # when cache is expired or does not exist use callback to get data if possible if callable ( data_callback ) : cached_data = data_callback ( rid ) self . tcex . log . debug ( 'Using callback data for ({}).' . format ( rid ) ) if cached_data : self . update ( rid , cached_data , raise_on_error ) # update the cache data return cached_data
Get cached data from the data store .
304
8
27,558
def update ( self , rid , data , raise_on_error = True ) : cache_data = { 'cache-date' : self . _dt_to_epoch ( datetime . now ( ) ) , 'cache-data' : data } return self . ds . put ( rid , cache_data , raise_on_error )
Write updated cache data to the DataStore .
75
9
27,559
def _association_types ( self ) : # Dynamically create custom indicator class r = self . session . get ( '/v2/types/associationTypes' ) # check for bad status code and response that is not JSON if not r . ok or 'application/json' not in r . headers . get ( 'content-type' , '' ) : warn = u'Custom Indicators Associations are not supported.' self . log . warning ( warn ) return # validate successful API results data = r . json ( ) if data . get ( 'status' ) != 'Success' : warn = u'Bad Status: Custom Indicators Associations are not supported.' self . log . warning ( warn ) return try : # Association Type Name is not a unique value at this time, but should be. for association in data . get ( 'data' , { } ) . get ( 'associationType' , [ ] ) : self . _indicator_associations_types_data [ association . get ( 'name' ) ] = association except Exception as e : self . handle_error ( 200 , [ e ] )
Retrieve Custom Indicator Associations types from the ThreatConnect API .
237
14
27,560
def _log ( self ) : self . _log_platform ( ) self . _log_app_data ( ) self . _log_python_version ( ) self . _log_tcex_version ( ) self . _log_tc_proxy ( )
Send System and App data to logs .
57
8
27,561
def _log_app_data ( self ) : # Best Effort if self . install_json : app_commit_hash = self . install_json . get ( 'commitHash' ) app_features = ',' . join ( self . install_json . get ( 'features' , [ ] ) ) app_min_ver = self . install_json . get ( 'minServerVersion' , 'N/A' ) app_name = self . install_json . get ( 'displayName' ) app_runtime_level = self . install_json . get ( 'runtimeLevel' ) app_version = self . install_json . get ( 'programVersion' ) self . log . info ( u'App Name: {}' . format ( app_name ) ) if app_features : self . log . info ( u'App Features: {}' . format ( app_features ) ) self . log . info ( u'App Minimum ThreatConnect Version: {}' . format ( app_min_ver ) ) self . log . info ( u'App Runtime Level: {}' . format ( app_runtime_level ) ) self . log . info ( u'App Version: {}' . format ( app_version ) ) if app_commit_hash is not None : self . log . info ( u'App Commit Hash: {}' . format ( app_commit_hash ) )
Log the App data information .
297
6
27,562
def _log_python_version ( self ) : self . log . info ( u'Python Version: {}.{}.{}' . format ( sys . version_info . major , sys . version_info . minor , sys . version_info . micro ) )
Log the current Python version .
57
6
27,563
def _log_tc_proxy ( self ) : if self . default_args . tc_proxy_tc : self . log . info ( u'Proxy Server (TC): {}:{}.' . format ( self . default_args . tc_proxy_host , self . default_args . tc_proxy_port ) )
Log the proxy settings .
69
5
27,564
def _log_tcex_version ( self ) : self . log . info ( u'TcEx Version: {}' . format ( __import__ ( __name__ ) . __version__ ) )
Log the current TcEx version number .
45
9
27,565
def _logger ( self ) : level = logging . INFO self . log . setLevel ( level ) # clear all handlers self . log . handlers = [ ] # update logging level if self . default_args . logging is not None : level = self . _logger_levels [ self . default_args . logging ] elif self . default_args . tc_log_level is not None : level = self . _logger_levels [ self . default_args . tc_log_level ] self . log . setLevel ( level ) # add file handler if not already added if self . default_args . tc_log_path : self . _logger_fh ( ) # add api handler if not already added if self . default_args . tc_token is not None and self . default_args . tc_log_to_api : self . _logger_api ( ) self . log . info ( 'Logging Level: {}' . format ( logging . getLevelName ( level ) ) )
Create TcEx app logger instance .
218
8
27,566
def _logger_api ( self ) : from . tcex_logger import TcExLogHandler , TcExLogFormatter api = TcExLogHandler ( self . session ) api . set_name ( 'api' ) api . setLevel ( logging . DEBUG ) api . setFormatter ( TcExLogFormatter ( ) ) self . log . addHandler ( api )
Add API logging handler .
86
5
27,567
def _logger_fh ( self ) : logfile = os . path . join ( self . default_args . tc_log_path , self . default_args . tc_log_file ) fh = logging . FileHandler ( logfile ) fh . set_name ( 'fh' ) fh . setLevel ( logging . DEBUG ) fh . setFormatter ( self . _logger_formatter ) self . log . addHandler ( fh )
Add File logging handler .
103
5
27,568
def _logger_levels ( self ) : return { 'debug' : logging . DEBUG , 'info' : logging . INFO , 'warning' : logging . WARNING , 'error' : logging . ERROR , 'critical' : logging . CRITICAL , }
Return log levels .
55
4
27,569
def _logger_stream ( self ) : sh = logging . StreamHandler ( ) sh . set_name ( 'sh' ) sh . setLevel ( logging . INFO ) sh . setFormatter ( self . _logger_formatter ) self . log . addHandler ( sh )
Add stream logging handler .
61
5
27,570
def _resources ( self , custom_indicators = False ) : from importlib import import_module # create resource object self . resources = import_module ( 'tcex.tcex_resources' ) if custom_indicators : self . log . info ( 'Loading custom indicator types.' ) # Retrieve all indicator types from the API r = self . session . get ( '/v2/types/indicatorTypes' ) # check for bad status code and response that is not JSON if not r . ok or 'application/json' not in r . headers . get ( 'content-type' , '' ) : warn = u'Custom Indicators are not supported ({}).' . format ( r . text ) self . log . warning ( warn ) return response = r . json ( ) if response . get ( 'status' ) != 'Success' : warn = u'Bad Status: Custom Indicators are not supported ({}).' . format ( r . text ) self . log . warning ( warn ) return try : # Dynamically create custom indicator class data = response . get ( 'data' , { } ) . get ( 'indicatorType' , [ ] ) for entry in data : name = self . safe_rt ( entry . get ( 'name' ) ) # temp fix for API issue where boolean are returned as strings entry [ 'custom' ] = self . utils . to_bool ( entry . get ( 'custom' ) ) entry [ 'parsable' ] = self . utils . to_bool ( entry . get ( 'parsable' ) ) self . _indicator_types . append ( u'{}' . format ( entry . get ( 'name' ) ) ) self . _indicator_types_data [ entry . get ( 'name' ) ] = entry if not entry [ 'custom' ] : continue # Custom Indicator have 3 values. Only add the value if it is set. value_fields = [ ] if entry . get ( 'value1Label' ) : value_fields . append ( entry . get ( 'value1Label' ) ) if entry . get ( 'value2Label' ) : value_fields . append ( entry . get ( 'value2Label' ) ) if entry . get ( 'value3Label' ) : value_fields . append ( entry . get ( 'value3Label' ) ) # get instance of Indicator Class i = self . resources . Indicator ( self ) custom = { '_api_branch' : entry [ 'apiBranch' ] , '_api_entity' : entry [ 'apiEntity' ] , '_api_uri' : '{}/{}' . format ( i . api_branch , entry [ 'apiBranch' ] ) , '_case_preference' : entry [ 'casePreference' ] , '_custom' : entry [ 'custom' ] , '_name' : name , '_parsable' : entry [ 'parsable' ] , '_request_entity' : entry [ 'apiEntity' ] , '_request_uri' : '{}/{}' . format ( i . api_branch , entry [ 'apiBranch' ] ) , '_status_codes' : { 'DELETE' : [ 200 ] , 'GET' : [ 200 ] , 'POST' : [ 200 , 201 ] , 'PUT' : [ 200 ] , } , '_value_fields' : value_fields , } # Call custom indicator class factory setattr ( self . resources , name , self . resources . class_factory ( name , self . resources . Indicator , custom ) , ) except Exception as e : self . handle_error ( 220 , [ e ] )
Initialize the resource module .
807
6
27,571
def utils ( self ) : if self . _utils is None : from . tcex_utils import TcExUtils self . _utils = TcExUtils ( self ) return self . _utils
Include the Utils module .
46
7
27,572
def batch ( self , owner , action = None , attribute_write_type = None , halt_on_error = False , playbook_triggers_enabled = None , ) : from . tcex_ti_batch import TcExBatch return TcExBatch ( self , owner , action , attribute_write_type , halt_on_error , playbook_triggers_enabled )
Return instance of Batch
87
5
27,573
def cache ( self , domain , data_type , ttl_minutes = None , mapping = None ) : from . tcex_cache import TcExCache return TcExCache ( self , domain , data_type , ttl_minutes , mapping )
Get instance of the Cache module .
58
7
27,574
def data_filter ( self , data ) : try : from . tcex_data_filter import DataFilter return DataFilter ( self , data ) except ImportError as e : warn = u'Required Module is not installed ({}).' . format ( e ) self . log . warning ( warn )
Return an instance of the Data Filter Class .
64
9
27,575
def datastore ( self , domain , data_type , mapping = None ) : from . tcex_datastore import TcExDataStore return TcExDataStore ( self , domain , data_type , mapping )
Get instance of the DataStore module .
50
8
27,576
def error_codes ( self ) : if self . _error_codes is None : from . tcex_error_codes import TcExErrorCodes self . _error_codes = TcExErrorCodes ( ) return self . _error_codes
ThreatConnect error codes .
56
6
27,577
def exit ( self , code = None , msg = None ) : # add exit message to message.tc file and log if msg is not None : if code in [ 0 , 3 ] or ( code is None and self . exit_code in [ 0 , 3 ] ) : self . log . info ( msg ) else : self . log . error ( msg ) self . message_tc ( msg ) if code is None : code = self . exit_code elif code in [ 0 , 1 , 3 ] : pass else : self . log . error ( u'Invalid exit code' ) code = 1 if self . default_args . tc_aot_enabled : # push exit message self . playbook . aot_rpush ( code ) self . log . info ( u'Exit Code: {}' . format ( code ) ) sys . exit ( code )
Application exit method with proper exit code
182
7
27,578
def exit_code ( self , code ) : if code is not None and code in [ 0 , 1 , 3 ] : self . _exit_code = code else : self . log . warning ( u'Invalid exit code' )
Set the App exit code .
49
6
27,579
def get_type_from_api_entity ( self , api_entity ) : merged = self . group_types_data . copy ( ) merged . update ( self . indicator_types_data ) print ( merged ) for ( key , value ) in merged . items ( ) : if value . get ( 'apiEntity' ) == api_entity : return key return None
Returns the object type as a string given a api entity .
79
12
27,580
def install_json ( self ) : if self . _install_json is None : try : install_json_filename = os . path . join ( os . getcwd ( ) , 'install.json' ) with open ( install_json_filename , 'r' ) as fh : self . _install_json = json . load ( fh ) except IOError : self . log . warning ( u'Could not retrieve App Data.' ) self . _install_json = { } return self . _install_json
Return contents of install . json configuration file loading from disk if required .
112
14
27,581
def install_json_params ( self ) : if not self . _install_json_params : for param in self . install_json . get ( 'params' ) or [ ] : self . _install_json_params [ param . get ( 'name' ) ] = param return self . _install_json_params
Parse params from install . json into a dict by name .
69
13
27,582
def metric ( self , name , description , data_type , interval , keyed = False ) : from . tcex_metrics_v2 import TcExMetricsV2 return TcExMetricsV2 ( self , name , description , data_type , interval , keyed )
Get instance of the Metrics module .
64
8
27,583
def message_tc ( self , message , max_length = 255 ) : if os . access ( self . default_args . tc_out_path , os . W_OK ) : message_file = '{}/message.tc' . format ( self . default_args . tc_out_path ) else : message_file = 'message.tc' message = '{}\n' . format ( message ) if max_length - len ( message ) > 0 : with open ( message_file , 'a' ) as mh : mh . write ( message ) elif max_length > 0 : with open ( message_file , 'a' ) as mh : mh . write ( message [ : max_length ] ) max_length -= len ( message )
Write data to message_tc file in TcEX specified directory .
168
14
27,584
def playbook ( self ) : if self . _playbook is None : from . tcex_playbook import TcExPlaybook self . _playbook = TcExPlaybook ( self ) return self . _playbook
Include the Playbook Module .
49
7
27,585
def proxies ( self ) : proxies = { } if ( self . default_args . tc_proxy_host is not None and self . default_args . tc_proxy_port is not None ) : if ( self . default_args . tc_proxy_username is not None and self . default_args . tc_proxy_password is not None ) : tc_proxy_username = quote ( self . default_args . tc_proxy_username , safe = '~' ) tc_proxy_password = quote ( self . default_args . tc_proxy_password , safe = '~' ) # proxy url with auth proxy_url = '{}:{}@{}:{}' . format ( tc_proxy_username , tc_proxy_password , self . default_args . tc_proxy_host , self . default_args . tc_proxy_port , ) else : # proxy url without auth proxy_url = '{}:{}' . format ( self . default_args . tc_proxy_host , self . default_args . tc_proxy_port ) proxies = { 'http' : 'http://{}' . format ( proxy_url ) , 'https' : 'https://{}' . format ( proxy_url ) , } return proxies
Formats proxy configuration into required format for Python Requests module .
274
13
27,586
def request ( self , session = None ) : try : from . tcex_request import TcExRequest r = TcExRequest ( self , session ) if session is None and self . default_args . tc_proxy_external : self . log . info ( 'Using proxy server for external request {}:{}.' . format ( self . default_args . tc_proxy_host , self . default_args . tc_proxy_port ) ) r . proxies = self . proxies return r except ImportError as e : self . handle_error ( 105 , [ e ] )
Return an instance of the Request Class .
124
8
27,587
def resource ( self , resource_type ) : try : resource = getattr ( self . resources , self . safe_rt ( resource_type ) ) ( self ) except AttributeError : self . _resources ( True ) resource = getattr ( self . resources , self . safe_rt ( resource_type ) ) ( self ) return resource
Get instance of Resource Class with dynamic type .
72
9
27,588
def results_tc ( self , key , value ) : if os . access ( self . default_args . tc_out_path , os . W_OK ) : results_file = '{}/results.tc' . format ( self . default_args . tc_out_path ) else : results_file = 'results.tc' new = True open ( results_file , 'a' ) . close ( ) # ensure file exists with open ( results_file , 'r+' ) as fh : results = '' for line in fh . read ( ) . strip ( ) . split ( '\n' ) : if not line : continue try : k , v = line . split ( ' = ' ) except ValueError : # handle null/empty value (e.g., "name =") k , v = line . split ( ' =' ) if k == key : v = value new = False if v is not None : results += '{} = {}\n' . format ( k , v ) if new and value is not None : # indicates the key/value pair didn't already exist results += '{} = {}\n' . format ( key , value ) fh . seek ( 0 ) fh . write ( results ) fh . truncate ( )
Write data to results_tc file in TcEX specified directory .
277
14
27,589
def safe_indicator ( self , indicator , errors = 'strict' ) : if indicator is not None : try : indicator = quote ( self . s ( str ( indicator ) , errors = errors ) , safe = '~' ) except KeyError : indicator = quote ( bytes ( indicator ) , safe = '~' ) return indicator
Indicator encode value for safe HTTP request .
71
9
27,590
def safe_rt ( resource_type , lower = False ) : if resource_type is not None : resource_type = resource_type . replace ( ' ' , '_' ) if lower : resource_type = resource_type . lower ( ) return resource_type
Format the Resource Type .
57
5
27,591
def safe_group_name ( group_name , group_max_length = 100 , ellipsis = True ) : ellipsis_value = '' if ellipsis : ellipsis_value = ' ...' if group_name is not None and len ( group_name ) > group_max_length : # split name by spaces and reset group_name group_name_array = group_name . split ( ' ' ) group_name = '' for word in group_name_array : word = u'{}' . format ( word ) if ( len ( group_name ) + len ( word ) + len ( ellipsis_value ) ) >= group_max_length : group_name = '{}{}' . format ( group_name , ellipsis_value ) group_name = group_name . lstrip ( ' ' ) break group_name += ' {}' . format ( word ) return group_name
Truncate group name to match limit breaking on space and optionally add an ellipsis .
202
19
27,592
def safe_url ( self , url , errors = 'strict' ) : if url is not None : url = quote ( self . s ( url , errors = errors ) , safe = '~' ) return url
URL encode value for safe HTTP request .
46
8
27,593
def session ( self ) : if self . _session is None : from . tcex_session import TcExSession self . _session = TcExSession ( self ) return self . _session
Return an instance of Requests Session configured for the ThreatConnect API .
43
14
27,594
def ti ( self ) : if self . _ti is None : from . tcex_ti import TcExTi self . _ti = TcExTi ( self ) return self . _ti
Include the Threat Intel Module .
43
7
27,595
def assignees ( self ) : if not self . can_update ( ) : self . _tcex . handle_error ( 910 , [ self . type ] ) for a in self . tc_requests . assignees ( self . api_type , self . api_sub_type , self . unique_id ) : yield a
Gets the task assignees
73
6
27,596
def escalatees ( self ) : if not self . can_update ( ) : self . _tcex . handle_error ( 910 , [ self . type ] ) for e in self . tc_requests . escalatees ( self . api_type , self . api_sub_type , self . unique_id ) : yield e
Gets the task escalatees
73
6
27,597
def read ( self , key ) : key = quote ( key , safe = '~' ) url = '/internal/playbooks/keyValue/{}' . format ( key ) r = self . tcex . session . get ( url ) data = r . content if data is not None and not isinstance ( data , str ) : data = str ( r . content , 'utf-8' ) return data
Read data from remote KV store for the provided key .
89
12
27,598
def can_create ( self ) : if ( self . data . get ( 'key_name' ) and self . data . get ( 'value_name' ) and self . data . get ( 'value_type' ) ) : return True return False
If the key_name value_name and value_type has been provided returns that the Registry Key can be created otherwise returns that the Registry Key cannot be created .
54
33
27,599
def metric_create ( self ) : body = { 'dataType' : self . _metric_data_type , 'description' : self . _metric_description , 'interval' : self . _metric_interval , 'name' : self . _metric_name , 'keyedValues' : self . _metric_keyed , } self . tcex . log . debug ( 'metric body: {}' . format ( body ) ) r = self . tcex . session . post ( '/v2/customMetrics' , json = body ) if not r . ok or 'application/json' not in r . headers . get ( 'content-type' , '' ) : self . tcex . handle_error ( 700 , [ r . status_code , r . text ] ) data = r . json ( ) self . _metric_id = data . get ( 'data' , { } ) . get ( 'customMetricConfig' , { } ) . get ( 'id' ) self . tcex . log . debug ( 'metric data: {}' . format ( data ) )
Create the defined metric .
249
5