Module: Batch

Important

The Batch module requires ThreatConnect version 5.6 or higher.

The ThreatConnect TcEx Framework provides the Batch module to create, delete, and update both Groups and Indicators in the ThreatConnect platform. The App developer can dynamically build data objects, and the Batch module will write the data to the ThreatConnect API.

External ID (xid)

The batch JSON data requires an xid value for all Groups and Indicators. The xid is used internally in ThreatConnect for associations and for updating existing Groups. The xid must be unique for the entire instance of ThreatConnect.

The TcExBatch module provides the generate_xid() method to assist in generating two types of xid. The first type is a unique xid based on UUID4. No input is required to produce a unique xid. The second type is a unique and reproducible xid value. This is the preferred xid type, as it allows a Group to have the same xid on subsequent runs of the App. To generate a unique and reproducible xid, either a string or array of value can be passed to the method (e.g., myapp-adversary-5 or [‘myapp’, ‘adversary’, ‘222’]).

For Interface 1 and 2, the xid is optional; if not provided, a unique xid (UUID4) will be auto-generated. A string value can also be passed if the xid is a known value (e.g., the id field from a remote source). Passing in an xid, when possible, is best practice and allows Groups and Indicators to be easily updated.

Important

It is best practice to provide a unique and reproducible xid value when creating Groups. If the xid created for a new Group matches the xid for an existing Group, the existing Group will be overwritten.

Groups

Note

In all of the examples below, the code to create the content is removed. Read more on how to create the content in the Submit section.

There are three interfaces to add Group Threat Intelligence data to the Batch Module.

Group Interface 1

The first interface is for type-specific access. This interface allows for passing of all the data in the method call or of only the required fields, with optional fields being set via property setters. All metadata (e.g., Attributes, Security Labels, and Tags) can be added to the group instance directly.

The example below passes all supported fields to the adversary() method.

1batch = tcex.batch('MyOrg')
2adversary = batch.adversary('adversary-001', xid='my-xid-000')
3adversary.attribute('Description', 'Example Description', True)
4adversary.tag('Example Tag')
5adversary.security_label('TLP Green')
6# optional save method
7batch.save(adversary)

The example below passes only the required fields to document(). The optional properties can then be set whenever required. The same interface is used for the Attribute. The required Attribute properties are set first, and then optional values can be added.

 1batch = tcex.batch('MyOrg')
 2document = batch.document('document-001', 'example.txt')
 3document.malware = True
 4document.password = 'test'
 5document.file_content = 'example file content'
 6# Add Attribute
 7attr = document.attribute('Description', 'Example Description')
 8attr.displayed = True
 9# Add Tag
10document.tag('Example Tag')
11# Add Label
12label = document.security_label('My Label')
13label.color = 'ffffff'
14label.description = 'Security label description.'
15# optional save method
16batch.save(document)

Note

The optional batch.save() method will write the Group or Indicator to disk. When processing large amounts of data, this is the preferred method in order to save on the memory usage of the App.

Important

The file_content parameter for Documents and Reports will accept multiple types of data as well as a callback method. The callback method will be passed in the xid of the Documents and Reports and expects a single response containing the contents of the file. If loading a large number of Documents, it is best practice to not load the contents in memory, but instead to use the callback method so that the files can be processed one at a time.

Group Interface 2

The second and more dynamic interface uses the more generic group() method. In this interface the Group type, Group name, and optional xid are the only allowed fields. For a type-specific field, such as eventDate for an Event Group, the add_key_value() method is available. The field name must be exactly what the batch API expects (which are listed here). Added metadata behaves the same as in Interface 1.

1batch = tcex.batch('MyOrg')
2event = batch.group('Event', 'My event name', date_added='2008-12-12T12:12:12', xid='my-xid-0001')
3event.add_key_value('eventDate', 'yesterday')
4event.add_key_value('status', 'Needs Review')
5event.attribute('Description', 'Example Description 2', True, 'source')
6event.tag('Example Tag')

The code below demonstrates how to create a Document using this interface (and the same principle applies for Reports and any other Groups to which file contents can be added):

1batch = tcex.batch('MyOrg')
2document = batch.group('Document', 'document-001', xid='my-xid-0001')
3document.add_file('test.txt', 'Document content here...')
4document.add_key_value('fileName', 'test.txt')
5document.attribute('Description', 'Example Description', True, 'Attribute source')
6document.tag('Example Tag')
7document.security_label('TLP Green')

