### Create Post Example Source: https://docs.threatconnect.com/en/latest/rest_api/v3/posts/posts.html Example request and response for creating a new post. ```http POST /v3/posts Content-Type: application/json { "text": "A third post about Bad Guy", "objectType": "Group", "objectId" : 12345 } ``` ```json { "data": { "id": 30, "owner": "Demo Organization", "ownerId": 1, "name": "Indicator-Address-IPv6", "description": "1 fixed, 1 variable", "active": true, "managed": false }, "message": "Created", "status": "Success" } ``` -------------------------------- ### Install ThreatConnect SDK Source: https://docs.threatconnect.com/en/latest/_sources/python/quick_start.rst.txt Use pip to install the package. Escalated privileges may be required depending on your environment. ```shell pip install threatconnect ``` -------------------------------- ### Update Victim Example Request Source: https://docs.threatconnect.com/en/latest/rest_api/v3/victims/victims.html A specific example demonstrating how to update a Victim's name, add a website asset, and replace security labels. ```http PUT /v3/victims/2 Content-Type: application/json { "assets": { "data": [ { "website": "evilll.com", "type": "WebSite" } ] }, "name": "Jane Doe", "securityLabels": { "data": [ { "name": "TLP:RED" } ], "mode": "replace" } } ``` -------------------------------- ### LEEF Output Format Source: https://docs.threatconnect.com/en/latest/_sources/python/advanced.rst.txt Example output format for the leef method. ```text LEEF:0|threatconnect|threatconnect|2|355999|confidence="14" devTime="2015-06-21T10:40:33-05:00" description="TEST attribute #14" dnsActive="None" hostName="www.badguy_014.com" id="355999" lastModified="2015-06-21T10:40:33-05:00" ownerName="Example Community" severity="1.0" type="None" weblink="https://tc.sumx.us/auth/indicators/details/host.xhtml?host=www.badguy_014.com&owner=Example+Community" whoisActive="None" ``` -------------------------------- ### Display tcinit help information Source: https://docs.threatconnect.com/en/latest/_sources/tcex/building_apps_tcinit.rst.txt Run this command to view available templates and command-line arguments. ```bash usage: tcinit [-h] [--branch BRANCH] [--layout] [--migrate] [--update] [--template {external,external_ingress,job,job_batch,playbook,playbook_actions,playbook_utility,service_api,service_trigger,service_webhook}] optional arguments: -h, --help show this help message and exit --branch BRANCH Git branch. --layout Create a layout.json file. --migrate Enable this flag to migrate an existing App. --update Enable this flag to update an existing App. --template {external,external_ingress,job,job_batch,playbook,playbook_actions,playbook_utility,service_api,service_trigger,service_webhook} Choose an appropriate App template for the current project. ``` -------------------------------- ### GET /tc_taxii/collections Request Source: https://docs.threatconnect.com/en/latest/_sources/rest_api/taxii/taxii_2.1.rst.txt Example cURL request to retrieve TAXII 2.1 collections. ```bash curl --location --request GET '{baseUrl}{taxiiServicePath}/tc_taxii/collections' \ --header 'Accept: application/taxii+json;version=2.1' \ --header 'Authorization: Basic {credentials}' ``` -------------------------------- ### GET /tc_taxii JSON Response Source: https://docs.threatconnect.com/en/latest/_sources/rest_api/taxii/taxii_2.1.rst.txt Example JSON response for the API root request. ```json { "description": "This TAXII 2.1 server contains Indicators of Compromise from the ThreatConnect API Root.", "max_content_length": 100, "title": "ThreatConnect TAXII 2.1 Server API Root", "versions": [ "application/taxii+json;version=2.1" ] } ``` -------------------------------- ### Initialize a new App project Source: https://docs.threatconnect.com/en/latest/_sources/tcex/building_apps_quickstart.rst.txt Installs the TcEx package and uses the tcinit command to scaffold a new playbook utility App. ```bash pip install tcex mkdir TCPB_-_JsonPretty cd TCPB_-_JsonPretty tcinit --action create --template playbook_utility ``` -------------------------------- ### Initialize SDK and Retrieve Owners Source: https://docs.threatconnect.com/en/latest/_sources/python/quick_start.rst.txt Example script to read configuration, initialize the ThreatConnect client, and list accessible owners. ```python try: import ConfigParser except: import configparser as ConfigParser import sys from threatconnect import ThreatConnect config = ConfigParser.RawConfigParser() config.read('./tc.conf') try: api_access_id = config.get('threatconnect', 'api_access_id') api_secret_key = config.get('threatconnect', 'api_secret_key') api_default_org = config.get('threatconnect', 'api_default_org') api_base_url = config.get('threatconnect', 'api_base_url') except ConfigParser.NoOptionError: print('Could not read configuration file.') sys.exit(1) tc = ThreatConnect(api_access_id, api_secret_key, api_default_org, api_base_url) # instantiate Owners object owners = tc.owners() try: # retrieve the Owners owners.retrieve() except RuntimeError as e: print('Error: {0}'.format(e)) sys.exit(1) # iterate through the Owners for owner in owners: print(owner.id) print(owner.name) print(owner.type) print('') ``` -------------------------------- ### GET /tc_taxii Request Source: https://docs.threatconnect.com/en/latest/_sources/rest_api/taxii/taxii_2.1.rst.txt Example cURL request to retrieve the TAXII 2.1 API root. ```bash curl --location --request GET '{baseUrl}{taxiiServicePath}/tc_taxii' \ --header 'Accept: application/taxii+json;version=2.1' \ --header 'Authorization: Basic {credentials}' ``` -------------------------------- ### Key-Value Output Format Source: https://docs.threatconnect.com/en/latest/_sources/python/advanced.rst.txt Example output format for the keyval method. ```text confidence="14" dateAdded="2015-06-21T10:40:33-05:00" description="TEST attribute #14" dnsActive="None" hostName="www.badguy_014.com" id="355999" lastModified="2015-06-21T10:40:33-05:00" ownerName="Example Community" rating="1.0" type="None" weblink="https://tc.sumx.us/auth/indicators/details/host.xhtml?host=www.badguy_014.com&owner=Example+Community" whoisActive="None" ``` -------------------------------- ### Initialize a new App Source: https://docs.threatconnect.com/en/latest/_sources/tcex/building_apps_tcinit.rst.txt Execute this command within the project directory to scaffold a new App using a specific template. ```bash tcinit --template playbook_utility ``` -------------------------------- ### GET /api/v3/jobs Source: https://docs.threatconnect.com/en/latest/_sources/rest_api/v3/jobs/jobs.rst.txt Retrieve a list of available Jobs associated with installed TC Exchange™ Apps. ```APIDOC ## GET /api/v3/jobs ### Description Retrieve a list of Jobs that perform actions supported by installed TC Exchange™ Apps. ### Method GET ### Endpoint /api/v3/jobs ``` -------------------------------- ### Install Dependencies on Linux Source: https://docs.threatconnect.com/en/latest/_sources/javascript/javascript_sdk.rst.txt Commands to create a library directory and copy necessary CryptoJS files for the SDK. ```shell mkdir lib unzip CryptoJS\ v3.1.2.zip cp CyrptoJS\ v3.1.2/enc-base-64.js lib/ cp CyrptoJS\ v3.1.2/hmac-sha256.js lib/ cp CyrptoJS\ v3.1.2/sha256.js lib/ ``` -------------------------------- ### Retrieve Intelligence Reviews for a Group Source: https://docs.threatconnect.com/en/latest/rest_api/v3/groups/groups.html Example of a GET request to retrieve a specific Group including its associated Intelligence Reviews. ```http GET /v3/groups/216456?fields=intelReviews ``` -------------------------------- ### Intelligence Requirement Response Object Source: https://docs.threatconnect.com/en/latest/rest_api/v3/intelligence_requirements/intelligence_requirements.html Example JSON structure returned by successful GET, POST, and PUT requests to the /v3/intelRequirements endpoint. ```json { "id": 0, "xid": "", "createdBy": { "id": 0, "userName": "", "firstName": "", "lastName": "", "pseudonym": "", "owner": "" }, "lastModified": "", "webLink": "", "dateAdded": "", "uniqueId": "", "requirementText": "", "subtype": { "name": "", "description": "" }, "category": { "name": "", "description": "" }, "description": "", "keywordSections": [ { "compareValue": "", "keywords": [ { "value": "" } ] } ], "resultsLink": "", "earliestTimestamp": "", "latestTimestamp": "", "active": true } ``` -------------------------------- ### Initialize Datastore Instance Source: https://docs.threatconnect.com/en/latest/_sources/tcex/module_datastore.rst.txt Create a Datastore instance specifying the domain and data type. ```python ds = self.tcex.datastore('local', 'myDnsData') ``` -------------------------------- ### Example Configuration Data Source: https://docs.threatconnect.com/en/latest/_sources/tcex/building_apps_tcinit.rst.txt JSON structure for configuring an external App, including API credentials and proxy settings. ```javascript { "api_access_id": "API_ACCESS_ID", "api_default_org": "API_DEFAULT_ORG", "api_secret_key": "API_SECRET_KEY", "tc_api_path": "TC_API_PATH", "tc_log_level": "debug", "tc_log_path": "log", "tc_owner": "MyOwner", "tc_proxy_host": "TC_PROXY_HOST", "tc_proxy_password": "TC_PROXY_PASSWORD", "tc_proxy_port": "TC_PROXY_PORT", "tc_proxy_tc": false, "tc_proxy_username": "TC_PROXY_USERNAME" } ``` -------------------------------- ### GET /tc_taxii/collections JSON Response (App Version 2.0) Source: https://docs.threatconnect.com/en/latest/_sources/rest_api/taxii/taxii_2.1.rst.txt Example JSON response for collections when using App Version 2.0. ```json { "collections": [ { "can_read": true, "can_write": false, "description": null, "id": "a1a1a1a1-a1a1-a1a1-a1a1-a1a1a1a1a1a1", "media_types": [ "application/taxii+json; version=2.1" ], "title": "Demo Organization", "alias": null, "type": null, "x_custom_mappings": {}, "x_custom_ttl": {}, "x_custom": false, "x_tql": "(ownerName EQ \"Demo Organization\") AND typeName in (\"Registry Key\", \"Host\", \"File\", \"EmailAddress\", \"Address\", \"Email Subject\", \"CIDR\", \"ASN\", \"URL\")" }, { "can_read": true, "can_write": false, "description": null, "id": "b2b2b2b2-b2b2-b2b2-b2b2-b2b2b2b2b2b2", "media_types": [ "application/taxii+json; version=2.1" ], "title": "Demo Source", "alias": null, "type": null, "x_custom_mappings": {}, "x_custom_ttl": {}, "x_custom": false, "x_tql": "(ownerName EQ \"Demo Source\") AND typeName in (\"Registry Key\", \"Host\", \"File\", \"EmailAddress\", \"Address\", \"Email Subject\", \"CIDR\", \"ASN\", \"URL\")" } ] } ``` -------------------------------- ### Retrieve Data for Objects in a Community or Source Source: https://docs.threatconnect.com/en/latest/_sources/rest_api/v3/specify_owner.rst.txt Example of a GET request to retrieve group data filtered by a specific owner name. ```http GET /v3/groups?owner=Demo%20Community ``` -------------------------------- ### Initialize Key-Value Store Source: https://docs.threatconnect.com/en/latest/_modules/tcex/tcex.html Determines and returns the appropriate key-value store implementation based on configuration. ```python @registry.factory('KeyValueStore') @scoped_property def key_value_store(self) -> Union['KeyValueApi', 'KeyValueRedis']: """Return the correct KV store for this execution. The TCKeyValueAPI KV store is limited to two operations (create and read), while the Redis kvstore wraps a few other Redis methods. """ if self.inputs.model_unresolved.tc_kvstore_type == 'Redis': return KeyValueRedis(self.redis_client) if self.inputs.model_unresolved.tc_kvstore_type == 'TCKeyValueAPI': return KeyValueApi(self.session_tc) if self.inputs.model_unresolved.tc_kvstore_type == 'Mock': self.log.warning( 'Using mock key-value store. ' 'This should *never* happen when running in-platform.' ) return KeyValueMock() raise RuntimeError( f'Invalid KV Store Type: ({self.inputs.model_unresolved.tc_kvstore_type})' ) ``` -------------------------------- ### Delete Case Example Source: https://docs.threatconnect.com/en/latest/rest_api/v3/case_management/cases/cases.html An example request to delete a case with the ID of 1. ```http DELETE /v3/cases/1 ``` -------------------------------- ### Delete Group Example Source: https://docs.threatconnect.com/en/latest/rest_api/v3/groups/groups.html Example request to delete a specific group with ID 1. ```http DELETE /v3/groups/1 ``` -------------------------------- ### Bulk Indicator Download Example Source: https://docs.threatconnect.com/en/latest/python/indicators/indicators.html Demonstrates how to initialize the ThreatConnect object, apply filters and post-filters, and iterate through retrieved indicator data. ```python from threatconnect.Config.FilterOperator import FilterOperator # replace the line below with the standard, TC script heading described here: # https://docs.threatconnect.com/en/latest/python/quick_start.html#standard-script-heading ... tc = ThreatConnect(api_access_id, api_secret_key, api_default_org, api_base_url) # Bulk Indicator object indicators = tc.bulk_indicators() owner = 'Example Community' # add a Filter and Post Filters try: filter1 = indicators.add_filter() filter1.add_owner(owner) # only download Indicators with a confidence rating greater than or equal to 75 filter1.add_pf_confidence(75, FilterOperator.GE) # only download Indicators with a threat rating greater than 2.5 filter1.add_pf_rating('2.5', FilterOperator.GT) except AttributeError as e: print(e) sys.exit(1) try: # retrieve the Indicators indicators.retrieve() except RuntimeError as e: print(e) sys.exit(1) # iterate through the results for indicator in indicators: # if the Indicator is a File Indicator or custom Indicator, print it out appropriately if isinstance(indicator.indicator, dict): for indicator_type, indicator_value in indicator.indicator.items(): print('{0}: {1}'.format(indicator_type, indicator_value)) else: print(indicator.indicator) print(indicator.id) print(indicator.owner_name) print(indicator.date_added) print(indicator.last_modified) print(indicator.rating) print(indicator.threat_assess_rating) print(indicator.confidence) print(indicator.threat_assess_confidence) print(indicator.type) print(indicator.weblink) ``` -------------------------------- ### Delete Victim Example Source: https://docs.threatconnect.com/en/latest/rest_api/v3/victims/victims.html A concrete example of a request to delete a Victim with ID 1. ```http DELETE /v3/victims/1 ``` -------------------------------- ### Initialize Indicators for Key Value Export Source: https://docs.threatconnect.com/en/latest/_sources/python/advanced.rst.txt Setup code for retrieving indicators to be processed as key-value pairs. ```python # replace the line below with the standard, TC script heading described here: # https://docs.threatconnect.com/en/latest/python/quick_start.html#standard-script-heading ... tc = ThreatConnect(api_access_id, api_secret_key, api_default_org, api_base_url) # instantiate Indicators object indicators = tc.indicators() owner = 'Example Community' ``` -------------------------------- ### Retrieve a Specific Post Example Source: https://docs.threatconnect.com/en/latest/rest_api/v3/posts/posts.html Example request and response for fetching post ID 2. ```http GET /v3/posts/2 ``` ```json { "data": { "id": 2, "author": { "id": 3, "userName": "11112222333344445555", "firstName": "John", "lastName": "Smith", "pseudonym": "jsmithAPI", "owner": "Demo Organization" }, "authorType": "full", "dateAdded": "2026-01-11T16:54:55Z", "text": "Another post about Bad Guy", "linkedItems": [ { "id": "B12345", "type": "Adversary", "display": "Bad Guy", "owner": "Demo Organization" } ], "deleteAvailable": true }, "status": "Success" } ``` -------------------------------- ### Create a Case with Artifacts and Tags Source: https://docs.threatconnect.com/en/latest/rest_api/v3/case_management/cases/cases.html Example of creating a case with specific assignments, artifacts linked to indicators, and ATT&CK tags. ```JSON POST /v3/cases Content-Type: application/json { "artifacts": { "data": [ { "summary": "badguy.com", "type": "Host", "associatedIndicators": { "data": [ { "id": "2" } ] } } ] }, "assignee": { "type": "User", "data": { "userName": "smithj@threatconnect.com" } }, "name": "Phishing Investigation", "severity": "Low", "status": "Open", "tags": { "data": [ { "techniqueId": "T1566" } ] } } ``` -------------------------------- ### Define install.json for a Python App Source: https://docs.threatconnect.com/en/latest/deployment_config.html This JSON configuration file specifies the program version, language, main entry point, and required input parameters for the application. ```json 1{ 2 "programVersion": "1.0.0", 3 "programLanguage": "PYTHON", 4 "programMain": "auto_enrich", 5 "languageVersion": "2.7", 6 "runtimeLevel": "Organization", 7 "allowOnDemand": true, 8 "params": [{ 9 "name": "api_access_id", 10 "label": "Local ThreatConnect API Access ID", 11 "sequence": 1, 12 "required": true, 13 "validValues": ["${USER:TEXT}", "${ORGANIZATION:TEXT}"] 14 }, { 15 "name": "api_secret_key", 16 "label": "Local ThreatConnect API Secret Key", 17 "sequence": 2, 18 "encrypt": true, 19 "required": true, 20 "validValues": ["${USER:KEYCHAIN}", "${ORGANIZATION:KEYCHAIN}"] 21 }, { 22 "name": "owner", 23 "label": "Destination Owner", 24 "sequence": 3, 25 "required": true, 26 "type": "choice", 27 "validValues": ["${OWNERS}"] 28 }, { 29 "name": "remote_api_access_id", 30 "label": "Remote ThreatConnect API Access ID", 31 "sequence": 4, 32 "required": true, 33 "validValues": ["${USER:TEXT}", "${ORGANIZATION:TEXT}"] 34 }, { 35 "name": "remote_api_secret_key", 36 "label": "Remote ThreatConnect API Secret Key", 37 "sequence": 5, 38 "encrypt": true, 39 "required": true, 40 "validValues": ["${USER:KEYCHAIN}", "${ORGANIZATION:KEYCHAIN}"] 41 }, { 42 "name": "remote_api_path", 43 "label": "Remote ThreatConnect API Path", 44 "sequence": 6, 45 "required": true, 46 "default": "https://api.threatconnect.com", 47 "validValues": ["${USER:TEXT}", "${ORGANIZATION:TEXT}"] 48 }, { 49 "name": "remote_owner", 50 "label": "Remote Owner", 51 "sequence": 7, 52 "required": true 53 }, { 54 "name": "apply_threat_assess_rating", 55 "label": "Apply ThreatAssessRating from Remote Owner", 56 "type": "Boolean", 57 "sequence": 8 58 }, { 59 "name": "apply_rating", 60 "label": "Apply Rating from Remote Owner if ThreatAssessRating is not Available ", 61 "type" : "Boolean", 62 "sequence" : 9 63 }, { 64 "name": "apply_threat_assess_confidence", 65 "label": "Apply ThreatAssessConfidence from Remote Owner", 66 "type": "Boolean", 67 "sequence": 10 68 }, { 69 "name": "apply_confidence", 70 "label": "Apply Confidence from Remote Owner if ThreatAssessConfidence is not Available", 71 "type" : "Boolean", 72 "sequence": 11 73 }, { 74 "name": "apply_tags", 75 "label": "Apply Tags from Remote Owner", 76 "type": "Boolean", 77 "sequence": 12 78 }, { 79 "name": "apply_auto_enrich_tag", 80 "label": "Apply 'AutoEnriched' Tag", 81 "type": "Boolean", 82 "sequence": 13 83 }, { 84 "name": "apply_proxy_tc", 85 "label": "Apply Proxy to Local API Connection", 86 "type": "Boolean", 87 "sequence": 14, 88 "default": false 89 }, { 90 "name": "apply_proxy_ext", 91 "label": "Apply Proxy to Remote API Connection", 92 "type": "Boolean", 93 "sequence": 15, 94 "default": false 95 }, { 96 "name": "logging", 97 "label": "Logging Level", 98 "sequence": 16, 99 "default": "info", 100 "type": "choice", 101 "validValues": ["debug", "info", "warning", "error", "critical"] 102 }] 103} ``` -------------------------------- ### Delete Group Attribute Example Source: https://docs.threatconnect.com/en/latest/rest_api/v3/group_attributes/group_attributes.html An example request to delete a Group Attribute with the ID of 10. ```http DELETE /v3/groupAttributes/10 ``` -------------------------------- ### Retrieve Case Example Request Source: https://docs.threatconnect.com/en/latest/rest_api/v3/case_management/cases/cases.html An example request to retrieve data for the Case with ID 3. ```http GET /v3/cases/3 ``` -------------------------------- ### Initialize Playbook Module Source: https://docs.threatconnect.com/en/latest/_modules/tcex/tcex.html Returns an instance of the Playbooks module. ```python @registry.factory(Playbook) @scoped_property def playbook(self) -> 'Playbook': """Return an instance of Playbooks module. This property defaults context and outputvariables to arg values. """ ``` -------------------------------- ### Delete Victim Attribute Example Source: https://docs.threatconnect.com/en/latest/rest_api/v3/victim_attributes/victim_attributes.html An example request to delete a specific victim attribute with ID 1. ```http DELETE /v3/victimAttributes/1 ``` -------------------------------- ### Initialize Playbook Module Source: https://docs.threatconnect.com/en/latest/_modules/tcex/tcex.html Returns a new instance of the Playbook module, optionally specifying context and output variables. ```python [docs] def get_playbook( self, context: Optional[str] = None, output_variables: Optional[list] = None ) -> 'Playbook': """Return a new instance of playbook module. Args: context: The KV Store context/session_id. For PB Apps the context is provided on startup, but for service Apps each request gets a different context. output_variables: The requested output variables. For PB Apps outputs are provided on startup, but for service Apps each request gets different outputs. """ return Playbook(self.key_value_store, context, output_variables) ``` -------------------------------- ### REST API Incident Pagination Example Source: https://docs.threatconnect.com/en/latest/rest_api/overview.html A concrete example of retrieving a specific range of incident records. ```http /v2/groups/incidents?resultStart=0&resultLimit=50 ``` -------------------------------- ### Reference TEXT variables in install.json Source: https://docs.threatconnect.com/en/latest/_sources/deployment_config.rst.txt Use this format to allow users to select plain-text variables from Organization and User levels. ```json "validValues": ["${USER:TEXT}", "${ORGANIZATION:TEXT}"] ``` -------------------------------- ### Delete Intelligence Requirement Example Source: https://docs.threatconnect.com/en/latest/rest_api/v3/intelligence_requirements/intelligence_requirements.html Example request to delete an IR with ID 10 and the corresponding success response. ```http DELETE /v3/intelRequirements/10 ``` ```json { "message": "Deleted", "status": "Success" } ``` -------------------------------- ### Create a New Email Resource Source: https://docs.threatconnect.com/en/latest/python/groups/groups.html Demonstrates how to instantiate an email object, set required and optional properties, and commit the changes to the platform. ```python # replace the line below with the standard, TC script heading described here: # https://docs.threatconnect.com/en/latest/python/quick_start.html#standard-script-heading ... tc = ThreatConnect(api_access_id, api_secret_key, api_default_org, api_base_url) # instantiate Emails object emails = tc.emails() owner = 'Example Community' # create a new Email in 'Example Community' with the name: 'New Email' email = emails.add('New Email', owner) # set Email specific properties email.set_body('This is an email body.') # REQUIRED email.set_from_address('bad_guy@example.com') # OPTIONAL email.set_header('This is an improper email header.') # REQUIRED email.set_subject('This is an email subject.') # REQUIRED email.set_to('victim@example.com') # OPTIONAL # add a description attribute email.add_attribute('Description', 'Description Example') # add a tag email.add_tag('EXAMPLE') # add a security label email.set_security_label('TLP Green') try: # create the Email email.commit() except RuntimeError as e: print('Error: {0}'.format(e)) sys.exit(1) ``` -------------------------------- ### Update Intelligence Requirement Example Source: https://docs.threatconnect.com/en/latest/rest_api/v3/intelligence_requirements/intelligence_requirements.html Example request to update keywords and associate a group for an IR with ID 10. ```http PUT /v3/intelRequirements/10 Content-Type: application/json { "associatedGroups": { "data": [ { "id": 15 } ] }, "keywordSections": [ { "compareValue": "includes", "keywords": [ { "value": "medical device companies" }, { "value": "healthcare" }, { "value": "mangled spider" }, { "value": "threats to medical" }, { "value": "medical device" } ], "sectionNumber": 0 }, { "compareValue": "excludes", "keywords": [ { "value": "mrap" } ], "sectionNumber": 0 } ] } ``` -------------------------------- ### Initialize MQTT client Source: https://docs.threatconnect.com/en/latest/_modules/tcex/services/mqtt_message_broker.html Retrieves or initializes the MQTT client with TLS and authentication settings. ```python @property def client(self) -> object: """Return MQTT client.""" if self._client is None: try: self._client = mqtt.Client(client_id='', clean_session=True) self._client.reconnect_delay_set(min_delay=1, max_delay=5) self._client.connect(self.broker_host, self.broker_port, self.broker_timeout) if self.broker_cacert is not None: self._client.tls_set( ca_certs=self.broker_cacert, cert_reqs=ssl.CERT_REQUIRED, tls_version=ssl.PROTOCOL_TLSv1_2, ) self._client.tls_insecure_set(False) # add logger when logging in TRACE if self.log.getEffectiveLevel() == 5: self._client.enable_logger(logger=self.log) # username must be a empty string if self.broker_token is not None: self._client.username_pw_set('', password=self.broker_token.value) except Exception as e: self.log.error(f'feature=message-broker, event=failed-connection, error="""{e}"""') self.log.trace(traceback.format_exc()) self.shutdown = True return self._client ``` -------------------------------- ### Build project dependencies Source: https://docs.threatconnect.com/en/latest/_sources/tcex/building_apps_tclib.rst.txt Standard command to build or update the 'lib' directory based on requirements.txt. ```bash tclib ``` ```bash tclib --no_cache_dir ``` -------------------------------- ### Update Group Attribute Example Source: https://docs.threatconnect.com/en/latest/rest_api/v3/group_attributes/group_attributes.html A concrete example of updating the value and source of a Group Attribute with ID 10. ```http PUT /v3/groupAttributes/10 Content-Type: application/json { "source": "CAL", "value": "APT28, IRON TWILIGHT, SNAKEMACKEREL, Swallowtail, Group 74, Sednit, Sofacy, Pawn Storm, Fancy Bear, STRONTIUM, Tsar Team, Threat Group-4127, TG-4127" } ``` -------------------------------- ### Artifact Types JSON Response Example Source: https://docs.threatconnect.com/en/latest/rest_api/v3/case_management/artifact_types/artifact_types.html Example JSON response structure for a request to retrieve all artifact types. ```json { "data": [ { "id": 1, "name": "Email Address", "description": "A name that identifies an electronic post office box on a network where Electronic-Mail (e-mail) can be sent.", "dataType": "String", "intelType": "indicator-EmailAddress", "derivedLink": true }, { "id": 2, "name": "Host", "description": "A hostname. A host is any hardware device that has the capability of permitting access to a network via a user interface, specialized software, network address, protocol stack, or any other means.", "dataType": "String", "intelType": "indicator-Host", "derivedLink": true }, {...} ], "status": "Success" } ``` -------------------------------- ### Configure single app packaging Source: https://docs.threatconnect.com/en/latest/tcex/building_apps_tcpackage.html Example configuration for a single app within the tcex.json file. ```json "package": { "app_name": "MyApp", "app_version": "v1.0", "bundle": false, "excludes": [ "log", "requirements.txt", "tcex.d" ], "outdir": "target" } ``` -------------------------------- ### RedisClient.__init__ Source: https://docs.threatconnect.com/en/latest/_modules/tcex/key_value_store/redis_client.html Initializes a new RedisClient instance with a connection pool. ```APIDOC ## RedisClient(host='localhost', port=6379, db=0, blocking_pool=False, **kwargs) ### Description Initializes a shared Redis client connection using a Connection Pool. Supports standard redis-py connection arguments. ### Parameters - **host** (str) - Optional - The Redis host. Defaults to 'localhost'. - **port** (int) - Optional - The Redis port. Defaults to 6379. - **db** (int) - Optional - The Redis db. Defaults to 0. - **blocking_pool** (bool) - Optional - Use BlockingConnectionPool instead of ConnectionPool. - **kwargs** (dict) - Optional - Additional arguments passed to the underlying redis-py connection (e.g., password, username, socket_timeout, max_connections). ``` -------------------------------- ### Update Victim Attribute Example Source: https://docs.threatconnect.com/en/latest/rest_api/v3/victim_attributes/victim_attributes.html A concrete example of updating the value and default status of a Victim Attribute with ID 1. ```http PUT /v3/victimAttributes/1 Content-Type: application/json { "default": true, "value": "Based on additional analysis, it was determined that this victim's social media, bank, and email accounts were hacked as the result of a phishing attack." } ``` -------------------------------- ### Configure multiple App bundles Source: https://docs.threatconnect.com/en/latest/_sources/tcex/building_apps_tcpackage.rst.txt Example configuration for bundling multiple Apps within the tcex.json file. ```javascript <..snipped> "package": { "bundle": true, "bundle_name": "TCPB_-_Palo_Alto", "bundle_packages": [{ "name": "TCPB_-_My_Bundle_Create", "patterns": [ ".*Create.*" ] }, { "name": "TCPB_-_My_Bundle_Delete", "patterns": [ ".*Delete.*" ] }], "excludes": [ "log", "requirements.txt", "tcex.d" ], "outdir": "target" }, ``` -------------------------------- ### Execute Java Program with Configuration Source: https://docs.threatconnect.com/en/latest/java/java_sdk.html Run the application with the required configuration property on Windows or Linux. ```bash java -cp ".;threatconnect-sdk-.jar" -Dthreatconnect.api.config=myConfig.properties TestClass ``` ```bash java -cp ".:./threatconnect-sdk-.jar" -Dthreatconnect.api.config=myConfig.properties TestClass ``` -------------------------------- ### Owner API Filter URI Examples Source: https://docs.threatconnect.com/en/latest/_sources/python/advanced.rst.txt Examples of formatted URIs showing how the owner filter is applied as a query string. ```text /v2/indicators/address/10.20.30.40?owner=Example+Community ``` ```text /v2/groups/adversaries/5/indicators?owner=Example+Community ``` -------------------------------- ### Specific Artifact Type JSON Response Example Source: https://docs.threatconnect.com/en/latest/rest_api/v3/case_management/artifact_types/artifact_types.html Example JSON response structure for a request to retrieve a specific artifact type. ```json { "data": { "id": 3, "name": "URL", "description": "A uniform resource locator, or URL, is a short string containing an address which refers to an object in the web. URLs are a subset of URIs.", "dataType": "String", "intelType": "indicator-URL", "derivedLink": true }, "status": "Success" } ``` -------------------------------- ### Registering Tokens and Accessing Utilities Source: https://docs.threatconnect.com/en/latest/_modules/tcex/tcex.html Demonstrates the logic for registering tokens based on input models and provides property accessors for utility and API modules. ```python # register token for Apps that pass token on start if all( [self.inputs.model_unresolved.tc_token, self.inputs.model_unresolved.tc_token_expires] ): _tokens.register_token( key=threading.current_thread().name, token=self.inputs.model_unresolved.tc_token, expires=self.inputs.model_unresolved.tc_token_expires, ) return _tokens @property def ti_utils(self) -> 'ThreatIntelUtils': """Return instance of Threat Intel Utils.""" return ThreatIntelUtils(self.session_tc) @cached_property def utils(self) -> 'Utils': # pylint: disable=no-self-use """Include the Utils module.""" return Utils() @cached_property def v2(self) -> 'V2': """Return a case management instance.""" return V2(self.inputs, self.session_tc) @cached_property def v3(self) -> 'V3': """Return a case management instance.""" return V3(self.session_tc) ``` -------------------------------- ### Configure single App packaging Source: https://docs.threatconnect.com/en/latest/_sources/tcex/building_apps_tcpackage.rst.txt Example configuration for a single App within the tcex.json file. ```javascript <..snipped> "package": { "app_name": "MyApp", "app_version": "v1.0", "bundle": false, "excludes": [ "log", "requirements.txt", "tcex.d" ], "outdir": "target" }, ``` -------------------------------- ### Initialize Local Source: https://docs.threatconnect.com/en/latest/tcex/examples.html Initializes a local datastore scoped to the current App. ```python 1# when using a value of "local" the scope of the datastore is limited to this App in the current Playbook 2ds = self.tcex.datastore("local", "myDnsData") ``` -------------------------------- ### Update Incident Group Example Source: https://docs.threatconnect.com/en/latest/rest_api/v3/groups/groups.html A comprehensive PUT request example demonstrating how to associate indicators, add attributes, update status, and remove tags for an Incident Group. ```http PUT /v3/groups/3 Content-Type: application/json { "associatedIndicators": { "data": [ { "address": "verybadguy@bad.com", "type": "EmailAddress", "ownerName": "Demo Community" }, { "hostName": "ultrabadguy.com", "type": "Host" } ] }, "attributes": { "data": [ { "type": "Description", "value": "A very severe incident", "default": true } ] }, "status": "Incident Reported", "tags": { "data": [ { "name": "Targeted Attack" } ], "mode": "delete" } } ``` -------------------------------- ### Reference KEYCHAIN variables in install.json Source: https://docs.threatconnect.com/en/latest/_sources/deployment_config.rst.txt Use this format to allow users to select encrypted variables from Organization and User levels. ```json "validValues": ["${USER:KEYCHAIN}", "${ORGANIZATION:KEYCHAIN}"] ``` -------------------------------- ### GET /v3/groups Source: https://docs.threatconnect.com/en/latest/rest_api/v3/groups/groups.html Retrieves a list of all groups. ```APIDOC ## GET /v3/groups ### Description Retrieves data for all Groups. ### Method GET ### Endpoint /v3/groups ### Parameters #### Query Parameters - **owner** (string) - Optional - Limit the results to a specific owner. ### Response #### Success Response (200) - **data** (array) - List of group objects - **status** (string) - Status of the request ``` -------------------------------- ### Package the App for deployment Source: https://docs.threatconnect.com/en/latest/_sources/tcex/building_apps_quickstart.rst.txt Bundles the project files into a .tcx file located in the target directory. ```bash tcpackage ``` -------------------------------- ### GET /v3/security/owners Source: https://docs.threatconnect.com/en/latest/rest_api/v3/owners/owners.html Retrieves a list of all owners. ```APIDOC ## GET /v3/security/owners ### Description Retrieves data for all owners. ### Method GET ### Endpoint /v3/security/owners ### Response #### Success Response (200) - **data** (array) - List of owner objects - **status** (string) - Status of the request #### Response Example { "data": [ { "id": 2, "name": "Demo Source", "type": "Source", "ownerRole": "Director" } ], "status": "Success" } ``` -------------------------------- ### Instantiate Group Objects in Python Source: https://docs.threatconnect.com/en/latest/python/groups/groups.html Demonstrates how to initialize the ThreatConnect client and instantiate various group type objects. ```python # replace the line below with the standard, TC script heading described here: # https://docs.threatconnect.com/en/latest/python/quick_start.html#standard-script-heading ... tc = ThreatConnect(api_access_id, api_secret_key, api_default_org, api_base_url) # instantiate a generic Groups object groups = tc.groups() # instantiate an object for a specific Group type adversaries = tc.adversaries() campaigns = tc.campaigns() documents = tc.documents() emails = tc.emails() events = tc.events() incidents = tc.incidents() intrusionSets = tc.intrusionSets() reports = tc.reports() signatures = tc.signatures() threats = tc.threats() ``` -------------------------------- ### GET /v3/notes Source: https://docs.threatconnect.com/en/latest/rest_api/v3/case_management/notes/notes.html Retrieves a list of all notes. ```APIDOC ## GET /v3/notes ### Description Retrieves data for all notes. ### Method GET ### Endpoint /v3/notes ### Response #### Success Response (200) - **data** (array) - A list of note objects. - **status** (string) - Operation status. #### Response Example { "data": [ { "id": 1, "text": "Some notes about a case artifact.", "summary": "Some notes about a case artifact.", "author": "11112222333344445555", "dateAdded": "2021-04-22T20:17:15Z", "lastModified": "2021-04-22T20:17:15Z", "edited": false, "artifactId": 12 } ], "status": "Success" } ``` -------------------------------- ### Get Source: https://docs.threatconnect.com/en/latest/tcex/examples.html Retrieves data from the datastore by record ID. ```python 1response = ds.get(rid="one") ``` -------------------------------- ### Define install.json schema structure Source: https://docs.threatconnect.com/en/latest/_sources/deployment_config.rst.txt The base structure for the install.json configuration file, defining properties like allowOnDemand and feeds. ```json { "additionalProperties": false, "properties": { "allowOnDemand": { "type": "boolean" }, "apiUserTokenParam": { "type": "boolean" }, "displayName": { "type": "string" }, "feeds": { "items": { "additionalProperties": false, "properties": { "attributesFile": { "type": "string" }, "enableBulkJson": { "type": "boolean" }, "documentStorageLimitMb": { "type": "integer" }, "indicatorLimit": { "type": "integer" }, "jobFile": { "type": "string" }, "sourceCategory": { "type": "string" }, "sourceDescription": { "type": "string" }, "sourceName": { "type": "string" } } } }, "languageVersion": { "type": "string" }, "listDelimiter": { "type": "string" }, "minServerVersion": { "type": "string" }, "note": { "type": "string" }, "params": { "items": { "additionalProperties": false, "properties": { "allowMultiple": { "type": "boolean" }, "default": { "type": [ "boolean", "integer", "string" ] } ``` -------------------------------- ### Create a Basic Case Source: https://docs.threatconnect.com/en/latest/rest_api/v3/case_management/cases/cases.html Example of the minimal JSON structure required to create a new case. ```JSON POST /v3/cases Content-Type: application/json { "name": "Case name", "status": "Case status", "severity": "Case severity" } ``` -------------------------------- ### GET /v3/victimAttributes Source: https://docs.threatconnect.com/en/latest/rest_api/v3/victim_attributes/victim_attributes.html Retrieve data for all Victim Attributes. ```APIDOC ## GET /v3/victimAttributes ### Description Retrieve data for all Victim Attributes. ### Method GET ### Endpoint /v3/victimAttributes ### Response #### Success Response (200) - **data** (array) - List of victim attributes - **status** (string) - Status of the request #### Response Example { "data": [ { "id": 2, "dateAdded": "2021-11-09T15:49:22Z", "type": "Description", "value": "Ransomware attack victim.", "createdBy": { "id": 1, "userName": "smithj@threatconnect.com", "firstName": "John", "lastName": "Smith", "pseudonym": "jsmith", "owner": "Demo Organization" }, "lastModified": "2021-11-09T15:49:22Z", "pinned": false, "default": true } ], "status": "Success" } ``` -------------------------------- ### GET /v3/intelRequirements Source: https://docs.threatconnect.com/en/latest/rest_api/v3/intelligence_requirements/intelligence_requirements.html Retrieves a list of all intelligence requirements. ```APIDOC ## GET /v3/intelRequirements ### Description Retrieves data for all intelligence requirements (IRs) available in the system. ### Method GET ### Endpoint /v3/intelRequirements ### Response #### Success Response (200) - **data** (array) - A list of intelligence requirement objects. - **status** (string) - The status of the request (e.g., "Success"). #### Response Example { "data": [ { "id": 1, "uniqueId": "IR-001", "requirementText": "Double Secret Probation", "active": true } ], "status": "Success" } ``` -------------------------------- ### Standard Script Initialization Source: https://docs.threatconnect.com/en/latest/_sources/python/quick_start.rst.txt Boilerplate code for reading the configuration file and initializing the ThreatConnect client. ```python try: import ConfigParser except: import configparser as ConfigParser import sys from threatconnect import ThreatConnect config = ConfigParser.RawConfigParser() config.read('./tc.conf') try: api_access_id = config.get('threatconnect', 'api_access_id') api_secret_key = config.get('threatconnect', 'api_secret_key') api_default_org = config.get('threatconnect', 'api_default_org') api_base_url = config.get('threatconnect', 'api_base_url') except ConfigParser.NoOptionError: print('Could not read configuration file.') sys.exit(1) ``` -------------------------------- ### GET /v3/securityLabels Source: https://docs.threatconnect.com/en/latest/rest_api/v3/security_labels/security_labels.html Retrieve a list of all security labels. ```APIDOC ## GET /v3/securityLabels ### Description Retrieve data for all Security Labels. ### Method GET ### Endpoint /v3/securityLabels ### Response #### Success Response (200) - **data** (array) - List of security label objects. - **status** (string) - The status of the request. ``` -------------------------------- ### GET /v3/indicatorAttributes Source: https://docs.threatconnect.com/en/latest/rest_api/v3/indicator_attributes/indicator_attributes.html Retrieve data for all Indicator Attributes. ```APIDOC ## GET /v3/indicatorAttributes ### Description Retrieve data for all Indicator Attributes. ### Method GET ### Endpoint /v3/indicatorAttributes ### Response #### Success Response (200) - **data** (array) - List of indicator attribute objects - **status** (string) - Success status #### Response Example { "data": [ { "id": 10, "dateAdded": "2021-11-09T13:32:37Z", "type": "Additional Analysis and Context", "value": "Host used by hacker conglomerate traced to Iran.", "source": "Phase of Intrusion", "createdBy": { "id": 3, "userName": "11112222333344445555", "firstName": "John", "lastName": "Smith", "pseudonym": "jsmithAPI", "owner": "Demo Organization" }, "lastModified": "2021-11-09T13:32:37Z", "pinned": false, "default": false } ], "status": "Success" } ``` -------------------------------- ### Initialize Organization Source: https://docs.threatconnect.com/en/latest/tcex/examples.html Initializes an organization-scoped datastore. ```python 1ds = self.tcex.datastore("organization", "myDnsData") ```