idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
27,400
def _vars_match ( self ) : return re . compile ( r'#([A-Za-z]+)' r':([\d]+)' r':([A-Za-z0-9_\.\-\[\]]+)' r'!(StringArray|BinaryArray|KeyValueArray' r'|TCEntityArray|TCEnhancedEntityArray' r'|String|Binary|KeyValue|TCEntity|TCEnhancedEntity' r'|(?:(?!String)(?!Binary)(?!KeyValue)' r'(?!TCEntity)(?!TCEnhancedEntity)' r'[...
Regular expression to match playbook variable .
27,401
def autoclear ( self ) : for sd in self . staging_data : data_type = sd . get ( 'data_type' , 'redis' ) if data_type == 'redis' : self . clear_redis ( sd . get ( 'variable' ) , 'auto-clear' ) elif data_type == 'redis-array' : self . clear_redis ( sd . get ( 'variable' ) , 'auto-clear' ) for variables in sd . get ( 'dat...
Clear Redis and ThreatConnect data from staging data .
27,402
def clear ( self ) : for clear_data in self . profile . get ( 'clear' ) or [ ] : if clear_data . get ( 'data_type' ) == 'redis' : self . clear_redis ( clear_data . get ( 'variable' ) , 'clear' ) elif clear_data . get ( 'data_type' ) == 'threatconnect' : self . clear_tc ( clear_data . get ( 'owner' ) , clear_data , 'cle...
Clear Redis and ThreatConnect data defined in profile .
27,403
def clear_redis ( self , variable , clear_type ) : if variable is None : return if variable in self . _clear_redis_tracker : return if not re . match ( self . _vars_match , variable ) : return self . log . info ( '[{}] Deleting redis variable: {}.' . format ( clear_type , variable ) ) print ( 'Clearing Variables: {}{}{...
Delete Redis data for provided variable .
27,404
def clear_tc ( self , owner , data , clear_type ) : batch = self . tcex . batch ( owner , action = 'Delete' ) tc_type = data . get ( 'type' ) path = data . get ( 'path' ) if tc_type in self . tcex . group_types : name = self . tcex . playbook . read ( data . get ( 'name' ) ) name = self . path_data ( name , path ) if n...
Delete threat intel from ThreatConnect platform .
27,405
def data_in_db ( db_data , user_data ) : if isinstance ( user_data , list ) : if db_data in user_data : return True return False
Validate db data in user data .
27,406
def data_it ( db_data , user_type ) : data_type = { 'array' : ( list ) , 'dict' : ( dict ) , 'entity' : ( dict ) , 'list' : ( list ) , 'str' : ( string_types ) , 'string' : ( string_types ) , } if user_type is None : if db_data is None : return True elif user_type . lower ( ) in [ 'null' , 'none' ] : if db_data is None...
Validate data is type .
27,407
def data_not_in ( db_data , user_data ) : if isinstance ( user_data , list ) : if db_data not in user_data : return True return False
Validate data not in user data .
27,408
def data_string_compare ( db_data , user_data ) : db_data = '' . join ( db_data . split ( ) ) user_data = '' . join ( user_data . split ( ) ) if operator . eq ( db_data , user_data ) : return True return False
Validate string removing all white space before comparison .
27,409
def included_profiles ( self ) : profiles = [ ] for directory in self . tcex_json . get ( 'profile_include_dirs' ) or [ ] : profiles . extend ( self . _load_config_include ( directory ) ) return profiles
Load all profiles .
27,410
def load_tcex ( self ) : for arg , value in self . profile . get ( 'profile_args' , { } ) . data . items ( ) : if arg not in self . _tcex_required_args : continue sys . argv . extend ( [ '--tc_log_file' , 'tcex.log' ] ) sys . argv . extend ( [ '--tc_log_level' , 'error' ] ) arg = '--{}' . format ( arg ) if isinstance (...
Inject required TcEx CLI Args .
27,411
def operators ( self ) : return { 'dd' : self . deep_diff , 'deep-diff' : self . deep_diff , 'eq' : operator . eq , 'ew' : self . data_endswith , 'ends-with' : self . data_endswith , 'ge' : operator . ge , 'gt' : operator . gt , 'jc' : self . json_compare , 'json-compare' : self . json_compare , 'kva' : self . data_kva...
Return dict of Validation Operators .
27,412
def path_data ( self , variable_data , path ) : try : import jmespath except ImportError : print ( 'Could not import jmespath module (try "pip install jmespath").' ) sys . exit ( 1 ) if isinstance ( variable_data , string_types ) : try : variable_data = json . loads ( variable_data ) except Exception : self . log . deb...
Return JMESPath data .
27,413
def profile ( self , profile ) : self . _staging_data = None lang = profile . get ( 'install_json' , { } ) . get ( 'programLanguage' , 'PYTHON' ) profile_args = ArgBuilder ( lang , self . profile_args ( profile . get ( 'args' ) ) ) self . _profile = profile self . _profile [ 'profile_args' ] = profile_args self . load_...
Set the current profile .
27,414
def profile_args ( _args ) : if ( _args . get ( 'app' , { } ) . get ( 'optional' ) is not None or _args . get ( 'app' , { } ) . get ( 'required' ) is not None ) : app_args_optional = _args . get ( 'app' , { } ) . get ( 'optional' , { } ) app_args_required = _args . get ( 'app' , { } ) . get ( 'required' , { } ) default...
Return args for v1 v2 or v3 structure .
27,415
def profiles ( self ) : selected_profiles = [ ] for config in self . included_profiles : profile_selected = False profile_name = config . get ( 'profile_name' ) if profile_name == self . args . profile : profile_selected = True elif config . get ( 'group' ) is not None and config . get ( 'group' ) == self . args . grou...
Return all selected profiles .
27,416
def report ( self ) : print ( '\n{}{}{}' . format ( c . Style . BRIGHT , c . Fore . CYAN , 'Report:' ) ) print ( '{!s:<85}{!s:<20}' . format ( '' , 'Validations' ) ) print ( '{!s:<60}{!s:<25}{!s:<10}{!s:<10}' . format ( 'Profile:' , 'Execution:' , 'Passed:' , 'Failed:' ) ) for r in self . reports : d = r . data if not ...
Format and output report data to screen .
27,417
def run ( self ) : install_json = self . profile . get ( 'install_json' ) program_language = self . profile . get ( 'install_json' ) . get ( 'programLanguage' , 'python' ) . lower ( ) print ( '{}{}' . format ( c . Style . BRIGHT , '-' * 100 ) ) if install_json . get ( 'programMain' ) is not None : program_main = instal...
Run the App using the current profile .
27,418
def run_commands ( self , program_language , program_main ) : if program_language == 'python' : python_exe = sys . executable ptvsd_host = 'localhost' if self . args . docker : python_exe = 'python' ptvsd_host = '0.0.0.0' if self . args . vscd : self . update_environment ( ) command = [ python_exe , '-m' , 'ptvsd' , '-...
Return the run Print Command .
27,419
def run_local ( self , commands ) : process = subprocess . Popen ( commands . get ( 'cli_command' ) , shell = self . shell , stdin = subprocess . PIPE , stdout = subprocess . PIPE , stderr = subprocess . PIPE , ) out , err = process . communicate ( ) self . run_display_app_output ( out ) self . run_display_app_errors (...
Run the App on local system .
27,420
def run_docker ( self , commands ) : try : import docker except ImportError : print ( '{}{}Could not import docker module (try "pip install docker").' . format ( c . Style . BRIGHT , c . Fore . RED ) ) sys . exit ( 1 ) app_args_data = self . profile . get ( 'profile_args' ) . data install_json = self . profile . get ( ...
Run App in Docker Container .
27,421
def run_display_app_output ( self , out ) : if not self . profile . get ( 'quiet' ) and not self . args . quiet : print ( 'App Output:' ) for o in out . decode ( 'utf-8' ) . split ( '\n' ) : print ( ' {}{}{}' . format ( c . Style . BRIGHT , c . Fore . CYAN , o ) ) self . log . debug ( '[tcrun] App output: {}' . format...
Print any App output .
27,422
def run_validate_program_main ( self , program_main ) : program_language = self . profile . get ( 'install_json' ) . get ( 'programLanguage' , 'python' ) . lower ( ) if program_language == 'python' and not os . path . isfile ( '{}.py' . format ( program_main ) ) : print ( '{}{}Could not find program main file ({}).' . ...
Validate the program main file exists .
27,423
def stage ( self ) : for sd in self . staging_data : if not isinstance ( sd , dict ) : msg = 'Invalid staging data provided ({}).' . format ( sd ) sys . exit ( msg ) data_type = sd . get ( 'data_type' , 'redis' ) if data_type == 'redis' : self . log . debug ( 'Stage Redis Data' ) self . stage_redis ( sd . get ( 'variab...
Stage Redis and ThreatConnect data defined in profile .
27,424
def staging_data ( self ) : if self . _staging_data is None : staging_data = [ ] for staging_file in self . profile . get ( 'data_files' ) or [ ] : if os . path . isfile ( staging_file ) : print ( 'Staging Data: {}{}{}' . format ( c . Style . BRIGHT , c . Fore . MAGENTA , staging_file ) ) self . log . info ( '[stage] S...
Read data files and return all staging data for current profile .
27,425
def stage_redis ( self , variable , data ) : if isinstance ( data , int ) : data = str ( data ) if variable . endswith ( 'Binary' ) : try : data = base64 . b64decode ( data ) except binascii . Error : msg = 'The Binary staging data for variable {} is not properly base64 encoded.' msg = msg . format ( variable ) sys . e...
Stage data in Redis .
27,426
def stage_tc ( self , owner , staging_data , variable ) : resource_type = staging_data . pop ( 'type' ) if resource_type in self . tcex . indicator_types or resource_type in self . tcex . group_types : try : attributes = staging_data . pop ( 'attribute' ) except KeyError : attributes = [ ] try : security_labels = stagi...
Stage data using ThreatConnect API .
27,427
def stage_tc_create_security_label ( self , label , resource ) : sl_resource = resource . security_labels ( label ) sl_resource . http_method = 'POST' sl_response = sl_resource . request ( ) if sl_response . get ( 'status' ) != 'Success' : self . log . warning ( '[tcex] Failed adding security label "{}" ({}).' . format...
Add a security label to a resource .
27,428
def stage_tc_create_tag ( self , tag , resource ) : tag_resource = resource . tags ( self . tcex . safetag ( tag ) ) tag_resource . http_method = 'POST' t_response = tag_resource . request ( ) if t_response . get ( 'status' ) != 'Success' : self . log . warning ( '[tcex] Failed adding tag "{}" ({}).' . format ( tag , t...
Add a tag to a resource .
27,429
def stage_tc_batch ( self , owner , staging_data ) : batch = self . tcex . batch ( owner ) for group in staging_data . get ( 'group' ) or [ ] : variable = group . pop ( 'variable' , None ) path = group . pop ( 'path' , None ) data = self . path_data ( group , path ) if group . get ( 'xid' ) is None : group [ 'xid' ] = ...
Stage data in ThreatConnect Platform using batch API .
27,430
def stage_tc_batch_xid ( xid_type , xid_value , owner ) : xid_string = '{}-{}-{}' . format ( xid_type , xid_value , owner ) hash_object = hashlib . sha256 ( xid_string . encode ( 'utf-8' ) ) return hash_object . hexdigest ( )
Create an xid for a batch job .
27,431
def stage_tc_indicator_entity ( self , indicator_data ) : path = '@.{value: summary, ' path += 'type: type, ' path += 'ownerName: ownerName, ' path += 'confidence: confidence || `0`, ' path += 'rating: rating || `0`}' return self . path_data ( indicator_data , path )
Convert JSON data to TCEntity .
27,432
def validate_log_output ( self , passed , db_data , user_data , oper ) : truncate = self . args . truncate if db_data is not None and passed : if isinstance ( db_data , ( string_types ) ) and len ( db_data ) > truncate : db_data = db_data [ : truncate ] elif isinstance ( db_data , ( list ) ) : db_data_truncated = [ ] f...
Format the validation log output to be easier to read .
27,433
def _add_arg_python ( self , key , value = None , mask = False ) : self . _data [ key ] = value if not value : pass elif value is True : self . _args . append ( '--{}' . format ( key ) ) self . _args_quoted . append ( '--{}' . format ( key ) ) self . _args_masked . append ( '--{}' . format ( key ) ) else : self . _args...
Add CLI Arg formatted specifically for Python .
27,434
def _add_arg_java ( self , key , value , mask = False ) : if isinstance ( value , bool ) : value = int ( value ) self . _data [ key ] = value self . _args . append ( '{}{}={}' . format ( '-D' , key , value ) ) self . _args_quoted . append ( self . quote ( '{}{}={}' . format ( '-D' , key , value ) ) ) if mask : value = ...
Add CLI Arg formatted specifically for Java .
27,435
def _add_arg ( self , key , value , mask = False ) : if self . lang == 'python' : self . _add_arg_python ( key , value , mask ) elif self . lang == 'java' : self . _add_arg_java ( key , value , mask )
Add CLI Arg for the correct language .
27,436
def add ( self , key , value ) : if isinstance ( value , list ) : for val in value : self . _add_arg_python ( key , val ) elif isinstance ( value , dict ) : err = 'Dictionary types are not currently supported for field.' print ( '{}{}{}' . format ( c . Style . BRIGHT , c . Fore . RED , err ) ) else : mask = False env_v...
Add CLI Arg to lists value .
27,437
def quote ( self , data ) : if self . lang == 'python' : quote_char = "'" elif self . lang == 'java' : quote_char = "'" if re . findall ( r'[!\-\=\s\$\&]{1,}' , str ( data ) ) : data = '{0}{1}{0}' . format ( quote_char , data ) return data
Quote any parameters that contain spaces or special character .
27,438
def load ( self , profile_args ) : for key , value in profile_args . items ( ) : self . add ( key , value )
Load provided CLI Args .
27,439
def add_profile ( self , profile , selected ) : report = Report ( profile ) report . selected = selected if selected : self . report [ 'settings' ] [ 'selected_profiles' ] . append ( report . name ) self . report [ 'settings' ] [ 'selected_profile_count' ] += 1 self . report [ 'settings' ] [ 'total_profile_count' ] += ...
Add profile to report .
27,440
def profile ( self , name ) : self . selected_profile = self . profiles . get ( name ) return self . profiles . get ( name )
Return a specific profile .
27,441
def add_file ( self , filename , file_content ) : self . _group_data [ 'fileName' ] = filename self . _file_content = file_content
Add a file for Document and Report types .
27,442
def add_key_value ( self , key , value ) : key = self . _metadata_map . get ( key , key ) if key in [ 'dateAdded' , 'eventDate' , 'firstSeen' , 'publishDate' ] : self . _group_data [ key ] = self . _utils . format_datetime ( value , date_format = '%Y-%m-%dT%H:%M:%SZ' ) elif key == 'file_content' : pass else : self . _g...
Add custom field to Group object .
27,443
def data ( self ) : if self . _attributes : self . _group_data [ 'attribute' ] = [ ] for attr in self . _attributes : if attr . valid : self . _group_data [ 'attribute' ] . append ( attr . data ) if self . _labels : self . _group_data [ 'securityLabel' ] = [ ] for label in self . _labels : self . _group_data [ 'securit...
Return Group data .
27,444
def security_label ( self , name , description = None , color = None ) : label = SecurityLabel ( name , description , color ) for label_data in self . _labels : if label_data . name == name : label = label_data break else : self . _labels . append ( label ) return label
Return instance of SecurityLabel .
27,445
def tag ( self , name , formatter = None ) : tag = Tag ( name , formatter ) for tag_data in self . _tags : if tag_data . name == name : tag = tag_data break else : self . _tags . append ( tag ) return tag
Return instance of Tag .
27,446
def first_seen ( self , first_seen ) : self . _group_data [ 'firstSeen' ] = self . _utils . format_datetime ( first_seen , date_format = '%Y-%m-%dT%H:%M:%SZ' )
Set Document first seen .
27,447
def event_date ( self , event_date ) : self . _group_data [ 'eventDate' ] = self . _utils . format_datetime ( event_date , date_format = '%Y-%m-%dT%H:%M:%SZ' )
Set the Events event date value .
27,448
def publish_date ( self , publish_date ) : self . _group_data [ 'publishDate' ] = self . _utils . format_datetime ( publish_date , date_format = '%Y-%m-%dT%H:%M:%SZ' )
Set Report publish date
27,449
def find_lib_directory ( self ) : lib_directory = None if self . lib_micro_version in self . lib_directories : lib_directory = self . lib_micro_version elif self . lib_minor_version in self . lib_directories : lib_directory = self . lib_minor_version elif self . lib_major_version in self . lib_directories : lib_directo...
Find the optimal lib directory .
27,450
def lib_directories ( self ) : if self . _lib_directories is None : self . _lib_directories = [ ] app_path = os . getcwd ( ) contents = os . listdir ( app_path ) for c in contents : if c . startswith ( 'lib' ) and os . path . isdir ( c ) and ( os . access ( c , os . R_OK ) ) : self . _lib_directories . append ( c ) ret...
Get all lib directories .
27,451
def _set_unique_id ( self , json_response ) : self . unique_id = ( json_response . get ( 'md5' ) or json_response . get ( 'sha1' ) or json_response . get ( 'sha256' ) or '' )
Sets the unique_id provided a json response .
27,452
def rating ( self , value ) : if not self . can_update ( ) : self . _tcex . handle_error ( 910 , [ self . type ] ) request_data = { 'rating' : value } return self . tc_requests . update ( self . api_type , self . api_sub_type , self . unique_id , request_data , owner = self . owner )
Updates the Indicators rating
27,453
def add_observers ( self , count , date_observed ) : if not self . can_update ( ) : self . _tcex . handle_error ( 910 , [ self . type ] ) data = { 'count' : count , 'dataObserved' : self . _utils . format_datetime ( date_observed , date_format = '%Y-%m-%dT%H:%M:%SZ' ) , } return self . tc_requests . add_observations ( ...
Adds a Indicator Observation
27,454
def deleted ( self , deleted_since , filters = None , params = None ) : return self . tc_requests . deleted ( self . api_type , self . api_sub_type , deleted_since , owner = self . owner , filters = filters , params = params , )
Gets the indicators deleted .
27,455
def build_summary ( val1 = None , val2 = None , val3 = None ) : summary = [ ] if val1 is not None : summary . append ( val1 ) if val2 is not None : summary . append ( val2 ) if val3 is not None : summary . append ( val3 ) if not summary : return None return ' : ' . join ( summary )
Constructs the summary given va1 va2 val3
27,456
def name ( self , name ) : self . _data [ 'name' ] = name request = self . _base_request request [ 'name' ] = name return self . _tc_requests . update ( request , owner = self . owner )
Updates the security labels name .
27,457
def color ( self , color ) : self . _data [ 'color' ] = color request = self . _base_request request [ 'color' ] = color return self . _tc_requests . update ( request , owner = self . owner )
Updates the security labels color .
27,458
def description ( self , description ) : self . _data [ 'description' ] = description request = self . _base_request request [ 'description' ] = description return self . _tc_requests . update ( request , owner = self . owner )
Updates the security labels description .
27,459
def date_added ( self , date_added ) : date_added = self . _utils . format_datetime ( date_added , date_format = '%Y-%m-%dT%H:%M:%SZ' ) self . _data [ 'dateAdded' ] = date_added request = self . _base_request request [ 'dateAdded' ] = date_added return self . _tc_requests . update ( request , owner = self . owner )
Updates the security labels date_added
27,460
def first_seen ( self , first_seen ) : if not self . can_update ( ) : self . _tcex . handle_error ( 910 , [ self . type ] ) first_seen = self . _utils . format_datetime ( first_seen , date_format = '%Y-%m-%dT%H:%M:%SZ' ) self . _data [ 'firstSeen' ] = first_seen request = { 'firstSeen' : first_seen } return self . tc_r...
Updates the campaign with the new first_seen date .
27,461
def add_filter ( self , filter_key , operator , value ) : filter_key = self . _metadata_map . get ( filter_key , filter_key ) self . filters . append ( { 'filter' : filter_key , 'operator' : operator , 'value' : value } )
Adds a filter given a key operator and value
27,462
def recipients ( self , notification_type , recipients , priority = 'Low' ) : self . _notification_type = notification_type self . _recipients = recipients self . _priority = priority self . _is_organization = False
Set vars for the passed in data . Used for one or more recipient notification .
27,463
def org ( self , notification_type , priority = 'Low' ) : self . _notification_type = notification_type self . _recipients = None self . _priority = priority self . _is_organization = True
Set vars for the passed in data . Used for org notification .
27,464
def send ( self , message ) : body = { 'notificationType' : self . _notification_type , 'priority' : self . _priority , 'isOrganization' : self . _is_organization , 'message' : message , } if self . _recipients : body [ 'recipients' ] = self . _recipients self . _tcex . log . debug ( 'notification body: {}' . format ( ...
Send our message
27,465
def assets ( self , asset_type = None ) : if not self . can_update ( ) : self . _tcex . handle_error ( 910 , [ self . type ] ) if not asset_type : return self . tc_requests . adversary_assets ( self . api_type , self . api_sub_type , self . unique_id ) if asset_type == 'PHONE' : return self . tc_requests . adversary_ph...
Retrieves all of the assets of a given asset_type
27,466
def delete_asset ( self , asset_id , asset_type ) : return self . asset ( asset_id , asset_type = asset_type , action = 'DELETE' )
Delete the asset with the provided asset_id .
27,467
def _build_command ( self , python_executable , lib_dir_fq , proxy_enabled ) : exe_command = [ os . path . expanduser ( python_executable ) , '-m' , 'pip' , 'install' , '-r' , self . requirements_file , '--ignore-installed' , '--quiet' , '--target' , lib_dir_fq , ] if self . args . no_cache_dir : exe_command . append (...
Build the pip command for installing dependencies .
27,468
def _configure_proxy ( self ) : if os . getenv ( 'HTTP_PROXY' ) or os . getenv ( 'HTTPS_PROXY' ) : return True proxy_enabled = False if self . args . proxy_host is not None and self . args . proxy_port is not None : if self . args . proxy_user is not None and self . args . proxy_pass is not None : proxy_user = quote ( ...
Configure proxy settings using environment variables .
27,469
def _create_temp_requirements ( self ) : self . use_temp_requirements_file = True with open ( self . requirements_file , 'r' ) as fh : current_requirements = fh . read ( ) . strip ( ) . split ( '\n' ) self . requirements_file = 'temp-{}' . format ( self . requirements_file ) with open ( self . requirements_file , 'w' )...
Create a temporary requirements . txt .
27,470
def _gen_indicator_class ( self ) : for entry in self . tcex . indicator_types_data . values ( ) : name = entry . get ( 'name' ) class_name = name . replace ( ' ' , '' ) entry [ 'custom' ] = self . tcex . utils . to_bool ( entry . get ( 'custom' ) ) if class_name in globals ( ) : continue value_fields = [ ] if entry . ...
Generate Custom Indicator Classes .
27,471
def _group ( self , group_data ) : if isinstance ( group_data , dict ) : xid = group_data . get ( 'xid' ) else : xid = group_data . xid if self . groups . get ( xid ) is not None : group_data = self . groups . get ( xid ) elif self . groups_shelf . get ( xid ) is not None : group_data = self . groups_shelf . get ( xid ...
Return previously stored group or new group .
27,472
def _indicator ( self , indicator_data ) : if isinstance ( indicator_data , dict ) : xid = indicator_data . get ( 'xid' ) else : xid = indicator_data . xid if self . indicators . get ( xid ) is not None : indicator_data = self . indicators . get ( xid ) elif self . indicators_shelf . get ( xid ) is not None : indicator...
Return previously stored indicator or new indicator .
27,473
def add_indicator ( self , indicator_data ) : if indicator_data . get ( 'type' ) not in [ 'Address' , 'EmailAddress' , 'File' , 'Host' , 'URL' ] : index = 1 for value in self . _indicator_values ( indicator_data . get ( 'summary' ) ) : indicator_data [ 'value{}' . format ( index ) ] = value index += 1 if indicator_data...
Add an indicator to Batch Job .
27,474
def address ( self , ip , ** kwargs ) : indicator_obj = Address ( ip , ** kwargs ) return self . _indicator ( indicator_obj )
Add Address data to Batch object .
27,475
def adversary ( self , name , ** kwargs ) : group_obj = Adversary ( name , ** kwargs ) return self . _group ( group_obj )
Add Adversary data to Batch object .
27,476
def asn ( self , as_number , ** kwargs ) : indicator_obj = ASN ( as_number , ** kwargs ) return self . _indicator ( indicator_obj )
Add ASN data to Batch object .
27,477
def campaign ( self , name , ** kwargs ) : group_obj = Campaign ( name , ** kwargs ) return self . _group ( group_obj )
Add Campaign data to Batch object .
27,478
def cidr ( self , block , ** kwargs ) : indicator_obj = CIDR ( block , ** kwargs ) return self . _indicator ( indicator_obj )
Add CIDR data to Batch object .
27,479
def close ( self ) : self . groups_shelf . close ( ) self . indicators_shelf . close ( ) if self . debug and self . enable_saved_file : fqfn = os . path . join ( self . tcex . args . tc_temp_path , 'xids-saved' ) if os . path . isfile ( fqfn ) : os . remove ( fqfn ) with open ( fqfn , 'w' ) as fh : for xid in self . sa...
Cleanup batch job .
27,480
def data ( self ) : entity_count = 0 data = { 'group' : [ ] , 'indicator' : [ ] } group_data , entity_count = self . data_groups ( self . groups , entity_count ) data [ 'group' ] . extend ( group_data ) if entity_count >= self . _batch_max_chunk : return data group_data , entity_count = self . data_groups ( self . grou...
Return the batch data to be sent to the ThreatConnect API .
27,481
def data_group_association ( self , xid ) : groups = [ ] group_data = None if self . groups . get ( xid ) is not None : group_data = self . groups . get ( xid ) del self . groups [ xid ] elif self . groups_shelf . get ( xid ) is not None : group_data = self . groups_shelf . get ( xid ) del self . groups_shelf [ xid ] i...
Return group dict array following all associations .
27,482
def data_group_type ( self , group_data ) : if isinstance ( group_data , dict ) : file_content = group_data . pop ( 'fileContent' , None ) if file_content is not None : self . _files [ group_data . get ( 'xid' ) ] = { 'fileContent' : file_content , 'type' : group_data . get ( 'type' ) , } else : GROUPS_STRINGS_WITH_FIL...
Return dict representation of group data .
27,483
def data_groups ( self , groups , entity_count ) : data = [ ] for xid in groups . keys ( ) : assoc_group_data = self . data_group_association ( xid ) data += assoc_group_data entity_count += len ( assoc_group_data ) if entity_count >= self . _batch_max_chunk : break return data , entity_count
Process Group data .
27,484
def data_indicators ( self , indicators , entity_count ) : data = [ ] for xid , indicator_data in indicators . items ( ) : entity_count += 1 if isinstance ( indicator_data , dict ) : data . append ( indicator_data ) else : data . append ( indicator_data . data ) del indicators [ xid ] if entity_count >= self . _batch_m...
Process Indicator data .
27,485
def debug ( self ) : debug = False if os . path . isfile ( os . path . join ( self . tcex . args . tc_temp_path , 'DEBUG' ) ) : debug = True return debug
Return debug setting
27,486
def document ( self , name , file_name , ** kwargs ) : group_obj = Document ( name , file_name , ** kwargs ) return self . _group ( group_obj )
Add Document data to Batch object .
27,487
def email ( self , name , subject , header , body , ** kwargs ) : group_obj = Email ( name , subject , header , body , ** kwargs ) return self . _group ( group_obj )
Add Email data to Batch object .
27,488
def errors ( self , batch_id , halt_on_error = True ) : errors = [ ] try : r = self . tcex . session . get ( '/v2/batch/{}/errors' . format ( batch_id ) ) self . tcex . log . debug ( 'Retrieve Errors for ID {}: status code {}, errors {}' . format ( batch_id , r . status_code , r . text ) ) if r . ok : errors = json . l...
Retrieve Batch errors to ThreatConnect API .
27,489
def event ( self , name , ** kwargs ) : group_obj = Event ( name , ** kwargs ) return self . _group ( group_obj )
Add Event data to Batch object .
27,490
def file ( self , md5 = None , sha1 = None , sha256 = None , ** kwargs ) : indicator_obj = File ( md5 , sha1 , sha256 , ** kwargs ) return self . _indicator ( indicator_obj )
Add File data to Batch object .
27,491
def generate_xid ( identifier = None ) : if identifier is None : identifier = str ( uuid . uuid4 ( ) ) elif isinstance ( identifier , list ) : identifier = '-' . join ( [ str ( i ) for i in identifier ] ) identifier = hashlib . sha256 ( identifier . encode ( 'utf-8' ) ) . hexdigest ( ) return hashlib . sha256 ( identif...
Generate xid from provided identifiers .
27,492
def group ( self , group_type , name , ** kwargs ) : group_obj = Group ( group_type , name , ** kwargs ) return self . _group ( group_obj )
Add Group data to Batch object .
27,493
def group_shelf_fqfn ( self ) : if self . _group_shelf_fqfn is None : self . _group_shelf_fqfn = os . path . join ( self . tcex . args . tc_temp_path , 'groups-{}' . format ( str ( uuid . uuid4 ( ) ) ) ) if self . saved_groups : self . _group_shelf_fqfn = os . path . join ( self . tcex . args . tc_temp_path , 'groups-s...
Return groups shelf fully qualified filename .
27,494
def groups_shelf ( self ) : if self . _groups_shelf is None : self . _groups_shelf = shelve . open ( self . group_shelf_fqfn , writeback = False ) return self . _groups_shelf
Return dictionary of all Groups data .
27,495
def incident ( self , name , ** kwargs ) : group_obj = Incident ( name , ** kwargs ) return self . _group ( group_obj )
Add Incident data to Batch object .
27,496
def indicator ( self , indicator_type , summary , ** kwargs ) : indicator_obj = Indicator ( indicator_type , summary , ** kwargs ) return self . _indicator ( indicator_obj )
Add Indicator data to Batch object .
27,497
def indicator_shelf_fqfn ( self ) : if self . _indicator_shelf_fqfn is None : self . _indicator_shelf_fqfn = os . path . join ( self . tcex . args . tc_temp_path , 'indicators-{}' . format ( str ( uuid . uuid4 ( ) ) ) ) if self . saved_indicators : self . _indicator_shelf_fqfn = os . path . join ( self . tcex . args . ...
Return indicator shelf fully qualified filename .
27,498
def indicators_shelf ( self ) : if self . _indicators_shelf is None : self . _indicators_shelf = shelve . open ( self . indicator_shelf_fqfn , writeback = False ) return self . _indicators_shelf
Return dictionary of all Indicator data .
27,499
def intrusion_set ( self , name , ** kwargs ) : group_obj = IntrusionSet ( name , ** kwargs ) return self . _group ( group_obj )
Add Intrusion Set data to Batch object .