Group Interface 3

The third interface accepts the raw data formatted as a dictionary. This method requires that an xid be provided. All metadata should be included with in the JSON object. View the required fields for each group type here.

 1batch = tcex.batch('MyOrg')
 2xid = batch.generate_xid(['my', 'adversary', '123'])
 3batch.add_group({
 4    'name': 'document-002',
 5    'fileName': 'test2.txt',
 6    'fileContent': 'example content 2',
 7    'type': 'Document',
 8    'xid': xid,
 9    "associatedGroupXid": [
10        "my-xid-001"
11    ],
12    'attribute': [{
13        "displayed": True,
14        "type": "Description",
15        "value": "Example Description"
16    }],
17    'tag': [{
18        'name': 'SafeToDelete'
19    }]
20})

Indicators

There are three interfaces to add Indicator Threat Intelligence data to the Batch Module.

Indicator Interface 1

The first interface is for type-specific access. This interface allows for passing of all the data in the method call or of only the required fields, with optional fields being set via property setters. All metadata (e.g., Attributes, Security Labels, Associations, and Tags) can be added to the Indicator instance directly.

1batch = tcex.batch('MyOrg')
2address = batch.address('123.124.125.126', rating='5.0', confidence='100')
3address.attribute('Description', 'Example Description', True)
4address.tag('Example Tag')
5address.security_label('TLP Green')
6address.association('the_xid_of_pre_existing_group')
 1batch = tcex.batch('MyOrg')
 2file_hash = batch.file('43c3609411c83f363e051d455ade78a6')
 3file_hash.rating = 5.0
 4file_hash.confidence = 100
 5# Add Attribute
 6attr = file_hash.attribute('Description', 'Example Description')
 7attr.displayed = True
 8# Tag
 9file_hash.tag('Example Tag')
10# Add Label
11label = file_hash.security_label('My Label')
12label.color = 'ffffff'
13label.description = 'Security label description.'
14# Add Occurrence
15occurrence = file_hash.occurrence()
16occurrence.file_name = 'drop1.exe'
17occurrence.path = 'C:\\test\\'
18occurrence.date = '2017-02-02 01:02:03'
19# Add Association
20pre_existing_group_xid = 'the_xid_of_pre_existing_group'
21file_hash.association(pre_existing_group_xid)

Indicator Interface 2

The second and more dynamic interface uses the more generic indicator() method. In this interface, the Indicator type, Indicator value, optional rating, optional confidence, and optional xid are the only allowed fields. For a type-specific field, such as size for a File Indicator, the add_key_value() method is available. The field name must be exactly what the batch API expects (which are listed here). Added metadata behaves the same as in Interface 1.

1batch = tcex.batch('MyOrg')
2host = batch.indicator('Host', 'www.badguys2.com', rating='5.0', confidence='100')
3host.add_key_value('dnsActive', True)
4host.add_key_value('whoisActive', True)
5host.attribute('Description', 'Example Description 2', True, 'source')
6host.tag('Example Tag')
7# Add association
8pre_existing_group_xid = 'the_xid_of_pre_existing_group'
9host.association(pre_existing_group_xid)

Note

The case of the Indicator type (the first argument provided to the batch.indicator() function) should be the same as the name key provided when retrieving the Indicator types.

Indicator Interface 3

The third interface accepts the raw data formatted as a dictionary. This method requires that an xid be provided. All metadata should be included with in the data. View the required fields for each Indicator type here.

 1batch = tcex.batch('MyOrg')
 2batch.add_indicator({
 3    "type": "File",
 4    "rating": 5.00,
 5    "confidence": 50,
 6    "summary": "53c3609411c83f363e051d455ade78a7 : 57a49b478310e4313c54c0fee46e4d70a73dd580 : db31cb2a748b7e0046d8c97a32a7eb4efde32a0593e5dbd58e07a3b4ae6bf3d7",
 7    "associatedGroups": [
 8        {
 9            "groupXid": "e336e2dd-5dfb-48cd-a33a-f8809e83e904"
10        }
11    ],
12    "attribute": [{
13        "type": "Source",
14        "displayed": True,
15        "value": "Malware Analysis provided by external AMA."
16    }],
17    "fileOccurrence": [{
18        "fileName": "drop1.exe",
19        "date": "2017-03-03T18:00:00-06:00"
20    }],
21    "tag": [{
22        "name": "China"
23    }],
24    "xid": "e336e2dd-5dfb-48cd-a33a-f8809e83e904:170139"
25})

