---
name: implementing-security-information-sharing-with-stix-bf3205822486
description: 'Create, validate, and share STIX 2.1 threat intelligence objects using the stix2 Python library. Covers indicators,
  malware, campaigns, relationships, bundles, and TAXII 2.1 publishing.

  '
domain: cybersecurity
subdomain: threat-intelligence
tags:
- stix
- taxii
- threat-sharing
- intelligence-exchange
version: '1.0'
author: Krishna Kumar (xalgord)
license: Apache-2.0
d3fend_techniques:
- File Metadata Consistency Validation
- Application Protocol Command Analysis
- Identifier Analysis
- Content Format Conversion
- Message Analysis
nist_csf:
- ID.RA-01
- ID.RA-05
- DE.CM-01
- DE.AE-02
---

# Implementing Security Information Sharing with STIX 2.1

Build and share structured threat intelligence using STIX 2.1 objects
with the stix2 Python library and TAXII 2.1 transport protocol.

## When to Use

- Building a threat intelligence platform that exchanges IOCs with partner organizations
- Automating ingestion and export of indicators from MISP, OpenCTI, or other TIP platforms
- Creating machine-readable intelligence reports for ISAC/ISAO sharing communities
- Publishing threat data to a TAXII 2.1 server for downstream consumption by SIEMs and SOARs
- Converting unstructured threat reports into standardized STIX 2.1 bundles
- Enriching detection rules with context by linking indicators to malware, campaigns, and threat actors

**Do not use** for sharing simple IP blocklists or CSV-based IOC feeds that do not require relationship context; plain-text feeds with simpler formats like CSV or OpenIOC may be more efficient in those cases.

## Common Misconfigurations & Verification

- **Dangling relationship refs:** a `Relationship` whose `source_ref`/`target_ref` points to an object not in the bundle parses fine but breaks consumers. Verify every SRO endpoint resolves to an SDO/SCO `id` present in the bundle.
- **Invalid STIX patterns:** patterns like `[file:hashes.'SHA-256' = '...']` require correct property paths and quoting; a malformed `MATCHES` regex or missing bracket fails silently in some loaders. Lint with `stix2-validator`.
- **Missing required properties:** custom or hand-built objects dropping `type`/`id`/`created`/`modified` fail spec validation - always construct via the `stix2` library rather than raw dicts.
- **TAXII media-type errors:** publishing without `Content-Type: application/taxii+json;version=2.1` (or the matching accept header) yields 406/415 or silent rejection. Confirm `success_count` equals the number of objects sent.
- **TLP marking omitted:** objects without `object_marking_refs` default to unrestricted sharing - attach the correct TLP marking definition before publishing.
- **Verification:** re-parse the serialized bundle with `allow_custom=False`, round-trip published objects back from the TAXII collection to confirm no data loss, and run `stix2_validator` on the export.

## Prerequisites

- Python 3.8+ with `stix2` library (`pip install stix2`)
- `taxii2-client` for consuming TAXII feeds (`pip install taxii2-client`)
- A TAXII 2.1 server endpoint for publishing (e.g., OpenTAXII, Medallion, or MISP TAXII service)
- Familiarity with STIX 2.1 SDO types: Indicator, Malware, Threat Actor, Campaign, Attack Pattern, Identity
- Familiarity with STIX 2.1 SRO types: Relationship, Sighting
- Optional: OpenCTI or MISP instance for end-to-end integration testing

## Workflow

### Step 1: Install Dependencies

```bash
pip install stix2 taxii2-client requests
```

### Step 2: Create STIX 2.1 Domain Objects (SDOs)

Create core intelligence objects that describe threats, actors, and campaigns:

