repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
ThreatConnect-Inc/tcex | tcex/tcex_bin_run.py | TcExRun._vars_match | def _vars_match(self):
"""Regular expression to match playbook variable."""
return re.compile(
r'#([A-Za-z]+)' # match literal (#App) at beginning of String
r':([\d]+)' # app id (:7979)
r':([A-Za-z0-9_\.\-\[\]]+)' # variable name (:variable_name)
r'!(StringArray|BinaryArray|KeyValueArray' # variable type (array)
r'|TCEntityArray|TCEnhancedEntityArray' # variable type (array)
r'|String|Binary|KeyValue|TCEntity|TCEnhancedEntity' # variable type
r'|(?:(?!String)(?!Binary)(?!KeyValue)' # non matching for custom
r'(?!TCEntity)(?!TCEnhancedEntity)' # non matching for custom
r'[A-Za-z0-9_-]+))' # variable type (custom)
) | python | def _vars_match(self):
"""Regular expression to match playbook variable."""
return re.compile(
r'#([A-Za-z]+)' # match literal (#App) at beginning of String
r':([\d]+)' # app id (:7979)
r':([A-Za-z0-9_\.\-\[\]]+)' # variable name (:variable_name)
r'!(StringArray|BinaryArray|KeyValueArray' # variable type (array)
r'|TCEntityArray|TCEnhancedEntityArray' # variable type (array)
r'|String|Binary|KeyValue|TCEntity|TCEnhancedEntity' # variable type
r'|(?:(?!String)(?!Binary)(?!KeyValue)' # non matching for custom
r'(?!TCEntity)(?!TCEnhancedEntity)' # non matching for custom
r'[A-Za-z0-9_-]+))' # variable type (custom)
) | [
"def",
"_vars_match",
"(",
"self",
")",
":",
"return",
"re",
".",
"compile",
"(",
"r'#([A-Za-z]+)'",
"# match literal (#App) at beginning of String",
"r':([\\d]+)'",
"# app id (:7979)",
"r':([A-Za-z0-9_\\.\\-\\[\\]]+)'",
"# variable name (:variable_name)",
"r'!(StringArray|BinaryAr... | Regular expression to match playbook variable. | [
"Regular",
"expression",
"to",
"match",
"playbook",
"variable",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_run.py#L199-L211 | train | 27,400 |
ThreatConnect-Inc/tcex | tcex/tcex_bin_run.py | TcExRun.autoclear | def autoclear(self):
"""Clear Redis and ThreatConnect data from staging data."""
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('data', {}).get('variables') or []:
self.clear_redis(variables.get('value'), 'auto-clear')
elif data_type == 'threatconnect':
# self.clear_tc(sd.get('data_owner'), sd.get('data', {}), 'auto-clear')
# self.clear_redis(sd.get('variable'), 'auto-clear')
pass
elif data_type == 'threatconnect-association':
# assuming these have already been cleared
pass
elif data_type == 'threatconnect-batch':
for group in sd.get('data', {}).get('group') or []:
self.clear_tc(sd.get('data_owner'), group, 'auto-clear')
self.clear_redis(group.get('variable'), 'auto-clear')
for indicator in sd.get('data', {}).get('indicator') or []:
self.clear_tc(sd.get('data_owner'), indicator, 'auto-clear')
self.clear_redis(indicator.get('variable'), 'auto-clear')
for vd in self.profile.get('validations') or []:
data_type = vd.get('data_type', 'redis')
variable = vd.get('variable')
if data_type == 'redis':
self.clear_redis(variable, 'auto-clear') | python | def autoclear(self):
"""Clear Redis and ThreatConnect data from staging data."""
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('data', {}).get('variables') or []:
self.clear_redis(variables.get('value'), 'auto-clear')
elif data_type == 'threatconnect':
# self.clear_tc(sd.get('data_owner'), sd.get('data', {}), 'auto-clear')
# self.clear_redis(sd.get('variable'), 'auto-clear')
pass
elif data_type == 'threatconnect-association':
# assuming these have already been cleared
pass
elif data_type == 'threatconnect-batch':
for group in sd.get('data', {}).get('group') or []:
self.clear_tc(sd.get('data_owner'), group, 'auto-clear')
self.clear_redis(group.get('variable'), 'auto-clear')
for indicator in sd.get('data', {}).get('indicator') or []:
self.clear_tc(sd.get('data_owner'), indicator, 'auto-clear')
self.clear_redis(indicator.get('variable'), 'auto-clear')
for vd in self.profile.get('validations') or []:
data_type = vd.get('data_type', 'redis')
variable = vd.get('variable')
if data_type == 'redis':
self.clear_redis(variable, 'auto-clear') | [
"def",
"autoclear",
"(",
"self",
")",
":",
"for",
"sd",
"in",
"self",
".",
"staging_data",
":",
"data_type",
"=",
"sd",
".",
"get",
"(",
"'data_type'",
",",
"'redis'",
")",
"if",
"data_type",
"==",
"'redis'",
":",
"self",
".",
"clear_redis",
"(",
"sd",... | Clear Redis and ThreatConnect data from staging data. | [
"Clear",
"Redis",
"and",
"ThreatConnect",
"data",
"from",
"staging",
"data",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_run.py#L213-L241 | train | 27,401 |
ThreatConnect-Inc/tcex | tcex/tcex_bin_run.py | TcExRun.clear | def clear(self):
"""Clear Redis and ThreatConnect data defined in profile.
Redis Data:
.. code-block:: javascript
{
"data_type": "redis",
"variable": "#App:4768:tc.adversary!TCEntity"
}
ThreatConnect Data:
.. code-block:: javascript
{
"data_type": "threatconnect",
"owner": "TCI",
"type": "Address",
"value": "1.1.1.1"
}
"""
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, 'clear') | python | def clear(self):
"""Clear Redis and ThreatConnect data defined in profile.
Redis Data:
.. code-block:: javascript
{
"data_type": "redis",
"variable": "#App:4768:tc.adversary!TCEntity"
}
ThreatConnect Data:
.. code-block:: javascript
{
"data_type": "threatconnect",
"owner": "TCI",
"type": "Address",
"value": "1.1.1.1"
}
"""
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, 'clear') | [
"def",
"clear",
"(",
"self",
")",
":",
"for",
"clear_data",
"in",
"self",
".",
"profile",
".",
"get",
"(",
"'clear'",
")",
"or",
"[",
"]",
":",
"if",
"clear_data",
".",
"get",
"(",
"'data_type'",
")",
"==",
"'redis'",
":",
"self",
".",
"clear_redis",... | Clear Redis and ThreatConnect data defined in profile.
Redis Data:
.. code-block:: javascript
{
"data_type": "redis",
"variable": "#App:4768:tc.adversary!TCEntity"
}
ThreatConnect Data:
.. code-block:: javascript
{
"data_type": "threatconnect",
"owner": "TCI",
"type": "Address",
"value": "1.1.1.1"
} | [
"Clear",
"Redis",
"and",
"ThreatConnect",
"data",
"defined",
"in",
"profile",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_run.py#L243-L270 | train | 27,402 |
ThreatConnect-Inc/tcex | tcex/tcex_bin_run.py | TcExRun.clear_redis | def clear_redis(self, variable, clear_type):
"""Delete Redis data for provided variable.
Args:
variable (str): The Redis variable to delete.
clear_type (str): The type of clear action.
"""
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: {}{}{}'.format(c.Style.BRIGHT, c.Fore.MAGENTA, variable))
self.tcex.playbook.delete(variable)
self._clear_redis_tracker.append(variable) | python | def clear_redis(self, variable, clear_type):
"""Delete Redis data for provided variable.
Args:
variable (str): The Redis variable to delete.
clear_type (str): The type of clear action.
"""
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: {}{}{}'.format(c.Style.BRIGHT, c.Fore.MAGENTA, variable))
self.tcex.playbook.delete(variable)
self._clear_redis_tracker.append(variable) | [
"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",
".",... | Delete Redis data for provided variable.
Args:
variable (str): The Redis variable to delete.
clear_type (str): The type of clear action. | [
"Delete",
"Redis",
"data",
"for",
"provided",
"variable",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_run.py#L272-L288 | train | 27,403 |
ThreatConnect-Inc/tcex | tcex/tcex_bin_run.py | TcExRun.clear_tc | def clear_tc(self, owner, data, clear_type):
"""Delete threat intel from ThreatConnect platform.
Args:
owner (str): The ThreatConnect owner.
data (dict): The data for the threat intel to clear.
clear_type (str): The type of clear action.
"""
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 name is not None:
print(
'Deleting ThreatConnect Group: {}{}{}'.format(
c.Style.BRIGHT, c.Fore.MAGENTA, name
)
)
self.log.info(
'[{}] Deleting ThreatConnect {} with name: {}.'.format(
clear_type, tc_type, name
)
)
batch.group(tc_type, name)
elif tc_type in self.tcex.indicator_types:
if data.get('summary') is not None:
summary = self.tcex.playbook.read(data.get('summary'))
else:
resource = self.tcex.resource(tc_type)
summary = resource.summary(data)
summary = self.path_data(summary, path)
if summary is not None:
print(
'Deleting ThreatConnect Indicator: {}{}{}'.format(
c.Style.BRIGHT, c.Fore.MAGENTA, summary
)
)
self.log.info(
'[{}] Deleting ThreatConnect {} with value: {}.'.format(
clear_type, tc_type, summary
)
)
batch.indicator(tc_type, summary)
batch_results = batch.submit()
self.log.debug('[{}] Batch Results: {}'.format(clear_type, batch_results))
for error in batch_results.get('errors') or []:
self.log.error('[{}] Batch Error: {}'.format(clear_type, error)) | python | def clear_tc(self, owner, data, clear_type):
"""Delete threat intel from ThreatConnect platform.
Args:
owner (str): The ThreatConnect owner.
data (dict): The data for the threat intel to clear.
clear_type (str): The type of clear action.
"""
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 name is not None:
print(
'Deleting ThreatConnect Group: {}{}{}'.format(
c.Style.BRIGHT, c.Fore.MAGENTA, name
)
)
self.log.info(
'[{}] Deleting ThreatConnect {} with name: {}.'.format(
clear_type, tc_type, name
)
)
batch.group(tc_type, name)
elif tc_type in self.tcex.indicator_types:
if data.get('summary') is not None:
summary = self.tcex.playbook.read(data.get('summary'))
else:
resource = self.tcex.resource(tc_type)
summary = resource.summary(data)
summary = self.path_data(summary, path)
if summary is not None:
print(
'Deleting ThreatConnect Indicator: {}{}{}'.format(
c.Style.BRIGHT, c.Fore.MAGENTA, summary
)
)
self.log.info(
'[{}] Deleting ThreatConnect {} with value: {}.'.format(
clear_type, tc_type, summary
)
)
batch.indicator(tc_type, summary)
batch_results = batch.submit()
self.log.debug('[{}] Batch Results: {}'.format(clear_type, batch_results))
for error in batch_results.get('errors') or []:
self.log.error('[{}] Batch Error: {}'.format(clear_type, error)) | [
"def",
"clear_tc",
"(",
"self",
",",
"owner",
",",
"data",
",",
"clear_type",
")",
":",
"batch",
"=",
"self",
".",
"tcex",
".",
"batch",
"(",
"owner",
",",
"action",
"=",
"'Delete'",
")",
"tc_type",
"=",
"data",
".",
"get",
"(",
"'type'",
")",
"pat... | Delete threat intel from ThreatConnect platform.
Args:
owner (str): The ThreatConnect owner.
data (dict): The data for the threat intel to clear.
clear_type (str): The type of clear action. | [
"Delete",
"threat",
"intel",
"from",
"ThreatConnect",
"platform",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_run.py#L290-L338 | train | 27,404 |
ThreatConnect-Inc/tcex | tcex/tcex_bin_run.py | TcExRun.data_in_db | def data_in_db(db_data, user_data):
"""Validate db data in user data.
Args:
db_data (str): The data store in Redis.
user_data (list): The user provided data.
Returns:
bool: True if the data passed validation.
"""
if isinstance(user_data, list):
if db_data in user_data:
return True
return False | python | def data_in_db(db_data, user_data):
"""Validate db data in user data.
Args:
db_data (str): The data store in Redis.
user_data (list): The user provided data.
Returns:
bool: True if the data passed validation.
"""
if isinstance(user_data, list):
if db_data in user_data:
return True
return False | [
"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.
Args:
db_data (str): The data store in Redis.
user_data (list): The user provided data.
Returns:
bool: True if the data passed validation. | [
"Validate",
"db",
"data",
"in",
"user",
"data",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_run.py#L356-L369 | train | 27,405 |
ThreatConnect-Inc/tcex | tcex/tcex_bin_run.py | TcExRun.data_it | def data_it(db_data, user_type):
"""Validate data is type.
Args:
db_data (dict|str|list): The data store in Redis.
user_data (str): The user provided data.
Returns:
bool: True if the data passed validation.
"""
data_type = {
'array': (list),
# 'binary': (string_types),
# 'bytes': (string_types),
'dict': (dict),
'entity': (dict),
'list': (list),
'str': (string_types),
'string': (string_types),
}
# user_type_tuple = tuple([data_type[t] for t in user_types])
# if isinstance(db_data, user_type_tuple):
if user_type is None:
if db_data is None:
return True
elif user_type.lower() in ['null', 'none']:
if db_data is None:
return True
elif user_type.lower() in 'binary':
# this test is not 100%, but should be good enough
try:
base64.b64decode(db_data)
return True
except Exception:
return False
elif data_type.get(user_type.lower()) is not None:
if isinstance(db_data, data_type.get(user_type.lower())):
return True
return False | python | def data_it(db_data, user_type):
"""Validate data is type.
Args:
db_data (dict|str|list): The data store in Redis.
user_data (str): The user provided data.
Returns:
bool: True if the data passed validation.
"""
data_type = {
'array': (list),
# 'binary': (string_types),
# 'bytes': (string_types),
'dict': (dict),
'entity': (dict),
'list': (list),
'str': (string_types),
'string': (string_types),
}
# user_type_tuple = tuple([data_type[t] for t in user_types])
# if isinstance(db_data, user_type_tuple):
if user_type is None:
if db_data is None:
return True
elif user_type.lower() in ['null', 'none']:
if db_data is None:
return True
elif user_type.lower() in 'binary':
# this test is not 100%, but should be good enough
try:
base64.b64decode(db_data)
return True
except Exception:
return False
elif data_type.get(user_type.lower()) is not None:
if isinstance(db_data, data_type.get(user_type.lower())):
return True
return False | [
"def",
"data_it",
"(",
"db_data",
",",
"user_type",
")",
":",
"data_type",
"=",
"{",
"'array'",
":",
"(",
"list",
")",
",",
"# 'binary': (string_types),",
"# 'bytes': (string_types),",
"'dict'",
":",
"(",
"dict",
")",
",",
"'entity'",
":",
"(",
"dict",
")",
... | Validate data is type.
Args:
db_data (dict|str|list): The data store in Redis.
user_data (str): The user provided data.
Returns:
bool: True if the data passed validation. | [
"Validate",
"data",
"is",
"type",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_run.py#L387-L425 | train | 27,406 |
ThreatConnect-Inc/tcex | tcex/tcex_bin_run.py | TcExRun.data_not_in | def data_not_in(db_data, user_data):
"""Validate data not in user data.
Args:
db_data (str): The data store in Redis.
user_data (list): The user provided data.
Returns:
bool: True if the data passed validation.
"""
if isinstance(user_data, list):
if db_data not in user_data:
return True
return False | python | def data_not_in(db_data, user_data):
"""Validate data not in user data.
Args:
db_data (str): The data store in Redis.
user_data (list): The user provided data.
Returns:
bool: True if the data passed validation.
"""
if isinstance(user_data, list):
if db_data not in user_data:
return True
return False | [
"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.
Args:
db_data (str): The data store in Redis.
user_data (list): The user provided data.
Returns:
bool: True if the data passed validation. | [
"Validate",
"data",
"not",
"in",
"user",
"data",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_run.py#L445-L458 | train | 27,407 |
ThreatConnect-Inc/tcex | tcex/tcex_bin_run.py | TcExRun.data_string_compare | def data_string_compare(db_data, user_data):
"""Validate string removing all white space before comparison.
Args:
db_data (str): The data store in Redis.
user_data (str): The user provided data.
Returns:
bool: True if the data passed validation.
"""
db_data = ''.join(db_data.split())
user_data = ''.join(user_data.split())
if operator.eq(db_data, user_data):
return True
return False | python | def data_string_compare(db_data, user_data):
"""Validate string removing all white space before comparison.
Args:
db_data (str): The data store in Redis.
user_data (str): The user provided data.
Returns:
bool: True if the data passed validation.
"""
db_data = ''.join(db_data.split())
user_data = ''.join(user_data.split())
if operator.eq(db_data, user_data):
return True
return False | [
"def",
"data_string_compare",
"(",
"db_data",
",",
"user_data",
")",
":",
"db_data",
"=",
"''",
".",
"join",
"(",
"db_data",
".",
"split",
"(",
")",
")",
"user_data",
"=",
"''",
".",
"join",
"(",
"user_data",
".",
"split",
"(",
")",
")",
"if",
"opera... | Validate string removing all white space before comparison.
Args:
db_data (str): The data store in Redis.
user_data (str): The user provided data.
Returns:
bool: True if the data passed validation. | [
"Validate",
"string",
"removing",
"all",
"white",
"space",
"before",
"comparison",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_run.py#L476-L490 | train | 27,408 |
ThreatConnect-Inc/tcex | tcex/tcex_bin_run.py | TcExRun.included_profiles | def included_profiles(self):
"""Load all profiles."""
profiles = []
for directory in self.tcex_json.get('profile_include_dirs') or []:
profiles.extend(self._load_config_include(directory))
return profiles | python | def included_profiles(self):
"""Load all profiles."""
profiles = []
for directory in self.tcex_json.get('profile_include_dirs') or []:
profiles.extend(self._load_config_include(directory))
return profiles | [
"def",
"included_profiles",
"(",
"self",
")",
":",
"profiles",
"=",
"[",
"]",
"for",
"directory",
"in",
"self",
".",
"tcex_json",
".",
"get",
"(",
"'profile_include_dirs'",
")",
"or",
"[",
"]",
":",
"profiles",
".",
"extend",
"(",
"self",
".",
"_load_con... | Load all profiles. | [
"Load",
"all",
"profiles",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_run.py#L522-L527 | train | 27,409 |
ThreatConnect-Inc/tcex | tcex/tcex_bin_run.py | TcExRun.load_tcex | def load_tcex(self):
"""Inject required TcEx CLI Args."""
for arg, value in self.profile.get('profile_args', {}).data.items():
if arg not in self._tcex_required_args:
continue
# add new log file name and level
sys.argv.extend(['--tc_log_file', 'tcex.log'])
sys.argv.extend(['--tc_log_level', 'error'])
# format key
arg = '--{}'.format(arg)
if isinstance(value, (bool)):
# handle bool values as flags (e.g., --flag) with no value
if value:
sys.argv.append(arg)
else:
sys.argv.append(arg)
sys.argv.append('{}'.format(value))
self.tcex = TcEx()
# reset singal handlers
self._signal_handler_init() | python | def load_tcex(self):
"""Inject required TcEx CLI Args."""
for arg, value in self.profile.get('profile_args', {}).data.items():
if arg not in self._tcex_required_args:
continue
# add new log file name and level
sys.argv.extend(['--tc_log_file', 'tcex.log'])
sys.argv.extend(['--tc_log_level', 'error'])
# format key
arg = '--{}'.format(arg)
if isinstance(value, (bool)):
# handle bool values as flags (e.g., --flag) with no value
if value:
sys.argv.append(arg)
else:
sys.argv.append(arg)
sys.argv.append('{}'.format(value))
self.tcex = TcEx()
# reset singal handlers
self._signal_handler_init() | [
"def",
"load_tcex",
"(",
"self",
")",
":",
"for",
"arg",
",",
"value",
"in",
"self",
".",
"profile",
".",
"get",
"(",
"'profile_args'",
",",
"{",
"}",
")",
".",
"data",
".",
"items",
"(",
")",
":",
"if",
"arg",
"not",
"in",
"self",
".",
"_tcex_re... | Inject required TcEx CLI Args. | [
"Inject",
"required",
"TcEx",
"CLI",
"Args",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_run.py#L545-L567 | train | 27,410 |
ThreatConnect-Inc/tcex | tcex/tcex_bin_run.py | TcExRun.operators | def operators(self):
"""Return dict of Validation Operators.
+ deep-diff (dd): This operator can compare any object that can be represented as JSON.
+ eq: This operator does a equal to comparison for String and StringArray variables.
+ ends-with (ew): This operator compares the end of a String with a user provided value.
+ ge: This operator does a greater than or equal to comparison for String variables.
+ gt: This operator does a greater than comparison for String variables.
+ json-compare (jc): This operator will convert a String output variable to a JSON object
(dict) and compare to user provided data.
+ key-value-compare (kva): This operator will validate that key/value data is in
KeyValueArray.
+ in: This operator will check to see if a String output variable is in an user provided
array.
+ in-user-data: This operator will validate that user provided String value is in output
StringArray variable.
+ not-in (ni): This operator will check to see if a String variable is **not** in an user
provided array.
+ is-type (it): This operator will check to see if the variable "type" is equal to the user
provided "type".
+ le: This operator does a less than or equal to comparison for String variables.
+ lt: This operator does a less than comparison for String variables.
+ ne: This operator does a **not** equal to comparison for String and StringArray variables.
+ string-compare (se):
+ starts-with (sw): This operator compares the start of a String with a user provided value.
"""
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_compare,
'key-value-compare': self.data_kva_compare,
'in': self.data_in_db,
'in-db-data': self.data_in_db,
'in-user-data': self.data_in_user,
'ni': self.data_not_in,
'not-in': self.data_not_in,
'it': self.data_it, # is type
'is-type': self.data_it,
'lt': operator.lt,
'le': operator.le,
'ne': operator.ne,
'se': self.data_string_compare,
'string-compare': self.data_string_compare,
'sw': self.data_startswith,
'starts-with': self.data_startswith,
} | python | def operators(self):
"""Return dict of Validation Operators.
+ deep-diff (dd): This operator can compare any object that can be represented as JSON.
+ eq: This operator does a equal to comparison for String and StringArray variables.
+ ends-with (ew): This operator compares the end of a String with a user provided value.
+ ge: This operator does a greater than or equal to comparison for String variables.
+ gt: This operator does a greater than comparison for String variables.
+ json-compare (jc): This operator will convert a String output variable to a JSON object
(dict) and compare to user provided data.
+ key-value-compare (kva): This operator will validate that key/value data is in
KeyValueArray.
+ in: This operator will check to see if a String output variable is in an user provided
array.
+ in-user-data: This operator will validate that user provided String value is in output
StringArray variable.
+ not-in (ni): This operator will check to see if a String variable is **not** in an user
provided array.
+ is-type (it): This operator will check to see if the variable "type" is equal to the user
provided "type".
+ le: This operator does a less than or equal to comparison for String variables.
+ lt: This operator does a less than comparison for String variables.
+ ne: This operator does a **not** equal to comparison for String and StringArray variables.
+ string-compare (se):
+ starts-with (sw): This operator compares the start of a String with a user provided value.
"""
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_compare,
'key-value-compare': self.data_kva_compare,
'in': self.data_in_db,
'in-db-data': self.data_in_db,
'in-user-data': self.data_in_user,
'ni': self.data_not_in,
'not-in': self.data_not_in,
'it': self.data_it, # is type
'is-type': self.data_it,
'lt': operator.lt,
'le': operator.le,
'ne': operator.ne,
'se': self.data_string_compare,
'string-compare': self.data_string_compare,
'sw': self.data_startswith,
'starts-with': self.data_startswith,
} | [
"def",
"operators",
"(",
"self",
")",
":",
"return",
"{",
"'dd'",
":",
"self",
".",
"deep_diff",
",",
"'deep-diff'",
":",
"self",
".",
"deep_diff",
",",
"'eq'",
":",
"operator",
".",
"eq",
",",
"'ew'",
":",
"self",
".",
"data_endswith",
",",
"'ends-wit... | Return dict of Validation Operators.
+ deep-diff (dd): This operator can compare any object that can be represented as JSON.
+ eq: This operator does a equal to comparison for String and StringArray variables.
+ ends-with (ew): This operator compares the end of a String with a user provided value.
+ ge: This operator does a greater than or equal to comparison for String variables.
+ gt: This operator does a greater than comparison for String variables.
+ json-compare (jc): This operator will convert a String output variable to a JSON object
(dict) and compare to user provided data.
+ key-value-compare (kva): This operator will validate that key/value data is in
KeyValueArray.
+ in: This operator will check to see if a String output variable is in an user provided
array.
+ in-user-data: This operator will validate that user provided String value is in output
StringArray variable.
+ not-in (ni): This operator will check to see if a String variable is **not** in an user
provided array.
+ is-type (it): This operator will check to see if the variable "type" is equal to the user
provided "type".
+ le: This operator does a less than or equal to comparison for String variables.
+ lt: This operator does a less than comparison for String variables.
+ ne: This operator does a **not** equal to comparison for String and StringArray variables.
+ string-compare (se):
+ starts-with (sw): This operator compares the start of a String with a user provided value. | [
"Return",
"dict",
"of",
"Validation",
"Operators",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_run.py#L570-L622 | train | 27,411 |
ThreatConnect-Inc/tcex | tcex/tcex_bin_run.py | TcExRun.path_data | def path_data(self, variable_data, path):
"""Return JMESPath data.
Args:
variable_data (str): The JSON data to run path expression.
path (str): The JMESPath expression.
Returns:
dict: The resulting data from JMESPath.
"""
# NOTE: tcex does include the jmespath library as a dependencies since it is only
# required for local testing.
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 to convert string into list/dict before using expression
try:
variable_data = json.loads(variable_data)
except Exception:
self.log.debug('String value ({}) could not JSON serialized.'.format(variable_data))
if path is not None and isinstance(variable_data, (dict, list)):
expression = jmespath.compile(path)
variable_data = expression.search(
variable_data, jmespath.Options(dict_cls=collections.OrderedDict)
)
return variable_data | python | def path_data(self, variable_data, path):
"""Return JMESPath data.
Args:
variable_data (str): The JSON data to run path expression.
path (str): The JMESPath expression.
Returns:
dict: The resulting data from JMESPath.
"""
# NOTE: tcex does include the jmespath library as a dependencies since it is only
# required for local testing.
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 to convert string into list/dict before using expression
try:
variable_data = json.loads(variable_data)
except Exception:
self.log.debug('String value ({}) could not JSON serialized.'.format(variable_data))
if path is not None and isinstance(variable_data, (dict, list)):
expression = jmespath.compile(path)
variable_data = expression.search(
variable_data, jmespath.Options(dict_cls=collections.OrderedDict)
)
return variable_data | [
"def",
"path_data",
"(",
"self",
",",
"variable_data",
",",
"path",
")",
":",
"# NOTE: tcex does include the jmespath library as a dependencies since it is only",
"# required for local testing.",
"try",
":",
"import",
"jmespath",
"except",
"ImportError",
":",
"print",
"(",
... | Return JMESPath data.
Args:
variable_data (str): The JSON data to run path expression.
path (str): The JMESPath expression.
Returns:
dict: The resulting data from JMESPath. | [
"Return",
"JMESPath",
"data",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_run.py#L624-L653 | train | 27,412 |
ThreatConnect-Inc/tcex | tcex/tcex_bin_run.py | TcExRun.profile | def profile(self, profile):
"""Set the current profile.
Args:
profile (dict): The profile data.
"""
# clear staging data
self._staging_data = None
# retrieve language from install.json or assume Python
lang = profile.get('install_json', {}).get('programLanguage', 'PYTHON')
# load instance of ArgBuilder
profile_args = ArgBuilder(lang, self.profile_args(profile.get('args')))
# set current profile
self._profile = profile
# attach instance to current profile
self._profile['profile_args'] = profile_args
# load tcex module after current profile is set
self.load_tcex()
# select report for current profile
self.reports.profile(profile.get('profile_name'))
# create required directories for tcrun to function
self._create_tc_dirs() | python | def profile(self, profile):
"""Set the current profile.
Args:
profile (dict): The profile data.
"""
# clear staging data
self._staging_data = None
# retrieve language from install.json or assume Python
lang = profile.get('install_json', {}).get('programLanguage', 'PYTHON')
# load instance of ArgBuilder
profile_args = ArgBuilder(lang, self.profile_args(profile.get('args')))
# set current profile
self._profile = profile
# attach instance to current profile
self._profile['profile_args'] = profile_args
# load tcex module after current profile is set
self.load_tcex()
# select report for current profile
self.reports.profile(profile.get('profile_name'))
# create required directories for tcrun to function
self._create_tc_dirs() | [
"def",
"profile",
"(",
"self",
",",
"profile",
")",
":",
"# clear staging data",
"self",
".",
"_staging_data",
"=",
"None",
"# retrieve language from install.json or assume Python",
"lang",
"=",
"profile",
".",
"get",
"(",
"'install_json'",
",",
"{",
"}",
")",
"."... | Set the current profile.
Args:
profile (dict): The profile data. | [
"Set",
"the",
"current",
"profile",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_run.py#L661-L682 | train | 27,413 |
ThreatConnect-Inc/tcex | tcex/tcex_bin_run.py | TcExRun.profile_args | def profile_args(_args):
"""Return args for v1, v2, or v3 structure.
Args:
_args (dict): The args section from the profile.
Returns:
dict: A collapsed version of the args dict.
"""
# TODO: clean this up in a way that works for both py2/3
if (
_args.get('app', {}).get('optional') is not None
or _args.get('app', {}).get('required') is not None
):
# detect v3 schema
app_args_optional = _args.get('app', {}).get('optional', {})
app_args_required = _args.get('app', {}).get('required', {})
default_args = _args.get('default', {})
_args = {}
_args.update(app_args_optional)
_args.update(app_args_required)
_args.update(default_args)
elif _args.get('app') is not None and _args.get('default') is not None:
# detect v2 schema
app_args = _args.get('app', {})
default_args = _args.get('default', {})
_args = {}
_args.update(app_args)
_args.update(default_args)
return _args | python | def profile_args(_args):
"""Return args for v1, v2, or v3 structure.
Args:
_args (dict): The args section from the profile.
Returns:
dict: A collapsed version of the args dict.
"""
# TODO: clean this up in a way that works for both py2/3
if (
_args.get('app', {}).get('optional') is not None
or _args.get('app', {}).get('required') is not None
):
# detect v3 schema
app_args_optional = _args.get('app', {}).get('optional', {})
app_args_required = _args.get('app', {}).get('required', {})
default_args = _args.get('default', {})
_args = {}
_args.update(app_args_optional)
_args.update(app_args_required)
_args.update(default_args)
elif _args.get('app') is not None and _args.get('default') is not None:
# detect v2 schema
app_args = _args.get('app', {})
default_args = _args.get('default', {})
_args = {}
_args.update(app_args)
_args.update(default_args)
return _args | [
"def",
"profile_args",
"(",
"_args",
")",
":",
"# TODO: clean this up in a way that works for both py2/3",
"if",
"(",
"_args",
".",
"get",
"(",
"'app'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'optional'",
")",
"is",
"not",
"None",
"or",
"_args",
".",
"get",
... | Return args for v1, v2, or v3 structure.
Args:
_args (dict): The args section from the profile.
Returns:
dict: A collapsed version of the args dict. | [
"Return",
"args",
"for",
"v1",
"v2",
"or",
"v3",
"structure",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_run.py#L685-L715 | train | 27,414 |
ThreatConnect-Inc/tcex | tcex/tcex_bin_run.py | TcExRun.profiles | def profiles(self):
"""Return all selected profiles."""
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.group:
profile_selected = True
elif self.args.group in config.get('groups', []):
profile_selected = True
if profile_selected:
install_json_filename = config.get('install_json')
ij = {}
if install_json_filename is not None:
ij = self.load_install_json(install_json_filename)
config['install_json'] = ij
selected_profiles.append(config)
self.reports.add_profile(config, profile_selected)
if not selected_profiles:
print('{}{}No profiles selected to run.'.format(c.Style.BRIGHT, c.Fore.YELLOW))
return selected_profiles | python | def profiles(self):
"""Return all selected profiles."""
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.group:
profile_selected = True
elif self.args.group in config.get('groups', []):
profile_selected = True
if profile_selected:
install_json_filename = config.get('install_json')
ij = {}
if install_json_filename is not None:
ij = self.load_install_json(install_json_filename)
config['install_json'] = ij
selected_profiles.append(config)
self.reports.add_profile(config, profile_selected)
if not selected_profiles:
print('{}{}No profiles selected to run.'.format(c.Style.BRIGHT, c.Fore.YELLOW))
return selected_profiles | [
"def",
"profiles",
"(",
"self",
")",
":",
"selected_profiles",
"=",
"[",
"]",
"for",
"config",
"in",
"self",
".",
"included_profiles",
":",
"profile_selected",
"=",
"False",
"profile_name",
"=",
"config",
".",
"get",
"(",
"'profile_name'",
")",
"if",
"profil... | Return all selected profiles. | [
"Return",
"all",
"selected",
"profiles",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_run.py#L718-L745 | train | 27,415 |
ThreatConnect-Inc/tcex | tcex/tcex_bin_run.py | TcExRun.report | def report(self):
"""Format and output report data to screen."""
print('\n{}{}{}'.format(c.Style.BRIGHT, c.Fore.CYAN, 'Report:'))
# report headers
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 d.get('selected'):
continue
# execution
execution_color = c.Fore.RED
execution_text = 'Failed'
if d.get('execution_success'):
execution_color = c.Fore.GREEN
execution_text = 'Passed'
# pass count
pass_count_color = c.Fore.GREEN
pass_count = d.get('validation_pass_count', 0)
# fail count
fail_count = d.get('validation_fail_count', 0)
fail_count_color = c.Fore.GREEN
if fail_count > 0:
fail_count_color = c.Fore.RED
# report row
print(
'{!s:<60}{}{!s:<25}{}{!s:<10}{}{!s:<10}'.format(
d.get('name'),
execution_color,
execution_text,
pass_count_color,
pass_count,
fail_count_color,
fail_count,
)
)
# write report to disk
if self.args.report:
with open(self.args.report, 'w') as outfile:
outfile.write(str(self.reports)) | python | def report(self):
"""Format and output report data to screen."""
print('\n{}{}{}'.format(c.Style.BRIGHT, c.Fore.CYAN, 'Report:'))
# report headers
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 d.get('selected'):
continue
# execution
execution_color = c.Fore.RED
execution_text = 'Failed'
if d.get('execution_success'):
execution_color = c.Fore.GREEN
execution_text = 'Passed'
# pass count
pass_count_color = c.Fore.GREEN
pass_count = d.get('validation_pass_count', 0)
# fail count
fail_count = d.get('validation_fail_count', 0)
fail_count_color = c.Fore.GREEN
if fail_count > 0:
fail_count_color = c.Fore.RED
# report row
print(
'{!s:<60}{}{!s:<25}{}{!s:<10}{}{!s:<10}'.format(
d.get('name'),
execution_color,
execution_text,
pass_count_color,
pass_count,
fail_count_color,
fail_count,
)
)
# write report to disk
if self.args.report:
with open(self.args.report, 'w') as outfile:
outfile.write(str(self.reports)) | [
"def",
"report",
"(",
"self",
")",
":",
"print",
"(",
"'\\n{}{}{}'",
".",
"format",
"(",
"c",
".",
"Style",
".",
"BRIGHT",
",",
"c",
".",
"Fore",
".",
"CYAN",
",",
"'Report:'",
")",
")",
"# report headers",
"print",
"(",
"'{!s:<85}{!s:<20}'",
".",
"for... | Format and output report data to screen. | [
"Format",
"and",
"output",
"report",
"data",
"to",
"screen",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_run.py#L747-L794 | train | 27,416 |
ThreatConnect-Inc/tcex | tcex/tcex_bin_run.py | TcExRun.run | def run(self):
"""Run the App using the current profile.
The current profile has the install_json and args pre-loaded.
"""
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 = install_json.get('programMain').replace('.py', '')
elif self.profile.get('script') is not None:
# TODO: remove this option on version 1.0.0
program_main = self.profile.get('script').replace('.py', '')
else:
print('{}{}No Program Main or Script defined.'.format(c.Style.BRIGHT, c.Fore.RED))
sys.exit(1)
self.run_display_profile(program_main)
self.run_display_description()
self.run_validate_program_main(program_main)
# get the commands
commands = self.run_commands(program_language, program_main)
self.log.info('[run] Running command {}'.format(commands.get('print_command')))
# output command
print(
'Executing: {}{}{}'.format(c.Style.BRIGHT, c.Fore.GREEN, commands.get('print_command'))
)
if self.args.docker:
return self.run_docker(commands)
return self.run_local(commands) | python | def run(self):
"""Run the App using the current profile.
The current profile has the install_json and args pre-loaded.
"""
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 = install_json.get('programMain').replace('.py', '')
elif self.profile.get('script') is not None:
# TODO: remove this option on version 1.0.0
program_main = self.profile.get('script').replace('.py', '')
else:
print('{}{}No Program Main or Script defined.'.format(c.Style.BRIGHT, c.Fore.RED))
sys.exit(1)
self.run_display_profile(program_main)
self.run_display_description()
self.run_validate_program_main(program_main)
# get the commands
commands = self.run_commands(program_language, program_main)
self.log.info('[run] Running command {}'.format(commands.get('print_command')))
# output command
print(
'Executing: {}{}{}'.format(c.Style.BRIGHT, c.Fore.GREEN, commands.get('print_command'))
)
if self.args.docker:
return self.run_docker(commands)
return self.run_local(commands) | [
"def",
"run",
"(",
"self",
")",
":",
"install_json",
"=",
"self",
".",
"profile",
".",
"get",
"(",
"'install_json'",
")",
"program_language",
"=",
"self",
".",
"profile",
".",
"get",
"(",
"'install_json'",
")",
".",
"get",
"(",
"'programLanguage'",
",",
... | Run the App using the current profile.
The current profile has the install_json and args pre-loaded. | [
"Run",
"the",
"App",
"using",
"the",
"current",
"profile",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_run.py#L796-L831 | train | 27,417 |
ThreatConnect-Inc/tcex | tcex/tcex_bin_run.py | TcExRun.run_commands | def run_commands(self, program_language, program_main):
"""Return the run Print Command.
Args:
program_language (str): The language of the current App/Project.
program_main (str): The executable name.
Returns:
dict: A dictionary containing the run command and a printable version of the command.
"""
# build the command
if program_language == 'python':
python_exe = sys.executable
ptvsd_host = 'localhost'
if self.args.docker:
# use the default python command in the container
python_exe = 'python'
ptvsd_host = '0.0.0.0'
if self.args.vscd:
self.update_environment() # update PYTHONPATH for local testing
command = [
python_exe,
'-m',
'ptvsd',
'--host',
ptvsd_host,
'--port',
self.args.vscd_port,
'--wait',
'{}.py'.format(program_main),
]
else:
command = [python_exe, '.', program_main]
# exe command
cli_command = [str(s) for s in command + self.profile.get('profile_args').standard]
# print command
# print_command = ' '.join(command + self.profile.get('profile_args').masked)
print_command = ' '.join(
str(s) for s in command + self.profile.get('profile_args').masked
)
if self.args.unmask:
# print_command = ' '.join(command + self.profile.get('profile_args').quoted)
print_command = ' '.join(
str(s) for s in command + self.profile.get('profile_args').quoted
)
elif program_language == 'java':
if self.args.docker:
command = ['java', '-cp', self.tcex_json.get('class_path', './target/*')]
else:
command = [
self.tcex_json.get('java_path', program_language),
'-cp',
self.tcex_json.get('class_path', './target/*'),
]
# exe command
cli_command = command + self.profile.get('profile_args').standard + [program_main]
# print command
print_command = ' '.join(
command + self.profile.get('profile_args').masked + [program_main]
)
if self.args.unmask:
print_command = ' '.join(
command + self.profile.get('profile_args').quoted + [program_main]
)
return {'cli_command': cli_command, 'print_command': print_command} | python | def run_commands(self, program_language, program_main):
"""Return the run Print Command.
Args:
program_language (str): The language of the current App/Project.
program_main (str): The executable name.
Returns:
dict: A dictionary containing the run command and a printable version of the command.
"""
# build the command
if program_language == 'python':
python_exe = sys.executable
ptvsd_host = 'localhost'
if self.args.docker:
# use the default python command in the container
python_exe = 'python'
ptvsd_host = '0.0.0.0'
if self.args.vscd:
self.update_environment() # update PYTHONPATH for local testing
command = [
python_exe,
'-m',
'ptvsd',
'--host',
ptvsd_host,
'--port',
self.args.vscd_port,
'--wait',
'{}.py'.format(program_main),
]
else:
command = [python_exe, '.', program_main]
# exe command
cli_command = [str(s) for s in command + self.profile.get('profile_args').standard]
# print command
# print_command = ' '.join(command + self.profile.get('profile_args').masked)
print_command = ' '.join(
str(s) for s in command + self.profile.get('profile_args').masked
)
if self.args.unmask:
# print_command = ' '.join(command + self.profile.get('profile_args').quoted)
print_command = ' '.join(
str(s) for s in command + self.profile.get('profile_args').quoted
)
elif program_language == 'java':
if self.args.docker:
command = ['java', '-cp', self.tcex_json.get('class_path', './target/*')]
else:
command = [
self.tcex_json.get('java_path', program_language),
'-cp',
self.tcex_json.get('class_path', './target/*'),
]
# exe command
cli_command = command + self.profile.get('profile_args').standard + [program_main]
# print command
print_command = ' '.join(
command + self.profile.get('profile_args').masked + [program_main]
)
if self.args.unmask:
print_command = ' '.join(
command + self.profile.get('profile_args').quoted + [program_main]
)
return {'cli_command': cli_command, 'print_command': print_command} | [
"def",
"run_commands",
"(",
"self",
",",
"program_language",
",",
"program_main",
")",
":",
"# build the command",
"if",
"program_language",
"==",
"'python'",
":",
"python_exe",
"=",
"sys",
".",
"executable",
"ptvsd_host",
"=",
"'localhost'",
"if",
"self",
".",
... | Return the run Print Command.
Args:
program_language (str): The language of the current App/Project.
program_main (str): The executable name.
Returns:
dict: A dictionary containing the run command and a printable version of the command. | [
"Return",
"the",
"run",
"Print",
"Command",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_run.py#L833-L903 | train | 27,418 |
ThreatConnect-Inc/tcex | tcex/tcex_bin_run.py | TcExRun.run_local | def run_local(self, commands):
"""Run the App on local system.
Args:
commands (dict): A dictionary of the CLI commands.
Returns:
int: The exit code of the subprocess command.
"""
process = subprocess.Popen(
commands.get('cli_command'),
shell=self.shell,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
out, err = process.communicate()
# display app output
self.run_display_app_output(out)
self.run_display_app_errors(err)
# Exit Code
return self.run_exit_code(process.returncode) | python | def run_local(self, commands):
"""Run the App on local system.
Args:
commands (dict): A dictionary of the CLI commands.
Returns:
int: The exit code of the subprocess command.
"""
process = subprocess.Popen(
commands.get('cli_command'),
shell=self.shell,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
out, err = process.communicate()
# display app output
self.run_display_app_output(out)
self.run_display_app_errors(err)
# Exit Code
return self.run_exit_code(process.returncode) | [
"def",
"run_local",
"(",
"self",
",",
"commands",
")",
":",
"process",
"=",
"subprocess",
".",
"Popen",
"(",
"commands",
".",
"get",
"(",
"'cli_command'",
")",
",",
"shell",
"=",
"self",
".",
"shell",
",",
"stdin",
"=",
"subprocess",
".",
"PIPE",
",",
... | Run the App on local system.
Args:
commands (dict): A dictionary of the CLI commands.
Returns:
int: The exit code of the subprocess command. | [
"Run",
"the",
"App",
"on",
"local",
"system",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_run.py#L905-L929 | train | 27,419 |
ThreatConnect-Inc/tcex | tcex/tcex_bin_run.py | TcExRun.run_docker | def run_docker(self, commands):
"""Run App in Docker Container.
Args:
commands (dict): A dictionary of the CLI commands.
Returns:
int: The exit code of the subprocess command.
"""
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 = self.profile.get('profile_args').standard
app_args_data = self.profile.get('profile_args').data
install_json = self.profile.get('install_json')
# client
client = docker.from_env()
# app data
app_dir = os.getcwd()
# app_path = '{}/{}'.format(app_dir, program_main)
# ports
ports = {}
if self.args.vscd:
ports = {'{}/tcp'.format(self.args.vscd_port): self.args.vscd_port}
# volumes
volumes = {}
in_path = '{}/{}'.format(app_dir, app_args_data.get('tc_in_path'))
if app_args_data.get('tc_in_path') is not None:
volumes[in_path] = {'bind': in_path}
log_path = '{}/{}'.format(app_dir, app_args_data.get('tc_log_path'))
if app_args_data.get('tc_log_path') is not None:
volumes[log_path] = {'bind': log_path}
out_path = '{}/{}'.format(app_dir, app_args_data.get('tc_out_path'))
if app_args_data.get('tc_out_path') is not None:
volumes[out_path] = {'bind': out_path}
temp_path = '{}/{}'.format(app_dir, app_args_data.get('tc_temp_path'))
if app_args_data.get('tc_temp_path') is not None:
volumes[temp_path] = {'bind': temp_path}
volumes[app_dir] = {'bind': app_dir}
if self.args.docker_image is not None:
# user docker image from cli as an override.
docker_image = self.args.docker_image
else:
# docker image from install.json can be overridden by docker image in profile. if no
# image is defined in either file use the default image define as self.docker_image.
docker_image = self.profile.get(
'dockerImage', install_json.get('dockerImage', self.docker_image)
)
status_code = 1
try:
self.container = client.containers.run(
docker_image,
entrypoint=commands.get('cli_command'),
environment=['PYTHONPATH={}/lib_latest'.format(app_dir)],
detach=True,
# network_mode=install_json.get('docker_host', 'host'),
ports=ports,
remove=True,
volumes=volumes,
working_dir=app_dir,
)
results = self.container.wait()
status_code = results.get('StatusCode')
error = results.get('Error')
if error:
print('{}{}{}'.format(c.Style.BRIGHT, c.Fore.RED, error))
except Exception as e:
print('{}{}{}'.format(c.Style.BRIGHT, c.Fore.RED, e))
sys.exit()
# Exit Code
return self.run_exit_code(status_code) | python | def run_docker(self, commands):
"""Run App in Docker Container.
Args:
commands (dict): A dictionary of the CLI commands.
Returns:
int: The exit code of the subprocess command.
"""
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 = self.profile.get('profile_args').standard
app_args_data = self.profile.get('profile_args').data
install_json = self.profile.get('install_json')
# client
client = docker.from_env()
# app data
app_dir = os.getcwd()
# app_path = '{}/{}'.format(app_dir, program_main)
# ports
ports = {}
if self.args.vscd:
ports = {'{}/tcp'.format(self.args.vscd_port): self.args.vscd_port}
# volumes
volumes = {}
in_path = '{}/{}'.format(app_dir, app_args_data.get('tc_in_path'))
if app_args_data.get('tc_in_path') is not None:
volumes[in_path] = {'bind': in_path}
log_path = '{}/{}'.format(app_dir, app_args_data.get('tc_log_path'))
if app_args_data.get('tc_log_path') is not None:
volumes[log_path] = {'bind': log_path}
out_path = '{}/{}'.format(app_dir, app_args_data.get('tc_out_path'))
if app_args_data.get('tc_out_path') is not None:
volumes[out_path] = {'bind': out_path}
temp_path = '{}/{}'.format(app_dir, app_args_data.get('tc_temp_path'))
if app_args_data.get('tc_temp_path') is not None:
volumes[temp_path] = {'bind': temp_path}
volumes[app_dir] = {'bind': app_dir}
if self.args.docker_image is not None:
# user docker image from cli as an override.
docker_image = self.args.docker_image
else:
# docker image from install.json can be overridden by docker image in profile. if no
# image is defined in either file use the default image define as self.docker_image.
docker_image = self.profile.get(
'dockerImage', install_json.get('dockerImage', self.docker_image)
)
status_code = 1
try:
self.container = client.containers.run(
docker_image,
entrypoint=commands.get('cli_command'),
environment=['PYTHONPATH={}/lib_latest'.format(app_dir)],
detach=True,
# network_mode=install_json.get('docker_host', 'host'),
ports=ports,
remove=True,
volumes=volumes,
working_dir=app_dir,
)
results = self.container.wait()
status_code = results.get('StatusCode')
error = results.get('Error')
if error:
print('{}{}{}'.format(c.Style.BRIGHT, c.Fore.RED, error))
except Exception as e:
print('{}{}{}'.format(c.Style.BRIGHT, c.Fore.RED, e))
sys.exit()
# Exit Code
return self.run_exit_code(status_code) | [
"def",
"run_docker",
"(",
"self",
",",
"commands",
")",
":",
"try",
":",
"import",
"docker",
"except",
"ImportError",
":",
"print",
"(",
"'{}{}Could not import docker module (try \"pip install docker\").'",
".",
"format",
"(",
"c",
".",
"Style",
".",
"BRIGHT",
","... | Run App in Docker Container.
Args:
commands (dict): A dictionary of the CLI commands.
Returns:
int: The exit code of the subprocess command. | [
"Run",
"App",
"in",
"Docker",
"Container",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_run.py#L931-L1015 | train | 27,420 |
ThreatConnect-Inc/tcex | tcex/tcex_bin_run.py | TcExRun.run_display_app_output | def run_display_app_output(self, out):
"""Print any App output.
Args:
out (str): One or more lines of output messages.
"""
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(o)) | python | def run_display_app_output(self, out):
"""Print any App output.
Args:
out (str): One or more lines of output messages.
"""
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(o)) | [
"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... | Print any App output.
Args:
out (str): One or more lines of output messages. | [
"Print",
"any",
"App",
"output",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_run.py#L1028-L1038 | train | 27,421 |
ThreatConnect-Inc/tcex | tcex/tcex_bin_run.py | TcExRun.run_validate_program_main | def run_validate_program_main(self, program_main):
"""Validate the program main file exists.
Args:
program_main (str): The executable name.
"""
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 ({}).'.format(
c.Style.BRIGHT, c.Fore.RED, program_main
)
)
sys.exit(1) | python | def run_validate_program_main(self, program_main):
"""Validate the program main file exists.
Args:
program_main (str): The executable name.
"""
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 ({}).'.format(
c.Style.BRIGHT, c.Fore.RED, program_main
)
)
sys.exit(1) | [
"def",
"run_validate_program_main",
"(",
"self",
",",
"program_main",
")",
":",
"program_language",
"=",
"self",
".",
"profile",
".",
"get",
"(",
"'install_json'",
")",
".",
"get",
"(",
"'programLanguage'",
",",
"'python'",
")",
".",
"lower",
"(",
")",
"if",... | Validate the program main file exists.
Args:
program_main (str): The executable name. | [
"Validate",
"the",
"program",
"main",
"file",
"exists",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_run.py#L1116-L1129 | train | 27,422 |
ThreatConnect-Inc/tcex | tcex/tcex_bin_run.py | TcExRun.stage | def stage(self):
"""Stage Redis and ThreatConnect data defined in profile.
Redis Data:
.. code-block:: javascript
{
"data": [
"This is an example Source #1",
"This is an example Source #2"
],
"variable": "#App:1234:source!StringArray"
}
Redis Array:
.. code-block:: javascript
{
"data": {
"variables": [{
"value": "#App:4768:tc.adversary!TCEntity",
}, {
"value": "#App:4768:tc.threat!TCEntity",
}]
},
"data_type": "redis_array",
"variable": "#App:4768:groups!TCEntityArray"
},
{
"data": {
"variables": [{
"value": "#App:4768:tc.adversary!TCEntity",
"path": ".name"
}, {
"value": "#App:4768:tc.threat!TCEntity",
"path": ".name"
}]
},
"data_type": "redis_array",
"variable": "#App:4768:groups!StringArray"
}
ThreatConnect Data:
.. code-block:: javascript
{
"data": {
"group": [{
"firstSeen": "2008-12-12T12:00:00Z",
"name": "campaign-002",
"type": "Campaign",
"xid": "camp-0002",
"attribute": [{
"displayed": True,
"type": "Description",
"value": "Campaign Example Description"
}],
"tag": [{
"name": "SafeToDelete"
}],
"variable": "#App:4768:tc.campaign!TCEntity"
}],
"indicator": [{
"associatedGroups": [
{
"groupXid": "campaign-002"
}
],
"confidence": 100,
"fileOccurrence": [
{
"date": "2017-02-02T01:02:03Z",
"fileName": "drop1.exe",
"path": "C:\\\\test\\\\"
}
],
"rating": 5.0,
"summary": "43c3609411c83f363e051d455ade78a6",
"tag": [
{
"name": "SafeToDelete"
}
],
"type": "File",
"xid": "55ee19565db5b16a0f511791a3b2a7ef0ccddf4d9d64e7008561329419cb675b",
"variable": "#App:4768:tc.file!TCEntity"
}]
},
"data_owner": "TCI",
"data_type": "threatconnect"
}
"""
for sd in self.staging_data:
if not isinstance(sd, dict):
# reported issue from qa where staging data is invalid
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('variable'), sd.get('data'))
elif data_type in ['redis-array', 'redis_array']:
self.log.debug('Stage Redis Array')
out_variable = sd.get('variable')
# build array
redis_array = []
for var in sd.get('data', {}).get('variables') or []:
variable = var.get('value')
if variable.endswith('Binary'):
data = self.tcex.playbook.read_binary(variable, False, False)
elif variable.endswith('BinaryArray'):
data = self.tcex.playbook.read_binary_array(variable, False, False)
else:
data = self.path_data(self.tcex.playbook.read(variable), var.get('path'))
# TODO: should None value be appended?
redis_array.append(data)
self.stage_redis(out_variable, redis_array)
# print(redis_array)
elif data_type == 'threatconnect':
self.log.debug('Stage ThreatConnect Data')
self.stage_tc(sd.get('data_owner'), sd.get('data', {}), sd.get('variable'))
elif data_type == 'threatconnect-association':
self.log.debug('Stage ThreatConnect Association Data')
data = sd.get('data')
self.stage_tc_associations(data.get('entity1'), data.get('entity2'))
elif data_type == 'threatconnect-batch':
self.log.debug('Stage ThreatConnect Batch Data')
self.stage_tc_batch(sd.get('data_owner'), sd.get('data', {})) | python | def stage(self):
"""Stage Redis and ThreatConnect data defined in profile.
Redis Data:
.. code-block:: javascript
{
"data": [
"This is an example Source #1",
"This is an example Source #2"
],
"variable": "#App:1234:source!StringArray"
}
Redis Array:
.. code-block:: javascript
{
"data": {
"variables": [{
"value": "#App:4768:tc.adversary!TCEntity",
}, {
"value": "#App:4768:tc.threat!TCEntity",
}]
},
"data_type": "redis_array",
"variable": "#App:4768:groups!TCEntityArray"
},
{
"data": {
"variables": [{
"value": "#App:4768:tc.adversary!TCEntity",
"path": ".name"
}, {
"value": "#App:4768:tc.threat!TCEntity",
"path": ".name"
}]
},
"data_type": "redis_array",
"variable": "#App:4768:groups!StringArray"
}
ThreatConnect Data:
.. code-block:: javascript
{
"data": {
"group": [{
"firstSeen": "2008-12-12T12:00:00Z",
"name": "campaign-002",
"type": "Campaign",
"xid": "camp-0002",
"attribute": [{
"displayed": True,
"type": "Description",
"value": "Campaign Example Description"
}],
"tag": [{
"name": "SafeToDelete"
}],
"variable": "#App:4768:tc.campaign!TCEntity"
}],
"indicator": [{
"associatedGroups": [
{
"groupXid": "campaign-002"
}
],
"confidence": 100,
"fileOccurrence": [
{
"date": "2017-02-02T01:02:03Z",
"fileName": "drop1.exe",
"path": "C:\\\\test\\\\"
}
],
"rating": 5.0,
"summary": "43c3609411c83f363e051d455ade78a6",
"tag": [
{
"name": "SafeToDelete"
}
],
"type": "File",
"xid": "55ee19565db5b16a0f511791a3b2a7ef0ccddf4d9d64e7008561329419cb675b",
"variable": "#App:4768:tc.file!TCEntity"
}]
},
"data_owner": "TCI",
"data_type": "threatconnect"
}
"""
for sd in self.staging_data:
if not isinstance(sd, dict):
# reported issue from qa where staging data is invalid
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('variable'), sd.get('data'))
elif data_type in ['redis-array', 'redis_array']:
self.log.debug('Stage Redis Array')
out_variable = sd.get('variable')
# build array
redis_array = []
for var in sd.get('data', {}).get('variables') or []:
variable = var.get('value')
if variable.endswith('Binary'):
data = self.tcex.playbook.read_binary(variable, False, False)
elif variable.endswith('BinaryArray'):
data = self.tcex.playbook.read_binary_array(variable, False, False)
else:
data = self.path_data(self.tcex.playbook.read(variable), var.get('path'))
# TODO: should None value be appended?
redis_array.append(data)
self.stage_redis(out_variable, redis_array)
# print(redis_array)
elif data_type == 'threatconnect':
self.log.debug('Stage ThreatConnect Data')
self.stage_tc(sd.get('data_owner'), sd.get('data', {}), sd.get('variable'))
elif data_type == 'threatconnect-association':
self.log.debug('Stage ThreatConnect Association Data')
data = sd.get('data')
self.stage_tc_associations(data.get('entity1'), data.get('entity2'))
elif data_type == 'threatconnect-batch':
self.log.debug('Stage ThreatConnect Batch Data')
self.stage_tc_batch(sd.get('data_owner'), sd.get('data', {})) | [
"def",
"stage",
"(",
"self",
")",
":",
"for",
"sd",
"in",
"self",
".",
"staging_data",
":",
"if",
"not",
"isinstance",
"(",
"sd",
",",
"dict",
")",
":",
"# reported issue from qa where staging data is invalid",
"msg",
"=",
"'Invalid staging data provided ({}).'",
... | Stage Redis and ThreatConnect data defined in profile.
Redis Data:
.. code-block:: javascript
{
"data": [
"This is an example Source #1",
"This is an example Source #2"
],
"variable": "#App:1234:source!StringArray"
}
Redis Array:
.. code-block:: javascript
{
"data": {
"variables": [{
"value": "#App:4768:tc.adversary!TCEntity",
}, {
"value": "#App:4768:tc.threat!TCEntity",
}]
},
"data_type": "redis_array",
"variable": "#App:4768:groups!TCEntityArray"
},
{
"data": {
"variables": [{
"value": "#App:4768:tc.adversary!TCEntity",
"path": ".name"
}, {
"value": "#App:4768:tc.threat!TCEntity",
"path": ".name"
}]
},
"data_type": "redis_array",
"variable": "#App:4768:groups!StringArray"
}
ThreatConnect Data:
.. code-block:: javascript
{
"data": {
"group": [{
"firstSeen": "2008-12-12T12:00:00Z",
"name": "campaign-002",
"type": "Campaign",
"xid": "camp-0002",
"attribute": [{
"displayed": True,
"type": "Description",
"value": "Campaign Example Description"
}],
"tag": [{
"name": "SafeToDelete"
}],
"variable": "#App:4768:tc.campaign!TCEntity"
}],
"indicator": [{
"associatedGroups": [
{
"groupXid": "campaign-002"
}
],
"confidence": 100,
"fileOccurrence": [
{
"date": "2017-02-02T01:02:03Z",
"fileName": "drop1.exe",
"path": "C:\\\\test\\\\"
}
],
"rating": 5.0,
"summary": "43c3609411c83f363e051d455ade78a6",
"tag": [
{
"name": "SafeToDelete"
}
],
"type": "File",
"xid": "55ee19565db5b16a0f511791a3b2a7ef0ccddf4d9d64e7008561329419cb675b",
"variable": "#App:4768:tc.file!TCEntity"
}]
},
"data_owner": "TCI",
"data_type": "threatconnect"
} | [
"Stage",
"Redis",
"and",
"ThreatConnect",
"data",
"defined",
"in",
"profile",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_run.py#L1131-L1261 | train | 27,423 |
ThreatConnect-Inc/tcex | tcex/tcex_bin_run.py | TcExRun.staging_data | def staging_data(self):
"""Read data files and return all staging data for current profile."""
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] Staging data file: {}'.format(staging_file))
f = open(staging_file, 'r')
staging_data.extend(json.load(f))
f.close()
else:
print(
'{}{}Could not find file {}.'.format(
c.Style.BRIGHT, c.Fore.RED, staging_file
)
)
self._staging_data = staging_data
return self._staging_data | python | def staging_data(self):
"""Read data files and return all staging data for current profile."""
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] Staging data file: {}'.format(staging_file))
f = open(staging_file, 'r')
staging_data.extend(json.load(f))
f.close()
else:
print(
'{}{}Could not find file {}.'.format(
c.Style.BRIGHT, c.Fore.RED, staging_file
)
)
self._staging_data = staging_data
return self._staging_data | [
"def",
"staging_data",
"(",
"self",
")",
":",
"if",
"self",
".",
"_staging_data",
"is",
"None",
":",
"staging_data",
"=",
"[",
"]",
"for",
"staging_file",
"in",
"self",
".",
"profile",
".",
"get",
"(",
"'data_files'",
")",
"or",
"[",
"]",
":",
"if",
... | Read data files and return all staging data for current profile. | [
"Read",
"data",
"files",
"and",
"return",
"all",
"staging",
"data",
"for",
"current",
"profile",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_run.py#L1264-L1284 | train | 27,424 |
ThreatConnect-Inc/tcex | tcex/tcex_bin_run.py | TcExRun.stage_redis | def stage_redis(self, variable, data):
"""Stage data in Redis.
Args:
variable (str): The Redis variable name.
data (dict|list|str): The data to store in Redis.
"""
if isinstance(data, int):
data = str(data)
# handle binary
if variable.endswith('Binary'):
try:
data = base64.b64decode(data)
except binascii.Error:
msg = 'The Binary staging data for variable {} is not properly base64 encoded.'
msg = msg.format(variable)
sys.exit(msg)
elif variable.endswith('BinaryArray'):
if isinstance(data, string_types):
data = json.loads(data)
try:
# loop through each entry
decoded_data = []
for d in data:
d_decoded = base64.b64decode(d)
decoded_data.append(d_decoded)
data = decoded_data
except binascii.Error:
msg = 'The BinaryArray staging data for variable {} is not properly base64 encoded.'
msg = msg.format(variable)
sys.exit(msg)
self.log.info(u'[stage] Creating variable {}'.format(variable))
self.tcex.playbook.create(variable, data) | python | def stage_redis(self, variable, data):
"""Stage data in Redis.
Args:
variable (str): The Redis variable name.
data (dict|list|str): The data to store in Redis.
"""
if isinstance(data, int):
data = str(data)
# handle binary
if variable.endswith('Binary'):
try:
data = base64.b64decode(data)
except binascii.Error:
msg = 'The Binary staging data for variable {} is not properly base64 encoded.'
msg = msg.format(variable)
sys.exit(msg)
elif variable.endswith('BinaryArray'):
if isinstance(data, string_types):
data = json.loads(data)
try:
# loop through each entry
decoded_data = []
for d in data:
d_decoded = base64.b64decode(d)
decoded_data.append(d_decoded)
data = decoded_data
except binascii.Error:
msg = 'The BinaryArray staging data for variable {} is not properly base64 encoded.'
msg = msg.format(variable)
sys.exit(msg)
self.log.info(u'[stage] Creating variable {}'.format(variable))
self.tcex.playbook.create(variable, data) | [
"def",
"stage_redis",
"(",
"self",
",",
"variable",
",",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"int",
")",
":",
"data",
"=",
"str",
"(",
"data",
")",
"# handle binary",
"if",
"variable",
".",
"endswith",
"(",
"'Binary'",
")",
":",
"... | Stage data in Redis.
Args:
variable (str): The Redis variable name.
data (dict|list|str): The data to store in Redis. | [
"Stage",
"data",
"in",
"Redis",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_run.py#L1286-L1319 | train | 27,425 |
ThreatConnect-Inc/tcex | tcex/tcex_bin_run.py | TcExRun.stage_tc | def stage_tc(self, owner, staging_data, variable):
"""Stage data using ThreatConnect API.
.. code-block:: javascript
[{
"data": {
"id": 116,
"value": "adversary001-build-testing",
"type": "Adversary",
"ownerName": "qa-build",
"dateAdded": "2017-08-16T18:35:07-04:00",
"webLink": "https://app.tci.ninja/auth/adversary/adversary.xhtml?adversary=116"
},
"data_type": "redis",
"variable": "#App:0822:adversary!TCEntity"
}]
Args:
owner (str): The ThreatConnect owner name.
staging_data (dict): A dict containing the ThreatConnect threat intel.
variable (str): A variable name to write to Redis.
"""
# parse resource_data
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 = staging_data.pop('security_label')
except KeyError:
security_labels = []
try:
tags = staging_data.pop('tag')
except KeyError:
tags = []
resource = self.tcex.resource(resource_type)
resource.http_method = 'POST'
resource.owner = owner
# special case for Email Group Type
if resource_type == 'Email':
resource.add_payload('option', 'createVictims')
self.log.debug('body: {}'.format(staging_data))
resource.body = json.dumps(staging_data)
response = resource.request()
if response.get('status') == 'Success':
# add resource id
if resource_type in self.tcex.indicator_types:
resource_id = resource.summary(response.get('data'))
self.log.info(
'[stage] Creating resource {}:{}'.format(resource_type, resource_id)
)
elif resource_type in self.tcex.group_types:
self.log.info(
'[stage] Creating resource {}:{}'.format(
resource_type, response.get('data', {}).get('name')
)
)
resource_id = response.get('data', {}).get('id')
self.log.debug('[stage] resource_id: {}'.format(resource_id))
resource.resource_id(resource_id)
entity = self.tcex.playbook.json_to_entity(
response.get('data'), resource.value_fields, resource.name, resource.parent
)
self.log.debug('[stage] Creating Entity: {} ({})'.format(variable, entity[0]))
self.stage_redis(variable, entity[0])
# self.tcex.playbook.create_tc_entity(variable, entity[0])
# update metadata
for attribute_data in attributes:
self.stage_tc_create_attribute(
attribute_data.get('type'), attribute_data.get('value'), resource
)
for label_data in security_labels:
self.stage_tc_create_security_label(label_data.get('name'), resource)
for tag_data in tags:
self.stage_tc_create_tag(tag_data.get('name'), resource)
else:
self.log.error('[stage] Unsupported resource type {}.'.format(resource_type)) | python | def stage_tc(self, owner, staging_data, variable):
"""Stage data using ThreatConnect API.
.. code-block:: javascript
[{
"data": {
"id": 116,
"value": "adversary001-build-testing",
"type": "Adversary",
"ownerName": "qa-build",
"dateAdded": "2017-08-16T18:35:07-04:00",
"webLink": "https://app.tci.ninja/auth/adversary/adversary.xhtml?adversary=116"
},
"data_type": "redis",
"variable": "#App:0822:adversary!TCEntity"
}]
Args:
owner (str): The ThreatConnect owner name.
staging_data (dict): A dict containing the ThreatConnect threat intel.
variable (str): A variable name to write to Redis.
"""
# parse resource_data
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 = staging_data.pop('security_label')
except KeyError:
security_labels = []
try:
tags = staging_data.pop('tag')
except KeyError:
tags = []
resource = self.tcex.resource(resource_type)
resource.http_method = 'POST'
resource.owner = owner
# special case for Email Group Type
if resource_type == 'Email':
resource.add_payload('option', 'createVictims')
self.log.debug('body: {}'.format(staging_data))
resource.body = json.dumps(staging_data)
response = resource.request()
if response.get('status') == 'Success':
# add resource id
if resource_type in self.tcex.indicator_types:
resource_id = resource.summary(response.get('data'))
self.log.info(
'[stage] Creating resource {}:{}'.format(resource_type, resource_id)
)
elif resource_type in self.tcex.group_types:
self.log.info(
'[stage] Creating resource {}:{}'.format(
resource_type, response.get('data', {}).get('name')
)
)
resource_id = response.get('data', {}).get('id')
self.log.debug('[stage] resource_id: {}'.format(resource_id))
resource.resource_id(resource_id)
entity = self.tcex.playbook.json_to_entity(
response.get('data'), resource.value_fields, resource.name, resource.parent
)
self.log.debug('[stage] Creating Entity: {} ({})'.format(variable, entity[0]))
self.stage_redis(variable, entity[0])
# self.tcex.playbook.create_tc_entity(variable, entity[0])
# update metadata
for attribute_data in attributes:
self.stage_tc_create_attribute(
attribute_data.get('type'), attribute_data.get('value'), resource
)
for label_data in security_labels:
self.stage_tc_create_security_label(label_data.get('name'), resource)
for tag_data in tags:
self.stage_tc_create_tag(tag_data.get('name'), resource)
else:
self.log.error('[stage] Unsupported resource type {}.'.format(resource_type)) | [
"def",
"stage_tc",
"(",
"self",
",",
"owner",
",",
"staging_data",
",",
"variable",
")",
":",
"# parse resource_data",
"resource_type",
"=",
"staging_data",
".",
"pop",
"(",
"'type'",
")",
"if",
"resource_type",
"in",
"self",
".",
"tcex",
".",
"indicator_types... | Stage data using ThreatConnect API.
.. code-block:: javascript
[{
"data": {
"id": 116,
"value": "adversary001-build-testing",
"type": "Adversary",
"ownerName": "qa-build",
"dateAdded": "2017-08-16T18:35:07-04:00",
"webLink": "https://app.tci.ninja/auth/adversary/adversary.xhtml?adversary=116"
},
"data_type": "redis",
"variable": "#App:0822:adversary!TCEntity"
}]
Args:
owner (str): The ThreatConnect owner name.
staging_data (dict): A dict containing the ThreatConnect threat intel.
variable (str): A variable name to write to Redis. | [
"Stage",
"data",
"using",
"ThreatConnect",
"API",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_run.py#L1321-L1408 | train | 27,426 |
ThreatConnect-Inc/tcex | tcex/tcex_bin_run.py | TcExRun.stage_tc_create_security_label | def stage_tc_create_security_label(self, label, resource):
"""Add a security label to a resource.
Args:
label (str): The security label (must exit in ThreatConnect).
resource (obj): An instance of tcex resource class.
"""
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(
label, sl_response.get('response').text
)
) | python | def stage_tc_create_security_label(self, label, resource):
"""Add a security label to a resource.
Args:
label (str): The security label (must exit in ThreatConnect).
resource (obj): An instance of tcex resource class.
"""
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(
label, sl_response.get('response').text
)
) | [
"def",
"stage_tc_create_security_label",
"(",
"self",
",",
"label",
",",
"resource",
")",
":",
"sl_resource",
"=",
"resource",
".",
"security_labels",
"(",
"label",
")",
"sl_resource",
".",
"http_method",
"=",
"'POST'",
"sl_response",
"=",
"sl_resource",
".",
"r... | Add a security label to a resource.
Args:
label (str): The security label (must exit in ThreatConnect).
resource (obj): An instance of tcex resource class. | [
"Add",
"a",
"security",
"label",
"to",
"a",
"resource",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_run.py#L1436-L1451 | train | 27,427 |
ThreatConnect-Inc/tcex | tcex/tcex_bin_run.py | TcExRun.stage_tc_create_tag | def stage_tc_create_tag(self, tag, resource):
"""Add a tag to a resource.
Args:
tag (str): The tag to be added to the resource.
resource (obj): An instance of tcex resource class.
"""
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_response.get('response').text)
) | python | def stage_tc_create_tag(self, tag, resource):
"""Add a tag to a resource.
Args:
tag (str): The tag to be added to the resource.
resource (obj): An instance of tcex resource class.
"""
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_response.get('response').text)
) | [
"def",
"stage_tc_create_tag",
"(",
"self",
",",
"tag",
",",
"resource",
")",
":",
"tag_resource",
"=",
"resource",
".",
"tags",
"(",
"self",
".",
"tcex",
".",
"safetag",
"(",
"tag",
")",
")",
"tag_resource",
".",
"http_method",
"=",
"'POST'",
"t_response",... | Add a tag to a resource.
Args:
tag (str): The tag to be added to the resource.
resource (obj): An instance of tcex resource class. | [
"Add",
"a",
"tag",
"to",
"a",
"resource",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_run.py#L1453-L1466 | train | 27,428 |
ThreatConnect-Inc/tcex | tcex/tcex_bin_run.py | TcExRun.stage_tc_batch | def stage_tc_batch(self, owner, staging_data):
"""Stage data in ThreatConnect Platform using batch API.
Args:
owner (str): The ThreatConnect owner to submit batch job.
staging_data (dict): A dict of ThreatConnect batch data.
"""
batch = self.tcex.batch(owner)
for group in staging_data.get('group') or []:
# add to redis
variable = group.pop('variable', None)
path = group.pop('path', None)
data = self.path_data(group, path)
# update group data
if group.get('xid') is None:
# add xid if one doesn't exist
group['xid'] = self.stage_tc_batch_xid(group.get('type'), group.get('name'), owner)
# add owner name
group['ownerName'] = owner
# add to batch
batch.add_group(group)
# create tcentity
if variable is not None and data is not None:
self.stage_redis(variable, self.stage_tc_group_entity(data))
for indicator in staging_data.get('indicator') or []:
# add to redis
variable = indicator.pop('variable', None)
path = indicator.pop('path', None)
if indicator.get('xid') is None:
indicator['xid'] = self.stage_tc_batch_xid(
indicator.get('type'), indicator.get('summary'), owner
)
indicator['ownerName'] = owner
# add to batch after extra data has been popped
batch.add_indicator(indicator)
data = self.path_data(dict(indicator), path)
if variable is not None and data is not None:
# if isinstance(data, (dict)):
# tcentity uses value as the name
# data['value'] = data.pop('summary')
self.stage_redis(variable, self.stage_tc_indicator_entity(data))
# submit batch
batch_results = batch.submit()
self.log.debug('[stage] Batch Results: {}'.format(batch_results))
for error in batch_results.get('errors') or []:
self.log.error('[stage] {}'.format(error)) | python | def stage_tc_batch(self, owner, staging_data):
"""Stage data in ThreatConnect Platform using batch API.
Args:
owner (str): The ThreatConnect owner to submit batch job.
staging_data (dict): A dict of ThreatConnect batch data.
"""
batch = self.tcex.batch(owner)
for group in staging_data.get('group') or []:
# add to redis
variable = group.pop('variable', None)
path = group.pop('path', None)
data = self.path_data(group, path)
# update group data
if group.get('xid') is None:
# add xid if one doesn't exist
group['xid'] = self.stage_tc_batch_xid(group.get('type'), group.get('name'), owner)
# add owner name
group['ownerName'] = owner
# add to batch
batch.add_group(group)
# create tcentity
if variable is not None and data is not None:
self.stage_redis(variable, self.stage_tc_group_entity(data))
for indicator in staging_data.get('indicator') or []:
# add to redis
variable = indicator.pop('variable', None)
path = indicator.pop('path', None)
if indicator.get('xid') is None:
indicator['xid'] = self.stage_tc_batch_xid(
indicator.get('type'), indicator.get('summary'), owner
)
indicator['ownerName'] = owner
# add to batch after extra data has been popped
batch.add_indicator(indicator)
data = self.path_data(dict(indicator), path)
if variable is not None and data is not None:
# if isinstance(data, (dict)):
# tcentity uses value as the name
# data['value'] = data.pop('summary')
self.stage_redis(variable, self.stage_tc_indicator_entity(data))
# submit batch
batch_results = batch.submit()
self.log.debug('[stage] Batch Results: {}'.format(batch_results))
for error in batch_results.get('errors') or []:
self.log.error('[stage] {}'.format(error)) | [
"def",
"stage_tc_batch",
"(",
"self",
",",
"owner",
",",
"staging_data",
")",
":",
"batch",
"=",
"self",
".",
"tcex",
".",
"batch",
"(",
"owner",
")",
"for",
"group",
"in",
"staging_data",
".",
"get",
"(",
"'group'",
")",
"or",
"[",
"]",
":",
"# add ... | Stage data in ThreatConnect Platform using batch API.
Args:
owner (str): The ThreatConnect owner to submit batch job.
staging_data (dict): A dict of ThreatConnect batch data. | [
"Stage",
"data",
"in",
"ThreatConnect",
"Platform",
"using",
"batch",
"API",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_run.py#L1516-L1561 | train | 27,429 |
ThreatConnect-Inc/tcex | tcex/tcex_bin_run.py | TcExRun.stage_tc_batch_xid | def stage_tc_batch_xid(xid_type, xid_value, owner):
"""Create an xid for a batch job.
Args:
xid_type (str): [description]
xid_value (str): [description]
owner (str): [description]
Returns:
[type]: [description]
"""
xid_string = '{}-{}-{}'.format(xid_type, xid_value, owner)
hash_object = hashlib.sha256(xid_string.encode('utf-8'))
return hash_object.hexdigest() | python | def stage_tc_batch_xid(xid_type, xid_value, owner):
"""Create an xid for a batch job.
Args:
xid_type (str): [description]
xid_value (str): [description]
owner (str): [description]
Returns:
[type]: [description]
"""
xid_string = '{}-{}-{}'.format(xid_type, xid_value, owner)
hash_object = hashlib.sha256(xid_string.encode('utf-8'))
return hash_object.hexdigest() | [
"def",
"stage_tc_batch_xid",
"(",
"xid_type",
",",
"xid_value",
",",
"owner",
")",
":",
"xid_string",
"=",
"'{}-{}-{}'",
".",
"format",
"(",
"xid_type",
",",
"xid_value",
",",
"owner",
")",
"hash_object",
"=",
"hashlib",
".",
"sha256",
"(",
"xid_string",
"."... | Create an xid for a batch job.
Args:
xid_type (str): [description]
xid_value (str): [description]
owner (str): [description]
Returns:
[type]: [description] | [
"Create",
"an",
"xid",
"for",
"a",
"batch",
"job",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_run.py#L1564-L1577 | train | 27,430 |
ThreatConnect-Inc/tcex | tcex/tcex_bin_run.py | TcExRun.stage_tc_indicator_entity | def stage_tc_indicator_entity(self, indicator_data):
"""Convert JSON data to TCEntity.
Args:
indicator_data (str): [description]
Returns:
[type]: [description]
"""
path = '@.{value: summary, '
path += 'type: type, '
path += 'ownerName: ownerName, '
path += 'confidence: confidence || `0`, '
path += 'rating: rating || `0`}'
return self.path_data(indicator_data, path) | python | def stage_tc_indicator_entity(self, indicator_data):
"""Convert JSON data to TCEntity.
Args:
indicator_data (str): [description]
Returns:
[type]: [description]
"""
path = '@.{value: summary, '
path += 'type: type, '
path += 'ownerName: ownerName, '
path += 'confidence: confidence || `0`, '
path += 'rating: rating || `0`}'
return self.path_data(indicator_data, path) | [
"def",
"stage_tc_indicator_entity",
"(",
"self",
",",
"indicator_data",
")",
":",
"path",
"=",
"'@.{value: summary, '",
"path",
"+=",
"'type: type, '",
"path",
"+=",
"'ownerName: ownerName, '",
"path",
"+=",
"'confidence: confidence || `0`, '",
"path",
"+=",
"'rating: rat... | Convert JSON data to TCEntity.
Args:
indicator_data (str): [description]
Returns:
[type]: [description] | [
"Convert",
"JSON",
"data",
"to",
"TCEntity",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_run.py#L1591-L1605 | train | 27,431 |
ThreatConnect-Inc/tcex | tcex/tcex_bin_run.py | TcExRun.validate_log_output | def validate_log_output(self, passed, db_data, user_data, oper):
"""Format the validation log output to be easier to read.
Args:
passed (bool): The results of the validation test.
db_data (str): The data store in Redis.
user_data (str): The user provided data.
oper (str): The comparison operator.
Raises:
RuntimeError: Raise error on validation failure if halt_on_fail is True.
"""
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 = []
for d in db_data:
if d is not None and isinstance(d, string_types) and len(d) > truncate:
db_data_truncated.append('{} ...'.format(d[: self.args.truncate]))
else:
db_data_truncated.append(d)
db_data = db_data_truncated
if user_data is not None and passed:
if isinstance(user_data, (string_types)) and len(user_data) > truncate:
user_data = user_data[: self.args.truncate]
elif isinstance(user_data, (list)):
user_data_truncated = []
for u in user_data:
if isinstance(db_data, (string_types)) and len(u) > truncate:
user_data_truncated.append('{} ...'.format(u[: self.args.truncate]))
else:
user_data_truncated.append(u)
user_data = user_data_truncated
self.log.info('[validate] DB Data : ({}), Type: [{}]'.format(db_data, type(db_data)))
self.log.info('[validate] Operator : ({})'.format(oper))
self.log.info('[validate] User Data : ({}), Type: [{}]'.format(user_data, type(user_data)))
if passed:
self.log.info('[validate] Results : Passed')
else:
self.log.error('[validate] Results : Failed')
if db_data is not None and user_data is not None and oper in ['eq', 'ne']:
try:
diff_count = 0
for i, diff in enumerate(difflib.ndiff(db_data, user_data)):
if diff[0] == ' ': # no difference
continue
elif diff[0] == '-':
self.log.info(
'[validate] Diff : Missing data at index {}'.format(i)
)
elif diff[0] == '+':
self.log.info('[validate] Diff : Extra data at index {}'.format(i))
if diff_count > self.max_diff:
# don't spam the logs if string are vastly different
self.log.info('Max number of differences reached.')
break
diff_count += 1
except TypeError:
pass
except KeyError:
pass
# halt all further actions
if self.args.halt_on_fail:
raise RuntimeError('Failed validating data.') | python | def validate_log_output(self, passed, db_data, user_data, oper):
"""Format the validation log output to be easier to read.
Args:
passed (bool): The results of the validation test.
db_data (str): The data store in Redis.
user_data (str): The user provided data.
oper (str): The comparison operator.
Raises:
RuntimeError: Raise error on validation failure if halt_on_fail is True.
"""
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 = []
for d in db_data:
if d is not None and isinstance(d, string_types) and len(d) > truncate:
db_data_truncated.append('{} ...'.format(d[: self.args.truncate]))
else:
db_data_truncated.append(d)
db_data = db_data_truncated
if user_data is not None and passed:
if isinstance(user_data, (string_types)) and len(user_data) > truncate:
user_data = user_data[: self.args.truncate]
elif isinstance(user_data, (list)):
user_data_truncated = []
for u in user_data:
if isinstance(db_data, (string_types)) and len(u) > truncate:
user_data_truncated.append('{} ...'.format(u[: self.args.truncate]))
else:
user_data_truncated.append(u)
user_data = user_data_truncated
self.log.info('[validate] DB Data : ({}), Type: [{}]'.format(db_data, type(db_data)))
self.log.info('[validate] Operator : ({})'.format(oper))
self.log.info('[validate] User Data : ({}), Type: [{}]'.format(user_data, type(user_data)))
if passed:
self.log.info('[validate] Results : Passed')
else:
self.log.error('[validate] Results : Failed')
if db_data is not None and user_data is not None and oper in ['eq', 'ne']:
try:
diff_count = 0
for i, diff in enumerate(difflib.ndiff(db_data, user_data)):
if diff[0] == ' ': # no difference
continue
elif diff[0] == '-':
self.log.info(
'[validate] Diff : Missing data at index {}'.format(i)
)
elif diff[0] == '+':
self.log.info('[validate] Diff : Extra data at index {}'.format(i))
if diff_count > self.max_diff:
# don't spam the logs if string are vastly different
self.log.info('Max number of differences reached.')
break
diff_count += 1
except TypeError:
pass
except KeyError:
pass
# halt all further actions
if self.args.halt_on_fail:
raise RuntimeError('Failed validating data.') | [
"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",
"(",... | Format the validation log output to be easier to read.
Args:
passed (bool): The results of the validation test.
db_data (str): The data store in Redis.
user_data (str): The user provided data.
oper (str): The comparison operator.
Raises:
RuntimeError: Raise error on validation failure if halt_on_fail is True. | [
"Format",
"the",
"validation",
"log",
"output",
"to",
"be",
"easier",
"to",
"read",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_run.py#L1715-L1784 | train | 27,432 |
ThreatConnect-Inc/tcex | tcex/tcex_bin_run.py | ArgBuilder._add_arg_python | def _add_arg_python(self, key, value=None, mask=False):
"""Add CLI Arg formatted specifically for Python.
Args:
key (string): The CLI Args key (e.g., --name).
value (string): The CLI Args value (e.g., bob).
mask (boolean, default:False): Indicates whether no mask value.
"""
self._data[key] = value
if not value:
# both false boolean values (flags) and empty values should not be added.
pass
elif value is True:
# true boolean values are flags and should not contain a value
self._args.append('--{}'.format(key))
self._args_quoted.append('--{}'.format(key))
self._args_masked.append('--{}'.format(key))
else:
self._args.append('--{}={}'.format(key, value))
if mask:
# mask sensitive values
value = 'x' * len(str(value))
else:
# quote all values that would get displayed
value = self.quote(value)
self._args_quoted.append('--{}={}'.format(key, value))
self._args_masked.append('--{}={}'.format(key, value)) | python | def _add_arg_python(self, key, value=None, mask=False):
"""Add CLI Arg formatted specifically for Python.
Args:
key (string): The CLI Args key (e.g., --name).
value (string): The CLI Args value (e.g., bob).
mask (boolean, default:False): Indicates whether no mask value.
"""
self._data[key] = value
if not value:
# both false boolean values (flags) and empty values should not be added.
pass
elif value is True:
# true boolean values are flags and should not contain a value
self._args.append('--{}'.format(key))
self._args_quoted.append('--{}'.format(key))
self._args_masked.append('--{}'.format(key))
else:
self._args.append('--{}={}'.format(key, value))
if mask:
# mask sensitive values
value = 'x' * len(str(value))
else:
# quote all values that would get displayed
value = self.quote(value)
self._args_quoted.append('--{}={}'.format(key, value))
self._args_masked.append('--{}={}'.format(key, value)) | [
"def",
"_add_arg_python",
"(",
"self",
",",
"key",
",",
"value",
"=",
"None",
",",
"mask",
"=",
"False",
")",
":",
"self",
".",
"_data",
"[",
"key",
"]",
"=",
"value",
"if",
"not",
"value",
":",
"# both false boolean values (flags) and empty values should not ... | Add CLI Arg formatted specifically for Python.
Args:
key (string): The CLI Args key (e.g., --name).
value (string): The CLI Args value (e.g., bob).
mask (boolean, default:False): Indicates whether no mask value. | [
"Add",
"CLI",
"Arg",
"formatted",
"specifically",
"for",
"Python",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_run.py#L1820-L1846 | train | 27,433 |
ThreatConnect-Inc/tcex | tcex/tcex_bin_run.py | ArgBuilder._add_arg_java | def _add_arg_java(self, key, value, mask=False):
"""Add CLI Arg formatted specifically for Java.
Args:
key (string): The CLI Args key (e.g., --name).
value (string): The CLI Args value (e.g., bob).
mask (boolean, default:False): Indicates whether no mask value.
"""
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 = 'x' * len(str(value))
self._args_masked.append('{}{}={}'.format('-D', key, value)) | python | def _add_arg_java(self, key, value, mask=False):
"""Add CLI Arg formatted specifically for Java.
Args:
key (string): The CLI Args key (e.g., --name).
value (string): The CLI Args value (e.g., bob).
mask (boolean, default:False): Indicates whether no mask value.
"""
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 = 'x' * len(str(value))
self._args_masked.append('{}{}={}'.format('-D', key, value)) | [
"def",
"_add_arg_java",
"(",
"self",
",",
"key",
",",
"value",
",",
"mask",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"bool",
")",
":",
"value",
"=",
"int",
"(",
"value",
")",
"self",
".",
"_data",
"[",
"key",
"]",
"=",
"valu... | Add CLI Arg formatted specifically for Java.
Args:
key (string): The CLI Args key (e.g., --name).
value (string): The CLI Args value (e.g., bob).
mask (boolean, default:False): Indicates whether no mask value. | [
"Add",
"CLI",
"Arg",
"formatted",
"specifically",
"for",
"Java",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_run.py#L1848-L1863 | train | 27,434 |
ThreatConnect-Inc/tcex | tcex/tcex_bin_run.py | ArgBuilder._add_arg | def _add_arg(self, key, value, mask=False):
"""Add CLI Arg for the correct language.
Args:
key (string): The CLI Args key (e.g., --name).
value (string): The CLI Args value (e.g., bob).
mask (boolean, default:False): Indicates whether no mask value.
"""
if self.lang == 'python':
self._add_arg_python(key, value, mask)
elif self.lang == 'java':
self._add_arg_java(key, value, mask) | python | def _add_arg(self, key, value, mask=False):
"""Add CLI Arg for the correct language.
Args:
key (string): The CLI Args key (e.g., --name).
value (string): The CLI Args value (e.g., bob).
mask (boolean, default:False): Indicates whether no mask value.
"""
if self.lang == 'python':
self._add_arg_python(key, value, mask)
elif self.lang == 'java':
self._add_arg_java(key, value, mask) | [
"def",
"_add_arg",
"(",
"self",
",",
"key",
",",
"value",
",",
"mask",
"=",
"False",
")",
":",
"if",
"self",
".",
"lang",
"==",
"'python'",
":",
"self",
".",
"_add_arg_python",
"(",
"key",
",",
"value",
",",
"mask",
")",
"elif",
"self",
".",
"lang"... | Add CLI Arg for the correct language.
Args:
key (string): The CLI Args key (e.g., --name).
value (string): The CLI Args value (e.g., bob).
mask (boolean, default:False): Indicates whether no mask value. | [
"Add",
"CLI",
"Arg",
"for",
"the",
"correct",
"language",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_run.py#L1865-L1876 | train | 27,435 |
ThreatConnect-Inc/tcex | tcex/tcex_bin_run.py | ArgBuilder.add | def add(self, key, value):
"""Add CLI Arg to lists value.
Args:
key (string): The CLI Args key (e.g., --name).
value (string): The CLI Args value (e.g., bob).
"""
if isinstance(value, list):
# TODO: support env vars in list w/masked values
for val in value:
self._add_arg_python(key, val)
elif isinstance(value, dict):
err = 'Dictionary types are not currently supported for field.'
print('{}{}{}'.format(c.Style.BRIGHT, c.Fore.RED, err))
else:
mask = False
env_var = re.compile(r'^\$env\.(.*)$')
envs_var = re.compile(r'^\$envs\.(.*)$')
if env_var.match(str(value)):
# read value from environment variable
env_key = env_var.match(str(value)).groups()[0]
value = os.environ.get(env_key, value)
elif envs_var.match(str(value)):
# read secure value from environment variable
env_key = envs_var.match(str(value)).groups()[0]
value = os.environ.get(env_key, value)
mask = True
self._add_arg(key, value, mask) | python | def add(self, key, value):
"""Add CLI Arg to lists value.
Args:
key (string): The CLI Args key (e.g., --name).
value (string): The CLI Args value (e.g., bob).
"""
if isinstance(value, list):
# TODO: support env vars in list w/masked values
for val in value:
self._add_arg_python(key, val)
elif isinstance(value, dict):
err = 'Dictionary types are not currently supported for field.'
print('{}{}{}'.format(c.Style.BRIGHT, c.Fore.RED, err))
else:
mask = False
env_var = re.compile(r'^\$env\.(.*)$')
envs_var = re.compile(r'^\$envs\.(.*)$')
if env_var.match(str(value)):
# read value from environment variable
env_key = env_var.match(str(value)).groups()[0]
value = os.environ.get(env_key, value)
elif envs_var.match(str(value)):
# read secure value from environment variable
env_key = envs_var.match(str(value)).groups()[0]
value = os.environ.get(env_key, value)
mask = True
self._add_arg(key, value, mask) | [
"def",
"add",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"# TODO: support env vars in list w/masked values",
"for",
"val",
"in",
"value",
":",
"self",
".",
"_add_arg_python",
"(",
"key",
",",
"... | Add CLI Arg to lists value.
Args:
key (string): The CLI Args key (e.g., --name).
value (string): The CLI Args value (e.g., bob). | [
"Add",
"CLI",
"Arg",
"to",
"lists",
"value",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_run.py#L1878-L1906 | train | 27,436 |
ThreatConnect-Inc/tcex | tcex/tcex_bin_run.py | ArgBuilder.quote | def quote(self, data):
"""Quote any parameters that contain spaces or special character.
Returns:
(string): String containing parameters wrapped in double quotes
"""
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 | python | def quote(self, data):
"""Quote any parameters that contain spaces or special character.
Returns:
(string): String containing parameters wrapped in double quotes
"""
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 | [
"def",
"quote",
"(",
"self",
",",
"data",
")",
":",
"if",
"self",
".",
"lang",
"==",
"'python'",
":",
"quote_char",
"=",
"\"'\"",
"elif",
"self",
".",
"lang",
"==",
"'java'",
":",
"quote_char",
"=",
"\"'\"",
"if",
"re",
".",
"findall",
"(",
"r'[!\\-\... | Quote any parameters that contain spaces or special character.
Returns:
(string): String containing parameters wrapped in double quotes | [
"Quote",
"any",
"parameters",
"that",
"contain",
"spaces",
"or",
"special",
"character",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_run.py#L1908-L1922 | train | 27,437 |
ThreatConnect-Inc/tcex | tcex/tcex_bin_run.py | ArgBuilder.load | def load(self, profile_args):
"""Load provided CLI Args.
Args:
args (dict): Dictionary of args in key/value format.
"""
for key, value in profile_args.items():
self.add(key, value) | python | def load(self, profile_args):
"""Load provided CLI Args.
Args:
args (dict): Dictionary of args in key/value format.
"""
for key, value in profile_args.items():
self.add(key, value) | [
"def",
"load",
"(",
"self",
",",
"profile_args",
")",
":",
"for",
"key",
",",
"value",
"in",
"profile_args",
".",
"items",
"(",
")",
":",
"self",
".",
"add",
"(",
"key",
",",
"value",
")"
] | Load provided CLI Args.
Args:
args (dict): Dictionary of args in key/value format. | [
"Load",
"provided",
"CLI",
"Args",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_run.py#L1924-L1931 | train | 27,438 |
ThreatConnect-Inc/tcex | tcex/tcex_bin_run.py | Reports.add_profile | def add_profile(self, profile, selected):
"""Add profile to report."""
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'] += 1
self.profiles.setdefault(report.name, report)
return report | python | def add_profile(self, profile, selected):
"""Add profile to report."""
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'] += 1
self.profiles.setdefault(report.name, report)
return report | [
"def",
"add_profile",
"(",
"self",
",",
"profile",
",",
"selected",
")",
":",
"report",
"=",
"Report",
"(",
"profile",
")",
"report",
".",
"selected",
"=",
"selected",
"if",
"selected",
":",
"self",
".",
"report",
"[",
"'settings'",
"]",
"[",
"'selected_... | Add profile to report. | [
"Add",
"profile",
"to",
"report",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_run.py#L2022-L2031 | train | 27,439 |
ThreatConnect-Inc/tcex | tcex/tcex_bin_run.py | Reports.profile | def profile(self, name):
"""Return a specific profile."""
self.selected_profile = self.profiles.get(name)
return self.profiles.get(name) | python | def profile(self, name):
"""Return a specific profile."""
self.selected_profile = self.profiles.get(name)
return self.profiles.get(name) | [
"def",
"profile",
"(",
"self",
",",
"name",
")",
":",
"self",
".",
"selected_profile",
"=",
"self",
".",
"profiles",
".",
"get",
"(",
"name",
")",
"return",
"self",
".",
"profiles",
".",
"get",
"(",
"name",
")"
] | Return a specific profile. | [
"Return",
"a",
"specific",
"profile",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_run.py#L2041-L2044 | train | 27,440 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_group.py | Group.add_file | def add_file(self, filename, file_content):
"""Add a file for Document and Report types.
Example::
document = tcex.batch.group('Document', 'My Document')
document.add_file('my_file.txt', 'my contents')
Args:
filename (str): The name of the file.
file_content (bytes|method|str): The contents of the file or callback to get contents.
"""
self._group_data['fileName'] = filename
self._file_content = file_content | python | def add_file(self, filename, file_content):
"""Add a file for Document and Report types.
Example::
document = tcex.batch.group('Document', 'My Document')
document.add_file('my_file.txt', 'my contents')
Args:
filename (str): The name of the file.
file_content (bytes|method|str): The contents of the file or callback to get contents.
"""
self._group_data['fileName'] = filename
self._file_content = file_content | [
"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.
Example::
document = tcex.batch.group('Document', 'My Document')
document.add_file('my_file.txt', 'my contents')
Args:
filename (str): The name of the file.
file_content (bytes|method|str): The contents of the file or callback to get contents. | [
"Add",
"a",
"file",
"for",
"Document",
"and",
"Report",
"types",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_group.py#L66-L79 | train | 27,441 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_group.py | Group.add_key_value | def add_key_value(self, key, value):
"""Add custom field to Group object.
.. note:: The key must be the exact name required by the batch schema.
Example::
document = tcex.batch.group('Document', 'My Document')
document.add_key_value('fileName', 'something.pdf')
Args:
key (str): The field key to add to the JSON batch data.
value (str): The field value to add to the JSON batch data.
"""
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':
# file content arg is not part of Group JSON
pass
else:
self._group_data[key] = value | python | def add_key_value(self, key, value):
"""Add custom field to Group object.
.. note:: The key must be the exact name required by the batch schema.
Example::
document = tcex.batch.group('Document', 'My Document')
document.add_key_value('fileName', 'something.pdf')
Args:
key (str): The field key to add to the JSON batch data.
value (str): The field value to add to the JSON batch data.
"""
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':
# file content arg is not part of Group JSON
pass
else:
self._group_data[key] = value | [
"def",
"add_key_value",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"key",
"=",
"self",
".",
"_metadata_map",
".",
"get",
"(",
"key",
",",
"key",
")",
"if",
"key",
"in",
"[",
"'dateAdded'",
",",
"'eventDate'",
",",
"'firstSeen'",
",",
"'publishDat... | Add custom field to Group object.
.. note:: The key must be the exact name required by the batch schema.
Example::
document = tcex.batch.group('Document', 'My Document')
document.add_key_value('fileName', 'something.pdf')
Args:
key (str): The field key to add to the JSON batch data.
value (str): The field value to add to the JSON batch data. | [
"Add",
"custom",
"field",
"to",
"Group",
"object",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_group.py#L81-L104 | train | 27,442 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_group.py | Group.data | def data(self):
"""Return Group data."""
# add attributes
if self._attributes:
self._group_data['attribute'] = []
for attr in self._attributes:
if attr.valid:
self._group_data['attribute'].append(attr.data)
# add security labels
if self._labels:
self._group_data['securityLabel'] = []
for label in self._labels:
self._group_data['securityLabel'].append(label.data)
# add tags
if self._tags:
self._group_data['tag'] = []
for tag in self._tags:
if tag.valid:
self._group_data['tag'].append(tag.data)
return self._group_data | python | def data(self):
"""Return Group data."""
# add attributes
if self._attributes:
self._group_data['attribute'] = []
for attr in self._attributes:
if attr.valid:
self._group_data['attribute'].append(attr.data)
# add security labels
if self._labels:
self._group_data['securityLabel'] = []
for label in self._labels:
self._group_data['securityLabel'].append(label.data)
# add tags
if self._tags:
self._group_data['tag'] = []
for tag in self._tags:
if tag.valid:
self._group_data['tag'].append(tag.data)
return self._group_data | [
"def",
"data",
"(",
"self",
")",
":",
"# add attributes",
"if",
"self",
".",
"_attributes",
":",
"self",
".",
"_group_data",
"[",
"'attribute'",
"]",
"=",
"[",
"]",
"for",
"attr",
"in",
"self",
".",
"_attributes",
":",
"if",
"attr",
".",
"valid",
":",
... | Return Group data. | [
"Return",
"Group",
"data",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_group.py#L156-L175 | train | 27,443 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_group.py | Group.security_label | def security_label(self, name, description=None, color=None):
"""Return instance of SecurityLabel.
.. note:: The provided security label will be create if it doesn't exist. If the security
label already exists nothing will be changed.
Args:
name (str): The value for this security label.
description (str): A description for this security label.
color (str): A color (hex value) for this security label.
Returns:
obj: An instance of SecurityLabel.
"""
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 | python | def security_label(self, name, description=None, color=None):
"""Return instance of SecurityLabel.
.. note:: The provided security label will be create if it doesn't exist. If the security
label already exists nothing will be changed.
Args:
name (str): The value for this security label.
description (str): A description for this security label.
color (str): A color (hex value) for this security label.
Returns:
obj: An instance of SecurityLabel.
"""
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 | [
"def",
"security_label",
"(",
"self",
",",
"name",
",",
"description",
"=",
"None",
",",
"color",
"=",
"None",
")",
":",
"label",
"=",
"SecurityLabel",
"(",
"name",
",",
"description",
",",
"color",
")",
"for",
"label_data",
"in",
"self",
".",
"_labels",... | Return instance of SecurityLabel.
.. note:: The provided security label will be create if it doesn't exist. If the security
label already exists nothing will be changed.
Args:
name (str): The value for this security label.
description (str): A description for this security label.
color (str): A color (hex value) for this security label.
Returns:
obj: An instance of SecurityLabel. | [
"Return",
"instance",
"of",
"SecurityLabel",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_group.py#L216-L237 | train | 27,444 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_group.py | Group.tag | def tag(self, name, formatter=None):
"""Return instance of Tag.
Args:
name (str): The value for this tag.
formatter (method, optional): A method that take a tag value and returns a
formatted tag.
Returns:
obj: An instance of Tag.
"""
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 | python | def tag(self, name, formatter=None):
"""Return instance of Tag.
Args:
name (str): The value for this tag.
formatter (method, optional): A method that take a tag value and returns a
formatted tag.
Returns:
obj: An instance of Tag.
"""
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 | [
"def",
"tag",
"(",
"self",
",",
"name",
",",
"formatter",
"=",
"None",
")",
":",
"tag",
"=",
"Tag",
"(",
"name",
",",
"formatter",
")",
"for",
"tag_data",
"in",
"self",
".",
"_tags",
":",
"if",
"tag_data",
".",
"name",
"==",
"name",
":",
"tag",
"... | Return instance of Tag.
Args:
name (str): The value for this tag.
formatter (method, optional): A method that take a tag value and returns a
formatted tag.
Returns:
obj: An instance of Tag. | [
"Return",
"instance",
"of",
"Tag",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_group.py#L239-L257 | train | 27,445 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_group.py | Campaign.first_seen | def first_seen(self, first_seen):
"""Set Document first seen."""
self._group_data['firstSeen'] = self._utils.format_datetime(
first_seen, date_format='%Y-%m-%dT%H:%M:%SZ'
) | python | def first_seen(self, first_seen):
"""Set Document first seen."""
self._group_data['firstSeen'] = self._utils.format_datetime(
first_seen, date_format='%Y-%m-%dT%H:%M:%SZ'
) | [
"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. | [
"Set",
"Document",
"first",
"seen",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_group.py#L314-L318 | train | 27,446 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_group.py | Event.event_date | def event_date(self, event_date):
"""Set the Events "event date" value."""
self._group_data['eventDate'] = self._utils.format_datetime(
event_date, date_format='%Y-%m-%dT%H:%M:%SZ'
) | python | def event_date(self, event_date):
"""Set the Events "event date" value."""
self._group_data['eventDate'] = self._utils.format_datetime(
event_date, date_format='%Y-%m-%dT%H:%M:%SZ'
) | [
"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. | [
"Set",
"the",
"Events",
"event",
"date",
"value",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_group.py#L471-L475 | train | 27,447 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_group.py | Report.publish_date | def publish_date(self, publish_date):
"""Set Report publish date"""
self._group_data['publishDate'] = self._utils.format_datetime(
publish_date, date_format='%Y-%m-%dT%H:%M:%SZ'
) | python | def publish_date(self, publish_date):
"""Set Report publish date"""
self._group_data['publishDate'] = self._utils.format_datetime(
publish_date, date_format='%Y-%m-%dT%H:%M:%SZ'
) | [
"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 | [
"Set",
"Report",
"publish",
"date"
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_group.py#L616-L620 | train | 27,448 |
ThreatConnect-Inc/tcex | app_init/__main__.py | AppLib.find_lib_directory | def find_lib_directory(self):
"""Find the optimal lib directory."""
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_directory = self.lib_major_version
else:
for lv in [self.lib_micro_version, self.lib_minor_version, self.lib_major_version]:
for d in self.lib_directories:
if lv in d:
lib_directory = d
break
else:
continue
break
return lib_directory | python | def find_lib_directory(self):
"""Find the optimal lib directory."""
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_directory = self.lib_major_version
else:
for lv in [self.lib_micro_version, self.lib_minor_version, self.lib_major_version]:
for d in self.lib_directories:
if lv in d:
lib_directory = d
break
else:
continue
break
return lib_directory | [
"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",
... | Find the optimal lib directory. | [
"Find",
"the",
"optimal",
"lib",
"directory",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/app_init/__main__.py#L26-L44 | train | 27,449 |
ThreatConnect-Inc/tcex | app_init/__main__.py | AppLib.lib_directories | def lib_directories(self):
"""Get all "lib" directories."""
if self._lib_directories is None:
self._lib_directories = []
app_path = os.getcwd()
contents = os.listdir(app_path)
for c in contents:
# ensure content starts with lib, is directory, and is readable
if c.startswith('lib') and os.path.isdir(c) and (os.access(c, os.R_OK)):
self._lib_directories.append(c)
return sorted(self._lib_directories, reverse=True) | python | def lib_directories(self):
"""Get all "lib" directories."""
if self._lib_directories is None:
self._lib_directories = []
app_path = os.getcwd()
contents = os.listdir(app_path)
for c in contents:
# ensure content starts with lib, is directory, and is readable
if c.startswith('lib') and os.path.isdir(c) and (os.access(c, os.R_OK)):
self._lib_directories.append(c)
return sorted(self._lib_directories, reverse=True) | [
"def",
"lib_directories",
"(",
"self",
")",
":",
"if",
"self",
".",
"_lib_directories",
"is",
"None",
":",
"self",
".",
"_lib_directories",
"=",
"[",
"]",
"app_path",
"=",
"os",
".",
"getcwd",
"(",
")",
"contents",
"=",
"os",
".",
"listdir",
"(",
"app_... | Get all "lib" directories. | [
"Get",
"all",
"lib",
"directories",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/app_init/__main__.py#L47-L57 | train | 27,450 |
ThreatConnect-Inc/tcex | tcex/tcex_ti/mappings/indicator/indicator_types/file.py | File._set_unique_id | def _set_unique_id(self, json_response):
"""
Sets the unique_id provided a json response.
Args:
json_response:
"""
self.unique_id = (
json_response.get('md5')
or json_response.get('sha1')
or json_response.get('sha256')
or ''
) | python | def _set_unique_id(self, json_response):
"""
Sets the unique_id provided a json response.
Args:
json_response:
"""
self.unique_id = (
json_response.get('md5')
or json_response.get('sha1')
or json_response.get('sha256')
or ''
) | [
"def",
"_set_unique_id",
"(",
"self",
",",
"json_response",
")",
":",
"self",
".",
"unique_id",
"=",
"(",
"json_response",
".",
"get",
"(",
"'md5'",
")",
"or",
"json_response",
".",
"get",
"(",
"'sha1'",
")",
"or",
"json_response",
".",
"get",
"(",
"'sha... | Sets the unique_id provided a json response.
Args:
json_response: | [
"Sets",
"the",
"unique_id",
"provided",
"a",
"json",
"response",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti/mappings/indicator/indicator_types/file.py#L56-L68 | train | 27,451 |
ThreatConnect-Inc/tcex | tcex/tcex_ti/mappings/indicator/tcex_ti_indicator.py | Indicator.rating | def rating(self, value):
"""
Updates the Indicators rating
Args:
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
) | python | def rating(self, value):
"""
Updates the Indicators rating
Args:
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
) | [
"def",
"rating",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"self",
".",
"can_update",
"(",
")",
":",
"self",
".",
"_tcex",
".",
"handle_error",
"(",
"910",
",",
"[",
"self",
".",
"type",
"]",
")",
"request_data",
"=",
"{",
"'rating'",
":",
... | Updates the Indicators rating
Args:
value: | [
"Updates",
"the",
"Indicators",
"rating"
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti/mappings/indicator/tcex_ti_indicator.py#L197-L209 | train | 27,452 |
ThreatConnect-Inc/tcex | tcex/tcex_ti/mappings/indicator/tcex_ti_indicator.py | Indicator.add_observers | def add_observers(self, count, date_observed):
"""
Adds a Indicator Observation
Args:
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(
self.api_type, self.api_sub_type, self.unique_id, data, owner=self.owner
) | python | def add_observers(self, count, date_observed):
"""
Adds a Indicator Observation
Args:
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(
self.api_type, self.api_sub_type, self.unique_id, data, owner=self.owner
) | [
"def",
"add_observers",
"(",
"self",
",",
"count",
",",
"date_observed",
")",
":",
"if",
"not",
"self",
".",
"can_update",
"(",
")",
":",
"self",
".",
"_tcex",
".",
"handle_error",
"(",
"910",
",",
"[",
"self",
".",
"type",
"]",
")",
"data",
"=",
"... | Adds a Indicator Observation
Args:
count:
date_observed: | [
"Adds",
"a",
"Indicator",
"Observation"
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti/mappings/indicator/tcex_ti_indicator.py#L236-L257 | train | 27,453 |
ThreatConnect-Inc/tcex | tcex/tcex_ti/mappings/indicator/tcex_ti_indicator.py | Indicator.deleted | def deleted(self, deleted_since, filters=None, params=None):
"""
Gets the indicators deleted.
Args:
params:
filters:
deleted_since: Date since its been deleted
"""
return self.tc_requests.deleted(
self.api_type,
self.api_sub_type,
deleted_since,
owner=self.owner,
filters=filters,
params=params,
) | python | def deleted(self, deleted_since, filters=None, params=None):
"""
Gets the indicators deleted.
Args:
params:
filters:
deleted_since: Date since its been deleted
"""
return self.tc_requests.deleted(
self.api_type,
self.api_sub_type,
deleted_since,
owner=self.owner,
filters=filters,
params=params,
) | [
"def",
"deleted",
"(",
"self",
",",
"deleted_since",
",",
"filters",
"=",
"None",
",",
"params",
"=",
"None",
")",
":",
"return",
"self",
".",
"tc_requests",
".",
"deleted",
"(",
"self",
".",
"api_type",
",",
"self",
".",
"api_sub_type",
",",
"deleted_si... | Gets the indicators deleted.
Args:
params:
filters:
deleted_since: Date since its been deleted | [
"Gets",
"the",
"indicators",
"deleted",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti/mappings/indicator/tcex_ti_indicator.py#L296-L314 | train | 27,454 |
ThreatConnect-Inc/tcex | tcex/tcex_ti/mappings/indicator/tcex_ti_indicator.py | Indicator.build_summary | def build_summary(val1=None, val2=None, val3=None):
"""
Constructs the summary given va1, va2, val3
Args:
val1:
val2:
val3:
Returns:
"""
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) | python | def build_summary(val1=None, val2=None, val3=None):
"""
Constructs the summary given va1, va2, val3
Args:
val1:
val2:
val3:
Returns:
"""
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) | [
"def",
"build_summary",
"(",
"val1",
"=",
"None",
",",
"val2",
"=",
"None",
",",
"val3",
"=",
"None",
")",
":",
"summary",
"=",
"[",
"]",
"if",
"val1",
"is",
"not",
"None",
":",
"summary",
".",
"append",
"(",
"val1",
")",
"if",
"val2",
"is",
"not... | Constructs the summary given va1, va2, val3
Args:
val1:
val2:
val3:
Returns: | [
"Constructs",
"the",
"summary",
"given",
"va1",
"va2",
"val3"
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti/mappings/indicator/tcex_ti_indicator.py#L317-L338 | train | 27,455 |
ThreatConnect-Inc/tcex | tcex/tcex_ti/mappings/security_label.py | SecurityLabel.name | def name(self, name):
"""
Updates the security labels name.
Args:
name:
"""
self._data['name'] = name
request = self._base_request
request['name'] = name
return self._tc_requests.update(request, owner=self.owner) | python | def name(self, name):
"""
Updates the security labels name.
Args:
name:
"""
self._data['name'] = name
request = self._base_request
request['name'] = name
return self._tc_requests.update(request, owner=self.owner) | [
"def",
"name",
"(",
"self",
",",
"name",
")",
":",
"self",
".",
"_data",
"[",
"'name'",
"]",
"=",
"name",
"request",
"=",
"self",
".",
"_base_request",
"request",
"[",
"'name'",
"]",
"=",
"name",
"return",
"self",
".",
"_tc_requests",
".",
"update",
... | Updates the security labels name.
Args:
name: | [
"Updates",
"the",
"security",
"labels",
"name",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti/mappings/security_label.py#L60-L70 | train | 27,456 |
ThreatConnect-Inc/tcex | tcex/tcex_ti/mappings/security_label.py | SecurityLabel.color | def color(self, color):
"""
Updates the security labels color.
Args:
color:
"""
self._data['color'] = color
request = self._base_request
request['color'] = color
return self._tc_requests.update(request, owner=self.owner) | python | def color(self, color):
"""
Updates the security labels color.
Args:
color:
"""
self._data['color'] = color
request = self._base_request
request['color'] = color
return self._tc_requests.update(request, owner=self.owner) | [
"def",
"color",
"(",
"self",
",",
"color",
")",
":",
"self",
".",
"_data",
"[",
"'color'",
"]",
"=",
"color",
"request",
"=",
"self",
".",
"_base_request",
"request",
"[",
"'color'",
"]",
"=",
"color",
"return",
"self",
".",
"_tc_requests",
".",
"updat... | Updates the security labels color.
Args:
color: | [
"Updates",
"the",
"security",
"labels",
"color",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti/mappings/security_label.py#L72-L83 | train | 27,457 |
ThreatConnect-Inc/tcex | tcex/tcex_ti/mappings/security_label.py | SecurityLabel.description | def description(self, description):
"""
Updates the security labels description.
Args:
description:
"""
self._data['description'] = description
request = self._base_request
request['description'] = description
return self._tc_requests.update(request, owner=self.owner) | python | def description(self, description):
"""
Updates the security labels description.
Args:
description:
"""
self._data['description'] = description
request = self._base_request
request['description'] = description
return self._tc_requests.update(request, owner=self.owner) | [
"def",
"description",
"(",
"self",
",",
"description",
")",
":",
"self",
".",
"_data",
"[",
"'description'",
"]",
"=",
"description",
"request",
"=",
"self",
".",
"_base_request",
"request",
"[",
"'description'",
"]",
"=",
"description",
"return",
"self",
".... | Updates the security labels description.
Args:
description: | [
"Updates",
"the",
"security",
"labels",
"description",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti/mappings/security_label.py#L85-L95 | train | 27,458 |
ThreatConnect-Inc/tcex | tcex/tcex_ti/mappings/security_label.py | SecurityLabel.date_added | def date_added(self, date_added):
"""
Updates the security labels date_added
Args:
date_added: Converted to %Y-%m-%dT%H:%M:%SZ date format
"""
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) | python | def date_added(self, date_added):
"""
Updates the security labels date_added
Args:
date_added: Converted to %Y-%m-%dT%H:%M:%SZ date format
"""
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) | [
"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'",
"]",
"=",
"dat... | Updates the security labels date_added
Args:
date_added: Converted to %Y-%m-%dT%H:%M:%SZ date format | [
"Updates",
"the",
"security",
"labels",
"date_added"
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti/mappings/security_label.py#L97-L109 | train | 27,459 |
ThreatConnect-Inc/tcex | tcex/tcex_ti/mappings/group/group_types/campaign.py | Campaign.first_seen | def first_seen(self, first_seen):
"""
Updates the campaign with the new first_seen date.
Args:
first_seen: The first_seen date. Converted to %Y-%m-%dT%H:%M:%SZ date format
Returns:
"""
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_requests.update(self.api_type, self.api_sub_type, self.unique_id, request) | python | def first_seen(self, first_seen):
"""
Updates the campaign with the new first_seen date.
Args:
first_seen: The first_seen date. Converted to %Y-%m-%dT%H:%M:%SZ date format
Returns:
"""
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_requests.update(self.api_type, self.api_sub_type, self.unique_id, request) | [
"def",
"first_seen",
"(",
"self",
",",
"first_seen",
")",
":",
"if",
"not",
"self",
".",
"can_update",
"(",
")",
":",
"self",
".",
"_tcex",
".",
"handle_error",
"(",
"910",
",",
"[",
"self",
".",
"type",
"]",
")",
"first_seen",
"=",
"self",
".",
"_... | Updates the campaign with the new first_seen date.
Args:
first_seen: The first_seen date. Converted to %Y-%m-%dT%H:%M:%SZ date format
Returns: | [
"Updates",
"the",
"campaign",
"with",
"the",
"new",
"first_seen",
"date",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti/mappings/group/group_types/campaign.py#L20-L36 | train | 27,460 |
ThreatConnect-Inc/tcex | tcex/tcex_ti/mappings/filters.py | Filters.add_filter | def add_filter(self, filter_key, operator, value):
""" Adds a filter given a key, operator, and value"""
filter_key = self._metadata_map.get(filter_key, filter_key)
self.filters.append({'filter': filter_key, 'operator': operator, 'value': value}) | python | def add_filter(self, filter_key, operator, value):
""" Adds a filter given a key, operator, and value"""
filter_key = self._metadata_map.get(filter_key, filter_key)
self.filters.append({'filter': filter_key, 'operator': operator, 'value': value}) | [
"def",
"add_filter",
"(",
"self",
",",
"filter_key",
",",
"operator",
",",
"value",
")",
":",
"filter_key",
"=",
"self",
".",
"_metadata_map",
".",
"get",
"(",
"filter_key",
",",
"filter_key",
")",
"self",
".",
"filters",
".",
"append",
"(",
"{",
"'filte... | Adds a filter given a key, operator, and value | [
"Adds",
"a",
"filter",
"given",
"a",
"key",
"operator",
"and",
"value"
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti/mappings/filters.py#L22-L25 | train | 27,461 |
ThreatConnect-Inc/tcex | tcex/tcex_notification_v2.py | TcExNotificationV2.recipients | def recipients(self, notification_type, recipients, priority='Low'):
"""Set vars for the passed in data. Used for one or more recipient notification.
.. code-block:: javascript
{
"notificationType": notification_type,
"priority": priority
"isOrganization": false,
"recipients": recipients
}
Args:
notification_type (str): The type of notification being sent.
recipients (str): A comma delimited string of recipients.
priority (str): The priority: Low, Medium, High.
"""
self._notification_type = notification_type
self._recipients = recipients
self._priority = priority
self._is_organization = False | python | def recipients(self, notification_type, recipients, priority='Low'):
"""Set vars for the passed in data. Used for one or more recipient notification.
.. code-block:: javascript
{
"notificationType": notification_type,
"priority": priority
"isOrganization": false,
"recipients": recipients
}
Args:
notification_type (str): The type of notification being sent.
recipients (str): A comma delimited string of recipients.
priority (str): The priority: Low, Medium, High.
"""
self._notification_type = notification_type
self._recipients = recipients
self._priority = priority
self._is_organization = False | [
"def",
"recipients",
"(",
"self",
",",
"notification_type",
",",
"recipients",
",",
"priority",
"=",
"'Low'",
")",
":",
"self",
".",
"_notification_type",
"=",
"notification_type",
"self",
".",
"_recipients",
"=",
"recipients",
"self",
".",
"_priority",
"=",
"... | Set vars for the passed in data. Used for one or more recipient notification.
.. code-block:: javascript
{
"notificationType": notification_type,
"priority": priority
"isOrganization": false,
"recipients": recipients
}
Args:
notification_type (str): The type of notification being sent.
recipients (str): A comma delimited string of recipients.
priority (str): The priority: Low, Medium, High. | [
"Set",
"vars",
"for",
"the",
"passed",
"in",
"data",
".",
"Used",
"for",
"one",
"or",
"more",
"recipient",
"notification",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_notification_v2.py#L21-L41 | train | 27,462 |
ThreatConnect-Inc/tcex | tcex/tcex_notification_v2.py | TcExNotificationV2.org | def org(self, notification_type, priority='Low'):
"""Set vars for the passed in data. Used for org notification.
.. code-block:: javascript
{
"notificationType": notification_type,
"priority": priority
"isOrganization": true
}
Args:
notification_type (str): The notification type.
priority (str): The priority: Low, Medium, High.
"""
self._notification_type = notification_type
self._recipients = None
self._priority = priority
self._is_organization = True | python | def org(self, notification_type, priority='Low'):
"""Set vars for the passed in data. Used for org notification.
.. code-block:: javascript
{
"notificationType": notification_type,
"priority": priority
"isOrganization": true
}
Args:
notification_type (str): The notification type.
priority (str): The priority: Low, Medium, High.
"""
self._notification_type = notification_type
self._recipients = None
self._priority = priority
self._is_organization = True | [
"def",
"org",
"(",
"self",
",",
"notification_type",
",",
"priority",
"=",
"'Low'",
")",
":",
"self",
".",
"_notification_type",
"=",
"notification_type",
"self",
".",
"_recipients",
"=",
"None",
"self",
".",
"_priority",
"=",
"priority",
"self",
".",
"_is_o... | Set vars for the passed in data. Used for org notification.
.. code-block:: javascript
{
"notificationType": notification_type,
"priority": priority
"isOrganization": true
}
Args:
notification_type (str): The notification type.
priority (str): The priority: Low, Medium, High. | [
"Set",
"vars",
"for",
"the",
"passed",
"in",
"data",
".",
"Used",
"for",
"org",
"notification",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_notification_v2.py#L43-L61 | train | 27,463 |
ThreatConnect-Inc/tcex | tcex/tcex_notification_v2.py | TcExNotificationV2.send | def send(self, message):
"""Send our message
Args:
message (str): The message to be sent.
Returns:
requests.models.Response: The response from the request.
"""
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(json.dumps(body)))
# create our tcex resource
resource = resource = self._tcex.resource('Notification')
resource.http_method = 'POST'
resource.body = json.dumps(body)
results = resource.request() # do the request
if results.get('response').status_code == 200:
# everything worked
response = results.get('response').json()
elif results.get('response').status_code == 400:
# failed..but known... user doesn't exist
# just return and let calling app handle it
err = 'Failed to send notification ({})'.format(results.get('response').text)
self._tcex.log.error(err)
response = results.get('response').json()
else:
# somekind of unknown error...raise
err = 'Failed to send notification ({})'.format(results.get('response').text)
self._tcex.log.error(err)
raise RuntimeError(err)
return response | python | def send(self, message):
"""Send our message
Args:
message (str): The message to be sent.
Returns:
requests.models.Response: The response from the request.
"""
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(json.dumps(body)))
# create our tcex resource
resource = resource = self._tcex.resource('Notification')
resource.http_method = 'POST'
resource.body = json.dumps(body)
results = resource.request() # do the request
if results.get('response').status_code == 200:
# everything worked
response = results.get('response').json()
elif results.get('response').status_code == 400:
# failed..but known... user doesn't exist
# just return and let calling app handle it
err = 'Failed to send notification ({})'.format(results.get('response').text)
self._tcex.log.error(err)
response = results.get('response').json()
else:
# somekind of unknown error...raise
err = 'Failed to send notification ({})'.format(results.get('response').text)
self._tcex.log.error(err)
raise RuntimeError(err)
return response | [
"def",
"send",
"(",
"self",
",",
"message",
")",
":",
"body",
"=",
"{",
"'notificationType'",
":",
"self",
".",
"_notification_type",
",",
"'priority'",
":",
"self",
".",
"_priority",
",",
"'isOrganization'",
":",
"self",
".",
"_is_organization",
",",
"'mess... | Send our message
Args:
message (str): The message to be sent.
Returns:
requests.models.Response: The response from the request. | [
"Send",
"our",
"message"
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_notification_v2.py#L63-L105 | train | 27,464 |
ThreatConnect-Inc/tcex | tcex/tcex_ti/mappings/group/group_types/adversarys.py | Adversary.assets | def assets(self, asset_type=None):
"""
Retrieves all of the assets of a given asset_type
Args:
asset_type: (str) Either None, PHONE, HANDLER, or URL
Returns:
"""
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_phone_assets(
self.api_type, self.api_sub_type, self.unique_id
)
if asset_type == 'HANDLER':
return self.tc_requests.adversary_handle_assets(
self.api_type, self.api_sub_type, self.unique_id
)
if asset_type == 'URL':
return self.tc_requests.adversary_url_assets(
self.api_type, self.api_sub_type, self.unique_id
)
self._tcex.handle_error(
925, ['asset_type', 'assets', 'asset_type', 'asset_type', asset_type]
)
return None | python | def assets(self, asset_type=None):
"""
Retrieves all of the assets of a given asset_type
Args:
asset_type: (str) Either None, PHONE, HANDLER, or URL
Returns:
"""
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_phone_assets(
self.api_type, self.api_sub_type, self.unique_id
)
if asset_type == 'HANDLER':
return self.tc_requests.adversary_handle_assets(
self.api_type, self.api_sub_type, self.unique_id
)
if asset_type == 'URL':
return self.tc_requests.adversary_url_assets(
self.api_type, self.api_sub_type, self.unique_id
)
self._tcex.handle_error(
925, ['asset_type', 'assets', 'asset_type', 'asset_type', asset_type]
)
return None | [
"def",
"assets",
"(",
"self",
",",
"asset_type",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"can_update",
"(",
")",
":",
"self",
".",
"_tcex",
".",
"handle_error",
"(",
"910",
",",
"[",
"self",
".",
"type",
"]",
")",
"if",
"not",
"asset_type"... | Retrieves all of the assets of a given asset_type
Args:
asset_type: (str) Either None, PHONE, HANDLER, or URL
Returns: | [
"Retrieves",
"all",
"of",
"the",
"assets",
"of",
"a",
"given",
"asset_type"
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti/mappings/group/group_types/adversarys.py#L79-L112 | train | 27,465 |
ThreatConnect-Inc/tcex | tcex/tcex_ti/mappings/group/group_types/adversarys.py | Adversary.delete_asset | def delete_asset(self, asset_id, asset_type):
"""
Delete the asset with the provided asset_id.
Args:
asset_id: The id of the asset.
asset_type: The asset type.
Returns:
"""
return self.asset(asset_id, asset_type=asset_type, action='DELETE') | python | def delete_asset(self, asset_id, asset_type):
"""
Delete the asset with the provided asset_id.
Args:
asset_id: The id of the asset.
asset_type: The asset type.
Returns:
"""
return self.asset(asset_id, asset_type=asset_type, action='DELETE') | [
"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.
Args:
asset_id: The id of the asset.
asset_type: The asset type.
Returns: | [
"Delete",
"the",
"asset",
"with",
"the",
"provided",
"asset_id",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti/mappings/group/group_types/adversarys.py#L127-L138 | train | 27,466 |
ThreatConnect-Inc/tcex | tcex/tcex_bin_lib.py | TcExLib._build_command | def _build_command(self, python_executable, lib_dir_fq, proxy_enabled):
"""Build the pip command for installing dependencies.
Args:
python_executable (str): The fully qualified path of the Python executable.
lib_dir_fq (str): The fully qualified path of the lib directory.
Returns:
list: The Python pip command with all required args.
"""
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('--no-cache-dir')
if proxy_enabled:
# trust the pypi hosts to avoid ssl errors
trusted_hosts = ['pypi.org', 'pypi.python.org', 'files.pythonhosted.org']
for host in trusted_hosts:
exe_command.append('--trusted-host')
exe_command.append(host)
return exe_command | python | def _build_command(self, python_executable, lib_dir_fq, proxy_enabled):
"""Build the pip command for installing dependencies.
Args:
python_executable (str): The fully qualified path of the Python executable.
lib_dir_fq (str): The fully qualified path of the lib directory.
Returns:
list: The Python pip command with all required args.
"""
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('--no-cache-dir')
if proxy_enabled:
# trust the pypi hosts to avoid ssl errors
trusted_hosts = ['pypi.org', 'pypi.python.org', 'files.pythonhosted.org']
for host in trusted_hosts:
exe_command.append('--trusted-host')
exe_command.append(host)
return exe_command | [
"def",
"_build_command",
"(",
"self",
",",
"python_executable",
",",
"lib_dir_fq",
",",
"proxy_enabled",
")",
":",
"exe_command",
"=",
"[",
"os",
".",
"path",
".",
"expanduser",
"(",
"python_executable",
")",
",",
"'-m'",
",",
"'pip'",
",",
"'install'",
",",... | Build the pip command for installing dependencies.
Args:
python_executable (str): The fully qualified path of the Python executable.
lib_dir_fq (str): The fully qualified path of the lib directory.
Returns:
list: The Python pip command with all required args. | [
"Build",
"the",
"pip",
"command",
"for",
"installing",
"dependencies",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_lib.py#L46-L79 | train | 27,467 |
ThreatConnect-Inc/tcex | tcex/tcex_bin_lib.py | TcExLib._configure_proxy | def _configure_proxy(self):
"""Configure proxy settings using environment variables."""
if os.getenv('HTTP_PROXY') or os.getenv('HTTPS_PROXY'):
# TODO: is this appropriate?
# don't change proxy settings if the OS already has them configured.
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(self.args.proxy_user, safe='~')
proxy_pass = quote(self.args.proxy_pass, safe='~')
# proxy url with auth
proxy_url = '{}:{}@{}:{}'.format(
proxy_user, proxy_pass, self.args.proxy_host, self.args.proxy_port
)
else:
# proxy url without auth
proxy_url = '{}:{}'.format(self.args.proxy_host, self.args.proxy_port)
os.putenv('HTTP_PROXY', 'http://{}'.format(proxy_url))
os.putenv('HTTPS_PROXY', 'https://{}'.format(proxy_url))
print(
'Using Proxy Server: {}{}:{}.'.format(
c.Fore.CYAN, self.args.proxy_host, self.args.proxy_port
)
)
proxy_enabled = True
return proxy_enabled | python | def _configure_proxy(self):
"""Configure proxy settings using environment variables."""
if os.getenv('HTTP_PROXY') or os.getenv('HTTPS_PROXY'):
# TODO: is this appropriate?
# don't change proxy settings if the OS already has them configured.
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(self.args.proxy_user, safe='~')
proxy_pass = quote(self.args.proxy_pass, safe='~')
# proxy url with auth
proxy_url = '{}:{}@{}:{}'.format(
proxy_user, proxy_pass, self.args.proxy_host, self.args.proxy_port
)
else:
# proxy url without auth
proxy_url = '{}:{}'.format(self.args.proxy_host, self.args.proxy_port)
os.putenv('HTTP_PROXY', 'http://{}'.format(proxy_url))
os.putenv('HTTPS_PROXY', 'https://{}'.format(proxy_url))
print(
'Using Proxy Server: {}{}:{}.'.format(
c.Fore.CYAN, self.args.proxy_host, self.args.proxy_port
)
)
proxy_enabled = True
return proxy_enabled | [
"def",
"_configure_proxy",
"(",
"self",
")",
":",
"if",
"os",
".",
"getenv",
"(",
"'HTTP_PROXY'",
")",
"or",
"os",
".",
"getenv",
"(",
"'HTTPS_PROXY'",
")",
":",
"# TODO: is this appropriate?",
"# don't change proxy settings if the OS already has them configured.",
"ret... | Configure proxy settings using environment variables. | [
"Configure",
"proxy",
"settings",
"using",
"environment",
"variables",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_lib.py#L81-L111 | train | 27,468 |
ThreatConnect-Inc/tcex | tcex/tcex_bin_lib.py | TcExLib._create_temp_requirements | def _create_temp_requirements(self):
"""Create a temporary requirements.txt.
This allows testing again a git branch instead of pulling from pypi.
"""
self.use_temp_requirements_file = True
# Replace tcex version with develop branch of tcex
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') as fh:
new_requirements = ''
for line in current_requirements:
if not line:
continue
if line.startswith('tcex'):
line = 'git+https://github.com/ThreatConnect-Inc/tcex.git@{}#egg=tcex'
line = line.format(self.args.branch)
# print('line', line)
new_requirements += '{}\n'.format(line)
fh.write(new_requirements) | python | def _create_temp_requirements(self):
"""Create a temporary requirements.txt.
This allows testing again a git branch instead of pulling from pypi.
"""
self.use_temp_requirements_file = True
# Replace tcex version with develop branch of tcex
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') as fh:
new_requirements = ''
for line in current_requirements:
if not line:
continue
if line.startswith('tcex'):
line = 'git+https://github.com/ThreatConnect-Inc/tcex.git@{}#egg=tcex'
line = line.format(self.args.branch)
# print('line', line)
new_requirements += '{}\n'.format(line)
fh.write(new_requirements) | [
"def",
"_create_temp_requirements",
"(",
"self",
")",
":",
"self",
".",
"use_temp_requirements_file",
"=",
"True",
"# Replace tcex version with develop branch of tcex",
"with",
"open",
"(",
"self",
".",
"requirements_file",
",",
"'r'",
")",
"as",
"fh",
":",
"current_r... | Create a temporary requirements.txt.
This allows testing again a git branch instead of pulling from pypi. | [
"Create",
"a",
"temporary",
"requirements",
".",
"txt",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_lib.py#L121-L142 | train | 27,469 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_batch.py | TcExBatch._gen_indicator_class | def _gen_indicator_class(self):
"""Generate Custom Indicator Classes."""
for entry in self.tcex.indicator_types_data.values():
name = entry.get('name')
class_name = name.replace(' ', '')
# temp fix for API issue where boolean are returned as strings
entry['custom'] = self.tcex.utils.to_bool(entry.get('custom'))
if class_name in globals():
# skip Indicator Type if a class already exists
continue
# Custom Indicator can have 3 values. Only add the value if it is set.
value_fields = []
if entry.get('value1Label'):
value_fields.append(entry['value1Label'])
if entry.get('value2Label'):
value_fields.append(entry['value2Label'])
if entry.get('value3Label'):
value_fields.append(entry['value3Label'])
value_count = len(value_fields)
class_data = {}
# Add Class for each Custom Indicator type to this module
custom_class = custom_indicator_class_factory(name, Indicator, class_data, value_fields)
setattr(module, class_name, custom_class)
# Add Custom Indicator Method
self._gen_indicator_method(name, custom_class, value_count) | python | def _gen_indicator_class(self):
"""Generate Custom Indicator Classes."""
for entry in self.tcex.indicator_types_data.values():
name = entry.get('name')
class_name = name.replace(' ', '')
# temp fix for API issue where boolean are returned as strings
entry['custom'] = self.tcex.utils.to_bool(entry.get('custom'))
if class_name in globals():
# skip Indicator Type if a class already exists
continue
# Custom Indicator can have 3 values. Only add the value if it is set.
value_fields = []
if entry.get('value1Label'):
value_fields.append(entry['value1Label'])
if entry.get('value2Label'):
value_fields.append(entry['value2Label'])
if entry.get('value3Label'):
value_fields.append(entry['value3Label'])
value_count = len(value_fields)
class_data = {}
# Add Class for each Custom Indicator type to this module
custom_class = custom_indicator_class_factory(name, Indicator, class_data, value_fields)
setattr(module, class_name, custom_class)
# Add Custom Indicator Method
self._gen_indicator_method(name, custom_class, value_count) | [
"def",
"_gen_indicator_class",
"(",
"self",
")",
":",
"for",
"entry",
"in",
"self",
".",
"tcex",
".",
"indicator_types_data",
".",
"values",
"(",
")",
":",
"name",
"=",
"entry",
".",
"get",
"(",
"'name'",
")",
"class_name",
"=",
"name",
".",
"replace",
... | Generate Custom Indicator Classes. | [
"Generate",
"Custom",
"Indicator",
"Classes",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_batch.py#L115-L144 | train | 27,470 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_batch.py | TcExBatch._group | def _group(self, group_data):
"""Return previously stored group or new group.
Args:
group_data (dict|obj): An Group dict or instance of Group object.
Returns:
dict|obj: The new Group dict/object or the previously stored dict/object.
"""
if isinstance(group_data, dict):
# get xid from dict
xid = group_data.get('xid')
else:
# get xid from object
xid = group_data.xid
if self.groups.get(xid) is not None:
# return existing group from memory
group_data = self.groups.get(xid)
elif self.groups_shelf.get(xid) is not None:
# return existing group from shelf
group_data = self.groups_shelf.get(xid)
else:
# store new group
self.groups[xid] = group_data
return group_data | python | def _group(self, group_data):
"""Return previously stored group or new group.
Args:
group_data (dict|obj): An Group dict or instance of Group object.
Returns:
dict|obj: The new Group dict/object or the previously stored dict/object.
"""
if isinstance(group_data, dict):
# get xid from dict
xid = group_data.get('xid')
else:
# get xid from object
xid = group_data.xid
if self.groups.get(xid) is not None:
# return existing group from memory
group_data = self.groups.get(xid)
elif self.groups_shelf.get(xid) is not None:
# return existing group from shelf
group_data = self.groups_shelf.get(xid)
else:
# store new group
self.groups[xid] = group_data
return group_data | [
"def",
"_group",
"(",
"self",
",",
"group_data",
")",
":",
"if",
"isinstance",
"(",
"group_data",
",",
"dict",
")",
":",
"# get xid from dict",
"xid",
"=",
"group_data",
".",
"get",
"(",
"'xid'",
")",
"else",
":",
"# get xid from object",
"xid",
"=",
"grou... | Return previously stored group or new group.
Args:
group_data (dict|obj): An Group dict or instance of Group object.
Returns:
dict|obj: The new Group dict/object or the previously stored dict/object. | [
"Return",
"previously",
"stored",
"group",
"or",
"new",
"group",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_batch.py#L175-L200 | train | 27,471 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_batch.py | TcExBatch._indicator | def _indicator(self, indicator_data):
"""Return previously stored indicator or new indicator.
Args:
indicator_data (dict|obj): An Indicator dict or instance of Indicator object.
Returns:
dict|obj: The new Indicator dict/object or the previously stored dict/object.
"""
if isinstance(indicator_data, dict):
# get xid from dict
xid = indicator_data.get('xid')
else:
# get xid from object
xid = indicator_data.xid
if self.indicators.get(xid) is not None:
# return existing indicator from memory
indicator_data = self.indicators.get(xid)
elif self.indicators_shelf.get(xid) is not None:
# return existing indicator from shelf
indicator_data = self.indicators_shelf.get(xid)
else:
# store new indicators
self.indicators[xid] = indicator_data
return indicator_data | python | def _indicator(self, indicator_data):
"""Return previously stored indicator or new indicator.
Args:
indicator_data (dict|obj): An Indicator dict or instance of Indicator object.
Returns:
dict|obj: The new Indicator dict/object or the previously stored dict/object.
"""
if isinstance(indicator_data, dict):
# get xid from dict
xid = indicator_data.get('xid')
else:
# get xid from object
xid = indicator_data.xid
if self.indicators.get(xid) is not None:
# return existing indicator from memory
indicator_data = self.indicators.get(xid)
elif self.indicators_shelf.get(xid) is not None:
# return existing indicator from shelf
indicator_data = self.indicators_shelf.get(xid)
else:
# store new indicators
self.indicators[xid] = indicator_data
return indicator_data | [
"def",
"_indicator",
"(",
"self",
",",
"indicator_data",
")",
":",
"if",
"isinstance",
"(",
"indicator_data",
",",
"dict",
")",
":",
"# get xid from dict",
"xid",
"=",
"indicator_data",
".",
"get",
"(",
"'xid'",
")",
"else",
":",
"# get xid from object",
"xid"... | Return previously stored indicator or new indicator.
Args:
indicator_data (dict|obj): An Indicator dict or instance of Indicator object.
Returns:
dict|obj: The new Indicator dict/object or the previously stored dict/object. | [
"Return",
"previously",
"stored",
"indicator",
"or",
"new",
"indicator",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_batch.py#L202-L228 | train | 27,472 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_batch.py | TcExBatch.add_indicator | def add_indicator(self, indicator_data):
"""Add an indicator to Batch Job.
.. code-block:: javascript
{
"type": "File",
"rating": 5.00,
"confidence": 50,
"summary": "53c3609411c83f363e051d455ade78a7
: 57a49b478310e4313c54c0fee46e4d70a73dd580
: db31cb2a748b7e0046d8c97a32a7eb4efde32a0593e5dbd58e07a3b4ae6bf3d7",
"associatedGroups": [
{
"groupXid": "e336e2dd-5dfb-48cd-a33a-f8809e83e904"
}
],
"attribute": [{
"type": "Source",
"displayed": true,
"value": "Malware Analysis provided by external AMA."
}],
"fileOccurrence": [{
"fileName": "drop1.exe",
"date": "2017-03-03T18:00:00-06:00"
}],
"tag": [{
"name": "China"
}],
"xid": "e336e2dd-5dfb-48cd-a33a-f8809e83e904:170139"
}
Args:
indicator_data (dict): The Full Indicator data including attributes, labels, tags,
and associations.
"""
if indicator_data.get('type') not in ['Address', 'EmailAddress', 'File', 'Host', 'URL']:
# for custom indicator types the valueX fields are required.
# using the summary we can build the values
index = 1
for value in self._indicator_values(indicator_data.get('summary')):
indicator_data['value{}'.format(index)] = value
index += 1
if indicator_data.get('type') == 'File':
# convert custom field name to the appropriate value for batch v2
size = indicator_data.pop('size', None)
if size is not None:
indicator_data['intValue1'] = size
if indicator_data.get('type') == 'Host':
# convert custom field name to the appropriate value for batch v2
dns_active = indicator_data.pop('dnsActive', None)
if dns_active is not None:
indicator_data['flag1'] = dns_active
whois_active = indicator_data.pop('whoisActive', None)
if whois_active is not None:
indicator_data['flag2'] = whois_active
return self._indicator(indicator_data) | python | def add_indicator(self, indicator_data):
"""Add an indicator to Batch Job.
.. code-block:: javascript
{
"type": "File",
"rating": 5.00,
"confidence": 50,
"summary": "53c3609411c83f363e051d455ade78a7
: 57a49b478310e4313c54c0fee46e4d70a73dd580
: db31cb2a748b7e0046d8c97a32a7eb4efde32a0593e5dbd58e07a3b4ae6bf3d7",
"associatedGroups": [
{
"groupXid": "e336e2dd-5dfb-48cd-a33a-f8809e83e904"
}
],
"attribute": [{
"type": "Source",
"displayed": true,
"value": "Malware Analysis provided by external AMA."
}],
"fileOccurrence": [{
"fileName": "drop1.exe",
"date": "2017-03-03T18:00:00-06:00"
}],
"tag": [{
"name": "China"
}],
"xid": "e336e2dd-5dfb-48cd-a33a-f8809e83e904:170139"
}
Args:
indicator_data (dict): The Full Indicator data including attributes, labels, tags,
and associations.
"""
if indicator_data.get('type') not in ['Address', 'EmailAddress', 'File', 'Host', 'URL']:
# for custom indicator types the valueX fields are required.
# using the summary we can build the values
index = 1
for value in self._indicator_values(indicator_data.get('summary')):
indicator_data['value{}'.format(index)] = value
index += 1
if indicator_data.get('type') == 'File':
# convert custom field name to the appropriate value for batch v2
size = indicator_data.pop('size', None)
if size is not None:
indicator_data['intValue1'] = size
if indicator_data.get('type') == 'Host':
# convert custom field name to the appropriate value for batch v2
dns_active = indicator_data.pop('dnsActive', None)
if dns_active is not None:
indicator_data['flag1'] = dns_active
whois_active = indicator_data.pop('whoisActive', None)
if whois_active is not None:
indicator_data['flag2'] = whois_active
return self._indicator(indicator_data) | [
"def",
"add_indicator",
"(",
"self",
",",
"indicator_data",
")",
":",
"if",
"indicator_data",
".",
"get",
"(",
"'type'",
")",
"not",
"in",
"[",
"'Address'",
",",
"'EmailAddress'",
",",
"'File'",
",",
"'Host'",
",",
"'URL'",
"]",
":",
"# for custom indicator ... | Add an indicator to Batch Job.
.. code-block:: javascript
{
"type": "File",
"rating": 5.00,
"confidence": 50,
"summary": "53c3609411c83f363e051d455ade78a7
: 57a49b478310e4313c54c0fee46e4d70a73dd580
: db31cb2a748b7e0046d8c97a32a7eb4efde32a0593e5dbd58e07a3b4ae6bf3d7",
"associatedGroups": [
{
"groupXid": "e336e2dd-5dfb-48cd-a33a-f8809e83e904"
}
],
"attribute": [{
"type": "Source",
"displayed": true,
"value": "Malware Analysis provided by external AMA."
}],
"fileOccurrence": [{
"fileName": "drop1.exe",
"date": "2017-03-03T18:00:00-06:00"
}],
"tag": [{
"name": "China"
}],
"xid": "e336e2dd-5dfb-48cd-a33a-f8809e83e904:170139"
}
Args:
indicator_data (dict): The Full Indicator data including attributes, labels, tags,
and associations. | [
"Add",
"an",
"indicator",
"to",
"Batch",
"Job",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_batch.py#L301-L357 | train | 27,473 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_batch.py | TcExBatch.address | def address(self, ip, **kwargs):
"""Add Address data to Batch object.
Args:
ip (str): The value for this Indicator.
confidence (str, kwargs): The threat confidence for this Indicator.
date_added (str, kwargs): The date timestamp the Indicator was created.
last_modified (str, kwargs): The date timestamp the Indicator was last modified.
rating (str, kwargs): The threat rating for this Indicator.
xid (str, kwargs): The external id for this Indicator.
Returns:
obj: An instance of Address.
"""
indicator_obj = Address(ip, **kwargs)
return self._indicator(indicator_obj) | python | def address(self, ip, **kwargs):
"""Add Address data to Batch object.
Args:
ip (str): The value for this Indicator.
confidence (str, kwargs): The threat confidence for this Indicator.
date_added (str, kwargs): The date timestamp the Indicator was created.
last_modified (str, kwargs): The date timestamp the Indicator was last modified.
rating (str, kwargs): The threat rating for this Indicator.
xid (str, kwargs): The external id for this Indicator.
Returns:
obj: An instance of Address.
"""
indicator_obj = Address(ip, **kwargs)
return self._indicator(indicator_obj) | [
"def",
"address",
"(",
"self",
",",
"ip",
",",
"*",
"*",
"kwargs",
")",
":",
"indicator_obj",
"=",
"Address",
"(",
"ip",
",",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"_indicator",
"(",
"indicator_obj",
")"
] | Add Address data to Batch object.
Args:
ip (str): The value for this Indicator.
confidence (str, kwargs): The threat confidence for this Indicator.
date_added (str, kwargs): The date timestamp the Indicator was created.
last_modified (str, kwargs): The date timestamp the Indicator was last modified.
rating (str, kwargs): The threat rating for this Indicator.
xid (str, kwargs): The external id for this Indicator.
Returns:
obj: An instance of Address. | [
"Add",
"Address",
"data",
"to",
"Batch",
"object",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_batch.py#L359-L374 | train | 27,474 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_batch.py | TcExBatch.adversary | def adversary(self, name, **kwargs):
"""Add Adversary data to Batch object.
Args:
name (str): The name for this Group.
date_added (str, kwargs): The date timestamp the Indicator was created.
xid (str, kwargs): The external id for this Group.
Returns:
obj: An instance of Adversary.
"""
group_obj = Adversary(name, **kwargs)
return self._group(group_obj) | python | def adversary(self, name, **kwargs):
"""Add Adversary data to Batch object.
Args:
name (str): The name for this Group.
date_added (str, kwargs): The date timestamp the Indicator was created.
xid (str, kwargs): The external id for this Group.
Returns:
obj: An instance of Adversary.
"""
group_obj = Adversary(name, **kwargs)
return self._group(group_obj) | [
"def",
"adversary",
"(",
"self",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"group_obj",
"=",
"Adversary",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"_group",
"(",
"group_obj",
")"
] | Add Adversary data to Batch object.
Args:
name (str): The name for this Group.
date_added (str, kwargs): The date timestamp the Indicator was created.
xid (str, kwargs): The external id for this Group.
Returns:
obj: An instance of Adversary. | [
"Add",
"Adversary",
"data",
"to",
"Batch",
"object",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_batch.py#L376-L388 | train | 27,475 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_batch.py | TcExBatch.asn | def asn(self, as_number, **kwargs):
"""Add ASN data to Batch object.
Args:
as_number (str): The value for this Indicator.
confidence (str, kwargs): The threat confidence for this Indicator.
date_added (str, kwargs): The date timestamp the Indicator was created.
last_modified (str, kwargs): The date timestamp the Indicator was last modified.
rating (str, kwargs): The threat rating for this Indicator.
xid (str, kwargs): The external id for this Indicator.
Returns:
obj: An instance of ASN.
"""
indicator_obj = ASN(as_number, **kwargs)
return self._indicator(indicator_obj) | python | def asn(self, as_number, **kwargs):
"""Add ASN data to Batch object.
Args:
as_number (str): The value for this Indicator.
confidence (str, kwargs): The threat confidence for this Indicator.
date_added (str, kwargs): The date timestamp the Indicator was created.
last_modified (str, kwargs): The date timestamp the Indicator was last modified.
rating (str, kwargs): The threat rating for this Indicator.
xid (str, kwargs): The external id for this Indicator.
Returns:
obj: An instance of ASN.
"""
indicator_obj = ASN(as_number, **kwargs)
return self._indicator(indicator_obj) | [
"def",
"asn",
"(",
"self",
",",
"as_number",
",",
"*",
"*",
"kwargs",
")",
":",
"indicator_obj",
"=",
"ASN",
"(",
"as_number",
",",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"_indicator",
"(",
"indicator_obj",
")"
] | Add ASN data to Batch object.
Args:
as_number (str): The value for this Indicator.
confidence (str, kwargs): The threat confidence for this Indicator.
date_added (str, kwargs): The date timestamp the Indicator was created.
last_modified (str, kwargs): The date timestamp the Indicator was last modified.
rating (str, kwargs): The threat rating for this Indicator.
xid (str, kwargs): The external id for this Indicator.
Returns:
obj: An instance of ASN. | [
"Add",
"ASN",
"data",
"to",
"Batch",
"object",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_batch.py#L390-L405 | train | 27,476 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_batch.py | TcExBatch.campaign | def campaign(self, name, **kwargs):
"""Add Campaign data to Batch object.
Args:
name (str): The name for this Group.
date_added (str, kwargs): The date timestamp the Indicator was created.
first_seen (str, kwargs): The first seen datetime expression for this Group.
xid (str, kwargs): The external id for this Group.
Returns:
obj: An instance of Campaign.
"""
group_obj = Campaign(name, **kwargs)
return self._group(group_obj) | python | def campaign(self, name, **kwargs):
"""Add Campaign data to Batch object.
Args:
name (str): The name for this Group.
date_added (str, kwargs): The date timestamp the Indicator was created.
first_seen (str, kwargs): The first seen datetime expression for this Group.
xid (str, kwargs): The external id for this Group.
Returns:
obj: An instance of Campaign.
"""
group_obj = Campaign(name, **kwargs)
return self._group(group_obj) | [
"def",
"campaign",
"(",
"self",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"group_obj",
"=",
"Campaign",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"_group",
"(",
"group_obj",
")"
] | Add Campaign data to Batch object.
Args:
name (str): The name for this Group.
date_added (str, kwargs): The date timestamp the Indicator was created.
first_seen (str, kwargs): The first seen datetime expression for this Group.
xid (str, kwargs): The external id for this Group.
Returns:
obj: An instance of Campaign. | [
"Add",
"Campaign",
"data",
"to",
"Batch",
"object",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_batch.py#L417-L430 | train | 27,477 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_batch.py | TcExBatch.cidr | def cidr(self, block, **kwargs):
"""Add CIDR data to Batch object.
Args:
block (str): The value for this Indicator.
confidence (str, kwargs): The threat confidence for this Indicator.
date_added (str, kwargs): The date timestamp the Indicator was created.
last_modified (str, kwargs): The date timestamp the Indicator was last modified.
rating (str, kwargs): The threat rating for this Indicator.
xid (str, kwargs): The external id for this Indicator.
Returns:
obj: An instance of CIDR.
"""
indicator_obj = CIDR(block, **kwargs)
return self._indicator(indicator_obj) | python | def cidr(self, block, **kwargs):
"""Add CIDR data to Batch object.
Args:
block (str): The value for this Indicator.
confidence (str, kwargs): The threat confidence for this Indicator.
date_added (str, kwargs): The date timestamp the Indicator was created.
last_modified (str, kwargs): The date timestamp the Indicator was last modified.
rating (str, kwargs): The threat rating for this Indicator.
xid (str, kwargs): The external id for this Indicator.
Returns:
obj: An instance of CIDR.
"""
indicator_obj = CIDR(block, **kwargs)
return self._indicator(indicator_obj) | [
"def",
"cidr",
"(",
"self",
",",
"block",
",",
"*",
"*",
"kwargs",
")",
":",
"indicator_obj",
"=",
"CIDR",
"(",
"block",
",",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"_indicator",
"(",
"indicator_obj",
")"
] | Add CIDR data to Batch object.
Args:
block (str): The value for this Indicator.
confidence (str, kwargs): The threat confidence for this Indicator.
date_added (str, kwargs): The date timestamp the Indicator was created.
last_modified (str, kwargs): The date timestamp the Indicator was last modified.
rating (str, kwargs): The threat rating for this Indicator.
xid (str, kwargs): The external id for this Indicator.
Returns:
obj: An instance of CIDR. | [
"Add",
"CIDR",
"data",
"to",
"Batch",
"object",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_batch.py#L432-L447 | train | 27,478 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_batch.py | TcExBatch.close | def close(self):
"""Cleanup batch job."""
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) # remove previous file to prevent duplicates
with open(fqfn, 'w') as fh:
for xid in self.saved_xids:
fh.write('{}\n'.format(xid))
else:
# delete saved files
if os.path.isfile(self.group_shelf_fqfn):
os.remove(self.group_shelf_fqfn)
if os.path.isfile(self.group_shelf_fqfn):
os.remove(self.indicator_shelf_fqfn) | python | def close(self):
"""Cleanup batch job."""
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) # remove previous file to prevent duplicates
with open(fqfn, 'w') as fh:
for xid in self.saved_xids:
fh.write('{}\n'.format(xid))
else:
# delete saved files
if os.path.isfile(self.group_shelf_fqfn):
os.remove(self.group_shelf_fqfn)
if os.path.isfile(self.group_shelf_fqfn):
os.remove(self.indicator_shelf_fqfn) | [
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"groups_shelf",
".",
"close",
"(",
")",
"self",
".",
"indicators_shelf",
".",
"close",
"(",
")",
"if",
"self",
".",
"debug",
"and",
"self",
".",
"enable_saved_file",
":",
"fqfn",
"=",
"os",
".",
"pa... | Cleanup batch job. | [
"Cleanup",
"batch",
"job",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_batch.py#L449-L465 | train | 27,479 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_batch.py | TcExBatch.data | def data(self):
"""Return the batch data to be sent to the ThreatConnect API.
**Processing Order:**
* Process groups in memory up to max batch size.
* Process groups in shelf to max batch size.
* Process indicators in memory up to max batch size.
* Process indicators in shelf up to max batch size.
This method will remove the group/indicator from memory and/or shelf.
"""
entity_count = 0
data = {'group': [], 'indicator': []}
# process group data
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.groups_shelf, entity_count)
data['group'].extend(group_data)
if entity_count >= self._batch_max_chunk:
return data
# process indicator data
indicator_data, entity_count = self.data_indicators(self.indicators, entity_count)
data['indicator'].extend(indicator_data)
if entity_count >= self._batch_max_chunk:
return data
indicator_data, entity_count = self.data_indicators(self.indicators_shelf, entity_count)
data['indicator'].extend(indicator_data)
if entity_count >= self._batch_max_chunk:
return data
return data | python | def data(self):
"""Return the batch data to be sent to the ThreatConnect API.
**Processing Order:**
* Process groups in memory up to max batch size.
* Process groups in shelf to max batch size.
* Process indicators in memory up to max batch size.
* Process indicators in shelf up to max batch size.
This method will remove the group/indicator from memory and/or shelf.
"""
entity_count = 0
data = {'group': [], 'indicator': []}
# process group data
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.groups_shelf, entity_count)
data['group'].extend(group_data)
if entity_count >= self._batch_max_chunk:
return data
# process indicator data
indicator_data, entity_count = self.data_indicators(self.indicators, entity_count)
data['indicator'].extend(indicator_data)
if entity_count >= self._batch_max_chunk:
return data
indicator_data, entity_count = self.data_indicators(self.indicators_shelf, entity_count)
data['indicator'].extend(indicator_data)
if entity_count >= self._batch_max_chunk:
return data
return data | [
"def",
"data",
"(",
"self",
")",
":",
"entity_count",
"=",
"0",
"data",
"=",
"{",
"'group'",
":",
"[",
"]",
",",
"'indicator'",
":",
"[",
"]",
"}",
"# process group data",
"group_data",
",",
"entity_count",
"=",
"self",
".",
"data_groups",
"(",
"self",
... | Return the batch data to be sent to the ThreatConnect API.
**Processing Order:**
* Process groups in memory up to max batch size.
* Process groups in shelf to max batch size.
* Process indicators in memory up to max batch size.
* Process indicators in shelf up to max batch size.
This method will remove the group/indicator from memory and/or shelf. | [
"Return",
"the",
"batch",
"data",
"to",
"be",
"sent",
"to",
"the",
"ThreatConnect",
"API",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_batch.py#L468-L500 | train | 27,480 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_batch.py | TcExBatch.data_group_association | def data_group_association(self, xid):
"""Return group dict array following all associations.
Args:
xid (str): The xid of the group to retrieve associations.
Returns:
list: A list of group dicts.
"""
groups = []
group_data = None
# get group data from one of the arrays
if self.groups.get(xid) is not None:
group_data = self.groups.get(xid)
del self.groups[xid]
elif self.groups_shelf.get(xid) is not None:
group_data = self.groups_shelf.get(xid)
del self.groups_shelf[xid]
if group_data is not None:
# convert any obj into dict and process file data
group_data = self.data_group_type(group_data)
groups.append(group_data)
# recursively get associations
for assoc_xid in group_data.get('associatedGroupXid', []):
groups.extend(self.data_group_association(assoc_xid))
return groups | python | def data_group_association(self, xid):
"""Return group dict array following all associations.
Args:
xid (str): The xid of the group to retrieve associations.
Returns:
list: A list of group dicts.
"""
groups = []
group_data = None
# get group data from one of the arrays
if self.groups.get(xid) is not None:
group_data = self.groups.get(xid)
del self.groups[xid]
elif self.groups_shelf.get(xid) is not None:
group_data = self.groups_shelf.get(xid)
del self.groups_shelf[xid]
if group_data is not None:
# convert any obj into dict and process file data
group_data = self.data_group_type(group_data)
groups.append(group_data)
# recursively get associations
for assoc_xid in group_data.get('associatedGroupXid', []):
groups.extend(self.data_group_association(assoc_xid))
return groups | [
"def",
"data_group_association",
"(",
"self",
",",
"xid",
")",
":",
"groups",
"=",
"[",
"]",
"group_data",
"=",
"None",
"# get group data from one of the arrays",
"if",
"self",
".",
"groups",
".",
"get",
"(",
"xid",
")",
"is",
"not",
"None",
":",
"group_data... | Return group dict array following all associations.
Args:
xid (str): The xid of the group to retrieve associations.
Returns:
list: A list of group dicts. | [
"Return",
"group",
"dict",
"array",
"following",
"all",
"associations",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_batch.py#L502-L531 | train | 27,481 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_batch.py | TcExBatch.data_group_type | def data_group_type(self, group_data):
"""Return dict representation of group data.
Args:
group_data (dict|obj): The group data dict or object.
Returns:
dict: The group data in dict format.
"""
if isinstance(group_data, dict):
# process file content
file_content = group_data.pop('fileContent', None)
if file_content is not None:
self._files[group_data.get('xid')] = {
'fileContent': file_content,
'type': group_data.get('type'),
}
else:
GROUPS_STRINGS_WITH_FILE_CONTENTS = ['Document', 'Report']
# process file content
if group_data.data.get('type') in GROUPS_STRINGS_WITH_FILE_CONTENTS:
self._files[group_data.data.get('xid')] = group_data.file_data
group_data = group_data.data
return group_data | python | def data_group_type(self, group_data):
"""Return dict representation of group data.
Args:
group_data (dict|obj): The group data dict or object.
Returns:
dict: The group data in dict format.
"""
if isinstance(group_data, dict):
# process file content
file_content = group_data.pop('fileContent', None)
if file_content is not None:
self._files[group_data.get('xid')] = {
'fileContent': file_content,
'type': group_data.get('type'),
}
else:
GROUPS_STRINGS_WITH_FILE_CONTENTS = ['Document', 'Report']
# process file content
if group_data.data.get('type') in GROUPS_STRINGS_WITH_FILE_CONTENTS:
self._files[group_data.data.get('xid')] = group_data.file_data
group_data = group_data.data
return group_data | [
"def",
"data_group_type",
"(",
"self",
",",
"group_data",
")",
":",
"if",
"isinstance",
"(",
"group_data",
",",
"dict",
")",
":",
"# process file content",
"file_content",
"=",
"group_data",
".",
"pop",
"(",
"'fileContent'",
",",
"None",
")",
"if",
"file_conte... | Return dict representation of group data.
Args:
group_data (dict|obj): The group data dict or object.
Returns:
dict: The group data in dict format. | [
"Return",
"dict",
"representation",
"of",
"group",
"data",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_batch.py#L533-L556 | train | 27,482 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_batch.py | TcExBatch.data_groups | def data_groups(self, groups, entity_count):
"""Process Group data.
Args:
groups (list): The list of groups to process.
Returns:
list: A list of groups including associations
"""
data = []
# process group objects
for xid in groups.keys():
# get association from group data
assoc_group_data = self.data_group_association(xid)
data += assoc_group_data
entity_count += len(assoc_group_data)
if entity_count >= self._batch_max_chunk:
break
return data, entity_count | python | def data_groups(self, groups, entity_count):
"""Process Group data.
Args:
groups (list): The list of groups to process.
Returns:
list: A list of groups including associations
"""
data = []
# process group objects
for xid in groups.keys():
# get association from group data
assoc_group_data = self.data_group_association(xid)
data += assoc_group_data
entity_count += len(assoc_group_data)
if entity_count >= self._batch_max_chunk:
break
return data, entity_count | [
"def",
"data_groups",
"(",
"self",
",",
"groups",
",",
"entity_count",
")",
":",
"data",
"=",
"[",
"]",
"# process group objects",
"for",
"xid",
"in",
"groups",
".",
"keys",
"(",
")",
":",
"# get association from group data",
"assoc_group_data",
"=",
"self",
"... | Process Group data.
Args:
groups (list): The list of groups to process.
Returns:
list: A list of groups including associations | [
"Process",
"Group",
"data",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_batch.py#L558-L577 | train | 27,483 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_batch.py | TcExBatch.data_indicators | def data_indicators(self, indicators, entity_count):
"""Process Indicator data."""
data = []
# process indicator objects
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_max_chunk:
break
return data, entity_count | python | def data_indicators(self, indicators, entity_count):
"""Process Indicator data."""
data = []
# process indicator objects
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_max_chunk:
break
return data, entity_count | [
"def",
"data_indicators",
"(",
"self",
",",
"indicators",
",",
"entity_count",
")",
":",
"data",
"=",
"[",
"]",
"# process indicator objects",
"for",
"xid",
",",
"indicator_data",
"in",
"indicators",
".",
"items",
"(",
")",
":",
"entity_count",
"+=",
"1",
"i... | Process Indicator data. | [
"Process",
"Indicator",
"data",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_batch.py#L579-L592 | train | 27,484 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_batch.py | TcExBatch.debug | def debug(self):
"""Return debug setting"""
debug = False
if os.path.isfile(os.path.join(self.tcex.args.tc_temp_path, 'DEBUG')):
debug = True
return debug | python | def debug(self):
"""Return debug setting"""
debug = False
if os.path.isfile(os.path.join(self.tcex.args.tc_temp_path, 'DEBUG')):
debug = True
return debug | [
"def",
"debug",
"(",
"self",
")",
":",
"debug",
"=",
"False",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"tcex",
".",
"args",
".",
"tc_temp_path",
",",
"'DEBUG'",
")",
")",
":",
"debug",
"=",
... | Return debug setting | [
"Return",
"debug",
"setting"
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_batch.py#L595-L600 | train | 27,485 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_batch.py | TcExBatch.document | def document(self, name, file_name, **kwargs):
"""Add Document data to Batch object.
Args:
name (str): The name for this Group.
file_name (str): The name for the attached file for this Group.
date_added (str, kwargs): The date timestamp the Indicator was created.
file_content (str;method, kwargs): The file contents or callback method to retrieve
file content.
malware (bool, kwargs): If true the file is considered malware.
password (bool, kwargs): If malware is true a password for the zip archive is
xid (str, kwargs): The external id for this Group.
Returns:
obj: An instance of Document.
"""
group_obj = Document(name, file_name, **kwargs)
return self._group(group_obj) | python | def document(self, name, file_name, **kwargs):
"""Add Document data to Batch object.
Args:
name (str): The name for this Group.
file_name (str): The name for the attached file for this Group.
date_added (str, kwargs): The date timestamp the Indicator was created.
file_content (str;method, kwargs): The file contents or callback method to retrieve
file content.
malware (bool, kwargs): If true the file is considered malware.
password (bool, kwargs): If malware is true a password for the zip archive is
xid (str, kwargs): The external id for this Group.
Returns:
obj: An instance of Document.
"""
group_obj = Document(name, file_name, **kwargs)
return self._group(group_obj) | [
"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.
Args:
name (str): The name for this Group.
file_name (str): The name for the attached file for this Group.
date_added (str, kwargs): The date timestamp the Indicator was created.
file_content (str;method, kwargs): The file contents or callback method to retrieve
file content.
malware (bool, kwargs): If true the file is considered malware.
password (bool, kwargs): If malware is true a password for the zip archive is
xid (str, kwargs): The external id for this Group.
Returns:
obj: An instance of Document. | [
"Add",
"Document",
"data",
"to",
"Batch",
"object",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_batch.py#L602-L619 | train | 27,486 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_batch.py | TcExBatch.email | def email(self, name, subject, header, body, **kwargs):
"""Add Email data to Batch object.
Args:
name (str): The name for this Group.
subject (str): The subject for this Email.
header (str): The header for this Email.
body (str): The body for this Email.
date_added (str, kwargs): The date timestamp the Indicator was created.
from_addr (str, kwargs): The **from** address for this Email.
to_addr (str, kwargs): The **to** address for this Email.
xid (str, kwargs): The external id for this Group.
Returns:
obj: An instance of Email.
"""
group_obj = Email(name, subject, header, body, **kwargs)
return self._group(group_obj) | python | def email(self, name, subject, header, body, **kwargs):
"""Add Email data to Batch object.
Args:
name (str): The name for this Group.
subject (str): The subject for this Email.
header (str): The header for this Email.
body (str): The body for this Email.
date_added (str, kwargs): The date timestamp the Indicator was created.
from_addr (str, kwargs): The **from** address for this Email.
to_addr (str, kwargs): The **to** address for this Email.
xid (str, kwargs): The external id for this Group.
Returns:
obj: An instance of Email.
"""
group_obj = Email(name, subject, header, body, **kwargs)
return self._group(group_obj) | [
"def",
"email",
"(",
"self",
",",
"name",
",",
"subject",
",",
"header",
",",
"body",
",",
"*",
"*",
"kwargs",
")",
":",
"group_obj",
"=",
"Email",
"(",
"name",
",",
"subject",
",",
"header",
",",
"body",
",",
"*",
"*",
"kwargs",
")",
"return",
"... | Add Email data to Batch object.
Args:
name (str): The name for this Group.
subject (str): The subject for this Email.
header (str): The header for this Email.
body (str): The body for this Email.
date_added (str, kwargs): The date timestamp the Indicator was created.
from_addr (str, kwargs): The **from** address for this Email.
to_addr (str, kwargs): The **to** address for this Email.
xid (str, kwargs): The external id for this Group.
Returns:
obj: An instance of Email. | [
"Add",
"Email",
"data",
"to",
"Batch",
"object",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_batch.py#L621-L638 | train | 27,487 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_batch.py | TcExBatch.errors | def errors(self, batch_id, halt_on_error=True):
"""Retrieve Batch errors to ThreatConnect API.
.. code-block:: javascript
[{
"errorReason": "Incident incident-001 has an invalid status.",
"errorSource": "incident-001 is not valid."
}, {
"errorReason": "Incident incident-002 has an invalid status.",
"errorSource":"incident-002 is not valid."
}]
Args:
batch_id (str): The ID returned from the ThreatConnect API for the current batch job.
halt_on_error (bool, default:True): If True any exception will raise an error.
"""
errors = []
try:
r = self.tcex.session.get('/v2/batch/{}/errors'.format(batch_id))
# if r.status_code == 404:
# time.sleep(5) # allow time for errors to be processed
# 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
)
)
# self.tcex.log.debug('Retrieve Errors URL {}'.format(r.url))
# API does not return correct content type
if r.ok:
errors = json.loads(r.text)
# temporarily process errors to find "critical" errors.
# FR in core to return error codes.
for error in errors:
error_reason = error.get('errorReason')
for error_msg in self._critical_failures:
if re.findall(error_msg, error_reason):
self.tcex.handle_error(10500, [error_reason], halt_on_error)
return errors
except Exception as e:
self.tcex.handle_error(560, [e], halt_on_error) | python | def errors(self, batch_id, halt_on_error=True):
"""Retrieve Batch errors to ThreatConnect API.
.. code-block:: javascript
[{
"errorReason": "Incident incident-001 has an invalid status.",
"errorSource": "incident-001 is not valid."
}, {
"errorReason": "Incident incident-002 has an invalid status.",
"errorSource":"incident-002 is not valid."
}]
Args:
batch_id (str): The ID returned from the ThreatConnect API for the current batch job.
halt_on_error (bool, default:True): If True any exception will raise an error.
"""
errors = []
try:
r = self.tcex.session.get('/v2/batch/{}/errors'.format(batch_id))
# if r.status_code == 404:
# time.sleep(5) # allow time for errors to be processed
# 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
)
)
# self.tcex.log.debug('Retrieve Errors URL {}'.format(r.url))
# API does not return correct content type
if r.ok:
errors = json.loads(r.text)
# temporarily process errors to find "critical" errors.
# FR in core to return error codes.
for error in errors:
error_reason = error.get('errorReason')
for error_msg in self._critical_failures:
if re.findall(error_msg, error_reason):
self.tcex.handle_error(10500, [error_reason], halt_on_error)
return errors
except Exception as e:
self.tcex.handle_error(560, [e], halt_on_error) | [
"def",
"errors",
"(",
"self",
",",
"batch_id",
",",
"halt_on_error",
"=",
"True",
")",
":",
"errors",
"=",
"[",
"]",
"try",
":",
"r",
"=",
"self",
".",
"tcex",
".",
"session",
".",
"get",
"(",
"'/v2/batch/{}/errors'",
".",
"format",
"(",
"batch_id",
... | Retrieve Batch errors to ThreatConnect API.
.. code-block:: javascript
[{
"errorReason": "Incident incident-001 has an invalid status.",
"errorSource": "incident-001 is not valid."
}, {
"errorReason": "Incident incident-002 has an invalid status.",
"errorSource":"incident-002 is not valid."
}]
Args:
batch_id (str): The ID returned from the ThreatConnect API for the current batch job.
halt_on_error (bool, default:True): If True any exception will raise an error. | [
"Retrieve",
"Batch",
"errors",
"to",
"ThreatConnect",
"API",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_batch.py#L657-L698 | train | 27,488 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_batch.py | TcExBatch.event | def event(self, name, **kwargs):
"""Add Event data to Batch object.
Args:
name (str): The name for this Group.
date_added (str, kwargs): The date timestamp the Indicator was created.
event_date (str, kwargs): The event datetime expression for this Group.
status (str, kwargs): The status for this Group.
xid (str, kwargs): The external id for this Group.
Returns:
obj: An instance of Event.
"""
group_obj = Event(name, **kwargs)
return self._group(group_obj) | python | def event(self, name, **kwargs):
"""Add Event data to Batch object.
Args:
name (str): The name for this Group.
date_added (str, kwargs): The date timestamp the Indicator was created.
event_date (str, kwargs): The event datetime expression for this Group.
status (str, kwargs): The status for this Group.
xid (str, kwargs): The external id for this Group.
Returns:
obj: An instance of Event.
"""
group_obj = Event(name, **kwargs)
return self._group(group_obj) | [
"def",
"event",
"(",
"self",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"group_obj",
"=",
"Event",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"_group",
"(",
"group_obj",
")"
] | Add Event data to Batch object.
Args:
name (str): The name for this Group.
date_added (str, kwargs): The date timestamp the Indicator was created.
event_date (str, kwargs): The event datetime expression for this Group.
status (str, kwargs): The status for this Group.
xid (str, kwargs): The external id for this Group.
Returns:
obj: An instance of Event. | [
"Add",
"Event",
"data",
"to",
"Batch",
"object",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_batch.py#L700-L714 | train | 27,489 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_batch.py | TcExBatch.file | def file(self, md5=None, sha1=None, sha256=None, **kwargs):
"""Add File data to Batch object.
.. note:: A least one file hash value must be specified.
Args:
md5 (str, optional): The md5 value for this Indicator.
sha1 (str, optional): The sha1 value for this Indicator.
sha256 (str, optional): The sha256 value for this Indicator.
confidence (str, kwargs): The threat confidence for this Indicator.
date_added (str, kwargs): The date timestamp the Indicator was created.
last_modified (str, kwargs): The date timestamp the Indicator was last modified.
rating (str, kwargs): The threat rating for this Indicator.
size (str, kwargs): The file size for this Indicator.
xid (str, kwargs): The external id for this Indicator.
Returns:
obj: An instance of File.
"""
indicator_obj = File(md5, sha1, sha256, **kwargs)
return self._indicator(indicator_obj) | python | def file(self, md5=None, sha1=None, sha256=None, **kwargs):
"""Add File data to Batch object.
.. note:: A least one file hash value must be specified.
Args:
md5 (str, optional): The md5 value for this Indicator.
sha1 (str, optional): The sha1 value for this Indicator.
sha256 (str, optional): The sha256 value for this Indicator.
confidence (str, kwargs): The threat confidence for this Indicator.
date_added (str, kwargs): The date timestamp the Indicator was created.
last_modified (str, kwargs): The date timestamp the Indicator was last modified.
rating (str, kwargs): The threat rating for this Indicator.
size (str, kwargs): The file size for this Indicator.
xid (str, kwargs): The external id for this Indicator.
Returns:
obj: An instance of File.
"""
indicator_obj = File(md5, sha1, sha256, **kwargs)
return self._indicator(indicator_obj) | [
"def",
"file",
"(",
"self",
",",
"md5",
"=",
"None",
",",
"sha1",
"=",
"None",
",",
"sha256",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"indicator_obj",
"=",
"File",
"(",
"md5",
",",
"sha1",
",",
"sha256",
",",
"*",
"*",
"kwargs",
")",
"r... | Add File data to Batch object.
.. note:: A least one file hash value must be specified.
Args:
md5 (str, optional): The md5 value for this Indicator.
sha1 (str, optional): The sha1 value for this Indicator.
sha256 (str, optional): The sha256 value for this Indicator.
confidence (str, kwargs): The threat confidence for this Indicator.
date_added (str, kwargs): The date timestamp the Indicator was created.
last_modified (str, kwargs): The date timestamp the Indicator was last modified.
rating (str, kwargs): The threat rating for this Indicator.
size (str, kwargs): The file size for this Indicator.
xid (str, kwargs): The external id for this Indicator.
Returns:
obj: An instance of File. | [
"Add",
"File",
"data",
"to",
"Batch",
"object",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_batch.py#L716-L737 | train | 27,490 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_batch.py | TcExBatch.generate_xid | def generate_xid(identifier=None):
"""Generate xid from provided identifiers.
.. Important:: If no identifier is provided a unique xid will be returned, but it will
not be reproducible. If a list of identifiers are provided they must be
in the same order to generate a reproducible xid.
Args:
identifier (list|str): Optional *string* value(s) to be used to make a unique and
reproducible xid.
"""
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(identifier.encode('utf-8')).hexdigest() | python | def generate_xid(identifier=None):
"""Generate xid from provided identifiers.
.. Important:: If no identifier is provided a unique xid will be returned, but it will
not be reproducible. If a list of identifiers are provided they must be
in the same order to generate a reproducible xid.
Args:
identifier (list|str): Optional *string* value(s) to be used to make a unique and
reproducible xid.
"""
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(identifier.encode('utf-8')).hexdigest() | [
"def",
"generate_xid",
"(",
"identifier",
"=",
"None",
")",
":",
"if",
"identifier",
"is",
"None",
":",
"identifier",
"=",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")",
"elif",
"isinstance",
"(",
"identifier",
",",
"list",
")",
":",
"identifier",
"=... | Generate xid from provided identifiers.
.. Important:: If no identifier is provided a unique xid will be returned, but it will
not be reproducible. If a list of identifiers are provided they must be
in the same order to generate a reproducible xid.
Args:
identifier (list|str): Optional *string* value(s) to be used to make a unique and
reproducible xid. | [
"Generate",
"xid",
"from",
"provided",
"identifiers",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_batch.py#L753-L770 | train | 27,491 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_batch.py | TcExBatch.group | def group(self, group_type, name, **kwargs):
"""Add Group data to Batch object.
Args:
group_type (str): The ThreatConnect define Group type.
name (str): The name for this Group.
date_added (str, kwargs): The date timestamp the Indicator was created.
xid (str, kwargs): The external id for this Group.
Returns:
obj: An instance of Group.
"""
group_obj = Group(group_type, name, **kwargs)
return self._group(group_obj) | python | def group(self, group_type, name, **kwargs):
"""Add Group data to Batch object.
Args:
group_type (str): The ThreatConnect define Group type.
name (str): The name for this Group.
date_added (str, kwargs): The date timestamp the Indicator was created.
xid (str, kwargs): The external id for this Group.
Returns:
obj: An instance of Group.
"""
group_obj = Group(group_type, name, **kwargs)
return self._group(group_obj) | [
"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.
Args:
group_type (str): The ThreatConnect define Group type.
name (str): The name for this Group.
date_added (str, kwargs): The date timestamp the Indicator was created.
xid (str, kwargs): The external id for this Group.
Returns:
obj: An instance of Group. | [
"Add",
"Group",
"data",
"to",
"Batch",
"object",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_batch.py#L772-L785 | train | 27,492 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_batch.py | TcExBatch.group_shelf_fqfn | def group_shelf_fqfn(self):
"""Return groups shelf fully qualified filename.
For testing/debugging a previous shelf file can be copied into the tc_temp_path directory
instead of creating a new shelf file.
"""
if self._group_shelf_fqfn is None:
# new shelf file
self._group_shelf_fqfn = os.path.join(
self.tcex.args.tc_temp_path, 'groups-{}'.format(str(uuid.uuid4()))
)
# saved shelf file
if self.saved_groups:
self._group_shelf_fqfn = os.path.join(self.tcex.args.tc_temp_path, 'groups-saved')
return self._group_shelf_fqfn | python | def group_shelf_fqfn(self):
"""Return groups shelf fully qualified filename.
For testing/debugging a previous shelf file can be copied into the tc_temp_path directory
instead of creating a new shelf file.
"""
if self._group_shelf_fqfn is None:
# new shelf file
self._group_shelf_fqfn = os.path.join(
self.tcex.args.tc_temp_path, 'groups-{}'.format(str(uuid.uuid4()))
)
# saved shelf file
if self.saved_groups:
self._group_shelf_fqfn = os.path.join(self.tcex.args.tc_temp_path, 'groups-saved')
return self._group_shelf_fqfn | [
"def",
"group_shelf_fqfn",
"(",
"self",
")",
":",
"if",
"self",
".",
"_group_shelf_fqfn",
"is",
"None",
":",
"# new shelf file",
"self",
".",
"_group_shelf_fqfn",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"tcex",
".",
"args",
".",
"tc_temp_pat... | Return groups shelf fully qualified filename.
For testing/debugging a previous shelf file can be copied into the tc_temp_path directory
instead of creating a new shelf file. | [
"Return",
"groups",
"shelf",
"fully",
"qualified",
"filename",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_batch.py#L788-L803 | train | 27,493 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_batch.py | TcExBatch.groups_shelf | def groups_shelf(self):
"""Return dictionary of all Groups data."""
if self._groups_shelf is None:
self._groups_shelf = shelve.open(self.group_shelf_fqfn, writeback=False)
return self._groups_shelf | python | def groups_shelf(self):
"""Return dictionary of all Groups data."""
if self._groups_shelf is None:
self._groups_shelf = shelve.open(self.group_shelf_fqfn, writeback=False)
return self._groups_shelf | [
"def",
"groups_shelf",
"(",
"self",
")",
":",
"if",
"self",
".",
"_groups_shelf",
"is",
"None",
":",
"self",
".",
"_groups_shelf",
"=",
"shelve",
".",
"open",
"(",
"self",
".",
"group_shelf_fqfn",
",",
"writeback",
"=",
"False",
")",
"return",
"self",
".... | Return dictionary of all Groups data. | [
"Return",
"dictionary",
"of",
"all",
"Groups",
"data",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_batch.py#L814-L818 | train | 27,494 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_batch.py | TcExBatch.incident | def incident(self, name, **kwargs):
"""Add Incident data to Batch object.
Args:
name (str): The name for this Group.
date_added (str, kwargs): The date timestamp the Indicator was created.
event_date (str, kwargs): The event datetime expression for this Group.
status (str, kwargs): The status for this Group.
xid (str, kwargs): The external id for this Group.
Returns:
obj: An instance of Incident.
"""
group_obj = Incident(name, **kwargs)
return self._group(group_obj) | python | def incident(self, name, **kwargs):
"""Add Incident data to Batch object.
Args:
name (str): The name for this Group.
date_added (str, kwargs): The date timestamp the Indicator was created.
event_date (str, kwargs): The event datetime expression for this Group.
status (str, kwargs): The status for this Group.
xid (str, kwargs): The external id for this Group.
Returns:
obj: An instance of Incident.
"""
group_obj = Incident(name, **kwargs)
return self._group(group_obj) | [
"def",
"incident",
"(",
"self",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"group_obj",
"=",
"Incident",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"_group",
"(",
"group_obj",
")"
] | Add Incident data to Batch object.
Args:
name (str): The name for this Group.
date_added (str, kwargs): The date timestamp the Indicator was created.
event_date (str, kwargs): The event datetime expression for this Group.
status (str, kwargs): The status for this Group.
xid (str, kwargs): The external id for this Group.
Returns:
obj: An instance of Incident. | [
"Add",
"Incident",
"data",
"to",
"Batch",
"object",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_batch.py#L891-L905 | train | 27,495 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_batch.py | TcExBatch.indicator | def indicator(self, indicator_type, summary, **kwargs):
"""Add Indicator data to Batch object.
Args:
indicator_type (str): The ThreatConnect define Indicator type.
summary (str): The value for this Indicator.
confidence (str, kwargs): The threat confidence for this Indicator.
date_added (str, kwargs): The date timestamp the Indicator was created.
last_modified (str, kwargs): The date timestamp the Indicator was last modified.
rating (str, kwargs): The threat rating for this Indicator.
xid (str, kwargs): The external id for this Indicator.
Returns:
obj: An instance of Indicator.
"""
indicator_obj = Indicator(indicator_type, summary, **kwargs)
return self._indicator(indicator_obj) | python | def indicator(self, indicator_type, summary, **kwargs):
"""Add Indicator data to Batch object.
Args:
indicator_type (str): The ThreatConnect define Indicator type.
summary (str): The value for this Indicator.
confidence (str, kwargs): The threat confidence for this Indicator.
date_added (str, kwargs): The date timestamp the Indicator was created.
last_modified (str, kwargs): The date timestamp the Indicator was last modified.
rating (str, kwargs): The threat rating for this Indicator.
xid (str, kwargs): The external id for this Indicator.
Returns:
obj: An instance of Indicator.
"""
indicator_obj = Indicator(indicator_type, summary, **kwargs)
return self._indicator(indicator_obj) | [
"def",
"indicator",
"(",
"self",
",",
"indicator_type",
",",
"summary",
",",
"*",
"*",
"kwargs",
")",
":",
"indicator_obj",
"=",
"Indicator",
"(",
"indicator_type",
",",
"summary",
",",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"_indicator",
"(",
"... | Add Indicator data to Batch object.
Args:
indicator_type (str): The ThreatConnect define Indicator type.
summary (str): The value for this Indicator.
confidence (str, kwargs): The threat confidence for this Indicator.
date_added (str, kwargs): The date timestamp the Indicator was created.
last_modified (str, kwargs): The date timestamp the Indicator was last modified.
rating (str, kwargs): The threat rating for this Indicator.
xid (str, kwargs): The external id for this Indicator.
Returns:
obj: An instance of Indicator. | [
"Add",
"Indicator",
"data",
"to",
"Batch",
"object",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_batch.py#L907-L923 | train | 27,496 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_batch.py | TcExBatch.indicator_shelf_fqfn | def indicator_shelf_fqfn(self):
"""Return indicator shelf fully qualified filename.
For testing/debugging a previous shelf file can be copied into the tc_temp_path directory
instead of creating a new shelf file.
"""
if self._indicator_shelf_fqfn is None:
# new shelf file
self._indicator_shelf_fqfn = os.path.join(
self.tcex.args.tc_temp_path, 'indicators-{}'.format(str(uuid.uuid4()))
)
# saved shelf file
if self.saved_indicators:
self._indicator_shelf_fqfn = os.path.join(
self.tcex.args.tc_temp_path, 'indicators-saved'
)
return self._indicator_shelf_fqfn | python | def indicator_shelf_fqfn(self):
"""Return indicator shelf fully qualified filename.
For testing/debugging a previous shelf file can be copied into the tc_temp_path directory
instead of creating a new shelf file.
"""
if self._indicator_shelf_fqfn is None:
# new shelf file
self._indicator_shelf_fqfn = os.path.join(
self.tcex.args.tc_temp_path, 'indicators-{}'.format(str(uuid.uuid4()))
)
# saved shelf file
if self.saved_indicators:
self._indicator_shelf_fqfn = os.path.join(
self.tcex.args.tc_temp_path, 'indicators-saved'
)
return self._indicator_shelf_fqfn | [
"def",
"indicator_shelf_fqfn",
"(",
"self",
")",
":",
"if",
"self",
".",
"_indicator_shelf_fqfn",
"is",
"None",
":",
"# new shelf file",
"self",
".",
"_indicator_shelf_fqfn",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"tcex",
".",
"args",
".",
... | Return indicator shelf fully qualified filename.
For testing/debugging a previous shelf file can be copied into the tc_temp_path directory
instead of creating a new shelf file. | [
"Return",
"indicator",
"shelf",
"fully",
"qualified",
"filename",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_batch.py#L926-L943 | train | 27,497 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_batch.py | TcExBatch.indicators_shelf | def indicators_shelf(self):
"""Return dictionary of all Indicator data."""
if self._indicators_shelf is None:
self._indicators_shelf = shelve.open(self.indicator_shelf_fqfn, writeback=False)
return self._indicators_shelf | python | def indicators_shelf(self):
"""Return dictionary of all Indicator data."""
if self._indicators_shelf is None:
self._indicators_shelf = shelve.open(self.indicator_shelf_fqfn, writeback=False)
return self._indicators_shelf | [
"def",
"indicators_shelf",
"(",
"self",
")",
":",
"if",
"self",
".",
"_indicators_shelf",
"is",
"None",
":",
"self",
".",
"_indicators_shelf",
"=",
"shelve",
".",
"open",
"(",
"self",
".",
"indicator_shelf_fqfn",
",",
"writeback",
"=",
"False",
")",
"return"... | Return dictionary of all Indicator data. | [
"Return",
"dictionary",
"of",
"all",
"Indicator",
"data",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_batch.py#L954-L958 | train | 27,498 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_batch.py | TcExBatch.intrusion_set | def intrusion_set(self, name, **kwargs):
"""Add Intrusion Set data to Batch object.
Args:
name (str): The name for this Group.
date_added (str, kwargs): The date timestamp the Indicator was created.
xid (str, kwargs): The external id for this Group.
Returns:
obj: An instance of IntrusionSet.
"""
group_obj = IntrusionSet(name, **kwargs)
return self._group(group_obj) | python | def intrusion_set(self, name, **kwargs):
"""Add Intrusion Set data to Batch object.
Args:
name (str): The name for this Group.
date_added (str, kwargs): The date timestamp the Indicator was created.
xid (str, kwargs): The external id for this Group.
Returns:
obj: An instance of IntrusionSet.
"""
group_obj = IntrusionSet(name, **kwargs)
return self._group(group_obj) | [
"def",
"intrusion_set",
"(",
"self",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"group_obj",
"=",
"IntrusionSet",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"_group",
"(",
"group_obj",
")"
] | Add Intrusion Set data to Batch object.
Args:
name (str): The name for this Group.
date_added (str, kwargs): The date timestamp the Indicator was created.
xid (str, kwargs): The external id for this Group.
Returns:
obj: An instance of IntrusionSet. | [
"Add",
"Intrusion",
"Set",
"data",
"to",
"Batch",
"object",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_batch.py#L960-L972 | train | 27,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.