idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
27,500
def mutex ( self , mutex , ** kwargs ) : indicator_obj = Mutex ( mutex , ** kwargs ) return self . _indicator ( indicator_obj )
Add Mutex data to Batch object .
27,501
def poll ( self , batch_id , retry_seconds = None , back_off = None , timeout = None , halt_on_error = True ) : if self . halt_on_poll_error is not None : halt_on_error = self . halt_on_poll_error if self . _poll_interval is None and self . _batch_data_count is not None : self . _poll_interval = max ( math . ceil ( sel...
Poll Batch status to ThreatConnect API .
27,502
def registry_key ( self , key_name , value_name , value_type , ** kwargs ) : indicator_obj = RegistryKey ( key_name , value_name , value_type , ** kwargs ) return self . _indicator ( indicator_obj )
Add Registry Key data to Batch object .
27,503
def report ( self , name , ** kwargs ) : group_obj = Report ( name , ** kwargs ) return self . _group ( group_obj )
Add Report data to Batch object .
27,504
def save ( self , resource ) : resource_type = None xid = None if isinstance ( resource , dict ) : resource_type = resource . get ( 'type' ) xid = resource . get ( 'xid' ) else : resource_type = resource . type xid = resource . xid if resource_type is not None and xid is not None : saved = True if resource_type in self...
Save group|indicator dict or object to shelve .
27,505
def saved_groups ( self ) : if self . _saved_groups is None : self . _saved_groups = False fqfn_saved = os . path . join ( self . tcex . args . tc_temp_path , 'groups-saved' ) if ( self . enable_saved_file and os . path . isfile ( fqfn_saved ) and os . access ( fqfn_saved , os . R_OK ) ) : self . _saved_groups = True s...
Return True if saved group files exits else False .
27,506
def saved_xids ( self ) : if self . _saved_xids is None : self . _saved_xids = [ ] if self . debug : fpfn = os . path . join ( self . tcex . args . tc_temp_path , 'xids-saved' ) if os . path . isfile ( fpfn ) and os . access ( fpfn , os . R_OK ) : with open ( fpfn ) as fh : self . _saved_xids = fh . read ( ) . splitlin...
Return previously saved xids .
27,507
def settings ( self ) : _settings = { 'action' : self . _action , 'attributeWriteType' : 'Replace' , 'haltOnError' : str ( self . _halt_on_error ) . lower ( ) , 'owner' : self . _owner , 'version' : 'V2' , } if self . _playbook_triggers_enabled is not None : _settings [ 'playbookTriggersEnabled' ] = str ( self . _playb...
Return batch job settings .
27,508
def signature ( self , name , file_name , file_type , file_text , ** kwargs ) : group_obj = Signature ( name , file_name , file_type , file_text , ** kwargs ) return self . _group ( group_obj )
Add Signature data to Batch object .
27,509
def submit_files ( self , halt_on_error = True ) : if self . halt_on_file_error is not None : halt_on_error = self . halt_on_file_error upload_status = [ ] for xid , content_data in self . _files . items ( ) : del self . _files [ xid ] status = True if self . debug and xid in self . saved_xids : self . tcex . log . deb...
Submit Files for Documents and Reports to ThreatConnect API .
27,510
def submit_file_content ( self , method , url , data , headers , params , halt_on_error = True ) : r = None try : r = self . tcex . session . request ( method , url , data = data , headers = headers , params = params ) except Exception as e : self . tcex . handle_error ( 580 , [ e ] , halt_on_error ) return r
Submit File Content for Documents and Reports to ThreatConnect API .
27,511
def threat ( self , name , ** kwargs ) : group_obj = Threat ( name , ** kwargs ) return self . _group ( group_obj )
Add Threat data to Batch object
27,512
def user_agent ( self , text , ** kwargs ) : indicator_obj = UserAgent ( text , ** kwargs ) return self . _indicator ( indicator_obj )
Add User Agent data to Batch object
27,513
def url ( self , text , ** kwargs ) : indicator_obj = URL ( text , ** kwargs ) return self . _indicator ( indicator_obj )
Add URL Address data to Batch object .
27,514
def write_batch_json ( self , content ) : timestamp = str ( time . time ( ) ) . replace ( '.' , '' ) batch_json_file = os . path . join ( self . tcex . args . tc_temp_path , 'batch-{}.json' . format ( timestamp ) ) with open ( batch_json_file , 'w' ) as fh : json . dump ( content , fh , indent = 2 )
Write batch json data to a file .
27,515
def attribute_labels ( self , attribute_id , params = None ) : if params is None : params = { } if not self . can_update ( ) : self . _tcex . handle_error ( 910 , [ self . type ] ) for al in self . tc_requests . attribute_labels ( self . api_type , self . api_sub_type , self . unique_id , attribute_id , owner = self . ...
Gets the security labels from a attribute
27,516
def attribute_label ( self , attribute_id , label , action = 'GET' , params = None ) : if params is None : params = { } if not self . can_update ( ) : self . _tcex . handle_error ( 910 , [ self . type ] ) if action == 'GET' : return self . tc_requests . get_attribute_label ( self . api_type , self . api_sub_type , self...
Gets a security labels from a attribute
27,517
def add_attribute_label ( self , attribute_id , label ) : if not self . can_update ( ) : self . _tcex . handle_error ( 910 , [ self . type ] ) return self . tc_requests . add_attribute_label ( self . api_type , self . api_sub_type , self . unique_id , attribute_id , label , owner = self . owner )
Adds a security labels to a attribute
27,518
def bundle ( self , bundle_name ) : if self . args . bundle or self . tcex_json . get ( 'package' , { } ) . get ( 'bundle' , False ) : if self . tcex_json . get ( 'package' , { } ) . get ( 'bundle_packages' ) is not None : for bundle in self . tcex_json . get ( 'package' , { } ) . get ( 'bundle_packages' ) or [ ] : bun...
Bundle multiple Job or Playbook Apps into a single zip file .
27,519
def commit_hash ( self ) : commit_hash = None branch = None branch_file = '.git/HEAD' if os . path . isfile ( branch_file ) : with open ( branch_file , 'r' ) as f : try : branch = f . read ( ) . strip ( ) . split ( '/' ) [ 2 ] except IndexError : pass if branch : hash_file = '.git/refs/heads/{}' . format ( branch ) if ...
Return the current commit hash if available .
27,520
def print_results ( self ) : if self . package_data . get ( 'updates' ) : print ( '\n{}{}Updates:' . format ( c . Style . BRIGHT , c . Fore . BLUE ) ) for p in self . package_data [ 'updates' ] : print ( '{!s:<20}{}{} {!s:<50}' . format ( p . get ( 'action' ) , c . Style . BRIGHT , c . Fore . CYAN , p . get ( 'output' ...
Print results of the package command .
27,521
def zip_file ( self , app_path , app_name , tmp_path ) : zip_file = os . path . join ( app_path , self . args . outdir , app_name ) zip_file_zip = '{}.zip' . format ( zip_file ) zip_file_tcx = '{}.tcx' . format ( zip_file ) shutil . make_archive ( zip_file , 'zip' , tmp_path , app_name ) shutil . move ( zip_file_zip , ...
Zip the App with tcex extension .
27,522
def content_type ( self , data ) : self . _content_type = str ( data ) self . add_header ( 'Content-Type' , str ( data ) )
The Content - Type header value for this request .
27,523
def set_basic_auth ( self , username , password ) : credentials = str ( b64encode ( '{}:{}' . format ( username , password ) . encode ( 'utf-8' ) ) , 'utf-8' ) self . authorization = 'Basic {}' . format ( credentials )
Manually set basic auth in the header when normal method does not work .
27,524
def http_method ( self , data ) : data = data . upper ( ) if data in [ 'DELETE' , 'GET' , 'POST' , 'PUT' ] : self . _http_method = data if self . _headers . get ( 'Content-Type' ) is None and data in [ 'POST' , 'PUT' ] : self . add_header ( 'Content-Type' , 'application/json' ) else : raise AttributeError ( 'Request Ob...
The HTTP method for this request .
27,525
def send ( self , stream = False ) : 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 : er...
Send the HTTP request via Python Requests modules .
27,526
def run ( self ) : indent = int ( self . tcex . playbook . read ( self . args . indent ) ) json_data = self . tcex . playbook . read ( self . args . json_data ) json_data_type = self . tcex . playbook . variable_type ( self . args . json_data ) if json_data_type in [ 'String' ] : json_data = json . loads ( json_data ) ...
Run the App main logic .
27,527
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 ( ',' ) : parsed_key = self . parse_variable ( o ) variabl...
Internal method to parse the tc_playbook_out_variable arg .
27,528
def _variable_pattern ( self ) : variable_pattern = r'#([A-Za-z]+)' variable_pattern += r':([\d]+)' variable_pattern += r':([A-Za-z0-9_\.\-\[\]]+)' variable_pattern += r'!(StringArray|BinaryArray|KeyValueArray' variable_pattern += r'|TCEntityArray|TCEnhancedEntityArray' variable_pattern += r'|String|Binary|KeyValue|TCE...
Regex pattern to match and parse a playbook variable .
27,529
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 , '...
Dynamically add output to output_data dictionary to be written to DB later .
27,530
def aot_blpop ( self ) : 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 ...
Subscribe to AOT action channel .
27,531
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 .
27,532
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 .
27,533
def create ( self , key , value ) : data = None if key is not None : key = key . strip ( ) self . tcex . log . debug ( u'create variable {}' . format ( key ) ) parsed_key = self . parse_variable ( key . strip ( ) ) variable_type = parsed_key [ 'type' ] if variable_type in self . read_data_types : data = self . create_d...
Create method of CRUD operation for working with KeyValue DB .
27,534
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_e...
Map of standard playbook variable types to create method .
27,535
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 : v = self . out_variables_type . get ( key_type ) self . tcex . log . info ( u'Vari...
Wrapper for Create method of CRUD operation for working with KeyValue DB .
27,536
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...
Return the correct KV store for this execution .
27,537
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 .
27,538
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 elif code not in [ 0 , 1 ] : code = 1 self . tcex . exit ( code , msg )
Playbook wrapper on TcEx exit method
27,539
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 ) , '...
Method to parse an input or output variable .
27,540
def read ( self , key , array = False , embedded = True ) : self . tcex . log . debug ( 'read variable {}' . format ( key ) ) 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 : if key_type...
Read method of CRUD operation for working with KeyValue DB .
27,541
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 , 'TCEntit...
Map of standard playbook variable types to read method .
27,542
def read_embedded ( self , data , parent_var_type ) : if data is None : return data 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_t...
Read method for mixed variable type .
27,543
def variable_type ( self , variable ) : var_type = 'String' if variable is not None : variable = variable . strip ( ) 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 .
27,544
def wrap_embedded_keyvalue ( self , data ) : if data is not None : try : data = u'{}' . format ( data ) except UnicodeEncodeError : pass variables = [ ] for v in re . finditer ( self . _vars_keyvalue_embedded , data ) : variables . append ( v . group ( 0 ) ) for var in set ( variables ) : variable_string = re . search ...
Wrap keyvalue embedded variable in double quotes .
27,545
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 .
27,546
def create_binary ( self , key , value ) : data = None if key is not None and value is not None : try : data = self . db . create ( key . strip ( ) , json . dumps ( base64 . b64encode ( bytes ( value ) ) . decode ( 'utf-8' ) ) ) except TypeError : data = self . db . create ( key . strip ( ) , json . dumps ( base64 . b6...
Create method of CRUD operation for binary data .
27,547
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 : data = base64 . b64decode ( data ) if decode : try : data = data . decode ( 'utf-8' ) except UnicodeDecodeEr...
Read method of CRUD operation for binary data .
27,548
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 : value_encoded . append ( base64 . b64encode ( bytes ( v ) ) . decode ( 'utf-8' ) ) except TypeError : value_encoded . append ( base64 . b64encode ( bytes ( v , 'utf-8' ) ) ....
Create method of CRUD operation for binary array data .
27,549
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 : dd = base64 . b64decode ( d ) if decode : try...
Read method of CRUD operation for binary array data .
27,550
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 .
27,551
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 .
27,552
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 = u'{}' . format ( value ) data = self . db . create ( key . strip ( ) , u'{}' . format ( json . dumps ( value ) ) ) else : self . tcex . log . warning ( u'The...
Create method of CRUD operation for string data .
27,553
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 : try : data = json . loads ( data ) if embedded : data = self . read_embedded ( data , key_type ) if data is not None : data = u'{}...
Read method of CRUD operation for string data .
27,554
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 : data = self . db . create ( key . strip ( ) , value ) else : self . tcex . log . warning ( u'The key ...
Create method of CRUD operation for string array data .
27,555
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 = Ordered...
Read method of CRUD operation for string array data .
27,556
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 .
27,557
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 . ...
Convert Single TC Entity to Bulk format .
27,558
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 .
27,559
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 : values = [ ] for field in value_fields : if d . get ( field ) is not None : values . append ( d . get ( field ) ) del d [ field ] if resou...
Convert ThreatConnect JSON response to a Bulk Format .
27,560
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' ) } values = [ ] if 'summary' in d : values . append ( d . get ( ...
Convert ThreatConnect JSON response to a TCEntityArray .
27,561
def any_to_datetime ( self , time_input , tz = None ) : dt_value = self . unix_time_to_datetime ( time_input , tz ) if dt_value is None : dt_value = self . date_to_datetime ( time_input , tz ) if dt_value is None : dt_value = self . human_date_to_datetime ( time_input , tz ) if dt_value is None : raise RuntimeError ( '...
Return datetime object from multiple formats .
27,562
def date_to_datetime ( self , time_input , tz = None ) : dt = None try : dt = parser . parse ( time_input ) 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 ValueEr...
Convert ISO 8601 and other date strings to datetime . datetime type .
27,563
def format_datetime ( self , time_input , tz = None , date_format = None ) : dt_value = self . any_to_datetime ( time_input , tz ) 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 timestamp from multiple input formats .
27,564
def inflect ( self ) : if self . _inflect is None : import inflect self . _inflect = inflect . engine ( ) return self . _inflect
Return instance of inflect .
27,565
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 .
27,566
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 delta = relativedelta ( time_input1 , time_input2 ) total_months = ( delta . years * 12 ) + delta . months total_weeks = ( delta...
Calculates time delta between two time expressions .
27,567
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_r...
Updates the event_date .
27,568
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_as...
Adds a asset to the Victim
27,569
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_re...
Update a asset of a Victim
27,570
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_...
Gets a asset of a Victim
27,571
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 . v...
Gets the assets of a Victim
27,572
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 .
27,573
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_...
Create a temporary DB table .
27,574
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 .
27,575
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 "{}" ...
Return install . json contents .
27,576
def install_json_params ( self , ij = None ) : if self . _install_json_params is None or ij is not None : self . _install_json_params = { } 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_par...
Return install . json params in a dict with name param as key .
27,577
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 = { } if ij is None : ij = self . install_json for p in ij . get ( 'playbook' , { } ) . get ( 'outputVariables' ) or [ ] : self . _install_json_output_varia...
Return install . json output variables in a dict with name param as key .
27,578
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...
Return layout . json contents .
27,579
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 .
27,580
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 .
27,581
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 .
27,582
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 : ...
Return install . json data .
27,583
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 .
27,584
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 ({}).' ...
Return tcex . json file contents .
27,585
def update_system_path ( ) : cwd = os . getcwd ( ) lib_dir = os . path . join ( os . getcwd ( ) , 'lib_' ) lib_latest = os . path . join ( os . getcwd ( ) , 'lib_latest' ) if not [ p for p in sys . path if lib_dir in p ] : sys . path . insert ( 0 , lib_latest ) try : sys . path . remove ( cwd ) except ValueError : pass...
Update the system path to ensure project modules and dependencies can be found .
27,586
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 .
27,587
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 .
27,588
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 .
27,589
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 )...
Add custom field to Indicator object .
27,590
def association ( self , group_xid ) : association = { 'groupXid' : group_xid } self . _indicator_data . setdefault ( 'associatedGroups' , [ ] ) . append ( association )
Add association using xid value .
27,591
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_...
Return instance of Attribute
27,592
def data ( self ) : if self . _attributes : self . _indicator_data [ 'attribute' ] = [ ] for attr in self . _attributes : if attr . valid : self . _indicator_data [ 'attribute' ] . append ( attr . data ) if self . _file_actions : self . _indicator_data . setdefault ( 'fileAction' , { } ) self . _indicator_data [ 'fileA...
Return Indicator data .
27,593
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 .
27,594
def occurrence ( self , file_name = None , path = None , date = None ) : if self . _indicator_data . get ( 'type' ) != 'File' : return None occurrence_obj = FileOccurrence ( file_name , path , date ) self . _occurrences . append ( occurrence_obj ) return occurrence_obj
Add a file Occurrence .
27,595
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 .
27,596
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 .
27,597
def action ( self , relationship ) : action_obj = FileAction ( self . xid , relationship ) self . _children . append ( action_obj )
Add a nested File Action .
27,598
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 .
27,599
def address ( self , ip , owner = None , ** kwargs ) : return Address ( self . tcex , ip , owner = owner , ** kwargs )
Create the Address TI object .