```python
from stix2 import (
    Indicator, Malware, ThreatActor, Campaign,
    AttackPattern, Identity, Relationship, Bundle,
    ExternalReference
)
from datetime import datetime

# Create a producer identity
producer = Identity(
    name="ACME Threat Intel Team",
    identity_class="organization",
    sectors=["technology"],
    contact_information="threatintel@acme.example.com"
)

# Create a malware object
emotet_malware = Malware(
    name="Emotet",
    description="Banking trojan turned modular botnet loader. "
                "Distributed via malspam with macro-enabled Office documents.",
    malware_types=["trojan", "bot"],
    is_family=True,
    created_by_ref=producer.id
)

# Create an attack pattern referencing MITRE ATT&CK
spearphishing_pattern = AttackPattern(
    name="Spearphishing Attachment",
    description="Adversaries send spearphishing emails with a malicious attachment.",
    external_references=[
        ExternalReference(
            source_name="mitre-attack",
            external_id="T1566.001",
            url="https://attack.mitre.org/techniques/T1566/001/"
        )
    ],
    created_by_ref=producer.id
)

# Create a threat actor
threat_actor = ThreatActor(
    name="Mummy Spider",
    description="Cybercriminal group operating the Emotet botnet infrastructure.",
    threat_actor_types=["crime-syndicate"],
    aliases=["TA542", "Gold Crestwood"],
    primary_motivation="personal-gain",
    created_by_ref=producer.id
)

# Create a campaign
campaign = Campaign(
    name="Emotet Q1 2026 Resurgence",
    description="Renewed Emotet distribution campaign using thread-hijacked "
                "reply-chain emails with OneNote lure attachments.",
    first_seen="2026-01-15T00:00:00Z",
    created_by_ref=producer.id
)

print(f"Created malware SDO: {emotet_malware.id}")
print(f"Created threat actor SDO: {threat_actor.id}")
print(f"Created campaign SDO: {campaign.id}")
```

### Step 3: Create STIX Indicators with Patterns

Define detection patterns using the STIX Patterning Language:

```python
# File hash indicator
hash_indicator = Indicator(
    name="Emotet dropper hash",
    description="SHA-256 hash of Emotet first-stage dropper observed in Jan 2026 campaign.",
    indicator_types=["malicious-activity"],
    pattern_type="stix",
    pattern="[file:hashes.'SHA-256' = 'a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2']",
    valid_from="2026-01-15T00:00:00Z",
    created_by_ref=producer.id
)

# Network indicator for C2 domain
c2_indicator = Indicator(
    name="Emotet C2 domain",
    description="Command and control domain observed in Emotet tier-1 botnet infrastructure.",
    indicator_types=["malicious-activity"],
    pattern_type="stix",
    pattern="[domain-name:value = 'malicious-c2.example.com']",
    valid_from="2026-01-20T00:00:00Z",
    created_by_ref=producer.id
)

# Compound pattern: process spawning with suspicious command line
process_indicator = Indicator(
    name="Emotet PowerShell download cradle",
    description="PowerShell execution pattern used by Emotet to download next-stage payload.",
    indicator_types=["malicious-activity"],
    pattern_type="stix",
    pattern=(
        "[process:command_line MATCHES 'powershell.*-enc.*' "
        "AND process:parent_ref.name = 'winword.exe']"
    ),
    valid_from="2026-01-15T00:00:00Z",
    created_by_ref=producer.id
)

# Email subject indicator
email_indicator = Indicator(
    name="Emotet phishing subject line pattern",
    description="Subject line pattern seen in thread-hijacked Emotet phishing emails.",
    indicator_types=["malicious-activity"],
    pattern_type="stix",
    pattern="[email-message:subject MATCHES '^RE:.*Invoice.*[0-9]{6}']",
    valid_from="2026-01-15T00:00:00Z",
    created_by_ref=producer.id
)

print(f"Created {4} indicator objects")
```

### Step 4: Build Relationships Between Objects

Link SDOs together using Relationship objects to express how threats are connected:

