docstring stringlengths 52 499 | function stringlengths 67 35.2k | __index_level_0__ int64 52.6k 1.16M |
|---|---|---|
Read method of CRUD operation for binary array data.
Args:
key (string): The variable to read from the DB.
b64decode (bool): If true the data will be base64 decoded.
decode (bool): If true the data will be decoded to a String.
Returns:
(list): Results re... | def read_binary_array(self, key, b64decode=True, decode=False):
data = None
if key is not None:
data = self.db.read(key.strip())
if data is not None:
data_decoded = []
for d in json.loads(data, object_pairs_hook=OrderedDict):
... | 541,990 |
Create method of CRUD operation for raw data.
Args:
key (string): The variable to write to the DB.
value (any): The data to write to the DB.
Returns:
(string): Result of DB write. | def create_raw(self, key, value):
data = None
if key is not None and value is not None:
data = self.db.create(key.strip(), value)
else:
self.tcex.log.warning(u'The key or value field was None.')
return data | 541,991 |
Read method of CRUD operation for raw data.
Args:
key (string): The variable to read from the DB.
Returns:
(any): Results retrieved from DB. | def read_raw(self, key):
data = None
if key is not None:
data = self.db.read(key.strip())
else:
self.tcex.log.warning(u'The key field was None.')
return data | 541,992 |
Create method of CRUD operation for string data.
Args:
key (string): The variable to write to the DB.
value (any): The data to write to the DB.
Returns:
(string): Result of DB write. | def create_string(self, key, value):
data = None
if key is not None and value is not None:
if isinstance(value, (bool, list, int, dict)):
# value = str(value)
value = u'{}'.format(value)
# data = self.db.create(key.strip(), str(json.dumps(... | 541,993 |
Read method of CRUD operation for string data.
Args:
key (string): The variable to read from the DB.
embedded (boolean): Resolve embedded variables.
Returns:
(string): Results retrieved from DB. | def read_string(self, key, embedded=True):
data = None
if key is not None:
key_type = self.variable_type(key)
data = self.db.read(key.strip())
if data is not None:
# handle improperly saved string
try:
data ... | 541,994 |
Create method of CRUD operation for string array data.
Args:
key (string): The variable to write to the DB.
value (any): The data to write to the DB.
Returns:
(string): Result of DB write. | def create_string_array(self, key, value):
data = None
if key is not None and value is not None:
if isinstance(value, (list)):
data = self.db.create(key.strip(), json.dumps(value))
else:
# used to save raw value with embedded variables
... | 541,995 |
Read method of CRUD operation for string array data.
Args:
key (string): The variable to read from the DB.
embedded (boolean): Resolve embedded variables.
Returns:
(list): Results retrieved from DB. | def read_string_array(self, key, embedded=True):
data = None
if key is not None:
key_type = self.variable_type(key)
data = self.db.read(key.strip())
if embedded:
data = self.read_embedded(data, key_type)
if data is not None:
... | 541,996 |
Create method of CRUD operation for TC entity data.
Args:
key (string): The variable to write to the DB.
value (any): The data to write to the DB.
Returns:
(string): Result of DB write. | def create_tc_entity(self, key, value):
data = None
if key is not None and value is not None:
data = self.db.create(key.strip(), json.dumps(value))
else:
self.tcex.log.warning(u'The key or value field was None.')
return data | 541,997 |
Convert Single TC Entity to Bulk format.
.. Attention:: This method is subject to frequent changes
Args:
entities (dictionary): TC Entity to be converted to Bulk.
resource_type_parent (string): The resource parent type of the tc_data provided.
Returns:
(dic... | def entity_to_bulk(entities, resource_type_parent):
if not isinstance(entities, list):
entities = [entities]
bulk_array = []
for e in entities:
bulk = {'type': e.get('type'), 'ownerName': e.get('ownerName')}
if resource_type_parent in ['Group', 'Task... | 541,998 |
Convert TCEntityArray to Indicator Type dictionary.
Args:
tc_entity_array (dictionary): The TCEntityArray to convert.
Returns:
(dictionary): Dictionary containing arrays of indicators for each indicator type. | def indicator_arrays(tc_entity_array):
type_dict = {}
for ea in tc_entity_array:
type_dict.setdefault(ea['type'], []).append(ea['value'])
return type_dict | 541,999 |
Convert JSON data to a KeyValue/KeyValueArray.
Args:
json_data (dictionary|list): Array/List of JSON data.
key_field (string): Field name for the key.
value_field (string): Field name for the value or use the value of the key field.
array (boolean): Always return... | def json_to_key_value(json_data, key_field, value_field=None, array=False):
if not isinstance(json_data, list):
json_data = [json_data]
key_value_array = []
for d in json_data:
if d.get(key_field) is not None and value_field is None:
# key / valu... | 542,002 |
Convert ISO 8601 and other date strings to datetime.datetime type.
Args:
time_input (string): The time input string (see formats above).
tz (string): The time zone for the returned data.
Returns:
(datetime.datetime): Python datetime.datetime object. | def date_to_datetime(self, time_input, tz=None):
dt = None
try:
# dt = parser.parse(time_input, fuzzy_with_tokens=True)[0]
dt = parser.parse(time_input)
# don't convert timezone if dt timezone already in the correct timezone
if tz is not None and ... | 542,005 |
Write content to a temporary file.
Args:
content (bytes|str): The file content. If passing binary data the mode needs to be set
to 'wb'.
filename (str, optional): The filename to use when writing the file.
mode (str, optional): The file write mode which could... | def write_temp_file(self, content, filename=None, mode='w'):
if filename is None:
filename = str(uuid.uuid4())
fqpn = os.path.join(self.tcex.default_args.tc_temp_path, filename)
with open(fqpn, mode) as fh:
fh.write(content)
return fqpn | 542,009 |
Calculates time delta between two time expressions.
Args:
time_input1 (string): The time input string (see formats above).
time_input2 (string): The time input string (see formats above).
Returns:
(dict): Dict with delta values. | def timedelta(self, time_input1, time_input2):
time_input1 = self.any_to_datetime(time_input1)
time_input2 = self.any_to_datetime(time_input2)
diff = time_input1 - time_input2 # timedelta
delta = relativedelta(time_input1, time_input2) # relativedelta
# totals
... | 542,010 |
Updates the event_date.
Args:
event_date: Converted to %Y-%m-%dT%H:%M:%SZ date format.
Returns: | def event_date(self, event_date):
if not self.can_update():
self._tcex.handle_error(910, [self.type])
event_date = self._utils.format_datetime(event_date, date_format='%Y-%m-%dT%H:%M:%SZ')
self._data['eventDate'] = event_date
request = {'eventDate': event_date}
... | 542,013 |
Converts the value and adds it as a data field.
Args:
key:
value: | def add_key_value(self, key, value):
if key == 'unique_id':
self._unique_id = str(value)
else:
self._data[key] = value | 542,016 |
Adds a asset to the Victim
Valid asset_type:
+ PHONE
+ EMAIL
+ NETWORK
+ SOCIAL
+ WEB
Args:
asset:
asset_name:
asset_type: PHONE, EMAIL, NETWORK, SOCIAL, or WEB
Returns: | def add_asset(self, asset, asset_name, asset_type):
if not self.can_update():
self._tcex.handle_error(910, [self.type])
if asset == 'PHONE':
return self.tc_requests.add_victim_phone_asset(self.unique_id, asset_name)
if asset == 'EMAIL':
return self.t... | 542,017 |
Update a asset of a Victim
Valid asset_type:
+ PHONE
+ EMAIL
+ NETWORK
+ SOCIAL
+ WEB
Args:
asset:
asset_name:
asset_id:
asset_type: PHONE, EMAIL, NETWORK, SOCIAL, or WEB
Returns: | def update_asset(self, asset, asset_id, asset_name, asset_type):
if not self.can_update():
self._tcex.handle_error(910, [self.type])
if asset == 'PHONE':
return self.tc_requests.update_victim_phone_asset(self.unique_id, asset_id, asset_name)
if asset == 'EMAIL':... | 542,018 |
Gets a asset of a Victim
Valid asset_type:
+ PHONE
+ EMAIL
+ NETWORK
+ SOCIAL
+ WEB
Args:
asset_type:
asset_id:
action:
Returns: | def asset(self, asset_id, asset_type, action='GET'):
if not self.can_update():
self._tcex.handle_error(910, [self.type])
if asset_type == 'PHONE':
return self.tc_requests.victim_phone_asset(
self.api_type, self.api_sub_type, self.unique_id, asset_id, act... | 542,019 |
Gets the assets of a Victim
Args:
asset_type:
Yields: asset json | def assets(self, asset_type=None):
if not self.can_update():
self._tcex.handle_error(910, [self.type])
if not asset_type:
for a in self.tc_requests.victim_assets(
self.api_type, self.api_sub_type, self.unique_id
):
yield a
... | 542,020 |
Updates a Email Asset
Args:
name: The name provided to the email asset
asset_type: The type provided to the email asset
asset_id:
Returns: | def update_email_asset(self, asset_id, name, asset_type):
self.update_asset('EMAIL', asset_id, name, asset_type) | 542,021 |
Updates a Network Asset
Args:
name: The name provided to the network asset
asset_type: The type provided to the network asset
asset_id:
Returns: | def update_network_asset(self, asset_id, name, asset_type):
self.update_asset('NETWORK', asset_id, name, asset_type) | 542,022 |
Updates a Social Asset
Args:
name: The name provided to the social asset
asset_type: The type provided to the social asset
asset_id:
Returns: | def update_social_asset(self, asset_id, name, asset_type):
self.update_asset('SOCIAL', asset_id, name, asset_type) | 542,023 |
Implement __call__ function for decorator.
Args:
fn (function): The decorated function.
Returns:
function: The custom decorator function. | def __call__(self, fn):
def benchmark(app, *args, **kwargs):
# before = float('{0:.4f}'.format(time.clock()))
before = datetime.datetime.now()
data = fn(app, *args, **kwargs)
# after = float('{0:.4f}'.format(time.clock()))
after... | 542,024 |
Implement __call__ function for decorator.
Args:
fn (function): The decorated function.
Returns:
function: The custom decorator function. | def __call__(self, fn):
def debug(app, *args, **kwargs):
data = fn(app, *args, **kwargs)
app.tcex.log.debug(
'function: "{}", args: "{}", kwargs: "{}"'.format(
self.__class__.__name__, vars(args), kwargs
)
... | 542,025 |
Implement __call__ function for decorator.
Args:
fn (function): The decorated function.
Returns:
function: The custom decorator function. | def __call__(self, fn):
def fail(app, *args, **kwargs):
# self.enable (e.g., True or 'fail_on_false') enables/disables this feature
if isinstance(self.enable, bool):
enabled = self.enable
app.tcex.log.debug('Fail on input is ({}).'.... | 542,027 |
Implement __call__ function for decorator.
Args:
fn (function): The decorated function.
Returns:
function: The custom decorator function. | def __call__(self, fn):
def fail(app, *args, **kwargs):
data = fn(app, *args, **kwargs)
# self.enable (e.g., True or 'fail_on_false') enables/disables this feature
if isinstance(self.enable, bool):
enabled = self.enable
a... | 542,028 |
Implement __call__ function for decorator.
Args:
fn (function): The decorated function.
Returns:
function: The custom decorator function. | def __call__(self, fn):
def loop(app, *args, **kwargs):
# retrieve data from Redis if variable and always return and array.
r = []
arg_data = app.tcex.playbook.read(getattr(app.args, self.arg))
arg_type = app.tcex.playbook.variable_type(get... | 542,030 |
Implement __call__ function for decorator.
Args:
fn (function): The decorated function.
Returns:
function: The custom decorator function. | def __call__(self, fn):
def exception(app, *args, **kwargs):
try:
return fn(app, *args, **kwargs)
except Exception as e:
app.tcex.log.error('method failure ({})'.format(e))
app.tcex.exit(1, self.msg)
return ... | 542,031 |
Implement __call__ function for decorator.
Args:
fn (function): The decorated function.
Returns:
function: The custom decorator function. | def __call__(self, fn):
def completion(app, *args, **kwargs):
app.exit_message = self.msg
return fn(app, *args, **kwargs)
return completion | 542,032 |
Implement __call__ function for decorator.
Args:
fn (function): The decorated function.
Returns:
function: The custom decorator function. | def __call__(self, fn):
def output(app, *args, **kwargs):
data = fn(app, *args, **kwargs)
attr = getattr(app, self.attribute)
if isinstance(data, list) and isinstance(attr, list):
getattr(app, self.attribute).extend(data)
eli... | 542,033 |
Implement __call__ function for decorator.
Args:
fn (function): The decorated function.
Returns:
function: The custom decorator function. | def __call__(self, fn):
def output(app, *args, **kwargs):
data = fn(app, *args, **kwargs)
index = '{}-{}'.format(self.key, self.variable_type)
if self.value is not None:
# store user provided data
app.tcex.playbook.add_ou... | 542,036 |
Initialize the Class properties.
Args:
url (string): The URL to the value server.
token (string): The value token.
cert (string): The value cert. | def __init__(self, url=None, token=None, cert=None):
token = token or os.environ.get('VAULT_TOKEN')
url = url or 'http://localhost:8200'
self._client = hvac.Client(url=url, token=token, cert=cert) | 542,038 |
Create key/value pair in Vault.
Args:
key (string): The data key.
value (string): The data value.
lease (string): The least time. | def create(self, key, value, lease='1h'):
return self._client.write(key, value, lease=lease) | 542,039 |
Initialize Class properties.
Args:
_args (namespace): The argparser args Namespace. | def __init__(self, _args):
self.args = _args
# properties
self._db_conn = None
self._install_json = None
self._install_json_params = None
self._install_json_output_variables = None
self._layout_json = None
self._layout_json_names = None
s... | 542,040 |
Create a temporary DB table.
Arguments:
table_name (str): The name of the table.
columns (list): List of columns to add to the DB. | def db_create_table(self, table_name, columns):
formatted_columns = ''
for col in set(columns):
formatted_columns += '"{}" text, '.format(col.strip('"').strip('\''))
formatted_columns = formatted_columns.strip(', ')
create_table_sql = 'CREATE TABLE IF NOT EXISTS {} ... | 542,042 |
Insert records into DB.
Args:
table_name (str): The name of the table.
columns (list): List of columns for insert statement. | def db_insert_record(self, table_name, columns):
bindings = ('?,' * len(columns)).strip(',')
values = [None] * len(columns)
sql = 'INSERT INTO {} ({}) VALUES ({})'.format(table_name, ', '.join(columns), bindings)
cur = self.db_conn.cursor()
cur.execute(sql, values) | 542,043 |
Insert records into DB.
Args:
table_name (str): The name of the table.
column (str): The column name in which the value is to be updated.
value (str): The value to update in the column. | def db_update_record(self, table_name, column, value):
sql = 'UPDATE {} SET {} = \'{}\''.format(table_name, column, value)
cur = self.db_conn.cursor()
cur.execute(sql) | 542,044 |
Print errors message and optionally exit.
Args:
err (str): The error message to print.
halt (bool, optional): Defaults to True. If True the script will exit. | def handle_error(err, halt=True):
print('{}{}{}'.format(c.Style.BRIGHT, c.Fore.RED, err))
if halt:
sys.exit(1) | 542,045 |
Return install.json params in a dict with name param as key.
Args:
ij (dict, optional): Defaults to None. The install.json contents.
Returns:
dict: A dictionary containing the install.json input params with name as key. | def install_json_params(self, ij=None):
if self._install_json_params is None or ij is not None:
self._install_json_params = {}
# TODO: support for projects with multiple install.json files is not supported
if ij is None:
ij = self.install_json
... | 542,047 |
Return install.json output variables in a dict with name param as key.
Args:
ij (dict, optional): Defaults to None. The install.json contents.
Returns:
dict: A dictionary containing the install.json output variables with name as key. | def install_json_output_variables(self, ij=None):
if self._install_json_output_variables is None or ij is not None:
self._install_json_output_variables = {}
# TODO: currently there is no support for projects with multiple install.json files.
if ij is None:
... | 542,048 |
Return install.json data.
Args:
filename (str, optional): Defaults to None. The install.json filename (for bundled
Apps).
Returns:
dict: The contents of the install.json file. | def load_install_json(self, filename=None):
if filename is None:
filename = 'install.json'
file_fqpn = os.path.join(self.app_path, filename)
install_json = None
if os.path.isfile(file_fqpn):
try:
with open(file_fqpn, 'r') as fh:
... | 542,053 |
Add custom field to Indicator object.
.. note:: The key must be the exact name required by the batch schema.
Example::
file_hash = tcex.batch.file('File', '1d878cdc391461e392678ba3fc9f6f32')
file_hash.add_key_value('size', '1024')
Args:
key (str): The fiel... | def add_key_value(self, key, value):
key = self._metadata_map.get(key, key)
if key in ['dateAdded', 'lastModified']:
self._indicator_data[key] = self._utils.format_datetime(
value, date_format='%Y-%m-%dT%H:%M:%SZ'
)
elif key == 'confidence':
... | 542,064 |
Add association using xid value.
Args:
group_xid (str): The external id of the Group to associate. | def association(self, group_xid):
association = {'groupXid': group_xid}
self._indicator_data.setdefault('associatedGroups', []).append(association) | 542,065 |
Add a file Occurrence.
Args:
file_name (str, optional): The file name for this occurrence.
path (str, optional): The file path for this occurrence.
date (str, optional): The datetime expression for this occurrence.
Returns:
obj: An instance of Occurrence... | def occurrence(self, file_name=None, path=None, date=None):
if self._indicator_data.get('type') != 'File':
# Indicator object has no logger to output warning
return None
occurrence_obj = FileOccurrence(file_name, path, date)
self._occurrences.append(occurrence_o... | 542,070 |
Initialize Class Properties.
.. warning:: This code is not complete and may require some update to the API.
Args:
parent_xid (str): The external id of the parent Indicator.
relationship: ??? | def __init__(self, parent_xid, relationship):
self.xid = str(uuid.uuid4())
self._action_data = {
'indicatorXid': self.xid,
'relationship': relationship,
'parentIndicatorXid': parent_xid,
}
self._children = [] | 542,082 |
Initialize Class Properties
Args:
file_name (str, optional): The file name for this occurrence.
path (str, optional): The file path for this occurrence.
date (str, optional): The datetime expression for this occurrence. | def __init__(self, file_name=None, path=None, date=None):
self._utils = TcExUtils()
self._occurrence_data = {}
if file_name is not None:
self._occurrence_data['fileName'] = file_name
if path is not None:
self._occurrence_data['path'] = path
if dat... | 542,085 |
Create the Address TI object.
Args:
owner:
ip:
**kwargs:
Return: | def address(self, ip, owner=None, **kwargs):
return Address(self.tcex, ip, owner=owner, **kwargs) | 542,088 |
Create the URL TI object.
Args:
owner:
url:
**kwargs:
Return: | def url(self, url, owner=None, **kwargs):
return URL(self.tcex, url, owner=owner, **kwargs) | 542,089 |
Create the Email Address TI object.
Args:
owner:
address:
**kwargs:
Return: | def email_address(self, address, owner=None, **kwargs):
return EmailAddress(self.tcex, address, owner=owner, **kwargs) | 542,090 |
Create the File TI object.
Args:
owner:
**kwargs:
Return: | def file(self, owner=None, **kwargs):
return File(self.tcex, owner=owner, **kwargs) | 542,091 |
Create the Host TI object.
Args:
owner:
hostname:
**kwargs:
Return: | def host(self, hostname, owner=None, **kwargs):
return Host(self.tcex, hostname, owner=owner, **kwargs) | 542,092 |
Create the Indicator TI object.
Args:
owner:
indicator_type:
**kwargs:
Return: | def indicator(self, indicator_type=None, owner=None, **kwargs):
if not indicator_type:
return Indicator(self.tcex, None, owner=owner, **kwargs)
upper_indicator_type = indicator_type.upper()
indicator = None
if upper_indicator_type == 'ADDRESS':
indicato... | 542,093 |
Create the Group TI object.
Args:
owner:
group_type:
**kwargs:
Return: | def group(self, group_type=None, owner=None, **kwargs):
group = None
if not group_type:
return Group(self.tcex, None, None, owner=owner, **kwargs)
name = kwargs.pop('name', None)
group_type = group_type.upper()
if group_type == 'ADVERSARY':
grou... | 542,094 |
Create the Adversary TI object.
Args:
owner:
name:
**kwargs:
Return: | def adversary(self, name, owner=None, **kwargs):
return Adversary(self.tcex, name, owner=owner, **kwargs) | 542,095 |
Create the Campaign TI object.
Args:
owner:
name:
**kwargs:
Return: | def campaign(self, name, owner=None, **kwargs):
return Campaign(self.tcex, name, owner=owner, **kwargs) | 542,096 |
Create the Document TI object.
Args:
owner:
name:
file_name:
**kwargs:
Return: | def document(self, name, file_name, owner=None, **kwargs):
return Document(self.tcex, name, file_name, owner=owner, **kwargs) | 542,097 |
Create the Event TI object.
Args:
name:
**kwargs:
Return: | def event(self, name, owner=None, **kwargs):
return Event(self.tcex, name, owner=owner, **kwargs) | 542,098 |
Create the Email TI object.
Args:
owner:
to:
from_addr:
name:
subject:
header:
body:
**kwargs:
Return: | def email(self, name, to, from_addr, subject, body, header, owner=None, **kwargs):
return Email(self.tcex, name, to, from_addr, subject, body, header, owner=owner, **kwargs) | 542,099 |
Create the Incident TI object.
Args:
owner:
name:
**kwargs:
Return: | def incident(self, name, owner=None, **kwargs):
return Incident(self.tcex, name, owner=owner, **kwargs) | 542,100 |
Create the Intrustion Set TI object.
Args:
owner:
name:
**kwargs:
Return: | def intrusion_sets(self, name, owner=None, **kwargs):
return IntrusionSet(self.tcex, name, owner=owner, **kwargs) | 542,101 |
Create the Report TI object.
Args:
owner:
name:
**kwargs:
Return: | def report(self, name, owner=None, **kwargs):
return Report(self.tcex, name, owner=owner, **kwargs) | 542,102 |
Create the Signature TI object.
Args:
owner:
file_content:
file_name:
file_type:
name:
**kwargs:
Return: | def signature(self, name, file_name, file_type, file_content, owner=None, **kwargs):
return Signature(self.tcex, name, file_name, file_type, file_content, owner=owner, **kwargs) | 542,103 |
Create the Threat TI object.
Args:
owner:
name:
**kwargs:
Return: | def threat(self, name, owner=None, **kwargs):
return Threat(self.tcex, name, owner=owner, **kwargs) | 542,104 |
Create the Victim TI object.
Args:
owner:
name:
**kwargs:
Return: | def victim(self, name, owner=None, **kwargs):
return Victim(self.tcex, name, owner=owner, **kwargs) | 542,105 |
Dynamically generate custom Indicator methods.
Args:
name (str): The name of the method.
custom_class (object): The class to add.
value_count (int): The number of value parameters to support. | def _gen_indicator_method(self, name, custom_class, value_count):
method_name = name.replace(' ', '_').lower()
tcex = self.tcex
# Add Method for each Custom Indicator class
def method_1(owner, value1, **kwargs): # pylint: disable=W0641
return custom_cl... | 542,107 |
Initialize Class properties.
Args:
session (Request.Session): The preconfigured instance of Session for ThreatConnect API.
flush_limit (int): The limit to flush batch logs to the API. | def __init__(self, session, flush_limit=100):
super(TcExLogHandler, self).__init__()
self.session = session
self.flush_limit = flush_limit
self.entries = [] | 542,110 |
Initialize the Class properties.
Args:
tcex (object): Instance of TcEx. | def __init__(self, tcex):
self.tcex = tcex
# request
self._request = self.tcex.request(self.tcex.session)
# set default. can be overwritten for individual requests.
self._request.content_type = 'application/json'
# common
self._api_branch = None
... | 542,114 |
Add ThreatConnect API Filter for this resource request.
External Reference:
https://docs.threatconnect.com
Args:
name (string): The filter field name.
operator (string): The filter comparison operator.
value (string): The filter value. | def add_filter(self, name, operator, value):
self._filters.append({'name': name, 'operator': operator, 'value': value}) | 542,123 |
Add a key value pair to payload for this request.
.. Note:: For ``_search`` you can pass a search argument. (e.g. _search?summary=1.1.1.1).
Args:
key (string): The payload key
val (string): The payload value
append (bool): Indicate whether the value should be append... | def add_payload(self, key, val, append=False):
self._request.add_payload(key, val, append) | 542,124 |
The ID of the batch job used to push data and/or retrieve status.
Args:
batch_id (integer): The id of the batch job. | def batch_id(self, batch_id):
self._request_uri = '{}/{}'.format(self._api_uri, batch_id)
self._request_entity = 'batchStatus' | 542,147 |
Update the request URI to include the Indicator for specific indicator retrieval.
Args:
data (string): The indicator value | def indicator(self, data):
if self._name != 'Bulk' or self._name != 'Indicator':
self._request_uri = '{}/{}'.format(
self._api_uri, self.tcex.safe_indicator(data, 'ignore')
) | 542,148 |
Update the request URI to include the Indicator for specific indicator retrieval.
Overload to handle formatting of ipv6 addresses
Args:
data (string): The indicator value | def indicator(self, data):
try:
ip = ipaddress.ip_address(data)
except ValueError:
ip = ipaddress.ip_address(u'{}'.format(data))
if ip.version == 6:
data = ip.exploded
sections = []
# mangle perfectly good ipv6 address to match... | 542,153 |
Update request URI to return CSV data.
For onDemand bulk generation to work it must first be enabled in the
ThreatConnect platform under System settings.
Args:
ondemand (boolean): Enable on demand bulk generation. | def csv(self, ondemand=False):
self._request_uri = '{}/{}'.format(self._api_uri, 'csv')
self._stream = True
if ondemand:
self._request.add_payload('runNow', True) | 542,154 |
Update request URI to return JSON data.
For onDemand bulk generation to work it must first be enabled in the
ThreatConnect platform under System settings.
Args:
ondemand (boolean): Enable on demand bulk generation. | def json(self, ondemand=False):
self._request_entity = 'indicator'
self._request_uri = '{}/{}'.format(self._api_uri, 'json')
self._stream = True
if ondemand:
self._request.add_payload('runNow', True) | 542,155 |
Update the request URI to include the Indicator for specific indicator retrieval.
Args:
data (string): The indicator value | def indicator(self, data):
# handle hashes in form md5 : sha1 : sha256
data = self.get_first_hash(data)
super(File, self).indicator(data) | 542,156 |
Generate the appropriate dictionary content for POST of an File indicator
Args:
indicators (list): A list of one or more hash value(s). | def indicator_body(indicators):
hash_patterns = {
'md5': re.compile(r'^([a-fA-F\d]{32})$'),
'sha1': re.compile(r'^([a-fA-F\d]{40})$'),
'sha256': re.compile(r'^([a-fA-F\d]{64})$'),
}
body = {}
for indicator in indicators:
if indicat... | 542,157 |
Update the URI to retrieve file occurrences for the provided indicator.
Args:
indicator (string): The indicator to retrieve file occurrences. | def occurrence(self, indicator=None):
self._request_entity = 'fileOccurrence'
self._request_uri = '{}/fileOccurrences'.format(self._request_uri)
if indicator is not None:
self._request_uri = '{}/{}/fileOccurrences'.format(self._api_uri, indicator) | 542,158 |
Update the URI to retrieve host resolutions for the provided indicator.
Args:
indicator (string): The indicator to retrieve resolutions. | def resolution(self, indicator=None):
self._request_entity = 'dnsResolution'
self._request_uri = '{}/dnsResolutions'.format(self._request_uri)
if indicator is not None:
self._request_uri = '{}/{}/dnsResolutions'.format(self._api_uri, indicator) | 542,160 |
Update the request URI to include the Group ID for specific group retrieval.
Args:
resource_id (string): The group id. | def group_id(self, resource_id):
if self._name != 'group':
self._request_uri = '{}/{}'.format(self._api_uri, resource_id) | 542,161 |
Update the request URI to get the pdf for this resource.
Args:
resource_id (integer): The group id. | def pdf(self, resource_id):
self.resource_id(str(resource_id))
self._request_uri = '{}/pdf'.format(self._request_uri) | 542,162 |
Update the request URI to download the document for this resource.
Args:
resource_id (integer): The group id. | def download(self, resource_id):
self.resource_id(str(resource_id))
self._request_uri = '{}/download'.format(self._request_uri) | 542,163 |
Update the request URI to upload the a document to this resource.
Args:
resource_id (integer): The group id.
data (any): The raw data to upload. | def upload(self, resource_id, data):
self.body = data
self.content_type = 'application/octet-stream'
self.resource_id(str(resource_id))
self._request_uri = '{}/upload'.format(self._request_uri) | 542,164 |
Update the request URI to include the Tag for specific retrieval.
Args:
resource_id (string): The tag name. | def tag(self, resource_id):
self._request_uri = '{}/{}'.format(self._request_uri, self.tcex.safetag(resource_id)) | 542,167 |
Add an assignee to a Task
GET: /v2/tasks/{uniqueId}/assignees
GET: /v2/tasks/{uniqueId}/assignees/{assigneeId}
POST: /v2/tasks/{uniqueId}/assignees/{assigneeId}
DELETE: /v2/tasks/{uniqueId}/assignees/{assigneeId}
Args:
assignee (Optional [string]): The assignee name... | def assignees(self, assignee=None, resource_id=None):
if resource_id is not None:
self.resource_id(resource_id)
self._request_uri = '{}/assignees'.format(self._request_uri)
if assignee is not None:
self._request_uri = '{}/{}'.format(self._request_uri, assignee) | 542,169 |
Add an escalatee to a Task
GET: /v2/tasks/{uniqueId}/escalatees
GET: /v2/tasks/{uniqueId}/escalatees/{escalateeId}
POST: /v2/tasks/{uniqueId}/escalatees/{escalateeId}
DELETE: /v2/tasks/{uniqueId}/escalatees/{escalateeId}
Args:
escalatee (Optional [string]): The esca... | def escalatees(self, escalatee=None, resource_id=None):
if resource_id is not None:
self.resource_id(resource_id)
self._request_uri = '{}/escalatees'.format(self._request_uri)
if escalatee is not None:
self._request_uri = '{}/{}'.format(self._request_uri, escalat... | 542,170 |
Make the API request for a Data Store CRUD operation
Args:
domain (string): One of 'local', 'organization', or 'system'.
type_name (string): This is a free form index type name. The ThreatConnect API will use
this resource verbatim.
search_com... | def _request(self, domain, type_name, search_command, db_method, body=None):
headers = {'Content-Type': 'application/json', 'DB-Method': db_method}
search_command = self._clean_datastore_path(search_command)
url = '/v2/exchange/db/{}/{}/{}'.format(domain, type_name, search_command)
... | 542,171 |
Add a key value pair to payload for this request.
.. Note:: For ``_search`` you can pass a search argument. (e.g. _search?summary=1.1.1.1).
Args:
key (string): The payload key
val (string): The payload value
append (bool): Indicates whether the value should be appen... | def add_payload(self, key, val, append=True):
if append:
self._params.setdefault(key, []).append(val)
else:
self._params[key] = val | 542,172 |
Create entry in ThreatConnect Data Store
Args:
domain (string): One of 'local', 'organization', or 'system'.
type_name (string): This is a free form index type name. The ThreatConnect API will use
this resource verbatim.
search_command (string): Search comman... | def create(self, domain, type_name, search_command, body):
return self._request(domain, type_name, search_command, 'POST', body) | 542,173 |
Delete entry in ThreatConnect Data Store
Args:
domain (string): One of 'local', 'organization', or 'system'.
type_name (string): This is a free form index type name. The ThreatConnect API will use
this resource verbatim.
search_command (string): Search comman... | def delete(self, domain, type_name, search_command):
return self._request(domain, type_name, search_command, 'DELETE', None) | 542,174 |
Read entry in ThreatConnect Data Store
Args:
domain (string): One of 'local', 'organization', or 'system'.
type_name (string): This is a free form index type name. The ThreatConnect API will use
this resource verbatim.
search_command (string): Search command ... | def read(self, domain, type_name, search_command, body=None):
return self._request(domain, type_name, search_command, 'GET', body) | 542,175 |
Update entry in ThreatConnect Data Store
Args:
domain (string): One of 'local', 'organization', or 'system'.
type_name (string): This is a free form index type name. The ThreatConnect API will use
this resource verbatim.
search_command (string): Search comman... | def update(self, domain, type_name, search_command, body):
return self._request(domain, type_name, search_command, 'PUT', body) | 542,176 |
Updates the file content.
Args:
file_content: The file_content to upload.
update_if_exists:
Returns: | def file_content(self, file_content, update_if_exists=True):
if not self.can_update():
self._tcex.handle_error(910, [self.type])
self._data['fileContent'] = file_content
return self.tc_requests.upload(
self.api_type,
self.api_sub_type,
se... | 542,178 |
Updates the file_name.
Args:
file_name: | def file_name(self, file_name):
if not self.can_update():
self._tcex.handle_error(910, [self.type])
self._data['fileName'] = file_name
request = {'fileName': file_name}
return self.tc_requests.update(self.api_type, self.api_sub_type, self.unique_id, request) | 542,179 |
Uploads to malware vault.
Args:
malware:
password:
file_name: | def malware(self, malware, password, file_name):
if not self.can_update():
self._tcex.handle_error(910, [self.type])
self._data['malware'] = malware
self._data['password'] = password
self._data['fileName'] = file_name
request = {'malware': malware, 'password... | 542,180 |
Init Class properties.
Args:
_args (namespace): The argparser args Namespace. | def __init__(self, _args):
super(TcExValidate, self).__init__(_args)
# class properties
self._app_packages = []
self._install_json_schema = None
self._layout_json_schema = None
self.config = {}
if 'pkg_resources' in sys.modules:
# only set t... | 542,181 |
Check if module is in Python stdlib.
Args:
module (str): The name of the module to check.
Returns:
bool: Returns True if the module is in the stdlib or template. | def check_import_stdlib(module):
if (
module in stdlib_list('2.7') # pylint: disable=R0916
or module in stdlib_list('3.4')
or module in stdlib_list('3.5')
or module in stdlib_list('3.6')
or module in stdlib_list('3.7')
or module i... | 542,183 |
Check whether the provide module can be imported (package installed).
Args:
module (str): The name of the module to check availability.
Returns:
bool: True if the module can be imported, False otherwise. | def check_imported(module):
imported = True
module_info = ('', '', '')
# TODO: if possible, update to a cleaner method that doesn't require importing the module
# and running inline code.
try:
importlib.import_module(module)
module_info = imp.find... | 542,184 |
Run syntax on each ".py" and ".json" file.
Args:
app_path (str, optional): Defaults to None. The path of Python files. | def check_syntax(self, app_path=None):
app_path = app_path or '.'
for filename in sorted(os.listdir(app_path)):
error = None
status = True
if filename.endswith('.py'):
try:
with open(filename, 'rb') as f:
... | 542,188 |
Initialize class properties.
Args:
tcex (object): An instance of TcEx.
domain (): [description]
data_type ([type]): [description]
ttl_minutes (int, optional): Defaults to None. Number of minutes the cache is valid.
mapping ([type], optional): Defaults... | def __init__(self, tcex, domain, data_type, ttl_minutes=None, mapping=None):
self.tcex = tcex
# properties
self.ttl = None
if ttl_minutes is not None:
self.ttl = self._dt_to_epoch(datetime.now() - timedelta(minutes=int(ttl_minutes)))
self.ds = self.tcex.data... | 542,195 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.