File Occurrence

1# <... snipped>
2file_hash.occurrence('drop1.exe', 'C:\\test\\', '2017-02-02 01:02:03')
3# <snipped ...>
1# <... snipped>
2occurrence = file_hash.occurrence()
3occurrence.file_name = 'drop1.exe'
4occurrence.path = 'C:\\test\\'
5occurrence.date = '2017-02-02 01:02:03'
6# <snipped ...>

Associations

Associations are supported as Group -> Group or Indicator -> Group. For Interface 1 or 2, the behavior is the same as that for Group and Indicators. However, for Interface ,3 the structure is slightly different, as displayed below.

Group

Example of Group -> Group Association.

1{
2    "name": "document-002",
3    "type": "Document",
4    "xid": "my-xid-002",
5    "associatedGroupXid": [
6        "my-xid-001"
7    ]
8}

Indicator

Example of Indicator -> Group Association.

1{
2    "associatedGroups": [{
3        "groupXid": "my-xid-001"
4    }],
5    "summary": "HKEY_LOCAL_MACHINE\system : TRUE : REG_DWORD",
6    "type": "Registry Key",
7    "xid": "ba60d2d6-8049-4080-9c5c-2b33d8d97767"
8}

Submit

There are few options for submitting the batch job, all with an option to halt_on_error. The most common option, submit_all(), provides a simple interface that will perform all the individual step by default (e.g., request create and upload, poll for status, retrieve errors, and submit files). When using this method, it is possible to control the halt_on_error behavior for each step using global overrides.

 1batch = tcex.batch('MyOrg')
 2# defaults to true or uses the provided value passed to the submit method. this value controls the behavior
 3# for errors when creating batch job and submitting the data.
 4batch.halt_on_batch_error = False
 5
 6# defaults to true or uses the provided value passed to the submit method. this value controls the behavior
 7# for errors when submitting files. if set to True a single file upload error would cause the batch module
 8# to raise and exception and potentially cause the job to fail.
 9batch.halt_on_file_error = False
10
11# defaults to true or uses the provided value passed to the submit method. this value controls the behavior
12# for errors when polling batch status.
13batch.halt_on_poll_error = False
14
15if errors:
16    tcex.exit(1, 'Errors during Batch: {}'.format(errors))

In some cases, handling errors may require more control. For these cases the submit method can be called with some or all of the additional features (e.g., polling, retrieving errors, and uploading files) disabled. It is also possible to call each method individually. A possible workflow could be to use submit_create_and_upload() and then to retrieve data from a remote endpoint while ThreatConnect processes the batch job. Next, poll by using poll() for status, and when the job is completed, the next job request can be submitted. If batch errors are reported in the Batch status, the errors() method can be used to retrieve the errors. Submitting files for Documents and Reports can be done using the submit_files() method.

Note

The synchronousBatchSaveLimit setting, configured in the System Settings screen, which is accessed in the ThreatConnect UI, controls the synchronous processing of batch jobs. If the batch job is smaller than the defined value, the batch data will be processed synchronously, and the batch status will be returned on completion without the need to poll. The submit() method provides logic for handling this so that the developer is not required to check if the job was queued.

Option 1

Submit the job and wait for completion. In the example below, any error messages are requested to be returned as well.

1batch_data = batch.submit_all()
2errors = []
3[errors.extend(d.get('errors', [])) for d in batch_data if d.get('errors', None)]
4if errors:
5    tcex.exit(1, 'Errors during Batch: {}'.format(errors))

Option 2

Call each step in submitting the batch job manually. A check for batch_id will indicate whether the job was processed asynchronously.

 1# submit batch job create and upload request
 2batch_data = batch.submit_create_and_upload().get('data').get('batchStatus')
 3
 4# check if job requires polling
 5batch_id = batch_data.get('id')
 6if batch_id is not None:
 7    # poll for batch status
 8    batch_status = batch.poll(batch_id)
 9
10    # check for errors
11    if batch_status.get('data', {}).get('batchStatus', {}).get('errorCount', 0) > 0:
12        # retrieve errors
13        errors = batch.errors(batch_id)
14        print(errors)
15
16# submit any documents or reports
17upload_status = batch.submit_files()