```python
# Malware uses attack pattern
rel_malware_attack = Relationship(
    relationship_type="uses",
    source_ref=emotet_malware.id,
    target_ref=spearphishing_pattern.id,
    description="Emotet is distributed via spearphishing attachments.",
    created_by_ref=producer.id
)

# Threat actor uses malware
rel_actor_malware = Relationship(
    relationship_type="uses",
    source_ref=threat_actor.id,
    target_ref=emotet_malware.id,
    description="Mummy Spider operates the Emotet malware infrastructure.",
    created_by_ref=producer.id
)

# Indicator indicates malware
rel_indicator_malware = Relationship(
    relationship_type="indicates",
    source_ref=hash_indicator.id,
    target_ref=emotet_malware.id,
    description="File hash indicator for Emotet dropper binary.",
    created_by_ref=producer.id
)

# Campaign uses malware
rel_campaign_malware = Relationship(
    relationship_type="uses",
    source_ref=campaign.id,
    target_ref=emotet_malware.id,
    created_by_ref=producer.id
)

# Threat actor attributed to campaign
rel_actor_campaign = Relationship(
    relationship_type="attributed-to",
    source_ref=campaign.id,
    target_ref=threat_actor.id,
    created_by_ref=producer.id
)

print(f"Created {5} relationship objects linking threat intelligence")
```

### Step 5: Assemble and Serialize a STIX Bundle

Package all objects into a bundle for sharing:

```python
import json

bundle = Bundle(
    objects=[
        producer,
        emotet_malware,
        spearphishing_pattern,
        threat_actor,
        campaign,
        hash_indicator,
        c2_indicator,
        process_indicator,
        email_indicator,
        rel_malware_attack,
        rel_actor_malware,
        rel_indicator_malware,
        rel_campaign_malware,
        rel_actor_campaign,
    ]
)

# Serialize to JSON
bundle_json = bundle.serialize(pretty=True)

# Write bundle to file for sharing
with open("emotet_campaign_bundle.json", "w") as f:
    f.write(bundle_json)

print(f"Bundle {bundle.id} contains {len(bundle.objects)} objects")
print(f"Written to emotet_campaign_bundle.json")

# Validate the bundle by re-parsing
from stix2 import parse
parsed = parse(bundle_json, allow_custom=False)
print(f"Bundle validation passed: {len(parsed.objects)} objects parsed successfully")
```

### Step 6: Consume Intelligence from a TAXII 2.1 Server

Retrieve published threat intelligence from a TAXII feed:

```python
from taxii2client.v21 import Server, Collection, as_pages
import json

# Connect to a TAXII 2.1 server
taxii_server = Server(
    "https://taxii.example.com/taxii2/",
    user="readonly",
    password="readonly_password"
)

# Discover API roots and collections
api_root = taxii_server.api_roots[0]
print(f"API Root: {api_root.title}")

for collection in api_root.collections:
    print(f"  Collection: {collection.title} (ID: {collection.id})")

# Fetch indicators from a specific collection
target_collection = Collection(
    f"https://taxii.example.com/taxii2/collections/{api_root.collections[0].id}/",
    user="readonly",
    password="readonly_password"
)

# Retrieve objects with filtering
response = target_collection.get_objects(
    added_after="2026-01-01T00:00:00Z",
    type=["indicator", "malware"]
)

stix_data = json.loads(response.text)
print(f"Retrieved {len(stix_data.get('objects', []))} objects from TAXII server")

# Process each retrieved object
for obj in stix_data.get("objects", []):
    if obj["type"] == "indicator":
        print(f"  Indicator: {obj['name']} | Pattern: {obj['pattern'][:60]}...")
    elif obj["type"] == "malware":
        print(f"  Malware: {obj['name']} | Family: {obj.get('is_family', False)}")
```

### Step 7: Publish Intelligence to a TAXII 2.1 Server

Push your STIX bundle to a writable TAXII collection:

