Checking Semantic Equivalence

The Environment has a function for checking if two STIX Objects are semantically equivalent. For each supported object type, the algorithm checks if the values for a specific set of properties match. Then each matching property is weighted since every property doesn’t represent the same level of importance for semantic equivalence. The result will be the sum of these weighted values, in the range of 0 to 100. A result of 0 means that the the two objects are not equivalent, and a result of 100 means that they are equivalent.

TODO: Add a link to the committee note when it is released.

Below we will show examples of the semantic equivalence results of various objects. Unless otherwise specified, the ID of each object will be generated by the library, so the two objects will not have the same ID. This demonstrates that the semantic equivalence algorithm only looks at specific properties for each object type.

Attack Pattern Example

For Attack Patterns, the only properties that contribute to semantic equivalence are name and external_references, with weights of 30 and 70, respectively. In this example, both attack patterns have the same external reference but the second has a slightly different yet still similar name.

[3]:
import stix2
from stix2 import Environment, MemoryStore
from stix2.v21 import AttackPattern

env = Environment(store=MemoryStore())

ap1 = AttackPattern(
    name="Phishing",
    external_references=[
        {
            "url": "https://example2",
            "source_name": "some-source2",
        },
    ],
)
ap2 = AttackPattern(
    name="Spear phishing",
    external_references=[
        {
            "url": "https://example2",
            "source_name": "some-source2",
        },
    ],
)
print(env.semantically_equivalent(ap1, ap2))
[3]:
85.3

Campaign Example

For Campaigns, the only properties that contribute to semantic equivalence are name and aliases, with weights of 60 and 40, respectively. In this example, the two campaigns have completely different names, but slightly similar descriptions. The result may be higher than expected because the Jaro-Winkler algorithm used to compare string properties looks at the edit distance of the two strings rather than just the words in them.

[4]:
from stix2.v21 import Campaign

c1 = Campaign(
    name="Someone Attacks Somebody",)

c2 = Campaign(
    name="Another Campaign",)
print(env.semantically_equivalent(c1, c2))
[4]:
50.0

Identity Example

For Identities, the only properties that contribute to semantic equivalence are name, identity_class, and sectors, with weights of 60, 20, and 20, respectively. In this example, the two identities are identical, but are missing one of the contributing properties. The algorithm only compares properties that are actually present on the objects. Also note that they have completely different description properties, but because description is not one of the properties considered for semantic equivalence, this difference has no effect on the result.

[5]:
from stix2.v21 import Identity

id1 = Identity(
    name="John Smith",
    identity_class="individual",
    description="Just some guy",
)
id2 = Identity(
    name="John Smith",
    identity_class="individual",
    description="A person",
)
print(env.semantically_equivalent(id1, id2))
[5]:
100.0

Indicator Example

For Indicators, the only properties that contribute to semantic equivalence are indicator_types, pattern, and valid_from, with weights of 15, 80, and 5, respectively. In this example, the two indicators have patterns with different hashes but the same indicator_type and valid_from. For patterns, the algorithm currently only checks if they are identical.

[6]:
from stix2.v21 import Indicator

ind1 = Indicator(
    indicator_types=['malicious-activity'],
    pattern_type="stix",
    pattern="[file:hashes.MD5 = 'd41d8cd98f00b204e9800998ecf8427e']",
    valid_from="2017-01-01T12:34:56Z",
)
ind2 = Indicator(
    indicator_types=['malicious-activity'],
    pattern_type="stix",
    pattern="[file:hashes.MD5 = '79054025255fb1a26e4bc422aef54eb4']",
    valid_from="2017-01-01T12:34:56Z",
)
print(env.semantically_equivalent(ind1, ind2))
Indicator pattern equivalence is not fully defined; will default to zero if not completely identical
[6]:
20.0

If the patterns were identical the result would have been 100.

Location Example

For Locations, the only properties that contribute to semantic equivalence are longitude/latitude, region, and country, with weights of 34, 33, and 33, respectively. In this example, the two locations are Washington, D.C. and New York City. The algorithm computes the distance between two locations using the haversine formula and uses that to influence equivalence.

