### Install Dependencies (Bash) Source: https://github.com/openstix/stix2-python/blob/master/docs/contributing.rst Navigates into the cloned repository directory and installs the necessary development dependencies using pip from the requirements.txt file. ```bash cd cti-python-stix2 pip install -r requirements.txt ``` -------------------------------- ### Create STIX Indicator with Custom ID Source: https://github.com/openstix/stix2-python/blob/master/docs/guide/creating.ipynb Demonstrates creating a STIX Indicator with a pre-defined `id`. The example shows that the provided `id` must start with the correct prefix for the object type (e.g., 'indicator--'). Providing an `id` with an incorrect prefix will raise an `InvalidValueError`. ```python indicator4 = Indicator(id="campaign--63ce9068-b5ab-47fa-a2cf-a602ea01f21a", pattern_type="stix", pattern="[file:hashes.md5 = 'd41d8cd98f00b204e9800998ecf8427e']") ``` -------------------------------- ### Python: Query STIX 2 Objects with FileSystemSource and Filters Source: https://github.com/openstix/stix2-python/blob/master/docs/guide/filesystem.ipynb This example shows how to query STIX 2.x objects stored on the file system using `FileSystemSource` and `Filter` objects. It demonstrates creating a filter for a specific object type ('malware') and then appending additional filters (e.g., 'modified' date) to refine the query results. ```python from stix2 import Filter # create filter for type=malware query = [Filter("type", "=", "malware")] # query on the filter mals = fs_source.query(query) for mal in mals: print(mal.id) # add more filters to the query query.append(Filter("modified", ">" , "2017-05-31T21:33:10.772474Z")) mals = fs_source.query(query) # for visual purposes for mal in mals: print(mal.id) ``` -------------------------------- ### Install Pre-commit Hooks (Bash) Source: https://github.com/openstix/stix2-python/blob/master/docs/contributing.rst Installs the pre-commit git hooks, which automate code style checks and other pre-commit validations to ensure code quality. ```bash pre-commit install ``` -------------------------------- ### Install cti-python-stix2 using pip Source: https://github.com/openstix/stix2-python/blob/master/README.rst Installs the stix2 Python library using pip. Requires Python 3.6+. ```bash pip install stix2 ``` -------------------------------- ### Create and Serialize Custom STIX Object Instance Source: https://github.com/openstix/stix2-python/blob/master/docs/guide/custom.ipynb Demonstrates how to instantiate a custom STIX object ('x-animal') and serialize it to JSON format. This shows a successful creation with valid properties. ```python animal = Animal(species="lion", animal_class="mammal") print(animal.serialize(pretty=True)) ``` -------------------------------- ### Create STIX Malware Object Source: https://github.com/openstix/stix2-python/blob/master/docs/guide/creating.ipynb Shows how to create a STIX Malware object using the `stix2` Python library. The example initializes the `Malware` class with required properties like `name` and `is_family`. It also mentions that other common STIX properties like `type`, `id`, `created`, and `modified` are automatically set if not provided. ```python from stix2 import Malware malware = Malware(name="Poison Ivy", is_family=False) print(malware.serialize(pretty=True)) ``` -------------------------------- ### Create START-STOP Qualified Observation Expression Source: https://github.com/openstix/stix2-python/blob/master/docs/guide/patterns.ipynb Builds a QualifiedObservationExpression using a StartStopQualifier, which defines a temporal window for an observation. It includes start and end timestamps for the qualification. ```python from stix2 import ( ObservationExpression, EqualityComparisonExpression, ObjectPath, TimestampConstant, StartStopQualifier, QualifiedObservationExpression ) ece14 = ObservationExpression(EqualityComparisonExpression(ObjectPath("file", ["name"]), "foo.dll")) ssq = StartStopQualifier(TimestampConstant('2016-06-01T00:00:00Z'), TimestampConstant('2016-07-01T00:00:00Z')) qoe2 = QualifiedObservationExpression(ece14, ssq) print("(START-STOP)\n{} ".format(qoe2)) ``` -------------------------------- ### STIX 2.1 Is Subset Comparison Expression with Python Source: https://github.com/openstix/stix2-python/blob/master/docs/guide/patterns.ipynb Shows how to create a STIX 2.1 observation expression using `IsSubsetComparisonExpression`. This example checks if a destination IP address reference in network traffic is a subset of a given IPv6 CIDR range. Uses `stix2` library. ```python lhs = ObjectPath("network-traffic", ["dst_ref", "value"]) iss = ObservationExpression(IsSubsetComparisonExpression(lhs, StringConstant("2001:0db8:dead:beef:0000:0000:0000:0000/64"))) print("\t{}\n".format(iss)) ``` -------------------------------- ### Python: Initialize and Use MemoryStore Source: https://github.com/openstix/stix2-python/blob/master/docs/guide/memory.ipynb This Python snippet demonstrates how to initialize and use the MemoryStore from the stix2 library. The MemoryStore is designed for in-memory storage and retrieval of STIX content. It requires the 'stix2' library to be installed. ```python from stix2 import MemoryStore, Indicator # create default MemoryStore mem = MemoryStore() ``` -------------------------------- ### STIX 2.1 Object Path and Equality Comparison with Python Source: https://github.com/openstix/stix2-python/blob/master/docs/guide/patterns.ipynb Demonstrates creating STIX 2.1 observation expressions using `ObjectPath` and `EqualityComparisonExpression`. It shows how to compare the 'value' of a 'domain-name' and the 'path' of a 'file'. The output is formatted for display. ```python from stix2 import DomainName, File, IPv4Address from stix2 import ( ObjectPath, EqualityComparisonExpression, ObservationExpression, GreaterThanComparisonExpression, IsSubsetComparisonExpression, FloatConstant, StringConstant ) lhs = ObjectPath("domain-name", ["value"]) ece_1 = ObservationExpression(EqualityComparisonExpression(lhs, "site.of.interest.zaz")) print("\t{}\n".format(ece_1)) lhs = ObjectPath("file", ["parent_directory_ref","path"]) ece_2 = ObservationExpression(EqualityComparisonExpression(lhs, "C:\\Windows\\System32")) print("\t{}\n".format(ece_2)) ``` -------------------------------- ### Install Semantic Equivalence Dependencies (Shell) Source: https://github.com/openstix/stix2-python/blob/master/docs/guide/equivalence.ipynb This command installs the necessary dependencies for using the semantic equivalence functions within the stix2 library. It uses pip to install the `stix2` package with the `semantic` extra, which includes libraries required for comparing STIX objects based on their content. ```bash pip install stix2[semantic] ``` -------------------------------- ### Add Single Campaign Object to FileSystemSink (Python) Source: https://github.com/openstix/stix2-python/blob/master/docs/guide/filesystem.ipynb Demonstrates adding a single STIX 2.1 Campaign object to a FileSystemSink. The `add` method takes a STIX object as input and stores it. ```python # add Campaign object to FileSystemSink fs_sink.add(camp) ``` -------------------------------- ### Adding, Removing, and Setting Markings Source: https://github.com/openstix/stix2-python/blob/master/docs/guide/markings.ipynb Demonstrates how to add, remove, and set data markings on existing STIX objects. Note that these operations create new versions of the objects. ```APIDOC ## Managing Data Markings on STIX Objects ### Description Functions to modify data markings (object and granular) on existing STIX objects. ### Methods - `add_markings(marking)`: Adds a marking to the object. - `remove_markings(marking)`: Removes a specific marking from the object. - `set_markings(markings_list)`: Replaces all existing markings with the provided list. - `clear_markings()`: Removes all markings from the object. *Note: All these operations create a new version of the STIX object.* ### Request Example (Adding Markings) ```python # Assuming 'indicator' is an existing STIX object and 'marking_definition' is a marking object indicator_with_new_marking = indicator.add_markings(marking_definition) print(indicator_with_new_marking.serialize(pretty=True)) ``` ### Request Example (Removing Markings) ```python # Assuming 'indicator_with_new_marking' is an existing STIX object and 'marking_definition' is a marking object indicator_after_removal = indicator_with_new_marking.remove_markings(marking_definition) print(indicator_after_removal.serialize(pretty=True)) ``` ### Request Example (Setting Markings) ```python from stix2 import TLP_GREEN # Assuming 'indicator_after_removal' is an existing STIX object and 'marking_definition' is a marking object indicator_with_replaced_markings = indicator_after_removal.set_markings([TLP_GREEN, marking_definition]) print(indicator_with_replaced_markings.serialize(pretty=True)) ``` ### Request Example (Clearing Markings) ```python # Assuming 'indicator_after_removal' is an existing STIX object indicator_cleared = indicator_after_removal.clear_markings() print(indicator_cleared.serialize(pretty=True)) ``` ### Granular Markings These functions also support granular markings by passing a list of selectors. ``` -------------------------------- ### Create STIX 2 Bundle Source: https://github.com/openstix/stix2-python/blob/master/docs/guide/creating.ipynb Generates a STIX 2 Bundle by passing STIX objects as arguments to the Bundle constructor. Required properties like 'type', 'id', and 'spec_version' are automatically set. ```python from stix2 import Bundle bundle = Bundle(indicator, malware, relationship) print(bundle.serialize(pretty=True)) ``` -------------------------------- ### Filtering and Managing Lang/Marking-Ref Markings Source: https://github.com/openstix/stix2-python/blob/master/docs/guide/markings.ipynb Explains how to filter and manage specific types of markings (lang and marking-ref) during retrieval and modification. ```APIDOC ## Filtering and Managing Lang/Marking-Ref Markings ### Description Allows for selective retrieval and modification of markings based on type (lang or marking-ref). ### Methods - `get_markings(selector, lang=True, marking_ref=True)`: Retrieves markings, with options to exclude lang or marking-ref types. - `clear_markings(selector, lang=True, marking_ref=True)`: Clears markings, with options to exclude lang or marking-ref types. - `set_markings(markings_list, lang=True, marking_ref=True)`: Sets markings, with options to specify types. ### Request Example (Creating Object with Specific Markings) ```python from stix2 import Indicator v21_indicator = Indicator( description="Una descripcion sobre este indicador", pattern_type="stix", pattern="[file:hashes.md5 = 'd41d8cd98f00b204e9800998ecf8427e']", object_marking_refs=['marking-definition--f88d31f6-486f-44da-b317-01333bde0b82'], indicator_types=['malware'], granular_markings=[ { 'selectors': ['description'], 'lang': 'es' }, { 'selectors': ['description'], 'marking_ref': 'marking-definition--34098fce-860f-48ae-8e50-ebd3cc5e41da' } ] ) print(v21_indicator.serialize(pretty=True)) ``` ### Request Example (Getting Markings with Filters) ```python # Gets both lang and marking_ref markings for 'description' print(v21_indicator.get_markings('description')) # Exclude lang markings from results print(v21_indicator.get_markings('description', lang=False)) # Exclude marking-definition markings from results print(v21_indicator.get_markings('description', marking_ref=False)) ``` ### Request Example (Clearing Markings with Filters) ```python # By default, both types of markings will be removed print(v21_indicator.clear_markings("description").serialize(pretty=True)) # If lang is False, no lang markings will be removed print(v21_indicator.clear_markings("description", lang=False).serialize(pretty=True)) # If marking_ref is False, no marking-definition markings will be removed print(v21_indicator.clear_markings("description", marking_ref=False).serialize(pretty=True)) ``` ``` -------------------------------- ### Create and Serialize Custom Cyber Observable Instance Source: https://github.com/openstix/stix2-python/blob/master/docs/guide/custom.ipynb Instantiates a custom Cyber Observable object ('x-new-observable') with specified properties and serializes it to JSON. This demonstrates the creation of a valid custom observable. ```python new_observable = NewObservable(a_property="something", property_2=10) print(new_observable.serialize(pretty=True)) ``` -------------------------------- ### Create STIX Indicator with Observation Expression Source: https://github.com/openstix/stix2-python/blob/master/docs/guide/patterns.ipynb Demonstrates how to create a STIX 2.1 Indicator object by associating an Observation Expression with the 'pattern' property and specifying 'stix' as the 'pattern_type'. ```python from stix2 import Indicator, EqualityComparisonExpression, ObservationExpression, ObjectPath ece14 = ObservationExpression(EqualityComparisonExpression(ObjectPath("file", ["name"]), "$t00rzch$$.elf")) ind = Indicator(name="Cryptotorch", pattern_type="stix", pattern=ece14) print(ind.serialize(pretty=True)) ``` -------------------------------- ### Add Multiple STIX Objects to FileSystemSink (Python) Source: https://github.com/openstix/stix2-python/blob/master/docs/guide/filesystem.ipynb Illustrates adding multiple STIX 2.1 objects (Indicators in this case) to a FileSystemSink in a single operation. The `add` method accepts a list of STIX objects. ```python # can also add STIX objects to FileSystemSink in one call fs_sink.add([ind, ind1]) ``` -------------------------------- ### STIX Identity with Custom Properties Source: https://github.com/openstix/stix2-python/blob/master/docs/guide/custom.ipynb Demonstrates how to add custom properties to STIX objects, specifically an Identity object. It shows the error encountered when custom properties are not allowed and how to correctly include them using `custom_properties` or `allow_custom=True`. ```python from stix2 import Identity Identity(name="John Smith", identity_class="individual", x_foo="bar") ``` ```python identity = Identity(name="John Smith", identity_class="individual", custom_properties={ "x_foo": "bar" }) print(identity.serialize(pretty=True)) ``` ```python identity2 = Identity(name="John Smith", identity_class="individual", x_foo="bar", allow_custom=True) print(identity2.serialize(pretty=True)) ``` -------------------------------- ### Serialize STIX Indicator to Pretty JSON Source: https://github.com/openstix/stix2-python/blob/master/docs/guide/serializing.ipynb Demonstrates how to create a STIX Indicator object and serialize it into a human-readable, pretty-printed JSON format using the `stix2` Python library. This method is suitable for development and debugging. ```python from stix2 import Indicator indicator = Indicator(name="File hash for malware variant", pattern_type="stix", pattern="[file:hashes.md5 = 'd41d8cd98f00b204e9800998ecf8427e']") print(indicator.serialize(pretty=True)) ``` -------------------------------- ### Parsing STIX with Custom Properties Source: https://github.com/openstix/stix2-python/blob/master/docs/guide/custom.ipynb Shows how to parse a STIX JSON string that includes custom properties. The `allow_custom=True` argument must be passed to the `parse` function to successfully include these properties. ```python from stix2 import parse input_string = """ { "type": "identity", "spec_version": "2.1", "id": "identity--311b2d2d-f010-4473-83ec-1edf84858f4c", "created": "2015-12-21T19:59:11Z", "modified": "2015-12-21T19:59:11Z", "name": "John Smith", "identity_class": "individual", "x_foo": "bar" } """ identity3 = parse(input_string, allow_custom=True) print(identity3.x_foo) ``` -------------------------------- ### Import STIX 2.1 Core Objects and Expressions Source: https://github.com/openstix/stix2-python/blob/master/docs/guide/patterns.ipynb Imports necessary classes from the stix2 library for constructing STIX 2.1 objects and expressions, including constants, comparison expressions, and various types of observation expressions. ```python from stix2 import ( TimestampConstant, HashConstant, ObjectPath, EqualityComparisonExpression, AndBooleanExpression, WithinQualifier, RepeatQualifier, StartStopQualifier, QualifiedObservationExpression, FollowedByObservationExpression, ParentheticalExpression, ObservationExpression ) ``` -------------------------------- ### Serialize STIX Indicator to Compact JSON Source: https://github.com/openstix/stix2-python/blob/master/docs/guide/serializing.ipynb Shows how to serialize a STIX Indicator object to a compact JSON string. This method prioritizes performance over human readability and is recommended when the JSON output will be consumed programmatically. ```python print(indicator.serialize()) ``` -------------------------------- ### Create STIX 2 Relationship with Objects Source: https://github.com/openstix/stix2-python/blob/master/docs/guide/creating.ipynb Creates a STIX 2 Relationship object by passing STIX objects directly as positional arguments for source, relationship type, and target. This offers a more readable alternative to using IDs. ```python relationship2 = Relationship(indicator, 'indicates', malware) print(relationship2.serialize(pretty=True)) ``` -------------------------------- ### Python: Interact with STIX 2 FileSystemStore Source: https://github.com/openstix/stix2-python/blob/master/docs/guide/filesystem.ipynb Demonstrates how to use the `FileSystemStore` from the `stix2` library to persist and retrieve STIX 2.x objects. It shows the creation of a store, fetching specific STIX objects by ID, and printing them in a pretty-formatted JSON representation. ```python from stix2 import FileSystemStore # create FileSystemStore fs = FileSystemStore("/tmp/stix2_store") # retrieve STIX2 content from FileSystemStore ap = fs.get("attack-pattern--0a3ead4e-6d47-4ccb-854c-a6a4f9d96b22") mal = fs.get("malware--92ec0cbd-2c30-44a2-b270-73f4ec949841") # for visual purposes print(mal.serialize(pretty=True)) ``` -------------------------------- ### Get Object Markings from STIX Objects (Python) Source: https://github.com/openstix/stix2-python/blob/master/docs/guide/markings.ipynb Explains how to retrieve a list of all object markings associated with a STIX object. This is achieved by calling the `get_markings` method on the object. ```python indicator6.get_markings() ``` -------------------------------- ### Get Granular Markings from STIX Objects (Python) Source: https://github.com/openstix/stix2-python/blob/master/docs/guide/markings.ipynb Shows how to retrieve granular markings for a specific property (selector) of a STIX object. This can be done either by calling `get_markings` as a method on the object or as a standalone function, passing the object and the selector. ```python from stix2 import get_markings get_markings(malware, 'name') ``` ```python malware.get_markings('name') ``` -------------------------------- ### Python: Retrieve STIX 2 Objects using FileSystemSource Source: https://github.com/openstix/stix2-python/blob/master/docs/guide/filesystem.ipynb This code demonstrates retrieving STIX 2.x objects from the file system using `FileSystemSource`. It shows how to initialize the source with a directory path and then fetch individual STIX objects by their ID. ```python from stix2 import FileSystemSource # create FileSystemSource fs_source = FileSystemSource("/tmp/stix2_source") # retrieve STIX 2 objects ap = fs_source.get("attack-pattern--0a3ead4e-6d47-4ccb-854c-a6a4f9d96b22") # for visual purposes print(ap) ``` -------------------------------- ### Python: Initialize ObjectFactory with Default 'created_by_ref' Source: https://github.com/openstix/stix2-python/blob/master/docs/guide/environment.ipynb Initializes an ObjectFactory in Python with a default 'created_by_ref' property. This factory will automatically assign the specified identity reference to the 'created_by_ref' field of any STIX objects created through it. No external dependencies are strictly required for this basic setup, but the 'stix2' library must be installed. ```python from stix2 import Indicator, ObjectFactory factory = ObjectFactory(created_by_ref="identity--311b2d2d-f010-4473-83ec-1edf84858f4c") ``` -------------------------------- ### Create and Manage STIX 2.x Bundles with Python Source: https://context7.com/openstix/stix2-python/llms.txt Illustrates how to create STIX bundles by grouping multiple STIX objects. It covers creating bundles from individual objects, explicitly setting a bundle ID, serializing bundles to JSON, parsing JSON back into bundles, and saving/loading bundles from files. It also shows basic usage of FileSystemStore with the bundlify option. ```python import stix2 # Create objects indicator = stix2.Indicator( name="Malicious IP", indicator_types=["malicious-activity"], pattern_type="stix", pattern="[ipv4-addr:value = '198.51.100.1']" ) malware = stix2.Malware( name="Emotet", malware_types=["trojan"], is_family=True ) relationship = stix2.Relationship(indicator, 'indicates', malware) # Create bundle from objects bundle = stix2.Bundle(indicator, malware, relationship) # Bundle with explicit ID custom_bundle = stix2.Bundle( id="bundle--12345678-1234-1234-1234-123456789012", objects=[indicator, malware, relationship] ) # Serialize bundle bundle_json = bundle.serialize(pretty=True) print(bundle_json) # Parse bundle parsed_bundle = stix2.parse(bundle_json) print(f"Bundle contains {len(parsed_bundle.objects)} objects") # Access objects in bundle for obj in parsed_bundle.objects: print(f"Type: {obj.type}, ID: {obj.id}") # Save bundle to file with open("threat_intel_bundle.json", "w") as f: bundle.fp_serialize(f, pretty=True) # Load and parse from file with open("threat_intel_bundle.json", "r") as f: loaded_bundle = stix2.parse(f.read()) # FileSystemStore bundlify option fs_bundled = stix2.FileSystemStore("/var/stix-bundles", bundlify=True) fs_bundled.add([indicator, malware, relationship]) # Automatically wrapped in bundle when saved ``` -------------------------------- ### Python: Create and Add STIX 2 Objects to FileSystemStore Source: https://github.com/openstix/stix2-python/blob/master/docs/guide/filesystem.ipynb This snippet illustrates the creation of STIX 2.x Threat Actor and Indicator objects using the `stix2` library. It then demonstrates how to add these newly created objects to a `FileSystemStore`, both individually and as a list. ```python from stix2 import ThreatActor, Indicator # create new STIX threat-actor ta = ThreatActor(name="Adjective Bear", sophistication="innovator", resource_level="government", goals=[ "compromising media outlets", "water-hole attacks geared towards political, military targets", "intelligence collection" ]) # create new indicators ind = Indicator(description="Crusades C2 implant", pattern_type="stix", pattern="[file:hashes.'SHA-256' = '54b7e05e39a59428743635242e4a867c932140a999f52a1e54fa7ee6a440c73b']") ind1 = Indicator(description="Crusades C2 implant 2", pattern_type="stix", pattern="[file:hashes.'SHA-256' = '64c7e05e40a59511743635242e4a867c932140a999f52a1e54fa7ee6a440c73b']") # add STIX object (threat-actor) to FileSystemStore fs.add(ta) # can also add multiple STIX objects to FileSystemStore in one call fs.add([ind, ind1]) ``` -------------------------------- ### STIX 2.1 Greater Than Comparison Expression with Python Source: https://github.com/openstix/stix2-python/blob/master/docs/guide/patterns.ipynb Illustrates creating a STIX 2.1 observation expression using `GreaterThanComparisonExpression`. This example checks if the 'entropy' of a file's sections (using a wildcard) is greater than a specified float value. Requires `stix2` library. ```python lhs = ObjectPath("file", ["extensions", "windows-pebinary-ext", "sections[* Amd"]) gte = ObservationExpression(GreaterThanComparisonExpression(lhs, FloatConstant("7.0"))) print("\t{}\n".format(gte)) ``` -------------------------------- ### Attempt to Modify STIX Object Property via Item Assignment Source: https://github.com/openstix/stix2-python/blob/master/docs/guide/creating.ipynb This example demonstrates that STIX objects created with the `stix2` library are immutable. Attempting to modify a property using dictionary item assignment (e.g., `indicator['name'] = ...`) will raise a `TypeError`. ```python indicator['name'] = "This is a revised name" ``` -------------------------------- ### Create STIX Indicator Object Source: https://github.com/openstix/stix2-python/blob/master/docs/guide/creating.ipynb Demonstrates the creation of a STIX Indicator object using the `stix2` Python library. It shows how to instantiate the `Indicator` class with required properties like `pattern` and `pattern_type`, and optional properties such as `name`. The resulting object is then serialized to a pretty-printed JSON string. ```python from stix2 import Indicator indicator = Indicator(name="File hash for malware variant", pattern="[file:hashes.md5 = 'd41d8cd98f00b204e9800998ecf8427e']", pattern_type="stix") print(indicator.serialize(pretty=True)) ``` -------------------------------- ### Create STIX 2.x Relationships and Sightings with Python Source: https://context7.com/openstix/stix2-python/llms.txt Shows how to create STIX domain objects like ThreatActor, Malware, Campaign, Identity, and Indicator. It further demonstrates creating relationships between these objects using constructors and shorthand methods, including adding confidence and timestamps. Finally, it illustrates the creation of a Sighting object. ```python import stix2 # Create domain objects threat_actor = stix2.ThreatActor( name="APT28", threat_actor_types=["nation-state"], sophistication="expert" ) malware = stix2.Malware( name="X-Agent", malware_types=["backdoor", "remote-access-trojan"], is_family=True ) campaign = stix2.Campaign( name="Operation Pawn Storm", description="Long-running cyber espionage campaign" ) identity = stix2.Identity( name="Government Agency", identity_class="organization", sectors=["government"] ) # Create relationships using constructor uses_rel = stix2.Relationship( source_ref=threat_actor.id, target_ref=malware.id, relationship_type="uses", description="APT28 frequently deploys X-Agent malware" ) # Shorthand relationship creation attributed_to = stix2.Relationship(campaign, 'attributed-to', threat_actor) targets_rel = stix2.Relationship(campaign, 'targets', identity) # Relationship with confidence and timestamps high_confidence_rel = stix2.Relationship( source_ref=malware.id, target_ref=identity.id, relationship_type="targets", confidence=95, start_time="2023-01-01T00:00:00Z", stop_time="2024-01-01T00:00:00Z" ) # Create sighting (observed instance) indicator = stix2.Indicator( name="X-Agent C2 domain", indicator_types=["malicious-activity"], pattern_type="stix", pattern="[domain-name:value = 'apt28-c2.example.com']" ) sighting = stix2.Sighting( sighting_of_ref=indicator.id, observed_data_refs=[], first_seen="2024-01-15T10:00:00Z", last_seen="2024-01-15T18:00:00Z", count=5, where_sighted_refs=[identity.id] ) # Store and query relationships store = stix2.MemoryStore() store.add([threat_actor, malware, campaign, identity, uses_rel, attributed_to, targets_rel, sighting]) # Query for specific relationship types attack_rels = store.query([ stix2.Filter("type", "=", "relationship"), stix2.Filter("relationship_type", "=", "uses") ]) # Common relationship types: # - uses, indicates, mitigates, targets, attributed-to # - compromises, related-to, delivers, based-on, derived-from ``` -------------------------------- ### STIX Top Level Property Extension Example Source: https://github.com/openstix/stix2-python/blob/master/docs/guide/extensions.ipynb This Python code demonstrates creating a STIX Indicator object with an unregistered top-level property extension. It shows how the stix2 library accepts unrecognized top-level properties as extensions by default. The example includes custom properties 'rank' and 'toxicity'. ```python import stix2 indicator = stix2.v21.Indicator( id='indicator--e97bfccf-8970-4a3c-9cd1-5b5b97ed5d0c', created='2014-02-20T09:16:08.989000Z', modified='2014-02-20T09:16:08.989000Z', name='File hash for Poison Ivy variant', description='This file hash indicates that a sample of Poison Ivy is present.', labels=[ 'malicious-activity', ], rank=5, toxicity=8, pattern='[file:hashes.\'SHA-256\' = \'ef537f25c895bfa782526529a9b63d97aa631564d5d789c2b765448c8635fb6c']', pattern_type='stix', valid_from='2014-02-20T09:00:00.000000Z', extensions={ "extension-definition--dd73de4f-a7f3-49ea-8ec1-8e884196b7a8" : { 'extension_type': 'toplevel-property-extension', }, } ) print(indicator.serialize(pretty=True)) ``` -------------------------------- ### Remove Optional STIX Properties with new_version() in Python Source: https://github.com/openstix/stix2-python/blob/master/docs/guide/versioning.ipynb Shows how to remove optional or custom properties from a STIX object when creating a new version by setting their value to `None`. This is useful for cleaning up or updating an object's metadata. The example demonstrates removing the `description` property. ```python indicator3 = indicator.new_version(description=None) print(indicator3.serialize(pretty=True)) ``` -------------------------------- ### Python: Add STIX 2 Objects to FileSystemSink Source: https://github.com/openstix/stix2-python/blob/master/docs/guide/filesystem.ipynb This code snippet demonstrates how to use `FileSystemSink` to write STIX 2.x objects to the file system. It includes the creation of STIX objects like `Campaign` and `Indicator` and then adds them to the sink, which will persist them to the specified directory. ```python from stix2 import FileSystemSink, Campaign, Indicator # create FileSystemSink fs_sink = FileSystemSink("/tmp/stix2_sink") # create STIX objects and add to sink camp = Campaign(name="The Crusades", objective="Infiltrating Israeli, Iranian and Palestinian digital infrastructure and government systems.", aliases=["Desert Moon"]) ind = Indicator(description="Crusades C2 implant", pattern_type="stix", pattern="[file:hashes.'SHA-256' = '54b7e05e39a59428743635242e4a867c932140a999f52a1e54fa7ee6a440c73b']") ind1 = Indicator(description="Crusades C2 implant", pattern_type="stix", pattern="[file:hashes.'SHA-256' = '54b7e05e39a59428743635242e4a867c932140a999f52a1e54fa7ee6a440c73b']") # fs_sink.add(camp) # fs_sink.add([ind, ind1]) # Example of adding objects to the sink ``` -------------------------------- ### Create STIX Indicator with Explicit Type Source: https://github.com/openstix/stix2-python/blob/master/docs/guide/creating.ipynb Illustrates creating a STIX Indicator object while explicitly specifying the `type` attribute. Although the `stix2` library automatically sets the correct type ('indicator') if omitted, this example shows how to provide it directly. It also includes other required properties like `pattern_type` and `pattern`. ```python indicator2 = Indicator(type='indicator', pattern_type="stix", pattern="[file:hashes.md5 = 'd41d8cd98f00b204e9800998ecf8427e']") ``` -------------------------------- ### STIX Environment and Object Factory in Python Source: https://context7.com/openstix/stix2-python/llms.txt Illustrates the use of STIX 2.1 ObjectFactory for setting default properties and creating objects, and STIX Environment for managing workflows, parsing, querying, and relationship operations. It shows how defaults are automatically applied and how to interact with a store. ```python import stix2 # Create identity for organization org_identity = stix2.Identity( name="ACME Security", identity_class="organization" ) # Create factory with defaults factory = stix2.ObjectFactory( created_by_ref=org_identity.id, object_marking_refs=[stix2.TLP_AMBER], external_references=[{ "source_name": "internal-system", "external_id": "ACME-2024" }] ) # Create objects with factory defaults indicator = factory.create( stix2.Indicator, name="Suspicious domain", indicator_types=["malicious-activity"], pattern_type="stix", pattern="[domain-name:value = 'evil.example.com']" ) # Automatically includes: created_by_ref, object_marking_refs, external_references print(indicator.created_by_ref) # org_identity.id print(indicator.object_marking_refs) # [TLP_AMBER] # Create Environment with factory and store env = stix2.Environment( factory=factory, store=stix2.MemoryStore() ) # Create and store objects in one operation malware = env.create( stix2.Malware, name="Locky", malware_types=["ransomware"], is_family=True ) # Automatically saved to store with factory defaults # Parse objects through environment parsed = env.parse('{ "type": "threat-actor", "spec_version": "2.1", "id": "threat-actor--8e2e2d2b-17d4-4cbf-938f-98ee46b3cd3f", "created": "2024-01-15T12:00:00.000Z", "modified": "2024-01-15T12:00:00.000Z", "name": "APT28", "threat_actor_types": ["nation-state"] }') # Query through environment results = env.query([ stix2.Filter("type", "=", "malware"), stix2.Filter("malware_types", "in", "ransomware") ]) # Get related objects campaign = env.create( stix2.Campaign, name="Operation Ransomware" ) rel = stix2.Relationship(campaign, 'uses', malware) env.add(rel) related_objects = env.related_to(campaign, relationship_type="uses") for obj in related_objects: print(f"Related: {obj.name}") # Get creator of object creator = env.creator_of(indicator) print(f"Created by: {creator.name}") # Check object similarity/equivalence similarity_score = env.object_similarity(malware, parsed) is_equivalent = env.object_equivalence(malware, parsed, threshold=70) print(f"Similarity: {similarity_score}, Equivalent: {is_equivalent}") ``` -------------------------------- ### Handling Invalid Selectors for Granular Markings in Python Source: https://github.com/openstix/stix2-python/blob/master/docs/guide/markings.ipynb This example demonstrates an error scenario in the STIX 2 Python library where an invalid selector is used for granular markings. If a 'selector' in `granular_markings` does not correspond to an existing and populated field on the STIX object, an `InvalidSelectorError` will be raised. This highlights the importance of using correct field names. ```python from stix2 import Malware, MarkingDefinition, StatementMarking # Assume marking_definition is already created marking_definition = MarkingDefinition( definition_type="statement", definition=StatementMarking(statement="Copyright 2017, Example Corp") ) # This will raise an InvalidSelectorError because 'title' is not a valid field Malware(name="Poison Ivy", description="A ransomware related to ...", is_family=False, granular_markings=[ { "selectors": ["title"], "marking_ref": marking_definition } ]) ``` -------------------------------- ### Evaluating Data Markings Source: https://github.com/openstix/stix2-python/blob/master/docs/guide/markings.ipynb Provides methods to retrieve and check for markings (both object and granular) on STIX objects. ```APIDOC ## Evaluating Data Markings on STIX Objects ### Description Methods to inspect the data markings applied to STIX objects. ### Methods - `get_markings()`: Returns a list of object markings. - `get_markings(selector)`: Returns a list of granular markings for the specified selector. - `is_marked(marking_id, selector=None)`: Checks if the object is marked by a specific marking ID, optionally checking for granular markings. ### Request Example (Get Object Markings) ```python # Assuming 'indicator6' is a STIX object with markings object_markings = indicator6.get_markings() print(object_markings) ``` ### Request Example (Get Granular Markings) ```python from stix2 import get_markings # Assuming 'malware' is a STIX object and 'name' is a selector # Using the module-level function granular_markings_module = get_markings(malware, 'name') print(granular_markings_module) # Using the object method granular_markings_method = malware.get_markings('name') print(granular_markings_method) ``` ### Request Example (Check if Marked) ```python # Assuming 'indicator' is a STIX object and 'TLP_AMBER' is a marking object marked_by_amber = indicator.is_marked(TLP_AMBER.id) print(marked_by_amber) # Assuming 'malware' is a STIX object and 'TLP_WHITE' is a marking object marked_by_white_name = malware.is_marked(TLP_WHITE.id, 'name') print(marked_by_white_name) marked_by_white_desc = malware.is_marked(TLP_WHITE.id, 'description') print(marked_by_white_desc) ``` ``` -------------------------------- ### Create STIX Malware with Granular Markings in Python Source: https://github.com/openstix/stix2-python/blob/master/docs/guide/markings.ipynb Shows how to create a STIX Malware object with granular markings applied to specific fields like 'description' and 'name'. It uses a combination of a custom statement marking and a predefined TLP_WHITE marking. This requires the `stix2` library and involves providing a list of dictionaries, each containing 'selectors' and 'marking_ref'. The output is serialized to pretty-printed JSON. ```python from stix2 import Malware, TLP_WHITE, MarkingDefinition, StatementMarking # Assume marking_definition is already created as in previous example marking_definition = MarkingDefinition( definition_type="statement", definition=StatementMarking(statement="Copyright 2017, Example Corp") ) malware = Malware(name="Poison Ivy", description="A ransomware related to ...", is_family=False, granular_markings=[ { "selectors": ["description"], "marking_ref": marking_definition }, { "selectors": ["name"], "marking_ref": TLP_WHITE } ]) print(malware.serialize(pretty=True)) ``` -------------------------------- ### Create FollowedBy Observation Expression Source: https://github.com/openstix/stix2-python/blob/master/docs/guide/patterns.ipynb Builds a FollowedByObservationExpression which represents a sequence of events where one observation must occur after another. It takes a list of ObservationExpressions as its argument. ```python from stix2 import (ObservationExpression, EqualityComparisonExpression, ObjectPath, HashConstant, FollowedByObservationExpression) ece10 = ObservationExpression(EqualityComparisonExpression(ObjectPath("file", ["hashes", "MD5"]), HashConstant("79054025255fb1a26e4bc422aef54eb4", "MD5"))) ece11 = ObservationExpression(EqualityComparisonExpression(ObjectPath("win-registry-key", ["key"]), "HKEY_LOCAL_MACHINE\foo\bar")) fbe = FollowedByObservationExpression([ece10, ece11]) print("(FollowedBy)\n{} ".format(fbe)) ``` -------------------------------- ### Create STIX Indicator with Predefined TLP Marking in Python Source: https://github.com/openstix/stix2-python/blob/master/docs/guide/markings.ipynb Demonstrates how to create a STIX Indicator object and apply a predefined Traffic Light Protocol (TLP) marking, specifically TLP_AMBER. This requires the `stix2` library. The `object_marking_refs` argument takes the marking object directly. The output is serialized to pretty-printed JSON. ```python from stix2 import Indicator, TLP_AMBER indicator = Indicator(pattern_type="stix", pattern="[file:hashes.md5 = 'd41d8cd98f00b204e9800998ecf8427e']", object_marking_refs=TLP_AMBER) print(indicator.serialize(pretty=True)) ``` -------------------------------- ### Query Malware by Type using Filter in MemoryStore Source: https://github.com/openstix/stix2-python/blob/master/docs/guide/memory.ipynb Demonstrates how to query the MemoryStore for specific STIX objects using the Filter class. This example retrieves Malware objects of type 'rootkit'. It requires the 'stix2' library and an initialized MemoryStore containing relevant data. ```python from stix2 import Filter # Assuming 'mem' is an initialized MemoryStore object with Malware data mal = mem.query([Filter("malware_types","=", "rootkit")])[0] print(mal.serialize(pretty=True)) ``` -------------------------------- ### Removing Custom Properties from STIX Objects Source: https://github.com/openstix/stix2-python/blob/master/docs/guide/custom.ipynb Illustrates how to remove a custom property from an existing STIX object by using the `new_version()` method and setting the custom property to `None`. ```python identity4 = identity3.new_version(x_foo=None) print(identity4.serialize(pretty=True)) ``` -------------------------------- ### Create and Version STIX Malware Objects in Python Source: https://context7.com/openstix/stix2-python/llms.txt Demonstrates how to create initial STIX Malware objects, create new versions with updated properties, revoke objects, and handle immutable property errors. It also shows how to store and retrieve multiple versions of an object using a MemoryStore. ```python import stix2 # Create initial version malware_v1 = stix2.Malware( name="Zeus", malware_types=["trojan"], is_family=True, description="Banking trojan" ) print(f"Version 1 ID: {malware_v1.id}") print(f"Version 1 created: {malware_v1.created}") print(f"Version 1 modified: {malware_v1.modified}") # Create new version with updates malware_v2 = malware_v1.new_version( description="Banking trojan with keylogging capabilities", malware_types=["trojan", "keylogger"] ) # Immutable properties (same in both versions) assert malware_v1.id == malware_v2.id assert malware_v1.created == malware_v2.created assert malware_v1.type == malware_v2.type # Modified timestamp is automatically updated assert malware_v2.modified > malware_v1.modified # Properties that changed print(f"V1 description: {malware_v1.description}") print(f"V2 description: {malware_v2.description}") # Create another version malware_v3 = malware_v2.new_version( name="Zeus v3", aliases=["Zbot", "PRG"] ) # Revoke an object revoked_malware = malware_v3.revoke() print(f"Revoked: {revoked_malware.revoked}") # True print(f"Revoked modified: {revoked_malware.modified}") # Cannot modify immutable properties (raises error) try: malware_bad = malware_v1.new_version( created="2023-01-01T00:00:00Z" # Error! ) except stix2.exceptions.UnmodifiablePropertyError as e: print(f"Error: {e}") # Store and retrieve versions store = stix2.MemoryStore() store.add([malware_v1, malware_v2, malware_v3]) all_versions = store.all_versions(malware_v1.id) print(f"Total versions: {len(all_versions)}") for v in all_versions: print(f" Modified: {v.modified}") # Get latest version (default behavior) latest = store.get(malware_v1.id) assert latest.modified == malware_v3.modified ``` -------------------------------- ### Create STIX 2.x Observables with Python Source: https://context7.com/openstix/stix2-python/llms.txt Demonstrates the creation of various STIX 2.x observable objects including EmailMessage, Process, URL, UserAccount, and WindowsRegistryKey. It also shows how to parse a JSON string into a STIX observable object. ```python import stix2 # Email message observable email = stix2.EmailMessage( is_multipart=False, subject="Urgent: Security Alert", from_ref=stix2.EmailAddress(value="attacker@evil.com").id, body="Click this link: http://phishing.example.com" ) # Process observable process = stix2.Process( pid=1234, name="malware.exe", command_line="malware.exe --silent", created_time="2024-01-15T10:30:00Z" ) # URL observable url = stix2.URL(value="https://malicious.example.com/payload.exe") # User account observable user_account = stix2.UserAccount( user_id="admin", account_login="administrator", account_type="windows-local" ) # Windows registry key observable registry_key = stix2.WindowsRegistryKey( key="HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows\\CurrentVersion\\Run", values=[ { "name": "Updater", "data": "C:\\malware\\update.exe", "data_type": "REG_SZ" } ] ) # Parse observable from JSON observable_json = '{"type": "ipv4-addr", "value": "10.0.0.1"}' parsed_ip = stix2.parse_observable(observable_json) print(parsed_ip.value) # 10.0.0.1 ``` -------------------------------- ### Check if STIX Object is Marked (Python) Source: https://github.com/openstix/stix2-python/blob/master/docs/guide/markings.ipynb Illustrates how to check if a STIX object is marked by a specific marking definition ID. For granular markings, a selector must also be provided. ```python indicator.is_marked(TLP_AMBER.id) ``` ```python malware.is_marked(TLP_WHITE.id, 'name') ``` ```python malware.is_marked(TLP_WHITE.id, 'description') ``` -------------------------------- ### Pretty Print JSON with Syntax Highlighting in IPython Source: https://github.com/openstix/stix2-python/blob/master/docs/guide/serializing.ipynb This code snippet configures IPython to pretty-print JSON output with HTML syntax highlighting. It replaces the default `print` function with a custom one that detects JSON and applies appropriate lexers and formatters from the Pygments library. ```python # JSON output syntax highlighting from __future__ import print_function from pygments import highlight from pygments.lexers import JsonLexer, TextLexer from pygments.formatters import HtmlFormatter from IPython.display import display, HTML from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = "all" def json_print(inpt): string = str(inpt) formatter = HtmlFormatter() if string[0] == '{': lexer = JsonLexer() else: lexer = TextLexer() return HTML('{}'.format( formatter.get_style_defs('.highlight'), highlight(string, lexer, formatter))) globals()['print'] = json_print ```