```python
import requests
import json

TAXII_URL = "https://taxii.example.com/taxii2/collections/COLLECTION_ID/objects/"
TAXII_USER = "publisher"
TAXII_PASS = "publisher_password"

headers = {
    "Content-Type": "application/taxii+json;version=2.1",
    "Accept": "application/taxii+json;version=2.1"
}

# Read the bundle we created earlier
with open("emotet_campaign_bundle.json", "r") as f:
    bundle_data = f.read()

response = requests.post(
    TAXII_URL,
    headers=headers,
    auth=(TAXII_USER, TAXII_PASS),
    data=bundle_data,
    timeout=30
)

if response.status_code in (200, 201, 202):
    status = response.json()
    print(f"Published successfully. Status ID: {status.get('id')}")
    print(f"  Total count: {status.get('total_count')}")
    print(f"  Success count: {status.get('success_count')}")
    print(f"  Failure count: {status.get('failure_count')}")
else:
    print(f"Publishing failed: {response.status_code} - {response.text}")
```

### Step 8: Validate and Lint STIX Objects

Ensure objects comply with the STIX 2.1 specification:

```python
from stix2 import parse, exceptions
import json

def validate_stix_bundle(bundle_path):
    """Validate all objects in a STIX bundle against the 2.1 spec."""
    with open(bundle_path, "r") as f:
        raw = json.load(f)

    errors = []
    valid_count = 0

    for obj in raw.get("objects", []):
        try:
            parsed = parse(json.dumps(obj), allow_custom=False)
            valid_count += 1
        except (exceptions.InvalidValueError, exceptions.MissingPropertiesError) as e:
            errors.append({
                "object_id": obj.get("id", "unknown"),
                "object_type": obj.get("type", "unknown"),
                "error": str(e)
            })

    print(f"Validation results: {valid_count} valid, {len(errors)} errors")
    for err in errors:
        print(f"  ERROR in {err['object_type']} ({err['object_id']}): {err['error']}")

    return len(errors) == 0

validate_stix_bundle("emotet_campaign_bundle.json")
```

## Verification

- Confirm all STIX objects serialize to valid JSON and include required properties (`type`, `id`, `created`, `modified`)
- Verify relationship `source_ref` and `target_ref` point to existing object IDs within the bundle
- Validate indicator patterns parse correctly using the STIX patterning grammar
- Test TAXII publishing returns a success status with `success_count` matching the number of objects sent
- Re-retrieve published objects from the TAXII server and confirm they round-trip without data loss
- Check that consuming systems (SIEM, SOAR, TIP) can ingest the bundle and create corresponding detection rules or enrichment data
- Run `stix2-validator` CLI tool against exported bundles: `stix2_validator emotet_campaign_bundle.json`


---
Source attribution: xalgord
Original project: https://github.com/xalgord/xalgorix/blob/cec44d71b1d998208e1e2091982d0ee2f928041f/internal/tools/skills/data/threat-intelligence/implementing-security-information-sharing-with-stix2/SKILL.md
License: Apache-2.0
License information: https://www.apache.org/licenses/LICENSE-2.0
Original upstream instructions; downloaded from Mega AI Hub.

## Upstream license notice


                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright 2026 xalgord

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.



# Mega AI Hub resource metadata

Creator / publisher: xalgord
Original project: https://github.com/xalgord/xalgorix/blob/cec44d71b1d998208e1e2091982d0ee2f928041f/internal/tools/skills/data/threat-intelligence/implementing-security-information-sharing-with-stix2/SKILL.md
Attribution basis: Source repository record

Fields of work: Data & Analytics, Development & Engineering
Roles: Data Scientist, ML / AI Engineer, Security Engineer
Specialties: API
Tools: Stix2, Taxii2 Client
Country applicability: Country not specified
Classification basis: Source catalog labels
Instruction SHA-256: a3422f852aeed9f8d26a6ae829e9169bb8e9951a7a39ef0e45d4fb977ae7317e