[7]:
from stix2.v21 import Location

loc1 = Location(
    latitude=38.889,
    longitude=-77.023,
)
loc2 = Location(
    latitude=40.713,
    longitude=-74.006,
)
print(env.semantically_equivalent(loc1, loc2))
[7]:
67.20663955882583

Malware Example

For Malware, the only properties that contribute to semantic equivalence are malware_types and name, with weights of 20 and 80, respectively. In this example, the two malware objects only differ in the strings in their malware_types lists. For lists, the algorithm bases its calculations on the intersection of the two lists. An empty intersection will result in a 0, and a complete intersection will result in a 1 for that property.

[8]:
from stix2.v21 import Malware

MALWARE_ID = "malware--9c4638ec-f1de-4ddb-abf4-1b760417654e"

mal1 = Malware(id=MALWARE_ID,
    malware_types=['ransomware'],
    name="Cryptolocker",
    is_family=False,
    )
mal2 = Malware(id=MALWARE_ID,
    malware_types=['ransomware', 'dropper'],
    name="Cryptolocker",
    is_family=False,
    )
print(env.semantically_equivalent(mal1, mal2))
[8]:
90.0

Threat Actor Example

For Threat Actors, the only properties that contribute to semantic equivalence are threat_actor_types, name, and aliases, with weights of 20, 60, and 20, respectively. In this example, the two threat actors have the same id properties but everything else is different. Since the id property does not factor into semantic equivalence, the result is not very high. The result is not zero because the algorithm is using the Jaro-Winkler distance between strings in the threat_actor_types and name properties.

[9]:
from stix2.v21 import ThreatActor

THREAT_ACTOR_ID = "threat-actor--8e2e2d2b-17d4-4cbf-938f-98ee46b3cd3f"

ta1 = ThreatActor(id=THREAT_ACTOR_ID,
    threat_actor_types=["crime-syndicate"],
    name="Evil Org",
    aliases=["super-evil"],
)
ta2 = ThreatActor(id=THREAT_ACTOR_ID,
    threat_actor_types=["spy"],
    name="James Bond",
    aliases=["007"],
)
print(env.semantically_equivalent(ta1, ta2))
[9]:
33.6

Tool Example

For Tools, the only properties that contribute to semantic equivalence are tool_types and name, with weights of 20 and 80, respectively. In this example, the two tools have the same values for properties that contribute to semantic equivalence but one has an additional, non-contributing property.

[10]:
from stix2.v21 import Tool

t1 = Tool(
    tool_types=["remote-access"],
    name="VNC",
)
t2 = Tool(
    tool_types=["remote-access"],
    name="VNC",
    description="This is a tool"
)
print(env.semantically_equivalent(t1, t2))
[10]:
100.0

Vulnerability Example

For Vulnerabilities, the only properties that contribute to semantic equivalence are name and external_references, with weights of 30 and 70, respectively. In this example, the two vulnerabilities have the same name but one also has an external reference. The algorithm doesn’t take into account any semantic equivalence contributing properties that are not present on both objects.

[11]:
from stix2.v21 import Vulnerability

vuln1 = Vulnerability(
    name="Heartbleed",
    external_references=[
        {
            "url": "https://example",
            "source_name": "some-source",
        },
    ],
)
vuln2 = Vulnerability(
    name="Heartbleed",
)
print(env.semantically_equivalent(vuln1, vuln2))
[11]:
100.0

Other Examples

Comparing objects of different types will result in an error.

[12]:
print(env.semantically_equivalent(ind1, vuln1))
ValueError: The objects to compare must be of the same type!

Some object types do not have a defined method for calculating semantic equivalence and by default will give a warning and a result of zero.

[13]:
from stix2.v21 import Report

r1 = Report(
    report_types=["campaign"],
    name="Bad Cybercrime",
    published="2016-04-06T20:03:00.000Z",
    object_refs=["indicator--a740531e-63ff-4e49-a9e1-a0a3eed0e3e7"],
)
r2 = Report(
    report_types=["campaign"],
    name="Bad Cybercrime",
    published="2016-04-06T20:03:00.000Z",
    object_refs=["indicator--a740531e-63ff-4e49-a9e1-a0a3eed0e3e7"],
)
print(env.semantically_equivalent(r1, r2))
'report' type has no semantic equivalence method to call!
[13]:
0

By default, comparing objects of different spec versions will result in a ValueError.

[14]:
from stix2.v20 import Identity as Identity20

id20 = Identity20(
    name="John Smith",
    identity_class="individual",
)
print(env.semantically_equivalent(id2, id20))
ValueError: The objects to compare must be of the same spec version!

You can optionally allow comparing across spec versions by providing a configuration dictionary like in the next example:

[15]:
from stix2.v20 import Identity as Identity20

id20 = Identity20(
    name="John Smith",
    identity_class="individual",
)
print(env.semantically_equivalent(id2, id20, **{"_internal": {"ignore_spec_version": True}}))
[15]:
100.0

You can modify the weights or provide your own functions for comparing objects of a certain type by providing them in a dictionary to the optional 3rd parameter to the semantic equivalence function. You can find functions (like partial_string_based) to help with this in the Environment API docs. In this example we define semantic equivalence for our new x-foobar object type:

[16]:
def _x_foobar_checks(obj1, obj2, **weights):
    matching_score = 0.0
    sum_weights = 0.0
    if stix2.environment.check_property_present("name", obj1, obj2):
        w = weights["name"]
        sum_weights += w
        matching_score += w * stix2.environment.partial_string_based(obj1["name"], obj2["name"])
    if stix2.environment.check_property_present("color", obj1, obj2):
        w = weights["color"]
        sum_weights += w
        matching_score += w * stix2.environment.partial_string_based(obj1["color"], obj2["color"])
    return matching_score, sum_weights

weights = {
    "x-foobar": {
        "name": 60,
        "color": 40,
        "method": _x_foobar_checks,
    },
    "_internal": {
        "ignore_spec_version": False,
    },
}
foo1 = {
    "type":"x-foobar",
    "id":"x-foobar--0c7b5b88-8ff7-4a4d-aa9d-feb398cd0061",
    "name": "Zot",
    "color": "red",
}
foo2 = {
    "type":"x-foobar",
    "id":"x-foobar--0c7b5b88-8ff7-4a4d-aa9d-feb398cd0061",
    "name": "Zot",
    "color": "blue",
}
print(env.semantically_equivalent(foo1, foo2, **weights))
[16]:
60.0

Detailed Results

If your logging level is set to DEBUG or higher, the function will log more detailed results. These show the semantic equivalence and weighting for each property that is checked, to show how the final result was arrived at.

[17]:
import logging
logging.basicConfig(format='%(message)s')
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)

ta3 = ThreatActor(
    threat_actor_types=["crime-syndicate"],
    name="Evil Org",
    aliases=["super-evil"],
)
ta4 = ThreatActor(
    threat_actor_types=["spy"],
    name="James Bond",
    aliases=["007"],
)
print(env.semantically_equivalent(ta3, ta4))
Starting semantic equivalence process between: 'threat-actor--54dc2aac-6fde-4a68-ae2a-0c0bc575ed70' and 'threat-actor--c51bce3b-a067-4692-ab77-fcdefdd3f157'
--              partial_string_based 'Evil Org' 'James Bond'    result: '0.56'
'name' check -- weight: 60, contributing score: 33.6
--              partial_list_based '['crime-syndicate']' '['spy']'      result: '0.0'
'threat_actor_types' check -- weight: 20, contributing score: 0.0
--              partial_list_based '['super-evil']' '['007']'   result: '0.0'
'aliases' check -- weight: 20, contributing score: 0.0
Matching Score: 33.6, Sum of Weights: 100.0
[17]:
33.6