From 4e5eb8845807c0c9d3c4cf7707ad6f7caba5ad68 Mon Sep 17 00:00:00 2001 From: Chris Lenk Date: Fri, 16 Mar 2018 16:38:29 -0400 Subject: [PATCH 01/61] Increase versioning code coverage slightly --- stix2/test/test_versioning.py | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/stix2/test/test_versioning.py b/stix2/test/test_versioning.py index 233587e..fa3bddb 100644 --- a/stix2/test/test_versioning.py +++ b/stix2/test/test_versioning.py @@ -233,12 +233,19 @@ def test_remove_custom_stix_object(): ("animal_class", stix2.properties.StringProperty()), ]) class Animal(object): - def __init__(self, animal_class=None, **kwargs): - if animal_class and animal_class not in ["mammal", "bird"]: - raise ValueError("Not a recognized class of animal") + pass animal = Animal(species="lion", animal_class="mammal") nc = stix2.utils.remove_custom_stix(animal) assert nc is None + + +def test_remove_custom_stix_no_custom(): + campaign_v1 = stix2.Campaign(**CAMPAIGN_MORE_KWARGS) + campaign_v2 = stix2.utils.remove_custom_stix(campaign_v1) + + assert len(campaign_v1.keys()) == len(campaign_v2.keys()) + assert campaign_v1.id == campaign_v2.id + assert campaign_v1.description == campaign_v2.description From 89cf4bc38f6b65769a6a989880124ab0905b8626 Mon Sep 17 00:00:00 2001 From: = Date: Thu, 29 Mar 2018 11:49:30 -0400 Subject: [PATCH 02/61] WIP:allow unknown custom objects to be processed by parse; WIP: splitting up parse utility into components; found bug in tests that wasnt providing for proper teardown cleaning, fixed --- stix2/core.py | 42 +++++++++++++++++++++++++++++++-------- stix2/test/test_memory.py | 23 ++++++++++++++++----- 2 files changed, 52 insertions(+), 13 deletions(-) diff --git a/stix2/core.py b/stix2/core.py index b6d295d..64307ff 100644 --- a/stix2/core.py +++ b/stix2/core.py @@ -77,14 +77,36 @@ def parse(data, allow_custom=False, version=None): Args: data (str, dict, file-like object): The STIX 2 content to be parsed. - allow_custom (bool): Whether to allow custom properties or not. - Default: False. + allow_custom (bool): Whether to allow custom properties as well unknown + custom objects. Note that unknown custom objects cannot be parsed + into STIX objects, and will be returned as is. Default: False. version (str): Which STIX2 version to use. (e.g. "2.0", "2.1"). If None, use latest version. Returns: An instantiated Python STIX object. + """ + # convert STIX object to dict, if not already + obj = get_dict(data) + + # convert dict to full python-stix2 obj + obj = dict_to_stix2(obj, allow_custom, version) + + return obj + + +def dict_to_stix2(stix_dict, allow_custom=False, version=None): + """convert dictionary to full python-stix2 object + + Args: + stix_dict (dict): a python dictionary of a STIX object + that (presumably) is semantically correct to be parsed + into a full python-stix2 obj + allow_custom (bool): Whether to allow custom properties as well unknown + custom objects. Note that unknown custom objects cannot be parsed + into STIX objects, and will be returned as is. Default: False. + """ if not version: # Use latest version @@ -93,16 +115,20 @@ def parse(data, allow_custom=False, version=None): v = 'v' + version.replace('.', '') OBJ_MAP = STIX2_OBJ_MAPS[v] - obj = get_dict(data) - if 'type' not in obj: - raise exceptions.ParseError("Can't parse object with no 'type' property: %s" % str(obj)) + if 'type' not in stix_dict: + raise exceptions.ParseError("Can't parse object with no 'type' property: %s" % str(stix_dict)) try: - obj_class = OBJ_MAP[obj['type']] + obj_class = OBJ_MAP[stix_dict['type']] except KeyError: - raise exceptions.ParseError("Can't parse unknown object type '%s'! For custom types, use the CustomObject decorator." % obj['type']) - return obj_class(allow_custom=allow_custom, **obj) + if allow_custom: + # flag allows for unknown custom objects too, but will not + # be parsed into STIX object, returned as is + return stix_dict + raise exceptions.ParseError("Can't parse unknown object type '%s'! For custom types, use the CustomObject decorator." % stix_dict['type']) + + return obj_class(allow_custom=allow_custom, **stix_dict) def _register_type(new_type, version=None): diff --git a/stix2/test/test_memory.py b/stix2/test/test_memory.py index 2384848..284c43e 100644 --- a/stix2/test/test_memory.py +++ b/stix2/test/test_memory.py @@ -136,6 +136,19 @@ def rel_mem_store(): yield MemoryStore(stix_objs) +@pytest.fixture +def fs_mem_store(request, mem_store): + filename = 'memory_test/mem_store.json' + mem_store.save_to_file(filename) + + def fin(): + # teardown, excecuted regardless of exception + shutil.rmtree(os.path.dirname(filename)) + request.addfinalizer(fin) + + return filename + + def test_memory_source_get(mem_source): resp = mem_source.get("indicator--d81f86b8-975b-bc0b-775e-810c5ad45a4f") assert resp["id"] == "indicator--d81f86b8-975b-bc0b-775e-810c5ad45a4f" @@ -187,9 +200,11 @@ def test_memory_store_query_multiple_filters(mem_store): assert len(resp) == 1 -def test_memory_store_save_load_file(mem_store): - filename = 'memory_test/mem_store.json' - mem_store.save_to_file(filename) +def test_memory_store_save_load_file(mem_store, fs_mem_store): + filename = fs_mem_store # the fixture fs_mem_store yields filename where the memory store was written to + + # STIX2 contents of mem_store have already been written to file + # (this is done in fixture 'fs_mem_store'), so can already read-in here contents = open(os.path.abspath(filename)).read() assert '"id": "indicator--d81f86b9-975b-bc0b-775e-810c5ad45a4f",' in contents @@ -200,8 +215,6 @@ def test_memory_store_save_load_file(mem_store): assert mem_store2.get("indicator--d81f86b8-975b-bc0b-775e-810c5ad45a4f") assert mem_store2.get("indicator--d81f86b9-975b-bc0b-775e-810c5ad45a4f") - shutil.rmtree(os.path.dirname(filename)) - def test_memory_store_add_invalid_object(mem_store): ind = ('indicator', IND1) # tuple isn't valid From aeff8f4bc09f36d9dc744a5781b3c61fae17dc75 Mon Sep 17 00:00:00 2001 From: Chris Lenk Date: Wed, 29 Nov 2017 08:58:01 -0500 Subject: [PATCH 03/61] Create Workbench layer Contains a default implicit Environment and functions to get all objects a specific type. --- stix2/test/constants.py | 57 +++++++++++--- stix2/test/test_workbench.py | 139 +++++++++++++++++++++++++++++++++++ stix2/workbench.py | 72 ++++++++++++++++++ 3 files changed, 259 insertions(+), 9 deletions(-) create mode 100644 stix2/test/test_workbench.py create mode 100644 stix2/workbench.py diff --git a/stix2/test/constants.py b/stix2/test/constants.py index 3db39d6..ab7fcf3 100644 --- a/stix2/test/constants.py +++ b/stix2/test/constants.py @@ -34,14 +34,18 @@ RELATIONSHIP_IDS = [ 'relationship--a0cbb21c-8daf-4a7f-96aa-7155a4ef8f70' ] -# All required args for a Campaign instance +# *_KWARGS contains all required arguments to create an instance of that STIX object +# *_MORE_KWARGS contains all the required arguments, plus some optional ones + +ATTACK_PATTERN_KWARGS = dict( + name="Phishing", +) + CAMPAIGN_KWARGS = dict( name="Green Group Attacks Against Finance", description="Campaign by Green Group against a series of targets in the financial services sector.", ) - -# All required args for a Campaign instance, plus some optional args CAMPAIGN_MORE_KWARGS = dict( type='campaign', id=CAMPAIGN_ID, @@ -52,25 +56,29 @@ CAMPAIGN_MORE_KWARGS = dict( description="Campaign by Green Group against a series of targets in the financial services sector.", ) -# Minimum required args for an Identity instance +COURSE_OF_ACTION_KWARGS = dict( + name="Block", +) + IDENTITY_KWARGS = dict( name="John Smith", identity_class="individual", ) -# Minimum required args for an Indicator instance INDICATOR_KWARGS = dict( labels=['malicious-activity'], pattern="[file:hashes.MD5 = 'd41d8cd98f00b204e9800998ecf8427e']", ) -# Minimum required args for a Malware instance +INTRUSION_SET_KWARGS = dict( + name="Bobcat Breakin", +) + MALWARE_KWARGS = dict( labels=['ransomware'], name="Cryptolocker", ) -# All required args for a Malware instance, plus some optional args MALWARE_MORE_KWARGS = dict( type='malware', id=MALWARE_ID, @@ -81,14 +89,45 @@ MALWARE_MORE_KWARGS = dict( description="A ransomware related to ..." ) -# Minimum required args for a Relationship instance +OBSERVED_DATA_KWARGS = dict( + first_observed=FAKE_TIME, + last_observed=FAKE_TIME, + number_observed=1, + objects={ + "0": { + "type": "windows-registry-key", + "key": "HKEY_LOCAL_MACHINE\\System\\Foo\\Bar", + } + } +) + +REPORT_KWARGS = dict( + labels=["campaign"], + name="Bad Cybercrime", + published=FAKE_TIME, + object_refs=[INDICATOR_ID], +) + RELATIONSHIP_KWARGS = dict( relationship_type="indicates", source_ref=INDICATOR_ID, target_ref=MALWARE_ID, ) -# Minimum required args for a Sighting instance SIGHTING_KWARGS = dict( sighting_of_ref=INDICATOR_ID, ) + +THREAT_ACTOR_KWARGS = dict( + labels=["crime-syndicate"], + name="Evil Org", +) + +TOOL_KWARGS = dict( + labels=["remote-access"], + name="VNC", +) + +VULNERABILITY_KWARGS = dict( + name="Heartbleed", +) diff --git a/stix2/test/test_workbench.py b/stix2/test/test_workbench.py new file mode 100644 index 0000000..5e2809b --- /dev/null +++ b/stix2/test/test_workbench.py @@ -0,0 +1,139 @@ +import stix2 +from stix2.workbench import (add, all_versions, attack_patterns, campaigns, + courses_of_action, create, get, identities, + indicators, intrusion_sets, malware, + observed_data, query, reports, threat_actors, + tools, vulnerabilities) + +from .constants import (ATTACK_PATTERN_ID, ATTACK_PATTERN_KWARGS, CAMPAIGN_ID, + CAMPAIGN_KWARGS, COURSE_OF_ACTION_ID, + COURSE_OF_ACTION_KWARGS, IDENTITY_ID, IDENTITY_KWARGS, + INDICATOR_ID, INDICATOR_KWARGS, INTRUSION_SET_ID, + INTRUSION_SET_KWARGS, MALWARE_ID, MALWARE_KWARGS, + OBSERVED_DATA_ID, OBSERVED_DATA_KWARGS, REPORT_ID, + REPORT_KWARGS, THREAT_ACTOR_ID, THREAT_ACTOR_KWARGS, + TOOL_ID, TOOL_KWARGS, VULNERABILITY_ID, + VULNERABILITY_KWARGS) + + +def test_workbench_environment(): + + # Create a STIX object + ind = create(stix2.Indicator, id=INDICATOR_ID, **INDICATOR_KWARGS) + add(ind) + + resp = get(INDICATOR_ID) + assert resp['labels'][0] == 'malicious-activity' + + resp = all_versions(INDICATOR_ID) + assert len(resp) == 1 + + # Search on something other than id + q = [stix2.Filter('type', '=', 'vulnerability')] + resp = query(q) + assert len(resp) == 0 + + +def test_workbench_get_all_attack_patterns(): + mal = stix2.AttackPattern(id=ATTACK_PATTERN_ID, **ATTACK_PATTERN_KWARGS) + add(mal) + + resp = attack_patterns() + assert len(resp) == 1 + assert resp[0].id == ATTACK_PATTERN_ID + + +def test_workbench_get_all_campaigns(): + cam = stix2.Campaign(id=CAMPAIGN_ID, **CAMPAIGN_KWARGS) + add(cam) + + resp = campaigns() + assert len(resp) == 1 + assert resp[0].id == CAMPAIGN_ID + + +def test_workbench_get_all_courses_of_action(): + coa = stix2.CourseOfAction(id=COURSE_OF_ACTION_ID, **COURSE_OF_ACTION_KWARGS) + add(coa) + + resp = courses_of_action() + assert len(resp) == 1 + assert resp[0].id == COURSE_OF_ACTION_ID + + +def test_workbench_get_all_identities(): + idty = stix2.Identity(id=IDENTITY_ID, **IDENTITY_KWARGS) + add(idty) + + resp = identities() + assert len(resp) == 1 + assert resp[0].id == IDENTITY_ID + + +def test_workbench_get_all_indicators(): + resp = indicators() + assert len(resp) == 1 + assert resp[0].id == INDICATOR_ID + + +def test_workbench_get_all_intrusion_sets(): + ins = stix2.IntrusionSet(id=INTRUSION_SET_ID, **INTRUSION_SET_KWARGS) + add(ins) + + resp = intrusion_sets() + assert len(resp) == 1 + assert resp[0].id == INTRUSION_SET_ID + + +def test_workbench_get_all_malware(): + mal = stix2.Malware(id=MALWARE_ID, **MALWARE_KWARGS) + add(mal) + + resp = malware() + assert len(resp) == 1 + assert resp[0].id == MALWARE_ID + + +def test_workbench_get_all_observed_data(): + od = stix2.ObservedData(id=OBSERVED_DATA_ID, **OBSERVED_DATA_KWARGS) + add(od) + + resp = observed_data() + assert len(resp) == 1 + assert resp[0].id == OBSERVED_DATA_ID + + +def test_workbench_get_all_reports(): + rep = stix2.Report(id=REPORT_ID, **REPORT_KWARGS) + add(rep) + + resp = reports() + assert len(resp) == 1 + assert resp[0].id == REPORT_ID + + +def test_workbench_get_all_threat_actors(): + thr = stix2.ThreatActor(id=THREAT_ACTOR_ID, **THREAT_ACTOR_KWARGS) + add(thr) + + resp = threat_actors() + assert len(resp) == 1 + assert resp[0].id == THREAT_ACTOR_ID + + +def test_workbench_get_all_tools(): + tool = stix2.Tool(id=TOOL_ID, **TOOL_KWARGS) + add(tool) + + resp = tools() + assert len(resp) == 1 + assert resp[0].id == TOOL_ID + + +def test_workbench_get_all_vulnerabilities(): + vuln = stix2.Vulnerability(id=VULNERABILITY_ID, **VULNERABILITY_KWARGS) + add(vuln) + + resp = vulnerabilities() + assert len(resp) == 1 + assert resp[0].id == VULNERABILITY_ID diff --git a/stix2/workbench.py b/stix2/workbench.py new file mode 100644 index 0000000..55c8009 --- /dev/null +++ b/stix2/workbench.py @@ -0,0 +1,72 @@ +"""Functions and class wrappers for interacting with STIX data at a high level. +""" + +from .environment import Environment +from .sources.filters import Filter +from .sources.memory import MemoryStore + +_environ = Environment(store=MemoryStore()) + +create = _environ.create +get = _environ.get +all_versions = _environ.all_versions +query = _environ.query +creator_of = _environ.creator_of +relationships = _environ.relationships +related_to = _environ.related_to +add = _environ.add +add_filters = _environ.add_filters +add_filter = _environ.add_filter +parse = _environ.parse +add_data_source = _environ.source.add_data_source + + +# Functions to get all objects of a specific type + + +def attack_patterns(): + return query(Filter('type', '=', 'attack-pattern')) + + +def campaigns(): + return query(Filter('type', '=', 'campaign')) + + +def courses_of_action(): + return query(Filter('type', '=', 'course-of-action')) + + +def identities(): + return query(Filter('type', '=', 'identity')) + + +def indicators(): + return query(Filter('type', '=', 'indicator')) + + +def intrusion_sets(): + return query(Filter('type', '=', 'intrusion-set')) + + +def malware(): + return query(Filter('type', '=', 'malware')) + + +def observed_data(): + return query(Filter('type', '=', 'observed-data')) + + +def reports(): + return query(Filter('type', '=', 'report')) + + +def threat_actors(): + return query(Filter('type', '=', 'threat-actor')) + + +def tools(): + return query(Filter('type', '=', 'tool')) + + +def vulnerabilities(): + return query(Filter('type', '=', 'vulnerability')) From b2613ca62c0c552b37900c1efc4a8b413e2391cb Mon Sep 17 00:00:00 2001 From: Chris Lenk Date: Wed, 29 Nov 2017 14:12:54 -0500 Subject: [PATCH 04/61] Add Workbench wrapper functions --- stix2/test/test_workbench.py | 31 +++++++++++++++++++++++++++++++ stix2/workbench.py | 28 ++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+) diff --git a/stix2/test/test_workbench.py b/stix2/test/test_workbench.py index 5e2809b..7f3c9fc 100644 --- a/stix2/test/test_workbench.py +++ b/stix2/test/test_workbench.py @@ -137,3 +137,34 @@ def test_workbench_get_all_vulnerabilities(): resp = vulnerabilities() assert len(resp) == 1 assert resp[0].id == VULNERABILITY_ID + + +def test_workbench_relationships(): + rel = stix2.Relationship(INDICATOR_ID, 'indicates', MALWARE_ID) + add(rel) + + ind = get(INDICATOR_ID) + resp = ind.relationships() + assert len(resp) == 1 + assert resp[0].relationship_type == 'indicates' + assert resp[0].source_ref == INDICATOR_ID + assert resp[0].target_ref == MALWARE_ID + + +def test_workbench_created_by(): + intset = stix2.IntrusionSet(name="Breach 123", created_by_ref=IDENTITY_ID) + add(intset) + creator = intset.created_by() + assert creator.id == IDENTITY_ID + + +def test_workbench_related(): + rel1 = stix2.Relationship(MALWARE_ID, 'targets', IDENTITY_ID) + rel2 = stix2.Relationship(CAMPAIGN_ID, 'uses', MALWARE_ID) + add([rel1, rel2]) + + resp = get(MALWARE_ID).related() + assert len(resp) == 3 + assert any(x['id'] == CAMPAIGN_ID for x in resp) + assert any(x['id'] == INDICATOR_ID for x in resp) + assert any(x['id'] == IDENTITY_ID for x in resp) diff --git a/stix2/workbench.py b/stix2/workbench.py index 55c8009..4069309 100644 --- a/stix2/workbench.py +++ b/stix2/workbench.py @@ -1,6 +1,9 @@ """Functions and class wrappers for interacting with STIX data at a high level. """ +from . import (AttackPattern, Campaign, CourseOfAction, CustomObject, Identity, + Indicator, IntrusionSet, Malware, ObservedData, Report, + ThreatActor, Tool, Vulnerability) from .environment import Environment from .sources.filters import Filter from .sources.memory import MemoryStore @@ -21,6 +24,31 @@ parse = _environ.parse add_data_source = _environ.source.add_data_source +# Wrap SDOs with helper functions + + +def created_by_wrapper(self, *args, **kwargs): + return _environ.creator_of(self, *args, **kwargs) + + +def relationships_wrapper(self, *args, **kwargs): + return _environ.relationships(self, *args, **kwargs) + + +def related_wrapper(self, *args, **kwargs): + return _environ.related_to(self, *args, **kwargs) + + +STIX_OBJS = [AttackPattern, Campaign, CourseOfAction, CustomObject, Identity, + Indicator, IntrusionSet, Malware, ObservedData, Report, + ThreatActor, Tool, Vulnerability] + +for obj_type in STIX_OBJS: + obj_type.created_by = created_by_wrapper + obj_type.relationships = relationships_wrapper + obj_type.related = related_wrapper + + # Functions to get all objects of a specific type From 5285934034d575d57dd08e7b77f1de17f52a1941 Mon Sep 17 00:00:00 2001 From: Chris Lenk Date: Wed, 29 Nov 2017 19:25:52 -0500 Subject: [PATCH 05/61] Make Workbench use implicit ObjectFactory This is needed to implement functions like `set_default_creator`. The changes to Tox are so that the wrapping we do in workbench doesn't affect the rest of our tests. If we test them all in one go, pytest will import all the tests before running any of them. This will cause the workbench versions of the SDO classes to be used in all tests. --- stix2/test/test_tool.py | 6 +++++ stix2/test/test_workbench.py | 31 +++++++++++++------------ stix2/workbench.py | 44 ++++++++++++++++++++++++++++-------- tox.ini | 3 ++- 4 files changed, 60 insertions(+), 24 deletions(-) diff --git a/stix2/test/test_tool.py b/stix2/test/test_tool.py index 21ece24..ce99fb8 100644 --- a/stix2/test/test_tool.py +++ b/stix2/test/test_tool.py @@ -58,4 +58,10 @@ def test_parse_tool(data): assert tool.labels == ["remote-access"] assert tool.name == "VNC" + +def test_tool_no_workbench_wrappers(): + tool = stix2.Tool(name='VNC', labels=['remote-access']) + with pytest.raises(AttributeError): + tool.created_by() + # TODO: Add other examples diff --git a/stix2/test/test_workbench.py b/stix2/test/test_workbench.py index 7f3c9fc..6a33f11 100644 --- a/stix2/test/test_workbench.py +++ b/stix2/test/test_workbench.py @@ -1,5 +1,8 @@ import stix2 -from stix2.workbench import (add, all_versions, attack_patterns, campaigns, +from stix2.workbench import (AttackPattern, Campaign, CourseOfAction, Identity, + Indicator, IntrusionSet, Malware, ObservedData, + Report, ThreatActor, Tool, Vulnerability, add, + all_versions, attack_patterns, campaigns, courses_of_action, create, get, identities, indicators, intrusion_sets, malware, observed_data, query, reports, threat_actors, @@ -19,7 +22,7 @@ from .constants import (ATTACK_PATTERN_ID, ATTACK_PATTERN_KWARGS, CAMPAIGN_ID, def test_workbench_environment(): # Create a STIX object - ind = create(stix2.Indicator, id=INDICATOR_ID, **INDICATOR_KWARGS) + ind = create(Indicator, id=INDICATOR_ID, **INDICATOR_KWARGS) add(ind) resp = get(INDICATOR_ID) @@ -35,7 +38,7 @@ def test_workbench_environment(): def test_workbench_get_all_attack_patterns(): - mal = stix2.AttackPattern(id=ATTACK_PATTERN_ID, **ATTACK_PATTERN_KWARGS) + mal = AttackPattern(id=ATTACK_PATTERN_ID, **ATTACK_PATTERN_KWARGS) add(mal) resp = attack_patterns() @@ -44,7 +47,7 @@ def test_workbench_get_all_attack_patterns(): def test_workbench_get_all_campaigns(): - cam = stix2.Campaign(id=CAMPAIGN_ID, **CAMPAIGN_KWARGS) + cam = Campaign(id=CAMPAIGN_ID, **CAMPAIGN_KWARGS) add(cam) resp = campaigns() @@ -53,7 +56,7 @@ def test_workbench_get_all_campaigns(): def test_workbench_get_all_courses_of_action(): - coa = stix2.CourseOfAction(id=COURSE_OF_ACTION_ID, **COURSE_OF_ACTION_KWARGS) + coa = CourseOfAction(id=COURSE_OF_ACTION_ID, **COURSE_OF_ACTION_KWARGS) add(coa) resp = courses_of_action() @@ -62,7 +65,7 @@ def test_workbench_get_all_courses_of_action(): def test_workbench_get_all_identities(): - idty = stix2.Identity(id=IDENTITY_ID, **IDENTITY_KWARGS) + idty = Identity(id=IDENTITY_ID, **IDENTITY_KWARGS) add(idty) resp = identities() @@ -77,7 +80,7 @@ def test_workbench_get_all_indicators(): def test_workbench_get_all_intrusion_sets(): - ins = stix2.IntrusionSet(id=INTRUSION_SET_ID, **INTRUSION_SET_KWARGS) + ins = IntrusionSet(id=INTRUSION_SET_ID, **INTRUSION_SET_KWARGS) add(ins) resp = intrusion_sets() @@ -86,7 +89,7 @@ def test_workbench_get_all_intrusion_sets(): def test_workbench_get_all_malware(): - mal = stix2.Malware(id=MALWARE_ID, **MALWARE_KWARGS) + mal = Malware(id=MALWARE_ID, **MALWARE_KWARGS) add(mal) resp = malware() @@ -95,7 +98,7 @@ def test_workbench_get_all_malware(): def test_workbench_get_all_observed_data(): - od = stix2.ObservedData(id=OBSERVED_DATA_ID, **OBSERVED_DATA_KWARGS) + od = ObservedData(id=OBSERVED_DATA_ID, **OBSERVED_DATA_KWARGS) add(od) resp = observed_data() @@ -104,7 +107,7 @@ def test_workbench_get_all_observed_data(): def test_workbench_get_all_reports(): - rep = stix2.Report(id=REPORT_ID, **REPORT_KWARGS) + rep = Report(id=REPORT_ID, **REPORT_KWARGS) add(rep) resp = reports() @@ -113,7 +116,7 @@ def test_workbench_get_all_reports(): def test_workbench_get_all_threat_actors(): - thr = stix2.ThreatActor(id=THREAT_ACTOR_ID, **THREAT_ACTOR_KWARGS) + thr = ThreatActor(id=THREAT_ACTOR_ID, **THREAT_ACTOR_KWARGS) add(thr) resp = threat_actors() @@ -122,7 +125,7 @@ def test_workbench_get_all_threat_actors(): def test_workbench_get_all_tools(): - tool = stix2.Tool(id=TOOL_ID, **TOOL_KWARGS) + tool = Tool(id=TOOL_ID, **TOOL_KWARGS) add(tool) resp = tools() @@ -131,7 +134,7 @@ def test_workbench_get_all_tools(): def test_workbench_get_all_vulnerabilities(): - vuln = stix2.Vulnerability(id=VULNERABILITY_ID, **VULNERABILITY_KWARGS) + vuln = Vulnerability(id=VULNERABILITY_ID, **VULNERABILITY_KWARGS) add(vuln) resp = vulnerabilities() @@ -152,7 +155,7 @@ def test_workbench_relationships(): def test_workbench_created_by(): - intset = stix2.IntrusionSet(name="Breach 123", created_by_ref=IDENTITY_ID) + intset = IntrusionSet(name="Breach 123", created_by_ref=IDENTITY_ID) add(intset) creator = intset.created_by() assert creator.id == IDENTITY_ID diff --git a/stix2/workbench.py b/stix2/workbench.py index 4069309..f5f2d32 100644 --- a/stix2/workbench.py +++ b/stix2/workbench.py @@ -1,9 +1,18 @@ """Functions and class wrappers for interacting with STIX data at a high level. """ -from . import (AttackPattern, Campaign, CourseOfAction, CustomObject, Identity, - Indicator, IntrusionSet, Malware, ObservedData, Report, - ThreatActor, Tool, Vulnerability) +from . import AttackPattern as _AttackPattern +from . import Campaign as _Campaign +from . import CourseOfAction as _CourseOfAction +from . import Identity as _Identity +from . import Indicator as _Indicator +from . import IntrusionSet as _IntrusionSet +from . import Malware as _Malware +from . import ObservedData as _ObservedData +from . import Report as _Report +from . import ThreatActor as _ThreatActor +from . import Tool as _Tool +from . import Vulnerability as _Vulnerability from .environment import Environment from .sources.filters import Filter from .sources.memory import MemoryStore @@ -27,6 +36,11 @@ add_data_source = _environ.source.add_data_source # Wrap SDOs with helper functions +STIX_OBJS = [_AttackPattern, _Campaign, _CourseOfAction, _Identity, + _Indicator, _IntrusionSet, _Malware, _ObservedData, _Report, + _ThreatActor, _Tool, _Vulnerability] + + def created_by_wrapper(self, *args, **kwargs): return _environ.creator_of(self, *args, **kwargs) @@ -39,14 +53,26 @@ def related_wrapper(self, *args, **kwargs): return _environ.related_to(self, *args, **kwargs) -STIX_OBJS = [AttackPattern, Campaign, CourseOfAction, CustomObject, Identity, - Indicator, IntrusionSet, Malware, ObservedData, Report, - ThreatActor, Tool, Vulnerability] +def constructor_wrapper(obj_type): + # Use an intermediate wrapper class so the implicit environment will create objects that have our wrapper functions + wrapped_type = type(obj_type.__name__, obj_type.__bases__, dict( + created_by=created_by_wrapper, + relationships=relationships_wrapper, + related=related_wrapper, + **obj_type.__dict__ + )) + @staticmethod + def new_constructor(cls, *args, **kwargs): + return _environ.create(wrapped_type, *args, **kwargs) + return new_constructor + + +# Create wrapper classes whose constructors call the implicit environment's create() for obj_type in STIX_OBJS: - obj_type.created_by = created_by_wrapper - obj_type.relationships = relationships_wrapper - obj_type.related = related_wrapper + new_class = type(obj_type.__name__, (), {}) + new_class.__new__ = constructor_wrapper(obj_type) + globals()[obj_type.__name__] = new_class # Functions to get all objects of a specific type diff --git a/tox.ini b/tox.ini index bfc8c1b..97d9519 100644 --- a/tox.ini +++ b/tox.ini @@ -9,7 +9,8 @@ deps = pytest-cov coverage commands = - py.test --cov=stix2 stix2/test/ --cov-report term-missing + py.test --ignore=stix2/test/test_workbench.py --cov=stix2 stix2/test/ --cov-report term-missing --cov-append + py.test stix2/test/test_workbench.py --cov=stix2 --cov-report term-missing --cov-append passenv = CI TRAVIS TRAVIS_* From e91b71f3009788f69c7303e22aca6a852c4cacf0 Mon Sep 17 00:00:00 2001 From: Chris Lenk Date: Wed, 14 Mar 2018 12:47:28 -0400 Subject: [PATCH 06/61] Test adding a data source to the workbench --- stix2/test/test_workbench.py | 24 +++++++++++++++++++++--- stix2/workbench.py | 6 ++++-- 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/stix2/test/test_workbench.py b/stix2/test/test_workbench.py index 6a33f11..b84b529 100644 --- a/stix2/test/test_workbench.py +++ b/stix2/test/test_workbench.py @@ -1,10 +1,12 @@ +import os + import stix2 from stix2.workbench import (AttackPattern, Campaign, CourseOfAction, Identity, Indicator, IntrusionSet, Malware, ObservedData, Report, ThreatActor, Tool, Vulnerability, add, - all_versions, attack_patterns, campaigns, - courses_of_action, create, get, identities, - indicators, intrusion_sets, malware, + add_data_source, all_versions, attack_patterns, + campaigns, courses_of_action, create, get, + identities, indicators, intrusion_sets, malware, observed_data, query, reports, threat_actors, tools, vulnerabilities) @@ -171,3 +173,19 @@ def test_workbench_related(): assert any(x['id'] == CAMPAIGN_ID for x in resp) assert any(x['id'] == INDICATOR_ID for x in resp) assert any(x['id'] == IDENTITY_ID for x in resp) + + resp = get(MALWARE_ID).related(relationship_type='indicates') + assert len(resp) == 1 + + +def test_add_data_source(): + fs_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "stix2_data") + fs = stix2.FileSystemSource(fs_path) + add_data_source(fs) + + resp = tools() + assert len(resp) == 3 + resp_ids = [tool.id for tool in resp] + assert TOOL_ID in resp_ids + assert 'tool--03342581-f790-4f03-ba41-e82e67392e23' in resp_ids + assert 'tool--242f3da3-4425-4d11-8f5c-b842886da966' in resp_ids diff --git a/stix2/workbench.py b/stix2/workbench.py index f5f2d32..60d1165 100644 --- a/stix2/workbench.py +++ b/stix2/workbench.py @@ -13,10 +13,11 @@ from . import Report as _Report from . import ThreatActor as _ThreatActor from . import Tool as _Tool from . import Vulnerability as _Vulnerability +from .datastore.filters import Filter +from .datastore.memory import MemoryStore from .environment import Environment -from .sources.filters import Filter -from .sources.memory import MemoryStore +# Use an implicit MemoryStore _environ = Environment(store=MemoryStore()) create = _environ.create @@ -31,6 +32,7 @@ add_filters = _environ.add_filters add_filter = _environ.add_filter parse = _environ.parse add_data_source = _environ.source.add_data_source +add_data_sources = _environ.source.add_data_sources # Wrap SDOs with helper functions From 44248092256a0e58902d5089bb387ee1c5e809cb Mon Sep 17 00:00:00 2001 From: Chris Lenk Date: Wed, 14 Mar 2018 14:19:14 -0400 Subject: [PATCH 07/61] Fix tox config (coverage was incorrectly reported) --- tox.ini | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tox.ini b/tox.ini index 97d9519..46d88c1 100644 --- a/tox.ini +++ b/tox.ini @@ -9,7 +9,7 @@ deps = pytest-cov coverage commands = - py.test --ignore=stix2/test/test_workbench.py --cov=stix2 stix2/test/ --cov-report term-missing --cov-append + py.test --ignore=stix2/test/test_workbench.py --cov=stix2 stix2/test/ --cov-report term-missing py.test stix2/test/test_workbench.py --cov=stix2 --cov-report term-missing --cov-append passenv = CI TRAVIS TRAVIS_* From 53c2d4fadfa0fffc63a05e89fc86ba6394271e98 Mon Sep 17 00:00:00 2001 From: Chris Lenk Date: Wed, 14 Mar 2018 14:33:45 -0400 Subject: [PATCH 08/61] Allow add'l filters in workbench query functions --- stix2/test/test_workbench.py | 11 +++++++ stix2/workbench.py | 59 +++++++++++++++++++++--------------- 2 files changed, 46 insertions(+), 24 deletions(-) diff --git a/stix2/test/test_workbench.py b/stix2/test/test_workbench.py index b84b529..324011b 100644 --- a/stix2/test/test_workbench.py +++ b/stix2/test/test_workbench.py @@ -189,3 +189,14 @@ def test_add_data_source(): assert TOOL_ID in resp_ids assert 'tool--03342581-f790-4f03-ba41-e82e67392e23' in resp_ids assert 'tool--242f3da3-4425-4d11-8f5c-b842886da966' in resp_ids + + +def test_additional_filter(): + resp = tools(stix2.Filter('created_by_ref', '=', 'identity--c78cb6e5-0c4b-4611-8297-d1b8b55e40b5')) + assert len(resp) == 2 + + +def test_additional_filters_list(): + resp = tools([stix2.Filter('created_by_ref', '=', 'identity--c78cb6e5-0c4b-4611-8297-d1b8b55e40b5'), + stix2.Filter('name', '=', 'Windows Credential Editor')]) + assert len(resp) == 1 diff --git a/stix2/workbench.py b/stix2/workbench.py index 60d1165..49e41c9 100644 --- a/stix2/workbench.py +++ b/stix2/workbench.py @@ -80,49 +80,60 @@ for obj_type in STIX_OBJS: # Functions to get all objects of a specific type -def attack_patterns(): - return query(Filter('type', '=', 'attack-pattern')) +def query_by_type(obj_type='indicator', filters=None): + filter_list = [Filter('type', '=', obj_type)] + if filters: + if isinstance(filters, list): + filter_list += filters + else: + filter_list.append(filters) + + return query(filter_list) -def campaigns(): - return query(Filter('type', '=', 'campaign')) +def attack_patterns(filters=None): + return query_by_type('attack-pattern', filters) -def courses_of_action(): - return query(Filter('type', '=', 'course-of-action')) +def campaigns(filters=None): + return query_by_type('campaign', filters) -def identities(): - return query(Filter('type', '=', 'identity')) +def courses_of_action(filters=None): + return query_by_type('course-of-action', filters) -def indicators(): - return query(Filter('type', '=', 'indicator')) +def identities(filters=None): + return query_by_type('identity', filters) -def intrusion_sets(): - return query(Filter('type', '=', 'intrusion-set')) +def indicators(filters=None): + return query_by_type('indicator', filters) -def malware(): - return query(Filter('type', '=', 'malware')) +def intrusion_sets(filters=None): + return query_by_type('intrusion-set', filters) -def observed_data(): - return query(Filter('type', '=', 'observed-data')) +def malware(filters=None): + return query_by_type('malware', filters) -def reports(): - return query(Filter('type', '=', 'report')) +def observed_data(filters=None): + return query_by_type('observed-data', filters) -def threat_actors(): - return query(Filter('type', '=', 'threat-actor')) +def reports(filters=None): + return query_by_type('report', filters) -def tools(): - return query(Filter('type', '=', 'tool')) +def threat_actors(filters=None): + return query_by_type('threat-actor', filters) -def vulnerabilities(): - return query(Filter('type', '=', 'vulnerability')) +def tools(filters=None): + return query_by_type('tool', filters) + + +def vulnerabilities(filters=None): + return query_by_type('vulnerability', filters) From eeb94562f9ec19f642d45eaa2bf01dad1fed7028 Mon Sep 17 00:00:00 2001 From: Chris Lenk Date: Fri, 16 Mar 2018 11:40:46 -0400 Subject: [PATCH 09/61] Clean up DataStore return value documentation --- stix2/datastore/__init__.py | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/stix2/datastore/__init__.py b/stix2/datastore/__init__.py index 78f7555..5920673 100644 --- a/stix2/datastore/__init__.py +++ b/stix2/datastore/__init__.py @@ -73,7 +73,7 @@ class DataStoreMixin(object): stix_id (str): the id of the STIX object to retrieve. Returns: - stix_objs (list): a list of STIX objects + list: All versions of the specified STIX object. """ try: @@ -91,7 +91,7 @@ class DataStoreMixin(object): to conduct search on. Returns: - stix_objs (list): a list of STIX objects + list: The STIX objects matching the query. """ try: @@ -136,7 +136,7 @@ class DataStoreMixin(object): object is the target_ref. Default: False. Returns: - (list): List of Relationship objects involving the given STIX object. + list: The Relationship objects involving the given STIX object. """ try: @@ -164,7 +164,7 @@ class DataStoreMixin(object): object is the target_ref. Default: False. Returns: - (list): List of STIX objects related to the given STIX object. + list: The STIX objects related to the given STIX object. """ try: @@ -240,7 +240,7 @@ class DataSource(with_metaclass(ABCMeta)): specified by the "id". Returns: - stix_obj: the STIX object + stix_obj: The STIX object. """ @@ -258,7 +258,7 @@ class DataSource(with_metaclass(ABCMeta)): specified by the "id". Returns: - stix_objs (list): a list of STIX objects + list: All versions of the specified STIX object. """ @@ -273,7 +273,7 @@ class DataSource(with_metaclass(ABCMeta)): to conduct search on. Returns: - stix_objs (list): a list of STIX objects + list: The STIX objects that matched the query. """ @@ -311,7 +311,7 @@ class DataSource(with_metaclass(ABCMeta)): object is the target_ref. Default: False. Returns: - (list): List of Relationship objects involving the given STIX object. + list: The Relationship objects involving the given STIX object. """ results = [] @@ -356,7 +356,7 @@ class DataSource(with_metaclass(ABCMeta)): object is the target_ref. Default: False. Returns: - (list): List of STIX objects related to the given STIX object. + list: The STIX objects related to the given STIX object. """ results = [] @@ -425,7 +425,7 @@ class CompositeDataSource(DataSource): to another parent CompositeDataSource), not user supplied. Returns: - stix_obj: the STIX object to be returned. + stix_obj: The STIX object to be returned. """ if not self.has_data_sources(): @@ -471,7 +471,7 @@ class CompositeDataSource(DataSource): attached to a parent CompositeDataSource), not user supplied. Returns: - all_data (list): list of STIX objects that have the specified id + list: The STIX objects that have the specified id. """ if not self.has_data_sources(): @@ -510,7 +510,7 @@ class CompositeDataSource(DataSource): attached to a parent CompositeDataSource), not user supplied. Returns: - all_data (list): list of STIX objects to be returned + list: The STIX objects to be returned. """ if not self.has_data_sources(): @@ -561,7 +561,7 @@ class CompositeDataSource(DataSource): object is the target_ref. Default: False. Returns: - (list): List of Relationship objects involving the given STIX object. + list: The Relationship objects involving the given STIX object. """ if not self.has_data_sources(): @@ -599,7 +599,7 @@ class CompositeDataSource(DataSource): object is the target_ref. Default: False. Returns: - (list): List of STIX objects related to the given STIX object. + list: The STIX objects related to the given STIX object. """ if not self.has_data_sources(): From fd6d9f74e955793103a059fdd56b26176e2c39f1 Mon Sep 17 00:00:00 2001 From: Chris Lenk Date: Fri, 16 Mar 2018 15:41:08 -0400 Subject: [PATCH 10/61] Move query_by_type() to DataStoreMixin --- stix2/datastore/__init__.py | 71 ++++++++++++++++++++++++++++++++++ stix2/environment.py | 2 + stix2/test/test_environment.py | 4 ++ stix2/workbench.py | 13 +------ 4 files changed, 78 insertions(+), 12 deletions(-) diff --git a/stix2/datastore/__init__.py b/stix2/datastore/__init__.py index 5920673..e482288 100644 --- a/stix2/datastore/__init__.py +++ b/stix2/datastore/__init__.py @@ -99,6 +99,25 @@ class DataStoreMixin(object): except AttributeError: raise AttributeError('%s has no data source to query' % self.__class__.__name__) + def query_by_type(self, *args, **kwargs): + """Retrieve all objects of the given STIX object type. + + Translate query_by_type() call to the appropriate DataSource call. + + Args: + obj_type (str): The STIX object type to retrieve. + filters (list, optional): A list of additional filters to apply to + the query. + + Returns: + list: The STIX objects that matched the query. + + """ + try: + return self.source.query_by_type(*args, **kwargs) + except AttributeError: + raise AttributeError('%s has no data source to query' % self.__class__.__name__) + def creator_of(self, *args, **kwargs): """Retrieve the Identity refered to by the object's `created_by_ref`. @@ -277,6 +296,29 @@ class DataSource(with_metaclass(ABCMeta)): """ + def query_by_type(self, obj_type='indicator', filters=None): + """Retrieve all objects of the given STIX object type. + + This helper function is a shortcut that calls query() under the hood. + + Args: + obj_type (str): The STIX object type to retrieve. + filters (list, optional): A list of additional filters to apply to + the query. + + Returns: + list: The STIX objects that matched the query. + + """ + filter_list = [Filter('type', '=', obj_type)] + if filters: + if isinstance(filters, list): + filter_list += filters + else: + filter_list.append(filters) + + return self.query(filter_list) + def creator_of(self, obj): """Retrieve the Identity refered to by the object's `created_by_ref`. @@ -542,6 +584,35 @@ class CompositeDataSource(DataSource): return all_data + def query_by_type(self, *args, **kwargs): + """Retrieve all objects of the given STIX object type. + + Federate the query to all DataSources attached to the + Composite Data Source. + + Args: + obj_type (str): The STIX object type to retrieve. + filters (list, optional): A list of additional filters to apply to + the query. + + Returns: + list: The STIX objects that matched the query. + + """ + if not self.has_data_sources(): + raise AttributeError('CompositeDataSource has no data sources') + + results = [] + for ds in self.data_sources: + results.extend(ds.query_by_type(*args, **kwargs)) + + # remove exact duplicates (where duplicates are STIX 2.0 + # objects with the same 'id' and 'modified' values) + if len(results) > 0: + results = deduplicate(results) + + return results + def relationships(self, *args, **kwargs): """Retrieve Relationships involving the given STIX object. diff --git a/stix2/environment.py b/stix2/environment.py index eb5583e..95f73e6 100644 --- a/stix2/environment.py +++ b/stix2/environment.py @@ -90,10 +90,12 @@ class Environment(DataStoreMixin): .. automethod:: get .. automethod:: all_versions .. automethod:: query + .. automethod:: query_by_type .. automethod:: creator_of .. automethod:: relationships .. automethod:: related_to .. automethod:: add + """ def __init__(self, factory=ObjectFactory(), store=None, source=None, sink=None): diff --git a/stix2/test/test_environment.py b/stix2/test/test_environment.py index 84ca803..456ec25 100644 --- a/stix2/test/test_environment.py +++ b/stix2/test/test_environment.py @@ -164,6 +164,10 @@ def test_environment_no_datastore(): env.query(INDICATOR_ID) assert 'Environment has no data source' in str(excinfo.value) + with pytest.raises(AttributeError) as excinfo: + env.query_by_type('indicator') + assert 'Environment has no data source' in str(excinfo.value) + with pytest.raises(AttributeError) as excinfo: env.relationships(INDICATOR_ID) assert 'Environment has no data source' in str(excinfo.value) diff --git a/stix2/workbench.py b/stix2/workbench.py index 49e41c9..7988329 100644 --- a/stix2/workbench.py +++ b/stix2/workbench.py @@ -13,7 +13,6 @@ from . import Report as _Report from . import ThreatActor as _ThreatActor from . import Tool as _Tool from . import Vulnerability as _Vulnerability -from .datastore.filters import Filter from .datastore.memory import MemoryStore from .environment import Environment @@ -24,6 +23,7 @@ create = _environ.create get = _environ.get all_versions = _environ.all_versions query = _environ.query +query_by_type = _environ.query_by_type creator_of = _environ.creator_of relationships = _environ.relationships related_to = _environ.related_to @@ -80,17 +80,6 @@ for obj_type in STIX_OBJS: # Functions to get all objects of a specific type -def query_by_type(obj_type='indicator', filters=None): - filter_list = [Filter('type', '=', obj_type)] - if filters: - if isinstance(filters, list): - filter_list += filters - else: - filter_list.append(filters) - - return query(filter_list) - - def attack_patterns(filters=None): return query_by_type('attack-pattern', filters) From 61733ad89981bf9c3a50bb109ce992b3b6e41c89 Mon Sep 17 00:00:00 2001 From: Chris Lenk Date: Mon, 19 Mar 2018 13:32:02 -0400 Subject: [PATCH 11/61] Add functions to set ObjectFactory default values --- stix2/environment.py | 54 +++++++++++++++++++++++++++++----- stix2/test/test_environment.py | 2 +- stix2/test/test_workbench.py | 43 ++++++++++++++++++++++++++- stix2/workbench.py | 4 +++ 4 files changed, 94 insertions(+), 9 deletions(-) diff --git a/stix2/environment.py b/stix2/environment.py index 95f73e6..69a394f 100644 --- a/stix2/environment.py +++ b/stix2/environment.py @@ -30,19 +30,43 @@ class ObjectFactory(object): self._defaults = {} if created_by_ref: - self._defaults['created_by_ref'] = created_by_ref + self.set_default_creator(created_by_ref) if created: - self._defaults['created'] = created - # If the user provides a default "created" time, we also want to use - # that as the modified time. - self._defaults['modified'] = created + self.set_default_created(created) if external_references: - self._defaults['external_references'] = external_references + self.set_default_external_refs(external_references) if object_marking_refs: - self._defaults['object_marking_refs'] = object_marking_refs + self.set_default_object_marking_refs(object_marking_refs) self._list_append = list_append self._list_properties = ['external_references', 'object_marking_refs'] + def set_default_creator(self, creator=None): + """Set default value for the `created_by_ref` property. + + """ + self._defaults['created_by_ref'] = creator + + def set_default_created(self, created=None): + """Set default value for the `created` property. + + """ + self._defaults['created'] = created + # If the user provides a default "created" time, we also want to use + # that as the modified time. + self._defaults['modified'] = created + + def set_default_external_refs(self, external_references=None): + """Set default external references. + + """ + self._defaults['external_references'] = external_references + + def set_default_object_marking_refs(self, object_marking_refs=None): + """Set default object markings. + + """ + self._defaults['object_marking_refs'] = object_marking_refs + def create(self, cls, **kwargs): """Create a STIX object using object factory defaults. @@ -115,6 +139,22 @@ class Environment(DataStoreMixin): return self.factory.create(*args, **kwargs) create.__doc__ = ObjectFactory.create.__doc__ + def set_default_creator(self, *args, **kwargs): + return self.factory.set_default_creator(*args, **kwargs) + set_default_creator.__doc__ = ObjectFactory.set_default_creator.__doc__ + + def set_default_created(self, *args, **kwargs): + return self.factory.set_default_created(*args, **kwargs) + set_default_created.__doc__ = ObjectFactory.set_default_created.__doc__ + + def set_default_external_refs(self, *args, **kwargs): + return self.factory.set_default_external_refs(*args, **kwargs) + set_default_external_refs.__doc__ = ObjectFactory.set_default_external_refs.__doc__ + + def set_default_object_marking_refs(self, *args, **kwargs): + return self.factory.set_default_object_marking_refs(*args, **kwargs) + set_default_object_marking_refs.__doc__ = ObjectFactory.set_default_object_marking_refs.__doc__ + def add_filters(self, *args, **kwargs): try: return self.source.filters.update(*args, **kwargs) diff --git a/stix2/test/test_environment.py b/stix2/test/test_environment.py index 456ec25..8764e25 100644 --- a/stix2/test/test_environment.py +++ b/stix2/test/test_environment.py @@ -47,7 +47,7 @@ def test_object_factory_created(): assert ind.modified == FAKE_TIME -def test_object_factory_external_resource(): +def test_object_factory_external_reference(): ext_ref = stix2.ExternalReference(source_name="ACME Threat Intel", description="Threat report") factory = stix2.ObjectFactory(external_references=ext_ref) diff --git a/stix2/test/test_workbench.py b/stix2/test/test_workbench.py index 324011b..c25cf1a 100644 --- a/stix2/test/test_workbench.py +++ b/stix2/test/test_workbench.py @@ -7,7 +7,10 @@ from stix2.workbench import (AttackPattern, Campaign, CourseOfAction, Identity, add_data_source, all_versions, attack_patterns, campaigns, courses_of_action, create, get, identities, indicators, intrusion_sets, malware, - observed_data, query, reports, threat_actors, + observed_data, query, reports, + set_default_created, set_default_creator, + set_default_external_refs, + set_default_object_marking_refs, threat_actors, tools, vulnerabilities) from .constants import (ATTACK_PATTERN_ID, ATTACK_PATTERN_KWARGS, CAMPAIGN_ID, @@ -200,3 +203,41 @@ def test_additional_filters_list(): resp = tools([stix2.Filter('created_by_ref', '=', 'identity--c78cb6e5-0c4b-4611-8297-d1b8b55e40b5'), stix2.Filter('name', '=', 'Windows Credential Editor')]) assert len(resp) == 1 + + +def test_default_creator(): + set_default_creator(IDENTITY_ID) + campaign = Campaign(**CAMPAIGN_KWARGS) + + assert 'created_by_ref' not in CAMPAIGN_KWARGS + assert campaign.created_by_ref == IDENTITY_ID + + +def test_default_created_timestamp(): + timestamp = "2018-03-19T01:02:03.000Z" + set_default_created(timestamp) + campaign = Campaign(**CAMPAIGN_KWARGS) + + assert 'created' not in CAMPAIGN_KWARGS + assert stix2.utils.format_datetime(campaign.created) == timestamp + assert stix2.utils.format_datetime(campaign.modified) == timestamp + + +def test_default_external_refs(): + ext_ref = stix2.ExternalReference(source_name="ACME Threat Intel", + description="Threat report") + set_default_external_refs(ext_ref) + campaign = Campaign(**CAMPAIGN_KWARGS) + + assert campaign.external_references[0].source_name == "ACME Threat Intel" + assert campaign.external_references[0].description == "Threat report" + + +def test_default_object_marking_refs(): + stmt_marking = stix2.StatementMarking("Copyright 2016, Example Corp") + mark_def = stix2.MarkingDefinition(definition_type="statement", + definition=stmt_marking) + set_default_object_marking_refs(mark_def) + campaign = Campaign(**CAMPAIGN_KWARGS) + + assert campaign.object_marking_refs[0] == mark_def.id diff --git a/stix2/workbench.py b/stix2/workbench.py index 7988329..4436609 100644 --- a/stix2/workbench.py +++ b/stix2/workbench.py @@ -20,6 +20,10 @@ from .environment import Environment _environ = Environment(store=MemoryStore()) create = _environ.create +set_default_creator = _environ.set_default_creator +set_default_created = _environ.set_default_created +set_default_external_refs = _environ.set_default_external_refs +set_default_object_marking_refs = _environ.set_default_object_marking_refs get = _environ.get all_versions = _environ.all_versions query = _environ.query From 4fb24f14de7e277f57695edb5b66c678c119272c Mon Sep 17 00:00:00 2001 From: Chris Lenk Date: Mon, 19 Mar 2018 15:56:20 -0400 Subject: [PATCH 12/61] Allow passing add'l filters to related_to() --- stix2/datastore/__init__.py | 16 +++++++++++++--- stix2/test/test_workbench.py | 13 +++++++++++++ 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/stix2/datastore/__init__.py b/stix2/datastore/__init__.py index e482288..f02d773 100644 --- a/stix2/datastore/__init__.py +++ b/stix2/datastore/__init__.py @@ -313,7 +313,7 @@ class DataSource(with_metaclass(ABCMeta)): filter_list = [Filter('type', '=', obj_type)] if filters: if isinstance(filters, list): - filter_list += filters + filter_list.extend(filters) else: filter_list.append(filters) @@ -380,7 +380,7 @@ class DataSource(with_metaclass(ABCMeta)): return results - def related_to(self, obj, relationship_type=None, source_only=False, target_only=False): + def related_to(self, obj, relationship_type=None, source_only=False, target_only=False, filters=None): """Retrieve STIX Objects that have a Relationship involving the given STIX object. @@ -396,6 +396,8 @@ class DataSource(with_metaclass(ABCMeta)): object is the source_ref. Default: False. target_only (bool): Only examine Relationships for which this object is the target_ref. Default: False. + filters (list): list of additional filters the related objects must + match. Returns: list: The STIX objects related to the given STIX object. @@ -416,8 +418,16 @@ class DataSource(with_metaclass(ABCMeta)): ids.update((r.source_ref, r.target_ref)) ids.remove(obj_id) + # Assemble filters + filter_list = [] + if filters: + if isinstance(filters, list): + filter_list.extend(filters) + else: + filter_list.append(filters) + for i in ids: - results.append(self.get(i)) + results.extend(self.query(filter_list + [Filter('id', '=', i)])) return results diff --git a/stix2/test/test_workbench.py b/stix2/test/test_workbench.py index c25cf1a..a8edfbc 100644 --- a/stix2/test/test_workbench.py +++ b/stix2/test/test_workbench.py @@ -181,6 +181,19 @@ def test_workbench_related(): assert len(resp) == 1 +def test_workbench_related_with_filters(): + malware = Malware(labels=["ransomware"], name="CryptorBit", created_by_ref=IDENTITY_ID) + rel = stix2.Relationship(malware.id, 'variant-of', MALWARE_ID) + add([malware, rel]) + + filters = [stix2.Filter('created_by_ref', '=', IDENTITY_ID)] + resp = get(MALWARE_ID).related(filters=filters) + + assert len(resp) == 1 + assert resp[0].name == malware.name + assert resp[0].created_by_ref == IDENTITY_ID + + def test_add_data_source(): fs_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "stix2_data") fs = stix2.FileSystemSource(fs_path) From e48e0886a8741746a9cfad2ef160a5f3fd43fb9c Mon Sep 17 00:00:00 2001 From: Chris Lenk Date: Mon, 19 Mar 2018 17:41:16 -0400 Subject: [PATCH 13/61] Improve code coverage slightly Environment will always have a CompositeDataSource, so the try/catches in add_filter/s did not make sense. --- stix2/environment.py | 10 ++-------- stix2/test/test_workbench.py | 4 ++++ 2 files changed, 6 insertions(+), 8 deletions(-) diff --git a/stix2/environment.py b/stix2/environment.py index 69a394f..9f55a7e 100644 --- a/stix2/environment.py +++ b/stix2/environment.py @@ -156,16 +156,10 @@ class Environment(DataStoreMixin): set_default_object_marking_refs.__doc__ = ObjectFactory.set_default_object_marking_refs.__doc__ def add_filters(self, *args, **kwargs): - try: - return self.source.filters.update(*args, **kwargs) - except AttributeError: - raise AttributeError('Environment has no data source') + return self.source.filters.update(*args, **kwargs) def add_filter(self, *args, **kwargs): - try: - return self.source.filters.add(*args, **kwargs) - except AttributeError: - raise AttributeError('Environment has no data source') + return self.source.filters.add(*args, **kwargs) def parse(self, *args, **kwargs): return _parse(*args, **kwargs) diff --git a/stix2/test/test_workbench.py b/stix2/test/test_workbench.py index a8edfbc..13aad23 100644 --- a/stix2/test/test_workbench.py +++ b/stix2/test/test_workbench.py @@ -193,6 +193,10 @@ def test_workbench_related_with_filters(): assert resp[0].name == malware.name assert resp[0].created_by_ref == IDENTITY_ID + # filters arg can also be single filter + resp = get(MALWARE_ID).related(filters=filters[0]) + assert len(resp) == 1 + def test_add_data_source(): fs_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "stix2_data") From efede514539a4a0310f4276643ad50f838e7f957 Mon Sep 17 00:00:00 2001 From: Chris Lenk Date: Wed, 21 Mar 2018 13:56:50 -0400 Subject: [PATCH 14/61] Skip documenting some workbench stuff --- docs/conf.py | 11 +++++++++++ stix2/workbench.py | 17 +++++++++-------- 2 files changed, 20 insertions(+), 8 deletions(-) diff --git a/docs/conf.py b/docs/conf.py index 49416a0..0764454 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -115,5 +115,16 @@ class STIXPropertyDocumenter(ClassDocumenter): self.add_line('', '') +def autodoc_skipper(app, what, name, obj, skip, options): + """Customize Sphinx to skip some member we don't want documented. + + Skips anything containing ':autodoc-skip:' in its docstring. + """ + if obj.__doc__ and ':autodoc-skip:' in obj.__doc__: + return skip or True + return skip + + def setup(app): app.add_autodocumenter(STIXPropertyDocumenter) + app.connect('autodoc-skip-member', autodoc_skipper) diff --git a/stix2/workbench.py b/stix2/workbench.py index 4436609..3a26a64 100644 --- a/stix2/workbench.py +++ b/stix2/workbench.py @@ -47,24 +47,24 @@ STIX_OBJS = [_AttackPattern, _Campaign, _CourseOfAction, _Identity, _ThreatActor, _Tool, _Vulnerability] -def created_by_wrapper(self, *args, **kwargs): +def _created_by_wrapper(self, *args, **kwargs): return _environ.creator_of(self, *args, **kwargs) -def relationships_wrapper(self, *args, **kwargs): +def _relationships_wrapper(self, *args, **kwargs): return _environ.relationships(self, *args, **kwargs) -def related_wrapper(self, *args, **kwargs): +def _related_wrapper(self, *args, **kwargs): return _environ.related_to(self, *args, **kwargs) -def constructor_wrapper(obj_type): +def _constructor_wrapper(obj_type): # Use an intermediate wrapper class so the implicit environment will create objects that have our wrapper functions wrapped_type = type(obj_type.__name__, obj_type.__bases__, dict( - created_by=created_by_wrapper, - relationships=relationships_wrapper, - related=related_wrapper, + created_by=_created_by_wrapper, + relationships=_relationships_wrapper, + related=_related_wrapper, **obj_type.__dict__ )) @@ -77,7 +77,8 @@ def constructor_wrapper(obj_type): # Create wrapper classes whose constructors call the implicit environment's create() for obj_type in STIX_OBJS: new_class = type(obj_type.__name__, (), {}) - new_class.__new__ = constructor_wrapper(obj_type) + new_class.__new__ = _constructor_wrapper(obj_type) + new_class.__doc__ = ':autodoc-skip:' globals()[obj_type.__name__] = new_class From b9bbd03481c3184af4a6a0606e14b21aca2082bf Mon Sep 17 00:00:00 2001 From: Chris Lenk Date: Thu, 22 Mar 2018 10:55:10 -0400 Subject: [PATCH 15/61] Update workbench imports and documentation Import a bunch of stuff so users can just "from stix2.workbench import *" and not need to import other stuff (e.g. MarkingDefinition, Cyber Observable Object classes, etc.) from stix2. --- .isort.cfg | 1 + docs/api/stix2.workbench.rst | 5 ++ stix2/__init__.py | 1 + stix2/test/test_workbench.py | 48 +++++------ stix2/workbench.py | 149 +++++++++++++++++++++++++++++++++-- 5 files changed, 176 insertions(+), 28 deletions(-) create mode 100644 docs/api/stix2.workbench.rst diff --git a/.isort.cfg b/.isort.cfg index 0fadb83..cca9d19 100644 --- a/.isort.cfg +++ b/.isort.cfg @@ -1,5 +1,6 @@ [settings] not_skip = __init__.py +skip = workbench.py known_third_party = dateutil, ordereddict, diff --git a/docs/api/stix2.workbench.rst b/docs/api/stix2.workbench.rst new file mode 100644 index 0000000..19345f0 --- /dev/null +++ b/docs/api/stix2.workbench.rst @@ -0,0 +1,5 @@ +workbench +=============== + +.. automodule:: stix2.workbench + :members: \ No newline at end of file diff --git a/stix2/__init__.py b/stix2/__init__.py index 401d44b..89043ec 100644 --- a/stix2/__init__.py +++ b/stix2/__init__.py @@ -11,6 +11,7 @@ patterns properties utils + workbench v20.common v20.observables v20.sdo diff --git a/stix2/test/test_workbench.py b/stix2/test/test_workbench.py index 13aad23..a2016cc 100644 --- a/stix2/test/test_workbench.py +++ b/stix2/test/test_workbench.py @@ -1,14 +1,16 @@ import os import stix2 -from stix2.workbench import (AttackPattern, Campaign, CourseOfAction, Identity, - Indicator, IntrusionSet, Malware, ObservedData, - Report, ThreatActor, Tool, Vulnerability, add, - add_data_source, all_versions, attack_patterns, - campaigns, courses_of_action, create, get, - identities, indicators, intrusion_sets, malware, - observed_data, query, reports, - set_default_created, set_default_creator, +from stix2.workbench import (AttackPattern, Campaign, CourseOfAction, + ExternalReference, FileSystemSource, Filter, + Identity, Indicator, IntrusionSet, Malware, + MarkingDefinition, ObservedData, Relationship, + Report, StatementMarking, ThreatActor, Tool, + Vulnerability, add, add_data_source, all_versions, + attack_patterns, campaigns, courses_of_action, + create, get, identities, indicators, + intrusion_sets, malware, observed_data, query, + reports, set_default_created, set_default_creator, set_default_external_refs, set_default_object_marking_refs, threat_actors, tools, vulnerabilities) @@ -37,7 +39,7 @@ def test_workbench_environment(): assert len(resp) == 1 # Search on something other than id - q = [stix2.Filter('type', '=', 'vulnerability')] + q = [Filter('type', '=', 'vulnerability')] resp = query(q) assert len(resp) == 0 @@ -148,7 +150,7 @@ def test_workbench_get_all_vulnerabilities(): def test_workbench_relationships(): - rel = stix2.Relationship(INDICATOR_ID, 'indicates', MALWARE_ID) + rel = Relationship(INDICATOR_ID, 'indicates', MALWARE_ID) add(rel) ind = get(INDICATOR_ID) @@ -167,8 +169,8 @@ def test_workbench_created_by(): def test_workbench_related(): - rel1 = stix2.Relationship(MALWARE_ID, 'targets', IDENTITY_ID) - rel2 = stix2.Relationship(CAMPAIGN_ID, 'uses', MALWARE_ID) + rel1 = Relationship(MALWARE_ID, 'targets', IDENTITY_ID) + rel2 = Relationship(CAMPAIGN_ID, 'uses', MALWARE_ID) add([rel1, rel2]) resp = get(MALWARE_ID).related() @@ -183,10 +185,10 @@ def test_workbench_related(): def test_workbench_related_with_filters(): malware = Malware(labels=["ransomware"], name="CryptorBit", created_by_ref=IDENTITY_ID) - rel = stix2.Relationship(malware.id, 'variant-of', MALWARE_ID) + rel = Relationship(malware.id, 'variant-of', MALWARE_ID) add([malware, rel]) - filters = [stix2.Filter('created_by_ref', '=', IDENTITY_ID)] + filters = [Filter('created_by_ref', '=', IDENTITY_ID)] resp = get(MALWARE_ID).related(filters=filters) assert len(resp) == 1 @@ -200,7 +202,7 @@ def test_workbench_related_with_filters(): def test_add_data_source(): fs_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "stix2_data") - fs = stix2.FileSystemSource(fs_path) + fs = FileSystemSource(fs_path) add_data_source(fs) resp = tools() @@ -212,13 +214,13 @@ def test_add_data_source(): def test_additional_filter(): - resp = tools(stix2.Filter('created_by_ref', '=', 'identity--c78cb6e5-0c4b-4611-8297-d1b8b55e40b5')) + resp = tools(Filter('created_by_ref', '=', 'identity--c78cb6e5-0c4b-4611-8297-d1b8b55e40b5')) assert len(resp) == 2 def test_additional_filters_list(): - resp = tools([stix2.Filter('created_by_ref', '=', 'identity--c78cb6e5-0c4b-4611-8297-d1b8b55e40b5'), - stix2.Filter('name', '=', 'Windows Credential Editor')]) + resp = tools([Filter('created_by_ref', '=', 'identity--c78cb6e5-0c4b-4611-8297-d1b8b55e40b5'), + Filter('name', '=', 'Windows Credential Editor')]) assert len(resp) == 1 @@ -241,8 +243,8 @@ def test_default_created_timestamp(): def test_default_external_refs(): - ext_ref = stix2.ExternalReference(source_name="ACME Threat Intel", - description="Threat report") + ext_ref = ExternalReference(source_name="ACME Threat Intel", + description="Threat report") set_default_external_refs(ext_ref) campaign = Campaign(**CAMPAIGN_KWARGS) @@ -251,9 +253,9 @@ def test_default_external_refs(): def test_default_object_marking_refs(): - stmt_marking = stix2.StatementMarking("Copyright 2016, Example Corp") - mark_def = stix2.MarkingDefinition(definition_type="statement", - definition=stmt_marking) + stmt_marking = StatementMarking("Copyright 2016, Example Corp") + mark_def = MarkingDefinition(definition_type="statement", + definition=stmt_marking) set_default_object_marking_refs(mark_def) campaign = Campaign(**CAMPAIGN_KWARGS) diff --git a/stix2/workbench.py b/stix2/workbench.py index 3a26a64..91d626d 100644 --- a/stix2/workbench.py +++ b/stix2/workbench.py @@ -1,4 +1,24 @@ """Functions and class wrappers for interacting with STIX data at a high level. + +.. autofunction:: create +.. autofunction:: set_default_creator +.. autofunction:: set_default_created +.. autofunction:: set_default_external_refs +.. autofunction:: set_default_object_marking_refs +.. autofunction:: get +.. autofunction:: all_versions +.. autofunction:: query +.. autofunction:: query_by_type +.. autofunction:: creator_of +.. autofunction:: relationships +.. autofunction:: related_to +.. autofunction:: add +.. autofunction:: add_filters +.. autofunction:: add_filter +.. autofunction:: parse +.. autofunction:: add_data_source +.. autofunction:: add_data_sources + """ from . import AttackPattern as _AttackPattern @@ -13,8 +33,21 @@ from . import Report as _Report from . import ThreatActor as _ThreatActor from . import Tool as _Tool from . import Vulnerability as _Vulnerability -from .datastore.memory import MemoryStore -from .environment import Environment +from . import (AlternateDataStream, ArchiveExt, Artifact, AutonomousSystem, # noqa: F401 + Bundle, CustomExtension, CustomMarking, CustomObservable, + Directory, DomainName, EmailAddress, EmailMessage, + EmailMIMEComponent, Environment, ExtensionsProperty, + ExternalReference, File, FileSystemSource, Filter, + GranularMarking, HTTPRequestExt, ICMPExt, IPv4Address, + IPv6Address, KillChainPhase, MACAddress, MarkingDefinition, + MemoryStore, Mutex, NetworkTraffic, NTFSExt, parse_observable, + PDFExt, Process, RasterImageExt, Relationship, Sighting, + SocketExt, Software, StatementMarking, TAXIICollectionSource, + TCPExt, TLP_AMBER, TLP_GREEN, TLP_RED, TLP_WHITE, TLPMarking, + UNIXAccountExt, URL, UserAccount, WindowsPEBinaryExt, + WindowsPEOptionalHeaderType, WindowsPESection, + WindowsProcessExt, WindowsRegistryKey, WindowsRegistryValueType, + WindowsServiceExt, X509Certificate, X509V3ExtenstionsType) # Use an implicit MemoryStore _environ = Environment(store=MemoryStore()) @@ -46,6 +79,24 @@ STIX_OBJS = [_AttackPattern, _Campaign, _CourseOfAction, _Identity, _Indicator, _IntrusionSet, _Malware, _ObservedData, _Report, _ThreatActor, _Tool, _Vulnerability] +STIX_OBJ_DOCS = """ + +.. method:: created_by(*args, **kwargs) + + {} + +.. method:: relationships(*args, **kwargs) + + {} + +.. method:: related(*args, **kwargs) + + {} + +""".format(_environ.creator_of.__doc__, + _environ.relationships.__doc__, + _environ.related_to.__doc__) + def _created_by_wrapper(self, *args, **kwargs): return _environ.creator_of(self, *args, **kwargs) @@ -76,58 +127,146 @@ def _constructor_wrapper(obj_type): # Create wrapper classes whose constructors call the implicit environment's create() for obj_type in STIX_OBJS: - new_class = type(obj_type.__name__, (), {}) - new_class.__new__ = _constructor_wrapper(obj_type) - new_class.__doc__ = ':autodoc-skip:' + new_class_dict = { + '__new__': _constructor_wrapper(obj_type), + '__doc__': 'Workbench wrapper around the `{0} `__. object. {1}'.format(obj_type.__name__, STIX_OBJ_DOCS) + } + new_class = type(obj_type.__name__, (), new_class_dict) + globals()[obj_type.__name__] = new_class + new_class = None # Functions to get all objects of a specific type def attack_patterns(filters=None): + """Retrieve all Attack Pattern objects. + + Args: + filters (list, optional): A list of additional filters to apply to + the query. + + """ return query_by_type('attack-pattern', filters) def campaigns(filters=None): + """Retrieve all Campaign objects. + + Args: + filters (list, optional): A list of additional filters to apply to + the query. + + """ return query_by_type('campaign', filters) def courses_of_action(filters=None): + """Retrieve all Course of Action objects. + + Args: + filters (list, optional): A list of additional filters to apply to + the query. + + """ return query_by_type('course-of-action', filters) def identities(filters=None): + """Retrieve all Identity objects. + + Args: + filters (list, optional): A list of additional filters to apply to + the query. + + """ return query_by_type('identity', filters) def indicators(filters=None): + """Retrieve all Indicator objects. + + Args: + filters (list, optional): A list of additional filters to apply to + the query. + + """ return query_by_type('indicator', filters) def intrusion_sets(filters=None): + """Retrieve all Intrusion Set objects. + + Args: + filters (list, optional): A list of additional filters to apply to + the query. + + """ return query_by_type('intrusion-set', filters) def malware(filters=None): + """Retrieve all Malware objects. + + Args: + filters (list, optional): A list of additional filters to apply to + the query. + + """ return query_by_type('malware', filters) def observed_data(filters=None): + """Retrieve all Observed Data objects. + + Args: + filters (list, optional): A list of additional filters to apply to + the query. + + """ return query_by_type('observed-data', filters) def reports(filters=None): + """Retrieve all Report objects. + + Args: + filters (list, optional): A list of additional filters to apply to + the query. + + """ return query_by_type('report', filters) def threat_actors(filters=None): + """Retrieve all Threat Actor objects. + + Args: + filters (list, optional): A list of additional filters to apply to + the query. + + """ return query_by_type('threat-actor', filters) def tools(filters=None): + """Retrieve all Tool objects. + + Args: + filters (list, optional): A list of additional filters to apply to + the query. + + """ return query_by_type('tool', filters) def vulnerabilities(filters=None): + """Retrieve all Vulnerability objects. + + Args: + filters (list, optional): A list of additional filters to apply to + the query. + + """ return query_by_type('vulnerability', filters) From 98cc86eef6e341b149494779c0318f963ed20af2 Mon Sep 17 00:00:00 2001 From: Chris Lenk Date: Fri, 23 Mar 2018 13:13:41 -0400 Subject: [PATCH 16/61] Fix workbench wrapped classes for `parse()`. The wrapped classes need to be in the OBJ_MAP mapping, not just the workbench.py globals. --- stix2/workbench.py | 29 +++++++++++++++++++---------- 1 file changed, 19 insertions(+), 10 deletions(-) diff --git a/stix2/workbench.py b/stix2/workbench.py index 91d626d..f57b5f4 100644 --- a/stix2/workbench.py +++ b/stix2/workbench.py @@ -21,6 +21,7 @@ """ +import stix2 from . import AttackPattern as _AttackPattern from . import Campaign as _Campaign from . import CourseOfAction as _CourseOfAction @@ -121,20 +122,28 @@ def _constructor_wrapper(obj_type): @staticmethod def new_constructor(cls, *args, **kwargs): - return _environ.create(wrapped_type, *args, **kwargs) + x = _environ.create(wrapped_type, *args, **kwargs) + return x return new_constructor -# Create wrapper classes whose constructors call the implicit environment's create() -for obj_type in STIX_OBJS: - new_class_dict = { - '__new__': _constructor_wrapper(obj_type), - '__doc__': 'Workbench wrapper around the `{0} `__. object. {1}'.format(obj_type.__name__, STIX_OBJ_DOCS) - } - new_class = type(obj_type.__name__, (), new_class_dict) +def _setup_workbench(): + # Create wrapper classes whose constructors call the implicit environment's create() + for obj_type in STIX_OBJS: + new_class_dict = { + '__new__': _constructor_wrapper(obj_type), + '__doc__': 'Workbench wrapper around the `{0} `__. object. {1}'.format(obj_type.__name__, STIX_OBJ_DOCS) + } + new_class = type(obj_type.__name__, (), new_class_dict) - globals()[obj_type.__name__] = new_class - new_class = None + # Add our new class to this module's globals and to the library-wide mapping. + # This allows parse() to use the wrapped classes. + globals()[obj_type.__name__] = new_class + stix2.OBJ_MAP[obj_type._type] = new_class + new_class = None + + +_setup_workbench() # Functions to get all objects of a specific type From 4a2ac6df3a8528eaac738e6d74b8ad0822d46aaa Mon Sep 17 00:00:00 2001 From: Chris Lenk Date: Fri, 30 Mar 2018 11:53:15 -0400 Subject: [PATCH 17/61] Add/fix workbench docs, rename add() -> save() --- docs/guide/workbench.ipynb | 472 +++++++++++++++++++++++++++++++++++ stix2/datastore/__init__.py | 10 +- stix2/test/test_workbench.py | 38 +-- stix2/workbench.py | 6 +- 4 files changed, 501 insertions(+), 25 deletions(-) create mode 100644 docs/guide/workbench.ipynb diff --git a/docs/guide/workbench.ipynb b/docs/guide/workbench.ipynb new file mode 100644 index 0000000..bc7942a --- /dev/null +++ b/docs/guide/workbench.ipynb @@ -0,0 +1,472 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "nbsphinx": "hidden" + }, + "outputs": [], + "source": [ + "# Delete this cell to re-enable tracebacks\n", + "import sys\n", + "ipython = get_ipython()\n", + "\n", + "def hide_traceback(exc_tuple=None, filename=None, tb_offset=None,\n", + " exception_only=False, running_compiled_code=False):\n", + " etype, value, tb = sys.exc_info()\n", + " return ipython._showtraceback(etype, value, ipython.InteractiveTB.get_exception_only(etype, value))\n", + "\n", + "ipython.showtraceback = hide_traceback" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": { + "nbsphinx": "hidden" + }, + "outputs": [], + "source": [ + "# JSON output syntax highlighting\n", + "from __future__ import print_function\n", + "from pygments import highlight\n", + "from pygments.lexers import JsonLexer\n", + "from pygments.formatters import HtmlFormatter\n", + "from six.moves import builtins\n", + "from IPython.display import display, HTML\n", + "\n", + "def json_print(inpt):\n", + " string = str(inpt)\n", + " if string[0] == '{':\n", + " formatter = HtmlFormatter()\n", + " display(HTML('{}'.format(\n", + " formatter.get_style_defs('.highlight'),\n", + " highlight(string, JsonLexer(), formatter))))\n", + " else:\n", + " builtins.print(inpt)\n", + "\n", + "globals()['print'] = json_print" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Using A Workbench" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The [Workbench API](../api/stix2.workbench.rst) hides most of the complexity of the rest of the library to make it easy to interact with STIX data. To use it, just import everything from ``stix2.workbench``:" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [], + "source": [ + "from stix2.workbench import *" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Retrieving STIX Data\n", + "\n", + "To get some STIX data to work with, let's set up a DataSource and add it to our workbench." + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": { + "scrolled": true + }, + "outputs": [], + "source": [ + "from taxii2client import Collection\n", + "\n", + "collection = Collection(\"http://127.0.0.1:5000/trustgroup1/collections/91a7b528-80eb-42ed-a74d-c6fbd5a26116/\", user=\"admin\", password=\"Password0\")\n", + "tc_source = TAXIICollectionSource(collection)\n", + "add_data_source(tc_source)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "Now we can get all of the indicators from the data source." + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [], + "source": [ + "response = indicators()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Similar functions are available for the other STIX Object types. See the full list [here](../api/stix2.workbench.rst#stix2.workbench.attack_patterns).\n", + "\n", + "If you want to only retrieve *some* indicators, you can pass in one or more [Filters](../api/datastore/stix2.datastore.filters.rst). This example finds all the indicators created by a specific identity:" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [], + "source": [ + "response = indicators(filters=Filter('created_by_ref', '=', 'identity--adede3e8-bf44-4e6f-b3c9-1958cbc3b188'))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The objects returned let you easily traverse their relationships. Get all Relationship objects involving that object with ``.relationships()``, all other objects related to this object with ``.related()``, and the Identity object for the creator of the object (if one exists) with ``.created_by()``. For full details on these methods and their arguments, see the [Workbench API](../api/stix2.workbench.rst) documentation." + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "indicator--a932fcc6-e032-176c-126f-cb970a5a1ade\n", + "indicates\n", + "malware--fdd60b30-b67c-11e3-b0b9-f01faf20d111\n" + ] + } + ], + "source": [ + "for i in indicators():\n", + " for rel in i.relationships():\n", + " print(rel.source_ref)\n", + " print(rel.relationship_type)\n", + " print(rel.target_ref)" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
{\n",
+       "    "type": "malware",\n",
+       "    "id": "malware--fdd60b30-b67c-11e3-b0b9-f01faf20d111",\n",
+       "    "created": "2017-01-27T13:49:53.997Z",\n",
+       "    "modified": "2017-01-27T13:49:53.997Z",\n",
+       "    "name": "Poison Ivy",\n",
+       "    "description": "Poison Ivy",\n",
+       "    "labels": [\n",
+       "        "remote-access-trojan"\n",
+       "    ]\n",
+       "}\n",
+       "
\n" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "for i in indicators():\n", + " for obj in i.related():\n", + " print(obj)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "If there are a lot of related objects, you can narrow it down by passing in one or more [Filters](../api/datastore/stix2.datastore.filters.rst) just as before. For example, if we want to get only the indicators related to a specific piece of malware (and not any entities that use it or are targeted by it):" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
{\n",
+       "    "type": "indicator",\n",
+       "    "id": "indicator--a932fcc6-e032-176c-126f-cb970a5a1ade",\n",
+       "    "created": "2014-05-08T09:00:00.000Z",\n",
+       "    "modified": "2014-05-08T09:00:00.000Z",\n",
+       "    "name": "File hash for Poison Ivy variant",\n",
+       "    "pattern": "[file:hashes.'SHA-256' = 'ef537f25c895bfa782526529a9b63d97aa631564d5d789c2b765448c8635fb6c']",\n",
+       "    "valid_from": "2014-05-08T09:00:00Z",\n",
+       "    "labels": [\n",
+       "        "file-hash-watchlist"\n",
+       "    ]\n",
+       "}\n",
+       "
\n" + ], + "text/plain": [ + "" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "malware = get('malware--fdd60b30-b67c-11e3-b0b9-f01faf20d111')\n", + "indicator = malware.related(filters=Filter('type', '=', 'indicator'))\n", + "print(indicator[0])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Creating STIX Data\n", + "\n", + "To create a STIX object, just use that object's class constructor. Once it's created, add it to the workbench with [save()](../api/datastore/stix2.workbench.rst#stix2.workbench.save)." + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [], + "source": [ + "identity = Identity(name=\"ACME Threat Intel Co.\", identity_class=\"organization\")\n", + "save(identity)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "You can also set defaults for certain properties when creating objects. For example, let's set the default creator to be the identity object we just created:" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [], + "source": [ + "set_default_creator(identity)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Now when we create an indicator (or any other STIX Domain Object), it will automatically have the right ``create_by_ref`` value." + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "ACME Threat Intel Co.\n" + ] + } + ], + "source": [ + "indicator = Indicator(labels=[\"malicious-activity\"], pattern=\"[file:hashes.MD5 = 'd41d8cd98f00b204e9800998ecf8427e']\")\n", + "save(indicator)\n", + "\n", + "indicator_creator = get(indicator.created_by_ref)\n", + "print(indicator_creator.name)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Defaults can also be set for the [created timestamp](../api/datastore/stix2.workbench.rst#stix2.workbench.set_default_created), [external references](../api/datastore/stix2.workbench.rst#stix2.workbench.set_default_external_refs) and [object marking references](../api/datastore/stix2.workbench.rst#stix2.workbench.set_default_object_marking_refs)." + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.3" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/stix2/datastore/__init__.py b/stix2/datastore/__init__.py index f02d773..9bf23a2 100644 --- a/stix2/datastore/__init__.py +++ b/stix2/datastore/__init__.py @@ -181,6 +181,8 @@ class DataStoreMixin(object): object is the source_ref. Default: False. target_only (bool): Only examine Relationships for which this object is the target_ref. Default: False. + filters (list): list of additional filters the related objects must + match. Returns: list: The STIX objects related to the given STIX object. @@ -194,8 +196,8 @@ class DataStoreMixin(object): def add(self, *args, **kwargs): """Method for storing STIX objects. - Define custom behavior before storing STIX objects using the associated - DataSink. Translates add() to the appropriate DataSink call. + Defines custom behavior before storing STIX objects using the + appropriate method call on the associated DataSink. Args: stix_objs (list): a list of STIX objects @@ -416,7 +418,7 @@ class DataSource(with_metaclass(ABCMeta)): ids = set() for r in rels: ids.update((r.source_ref, r.target_ref)) - ids.remove(obj_id) + ids.discard(obj_id) # Assemble filters filter_list = [] @@ -678,6 +680,8 @@ class CompositeDataSource(DataSource): object is the source_ref. Default: False. target_only (bool): Only examine Relationships for which this object is the target_ref. Default: False. + filters (list): list of additional filters the related objects must + match. Returns: list: The STIX objects related to the given STIX object. diff --git a/stix2/test/test_workbench.py b/stix2/test/test_workbench.py index a2016cc..7857eb2 100644 --- a/stix2/test/test_workbench.py +++ b/stix2/test/test_workbench.py @@ -6,12 +6,12 @@ from stix2.workbench import (AttackPattern, Campaign, CourseOfAction, Identity, Indicator, IntrusionSet, Malware, MarkingDefinition, ObservedData, Relationship, Report, StatementMarking, ThreatActor, Tool, - Vulnerability, add, add_data_source, all_versions, + Vulnerability, add_data_source, all_versions, attack_patterns, campaigns, courses_of_action, create, get, identities, indicators, intrusion_sets, malware, observed_data, query, - reports, set_default_created, set_default_creator, - set_default_external_refs, + reports, save, set_default_created, + set_default_creator, set_default_external_refs, set_default_object_marking_refs, threat_actors, tools, vulnerabilities) @@ -30,7 +30,7 @@ def test_workbench_environment(): # Create a STIX object ind = create(Indicator, id=INDICATOR_ID, **INDICATOR_KWARGS) - add(ind) + save(ind) resp = get(INDICATOR_ID) assert resp['labels'][0] == 'malicious-activity' @@ -46,7 +46,7 @@ def test_workbench_environment(): def test_workbench_get_all_attack_patterns(): mal = AttackPattern(id=ATTACK_PATTERN_ID, **ATTACK_PATTERN_KWARGS) - add(mal) + save(mal) resp = attack_patterns() assert len(resp) == 1 @@ -55,7 +55,7 @@ def test_workbench_get_all_attack_patterns(): def test_workbench_get_all_campaigns(): cam = Campaign(id=CAMPAIGN_ID, **CAMPAIGN_KWARGS) - add(cam) + save(cam) resp = campaigns() assert len(resp) == 1 @@ -64,7 +64,7 @@ def test_workbench_get_all_campaigns(): def test_workbench_get_all_courses_of_action(): coa = CourseOfAction(id=COURSE_OF_ACTION_ID, **COURSE_OF_ACTION_KWARGS) - add(coa) + save(coa) resp = courses_of_action() assert len(resp) == 1 @@ -73,7 +73,7 @@ def test_workbench_get_all_courses_of_action(): def test_workbench_get_all_identities(): idty = Identity(id=IDENTITY_ID, **IDENTITY_KWARGS) - add(idty) + save(idty) resp = identities() assert len(resp) == 1 @@ -88,7 +88,7 @@ def test_workbench_get_all_indicators(): def test_workbench_get_all_intrusion_sets(): ins = IntrusionSet(id=INTRUSION_SET_ID, **INTRUSION_SET_KWARGS) - add(ins) + save(ins) resp = intrusion_sets() assert len(resp) == 1 @@ -97,7 +97,7 @@ def test_workbench_get_all_intrusion_sets(): def test_workbench_get_all_malware(): mal = Malware(id=MALWARE_ID, **MALWARE_KWARGS) - add(mal) + save(mal) resp = malware() assert len(resp) == 1 @@ -106,7 +106,7 @@ def test_workbench_get_all_malware(): def test_workbench_get_all_observed_data(): od = ObservedData(id=OBSERVED_DATA_ID, **OBSERVED_DATA_KWARGS) - add(od) + save(od) resp = observed_data() assert len(resp) == 1 @@ -115,7 +115,7 @@ def test_workbench_get_all_observed_data(): def test_workbench_get_all_reports(): rep = Report(id=REPORT_ID, **REPORT_KWARGS) - add(rep) + save(rep) resp = reports() assert len(resp) == 1 @@ -124,7 +124,7 @@ def test_workbench_get_all_reports(): def test_workbench_get_all_threat_actors(): thr = ThreatActor(id=THREAT_ACTOR_ID, **THREAT_ACTOR_KWARGS) - add(thr) + save(thr) resp = threat_actors() assert len(resp) == 1 @@ -133,7 +133,7 @@ def test_workbench_get_all_threat_actors(): def test_workbench_get_all_tools(): tool = Tool(id=TOOL_ID, **TOOL_KWARGS) - add(tool) + save(tool) resp = tools() assert len(resp) == 1 @@ -142,7 +142,7 @@ def test_workbench_get_all_tools(): def test_workbench_get_all_vulnerabilities(): vuln = Vulnerability(id=VULNERABILITY_ID, **VULNERABILITY_KWARGS) - add(vuln) + save(vuln) resp = vulnerabilities() assert len(resp) == 1 @@ -151,7 +151,7 @@ def test_workbench_get_all_vulnerabilities(): def test_workbench_relationships(): rel = Relationship(INDICATOR_ID, 'indicates', MALWARE_ID) - add(rel) + save(rel) ind = get(INDICATOR_ID) resp = ind.relationships() @@ -163,7 +163,7 @@ def test_workbench_relationships(): def test_workbench_created_by(): intset = IntrusionSet(name="Breach 123", created_by_ref=IDENTITY_ID) - add(intset) + save(intset) creator = intset.created_by() assert creator.id == IDENTITY_ID @@ -171,7 +171,7 @@ def test_workbench_created_by(): def test_workbench_related(): rel1 = Relationship(MALWARE_ID, 'targets', IDENTITY_ID) rel2 = Relationship(CAMPAIGN_ID, 'uses', MALWARE_ID) - add([rel1, rel2]) + save([rel1, rel2]) resp = get(MALWARE_ID).related() assert len(resp) == 3 @@ -186,7 +186,7 @@ def test_workbench_related(): def test_workbench_related_with_filters(): malware = Malware(labels=["ransomware"], name="CryptorBit", created_by_ref=IDENTITY_ID) rel = Relationship(malware.id, 'variant-of', MALWARE_ID) - add([malware, rel]) + save([malware, rel]) filters = [Filter('created_by_ref', '=', IDENTITY_ID)] resp = get(MALWARE_ID).related(filters=filters) diff --git a/stix2/workbench.py b/stix2/workbench.py index f57b5f4..0338353 100644 --- a/stix2/workbench.py +++ b/stix2/workbench.py @@ -12,7 +12,7 @@ .. autofunction:: creator_of .. autofunction:: relationships .. autofunction:: related_to -.. autofunction:: add +.. autofunction:: save .. autofunction:: add_filters .. autofunction:: add_filter .. autofunction:: parse @@ -65,7 +65,7 @@ query_by_type = _environ.query_by_type creator_of = _environ.creator_of relationships = _environ.relationships related_to = _environ.related_to -add = _environ.add +save = _environ.add add_filters = _environ.add_filters add_filter = _environ.add_filter parse = _environ.parse @@ -132,7 +132,7 @@ def _setup_workbench(): for obj_type in STIX_OBJS: new_class_dict = { '__new__': _constructor_wrapper(obj_type), - '__doc__': 'Workbench wrapper around the `{0} `__. object. {1}'.format(obj_type.__name__, STIX_OBJ_DOCS) + '__doc__': 'Workbench wrapper around the `{0} `__ object. {1}'.format(obj_type.__name__, STIX_OBJ_DOCS) } new_class = type(obj_type.__name__, (), new_class_dict) From d453bf6f1a2c9ef2ac5014faa48ad941bbac26df Mon Sep 17 00:00:00 2001 From: Chris Lenk Date: Fri, 30 Mar 2018 13:12:51 -0400 Subject: [PATCH 18/61] Add a couple granular markings tests --- stix2/test/test_granular_markings.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/stix2/test/test_granular_markings.py b/stix2/test/test_granular_markings.py index f8fc803..9e024a1 100644 --- a/stix2/test/test_granular_markings.py +++ b/stix2/test/test_granular_markings.py @@ -2,6 +2,7 @@ import pytest from stix2 import TLP_RED, Malware, markings +from stix2.exceptions import MarkingNotFoundError from .constants import MALWARE_MORE_KWARGS as MALWARE_KWARGS_CONST from .constants import MARKING_IDS @@ -546,6 +547,20 @@ def test_remove_marking_bad_selector(): markings.remove_markings(before, ["marking-definition--1", "marking-definition--2"], ["title"]) +def test_remove_marking_not_present(): + before = Malware( + granular_markings=[ + { + "selectors": ["description"], + "marking_ref": MARKING_IDS[0] + } + ], + **MALWARE_KWARGS + ) + with pytest.raises(MarkingNotFoundError): + markings.remove_markings(before, [MARKING_IDS[1]], ["description"]) + + IS_MARKED_TEST_DATA = [ Malware( granular_markings=[ @@ -1044,3 +1059,10 @@ def test_clear_marking_bad_selector(data, selector): """Test bad selector raises exception.""" with pytest.raises(AssertionError): markings.clear_markings(data, selector) + + +@pytest.mark.parametrize("data", CLEAR_MARKINGS_TEST_DATA) +def test_clear_marking_not_present(data): + """Test clearing markings for a selector that has no associated markings.""" + with pytest.raises(MarkingNotFoundError): + data = markings.clear_markings(data, ["labels"]) From 90834c5b953c060a08bf866e437114b3bca3c4d4 Mon Sep 17 00:00:00 2001 From: = Date: Fri, 30 Mar 2018 13:21:07 -0400 Subject: [PATCH 19/61] docs and tests for parse() mod --- docs/guide/parsing.ipynb | 395 +++++++++++++++++++++++++++++++++++++- stix2/core.py | 19 +- stix2/test/test_custom.py | 14 ++ 3 files changed, 421 insertions(+), 7 deletions(-) diff --git a/docs/guide/parsing.ipynb b/docs/guide/parsing.ipynb index d24f994..b3460b3 100644 --- a/docs/guide/parsing.ipynb +++ b/docs/guide/parsing.ipynb @@ -63,21 +63,120 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Parsing STIX content is as easy as calling the [parse()](../api/stix2.core.rst#stix2.core.parse) function on a JSON string. It will automatically determine the type of the object. The STIX objects within `bundle` objects, and the cyber observables contained within `observed-data` objects will be parsed as well." + "Parsing STIX content is as easy as calling the [parse()](../api/stix2.core.rst#stix2.core.parse) function on a JSON string, dictionary, or file-like object. It will automatically determine the type of the object. The STIX objects within `bundle` objects, and the cyber observables contained within `observed-data` objects will be parsed as well.\n", + "\n", + "**Parsing a string**" ] }, { "cell_type": "code", - "execution_count": 3, + "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ - "observed-data\n", - "0969de02ecf8a5f003e3f6d063d848c8a193aada092623f8ce408c15bcb5f038\n" + "\n" ] + }, + { + "data": { + "text/html": [ + "
{\n",
+       "    "type": "observed-data",\n",
+       "    "id": "observed-data--b67d30ff-02ac-498a-92f9-32f845f448cf",\n",
+       "    "created": "2016-04-06T19:58:16.000Z",\n",
+       "    "modified": "2016-04-06T19:58:16.000Z",\n",
+       "    "first_observed": "2015-12-21T19:00:00Z",\n",
+       "    "last_observed": "2015-12-21T19:00:00Z",\n",
+       "    "number_observed": 50,\n",
+       "    "objects": {\n",
+       "        "0": {\n",
+       "            "type": "file",\n",
+       "            "hashes": {\n",
+       "                "SHA-256": "0969de02ecf8a5f003e3f6d063d848c8a193aada092623f8ce408c15bcb5f038"\n",
+       "            }\n",
+       "        }\n",
+       "    }\n",
+       "}\n",
+       "
\n" + ], + "text/plain": [ + "" + ] + }, + "execution_count": 10, + "metadata": {}, + "output_type": "execute_result" } ], "source": [ @@ -102,8 +201,292 @@ "}\"\"\"\n", "\n", "obj = parse(input_string)\n", - "print(obj.type)\n", - "print(obj.objects[\"0\"].hashes['SHA-256'])" + "print(type(obj))\n", + "print(obj)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Parsing a dictionary**" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n" + ] + }, + { + "data": { + "text/html": [ + "
{\n",
+       "    "type": "identity",\n",
+       "    "id": "identity--311b2d2d-f010-5473-83ec-1edf84858f4c",\n",
+       "    "created": "2015-12-21T19:59:11.000Z",\n",
+       "    "modified": "2015-12-21T19:59:11.000Z",\n",
+       "    "name": "Cole Powers",\n",
+       "    "identity_class": "individual"\n",
+       "}\n",
+       "
\n" + ], + "text/plain": [ + "" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "input_dict = {\n", + " \"type\": \"identity\",\n", + " \"id\": \"identity--311b2d2d-f010-5473-83ec-1edf84858f4c\",\n", + " \"created\": \"2015-12-21T19:59:11Z\",\n", + " \"modified\": \"2015-12-21T19:59:11Z\",\n", + " \"name\": \"Cole Powers\",\n", + " \"identity_class\": \"individual\"\n", + "}\n", + "\n", + "obj = parse(input_dict)\n", + "print(type(obj))\n", + "print(obj)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Parsing a file-like object**" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n" + ] + }, + { + "data": { + "text/html": [ + "
{\n",
+       "    "type": "course-of-action",\n",
+       "    "id": "course-of-action--d9727aee-48b8-4fdb-89e2-4c49746ba4dd",\n",
+       "    "created_by_ref": "identity--c78cb6e5-0c4b-4611-8297-d1b8b55e40b5",\n",
+       "    "created": "2017-05-31T21:30:41.022Z",\n",
+       "    "modified": "2017-05-31T21:30:41.022Z",\n",
+       "    "name": "Data from Network Shared Drive Mitigation",\n",
+       "    "description": "Identify unnecessary system utilities or potentially malicious software that may be used to collect data from a network share, and audit and/or block them by using whitelisting[[CiteRef::Beechey 2010]] tools, like AppLocker,[[CiteRef::Windows Commands JPCERT]][[CiteRef::NSA MS AppLocker]] or Software Restriction Policies[[CiteRef::Corio 2008]] where appropriate.[[CiteRef::TechNet Applocker vs SRP]]"\n",
+       "}\n",
+       "
\n" + ], + "text/plain": [ + "" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "file_handle = open(\"/home/michael/cti-python-stix2/stix2/test/stix2_data/course-of-action/course-of-action--d9727aee-48b8-4fdb-89e2-4c49746ba4dd.json\")\n", + "\n", + "obj = parse(file_handle)\n", + "print(type(obj))\n", + "print(obj)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Parsing Custom STIX Content" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Parsing custom STIX objects and/or STIX objects with custom properties is also completed easily with [parse()](../api/stix2.core.rst#stix2.core.parse). Just supply the keyword argument *allow_custom=True*. When *allow_custom* is specified, [parse()](../api/stix2.core.rst#stix2.core.parse) will attempt to convert the supplied STIX content to known STIX2 domain objects and/or previously defined custom defined STIX2 objects. If the conversion cannot be completed (and *allow_custom* is specified), [parse()](../api/stix2.core.rst#stix2.core.parse) will treat the supplied STIX2 content as valid STIX2 objects and return them. **Warning: Specifying *allow_custom* may lead to critical errors if further processing (searching, filtering, modifying etc...) of the custom STIX2 content occurs where the custom STIX2 content supplied is not valid STIX2**. This is an axiomatic possibility as the STIX2 library cannot guarantee proper processing of unknown custom STIX2 objects that were explicitly flagged to be allowed, and thus may not be valid.\n", + "\n", + "For examples on parsing STIX2 objects with custom STIX properties, see [Custom STIX Content:Custom Properties](custom.ipynb#Custom-Properties)\n", + "\n", + "For examples on parsing defined custom STIX2 objects, see [Custom STIX Content: Custom STIX Object Types](custom.ipynb#Custom-STIX-Object-Types)\n", + "\n", + "For the case where it is desired to retrieve STIX2 content from a source (e.g. file system, TAXII) that may possibly have custom STIX2 content unknown to the user, the user can create a STIX2 DataStore/Source with the flag *allow_custom=True*. As aforementioned this will configure the DataStore/Source to allow for unknown STIX2 content to be returned (albeit not converted to full STIX2 domain objects and properties); notable processing capabilites of the STIX2 library may be precluded by the unknown STIX2 content, if the content is not valid or actual STIX2 domain objects and properties." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "from taxii2client import Collection\n", + "from stix2 import CompositeDataSource, FileSystemSource, TAXIICollectionSource\n", + "\n", + "# to allow for the retrieval of unknown custom STIX2 content,\n", + "# just create *Stores/*Sources with the 'allow_custom' flag\n", + "\n", + "# create FileSystemStore\n", + "fs = FileSystemSource(\"/path/to/stix2_data/\", allow_custom=True)\n", + "\n", + "# create TAXIICollectionSource\n", + "colxn = Collection('http://taxii_url')\n", + "ts = TAXIICollectionSource(colxn, allow_custom=True)\n" ] } ], diff --git a/stix2/core.py b/stix2/core.py index 64307ff..7de7984 100644 --- a/stix2/core.py +++ b/stix2/core.py @@ -73,7 +73,7 @@ STIX2_OBJ_MAPS = {} def parse(data, allow_custom=False, version=None): - """Deserialize a string or file-like object into a STIX object. + """Convert a string, dict or file-like object into a STIX object. Args: data (str, dict, file-like object): The STIX 2 content to be parsed. @@ -86,6 +86,13 @@ def parse(data, allow_custom=False, version=None): Returns: An instantiated Python STIX object. + WARNING: 'allow_custom=True' will allow for the return of any supplied STIX + dict(s) that cannot be found to map to any known STIX object types (both STIX2 + domain objects or defined custom STIX2 objects); NO validation is done. This is + done to allow the processing of possibly unknown custom STIX objects (example + scenario: I need to query a third-party TAXII endpoint that could provide custom + STIX objects that I dont know about ahead of time) + """ # convert STIX object to dict, if not already obj = get_dict(data) @@ -107,6 +114,16 @@ def dict_to_stix2(stix_dict, allow_custom=False, version=None): custom objects. Note that unknown custom objects cannot be parsed into STIX objects, and will be returned as is. Default: False. + Returns: + An instantiated Python STIX object + + WARNING: 'allow_custom=True' will allow for the return of any supplied STIX + dict(s) that cannot be found to map to any known STIX object types (both STIX2 + domain objects or defined custom STIX2 objects); NO validation is done. This is + done to allow the processing of possibly unknown custom STIX objects (example + scenario: I need to query a third-party TAXII endpoint that could provide custom + STIX objects that I dont know about ahead of time) + """ if not version: # Use latest version diff --git a/stix2/test/test_custom.py b/stix2/test/test_custom.py index 76ad61b..cc8b32b 100644 --- a/stix2/test/test_custom.py +++ b/stix2/test/test_custom.py @@ -221,6 +221,20 @@ def test_parse_unregistered_custom_object_type(): assert "use the CustomObject decorator." in str(excinfo.value) +def test_parse_unregistered_custom_object_type_w_allow_custom(): + """parse an unknown custom object, allowed by passing + 'allow_custom' flag + """ + nt_string = """{ + "type": "x-foobar-observable", + "created": "2015-12-21T19:59:11Z", + "property1": "something" + }""" + + custom_obj = stix2.parse(nt_string, allow_custom=True) + assert custom_obj["type"] == "x-foobar-observable" + + @stix2.observables.CustomObservable('x-new-observable', [ ('property1', stix2.properties.StringProperty(required=True)), ('property2', stix2.properties.IntegerProperty()), From c5185332754b6b6e23c8bc0d28b5a03be7c93a8b Mon Sep 17 00:00:00 2001 From: Emmanuelle Vargas-Gonzalez Date: Mon, 2 Apr 2018 07:51:51 -0400 Subject: [PATCH 20/61] Update stix2 setup configuration # Remove taxii2-client as a requirement to install stix2 # Add taxii2-client to the Tox configuration instead # Re-factor the version and description loading --- setup.py | 8 ++++---- tox.ini | 1 + 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/setup.py b/setup.py index fa68616..5edf20f 100644 --- a/setup.py +++ b/setup.py @@ -4,11 +4,12 @@ import os.path from setuptools import find_packages, setup -here = os.path.abspath(os.path.dirname(__file__)) +BASE_DIR = os.path.dirname(os.path.abspath(__file__)) +VERSION_FILE = os.path.join(BASE_DIR, 'stix2', 'version.py') def get_version(): - with open('stix2/version.py', encoding="utf-8") as f: + with open(VERSION_FILE) as f: for line in f.readlines(): if line.startswith("__version__"): version = line.split()[-1].strip('"') @@ -16,7 +17,7 @@ def get_version(): raise AttributeError("Package does not have a __version__") -with open(os.path.join(here, 'README.rst'), encoding='utf-8') as f: +with open('README.rst') as f: long_description = f.read() @@ -52,6 +53,5 @@ setup( 'simplejson', 'six', 'stix2-patterns', - 'taxii2-client', ], ) diff --git a/tox.ini b/tox.ini index bfc8c1b..ed26bc0 100644 --- a/tox.ini +++ b/tox.ini @@ -8,6 +8,7 @@ deps = pytest pytest-cov coverage + taxii2-client commands = py.test --cov=stix2 stix2/test/ --cov-report term-missing From 470b3ec092039dcd32f5a1e30acb76d1fbcdf75e Mon Sep 17 00:00:00 2001 From: Emmanuelle Vargas-Gonzalez Date: Mon, 2 Apr 2018 09:25:26 -0400 Subject: [PATCH 21/61] Update setup.py to include taxii2-client as an extra dependency --- setup.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/setup.py b/setup.py index 5edf20f..9700ec8 100644 --- a/setup.py +++ b/setup.py @@ -54,4 +54,7 @@ setup( 'six', 'stix2-patterns', ], + extras_require={ + 'taxii': ['taxii2-client'] + } ) From 940afb0012f67b2cbe3e8ee2660d027968799112 Mon Sep 17 00:00:00 2001 From: Chris Lenk Date: Mon, 2 Apr 2018 09:54:22 -0400 Subject: [PATCH 22/61] Require a type when querying by type --- stix2/datastore/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/stix2/datastore/__init__.py b/stix2/datastore/__init__.py index 9bf23a2..890ac45 100644 --- a/stix2/datastore/__init__.py +++ b/stix2/datastore/__init__.py @@ -298,7 +298,7 @@ class DataSource(with_metaclass(ABCMeta)): """ - def query_by_type(self, obj_type='indicator', filters=None): + def query_by_type(self, obj_type, filters=None): """Retrieve all objects of the given STIX object type. This helper function is a shortcut that calls query() under the hood. From 3abfe7868a1393e7c60529a6ceca5aba306978f1 Mon Sep 17 00:00:00 2001 From: Chris Lenk Date: Mon, 2 Apr 2018 16:38:04 -0400 Subject: [PATCH 23/61] Add more patterning tests ... and fix bugs detected in doing so --- stix2/__init__.py | 5 +- stix2/patterns.py | 66 ++++---- stix2/test/test_pattern_expressions.py | 203 ++++++++++++++++++++++++- 3 files changed, 239 insertions(+), 35 deletions(-) diff --git a/stix2/__init__.py b/stix2/__init__.py index 401d44b..9ab99d8 100644 --- a/stix2/__init__.py +++ b/stix2/__init__.py @@ -31,11 +31,12 @@ from .environment import Environment, ObjectFactory from .markings import (add_markings, clear_markings, get_markings, is_marked, remove_markings, set_markings) from .patterns import (AndBooleanExpression, AndObservationExpression, - BasicObjectPathComponent, EqualityComparisonExpression, + BasicObjectPathComponent, BinaryConstant, + BooleanConstant, EqualityComparisonExpression, FloatConstant, FollowedByObservationExpression, GreaterThanComparisonExpression, GreaterThanEqualComparisonExpression, HashConstant, - HexConstant, IntegerConstant, + HexConstant, InComparisonExpression, IntegerConstant, IsSubsetComparisonExpression, IsSupersetComparisonExpression, LessThanComparisonExpression, diff --git a/stix2/patterns.py b/stix2/patterns.py index 94ae7d2..23ce71b 100644 --- a/stix2/patterns.py +++ b/stix2/patterns.py @@ -3,8 +3,11 @@ import base64 import binascii +import datetime import re +from .utils import parse_into_datetime + def escape_quotes_and_backslashes(s): return s.replace(u'\\', u'\\\\').replace(u"'", u"\\'") @@ -24,10 +27,13 @@ class StringConstant(_Constant): class TimestampConstant(_Constant): def __init__(self, value): - self.value = value + try: + self.value = parse_into_datetime(value) + except Exception: + raise ValueError("must be a datetime object or timestamp string.") def __str__(self): - return "t'%s'" % escape_quotes_and_backslashes(self.value) + return "t%s" % repr(self.value) class IntegerConstant(_Constant): @@ -46,7 +52,7 @@ class FloatConstant(_Constant): try: self.value = float(value) except Exception: - raise ValueError("must be an float.") + raise ValueError("must be a float.") def __str__(self): return "%s" % self.value @@ -56,24 +62,29 @@ class BooleanConstant(_Constant): def __init__(self, value): if isinstance(value, bool): self.value = value + return trues = ['true', 't'] falses = ['false', 'f'] try: if value.lower() in trues: self.value = True - if value.lower() in falses: + return + elif value.lower() in falses: self.value = False + return except AttributeError: if value == 1: self.value = True - if value == 0: + return + elif value == 0: self.value = False + return raise ValueError("must be a boolean value.") def __str__(self): - return "%s" % self.value + return str(self.value).lower() _HASH_REGEX = { @@ -132,20 +143,25 @@ class ListConstant(_Constant): self.value = values def __str__(self): - return "(" + ", ".join([("%s" % x) for x in self.value]) + ")" + return "(" + ", ".join([("%s" % make_constant(x)) for x in self.value]) + ")" def make_constant(value): + try: + return parse_into_datetime(value) + except ValueError: + pass + if isinstance(value, str): return StringConstant(value) + elif isinstance(value, bool): + return BooleanConstant(value) elif isinstance(value, int): return IntegerConstant(value) elif isinstance(value, float): return FloatConstant(value) elif isinstance(value, list): return ListConstant(value) - elif isinstance(value, bool): - return BooleanConstant(value) else: raise ValueError("Unable to create a constant from %s" % value) @@ -210,15 +226,12 @@ class ObjectPath(object): class _PatternExpression(object): - - @staticmethod - def escape_quotes_and_backslashes(s): - return s.replace(u'\\', u'\\\\').replace(u"'", u"\\'") + pass class _ComparisonExpression(_PatternExpression): def __init__(self, operator, lhs, rhs, negated=False): - if operator == "=" and isinstance(rhs, ListConstant): + if operator == "=" and isinstance(rhs, (ListConstant, list)): self.operator = "IN" else: self.operator = operator @@ -234,13 +247,6 @@ class _ComparisonExpression(_PatternExpression): self.root_type = self.lhs.object_type_name def __str__(self): - # if isinstance(self.rhs, list): - # final_rhs = [] - # for r in self.rhs: - # final_rhs.append("'" + self.escape_quotes_and_backslashes("%s" % r) + "'") - # rhs_string = "(" + ", ".join(final_rhs) + ")" - # else: - # rhs_string = self.rhs if self.negated: return "%s NOT %s %s" % (self.lhs, self.operator, self.rhs) else: @@ -383,7 +389,7 @@ class RepeatQualifier(_ExpressionQualifier): elif isinstance(times_to_repeat, int): self.times_to_repeat = IntegerConstant(times_to_repeat) else: - raise ValueError("%s is not a valid argument for a Within Qualifier" % times_to_repeat) + raise ValueError("%s is not a valid argument for a Repeat Qualifier" % times_to_repeat) def __str__(self): return "REPEATS %s TIMES" % self.times_to_repeat @@ -404,18 +410,18 @@ class WithinQualifier(_ExpressionQualifier): class StartStopQualifier(_ExpressionQualifier): def __init__(self, start_time, stop_time): - if isinstance(start_time, IntegerConstant): + if isinstance(start_time, TimestampConstant): self.start_time = start_time - elif isinstance(start_time, int): - self.start_time = IntegerConstant(start_time) + elif isinstance(start_time, datetime.date): + self.start_time = TimestampConstant(start_time) else: - raise ValueError("%s is not a valid argument for a Within Qualifier" % start_time) - if isinstance(stop_time, IntegerConstant): + raise ValueError("%s is not a valid argument for a Start/Stop Qualifier" % start_time) + if isinstance(stop_time, TimestampConstant): self.stop_time = stop_time - elif isinstance(stop_time, int): - self.stop_time = IntegerConstant(stop_time) + elif isinstance(stop_time, datetime.date): + self.stop_time = TimestampConstant(stop_time) else: - raise ValueError("%s is not a valid argument for a Within Qualifier" % stop_time) + raise ValueError("%s is not a valid argument for a Start/Stop Qualifier" % stop_time) def __str__(self): return "START %s STOP %s" % (self.start_time, self.stop_time) diff --git a/stix2/test/test_pattern_expressions.py b/stix2/test/test_pattern_expressions.py index 0db1083..363458a 100644 --- a/stix2/test/test_pattern_expressions.py +++ b/stix2/test/test_pattern_expressions.py @@ -1,3 +1,7 @@ +import datetime + +import pytest + import stix2 @@ -67,7 +71,11 @@ def test_file_observable_expression(): assert str(exp) == "[file:hashes.'SHA-256' = 'aec070645fe53ee3b3763059376134f058cc337247c978add178b6ccdfb0019f' AND file:mime_type = 'application/x-pdf']" # noqa -def test_multiple_file_observable_expression(): +@pytest.mark.parametrize("observation_class, op", [ + (stix2.AndObservationExpression, 'AND'), + (stix2.OrObservationExpression, 'OR'), +]) +def test_multiple_file_observable_expression(observation_class, op): exp1 = stix2.EqualityComparisonExpression("file:hashes.'SHA-256'", stix2.HashConstant( "bf07a7fbb825fc0aae7bf4a1177b2b31fcf8a3feeaf7092761e18c859ee52a9c", @@ -81,8 +89,8 @@ def test_multiple_file_observable_expression(): 'SHA-256')) op1_exp = stix2.ObservationExpression(bool1_exp) op2_exp = stix2.ObservationExpression(exp3) - exp = stix2.AndObservationExpression([op1_exp, op2_exp]) - assert str(exp) == "[file:hashes.'SHA-256' = 'bf07a7fbb825fc0aae7bf4a1177b2b31fcf8a3feeaf7092761e18c859ee52a9c' OR file:hashes.MD5 = 'cead3f77f6cda6ec00f57d76c9a6879f'] AND [file:hashes.'SHA-256' = 'aec070645fe53ee3b3763059376134f058cc337247c978add178b6ccdfb0019f']" # noqa + exp = observation_class([op1_exp, op2_exp]) + assert str(exp) == "[file:hashes.'SHA-256' = 'bf07a7fbb825fc0aae7bf4a1177b2b31fcf8a3feeaf7092761e18c859ee52a9c' OR file:hashes.MD5 = 'cead3f77f6cda6ec00f57d76c9a6879f'] {} [file:hashes.'SHA-256' = 'aec070645fe53ee3b3763059376134f058cc337247c978add178b6ccdfb0019f']".format(op) # noqa def test_root_types(): @@ -120,6 +128,31 @@ def test_greater_than(): assert str(exp) == "[file:extensions.windows-pebinary-ext.sections[*].entropy > 7.0]" +def test_less_than(): + exp = stix2.LessThanComparisonExpression("file:size", + 1024) + assert str(exp) == "file:size < 1024" + + +def test_greater_than_or_equal(): + exp = stix2.GreaterThanEqualComparisonExpression("file:size", + 1024) + assert str(exp) == "file:size >= 1024" + + +def test_less_than_or_equal(): + exp = stix2.LessThanEqualComparisonExpression("file:size", + 1024) + assert str(exp) == "file:size <= 1024" + + +def test_not(): + exp = stix2.LessThanComparisonExpression("file:size", + 1024, + negated=True) + assert str(exp) == "file:size NOT < 1024" + + def test_and_observable_expression(): exp1 = stix2.AndBooleanExpression([stix2.EqualityComparisonExpression("user-account:account_type", "unix"), @@ -145,6 +178,15 @@ def test_and_observable_expression(): assert str(exp) == "[user-account:account_type = 'unix' AND user-account:user_id = '1007' AND user-account:account_login = 'Peter'] AND [user-account:account_type = 'unix' AND user-account:user_id = '1008' AND user-account:account_login = 'Paul'] AND [user-account:account_type = 'unix' AND user-account:user_id = '1009' AND user-account:account_login = 'Mary']" # noqa +def test_invalid_and_observable_expression(): + with pytest.raises(ValueError) as excinfo: + stix2.AndBooleanExpression([stix2.EqualityComparisonExpression("user-account:display_name", + "admin"), + stix2.EqualityComparisonExpression("email-addr:display_name", + stix2.StringConstant("admin"))]) + assert "All operands to an 'AND' expression must have the same object type" in str(excinfo) + + def test_hex(): exp_and = stix2.AndBooleanExpression([stix2.EqualityComparisonExpression("file:mime_type", "image/bmp"), @@ -175,3 +217,158 @@ def test_set_op(): def test_timestamp(): ts = stix2.TimestampConstant('2014-01-13T07:03:17Z') assert str(ts) == "t'2014-01-13T07:03:17Z'" + + +def test_boolean(): + exp = stix2.EqualityComparisonExpression("email-message:is_multipart", + True) + assert str(exp) == "email-message:is_multipart = true" + + +def test_binary(): + const = stix2.BinaryConstant("dGhpcyBpcyBhIHRlc3Q=") + exp = stix2.EqualityComparisonExpression("artifact:payload_bin", + const) + assert str(exp) == "artifact:payload_bin = b'dGhpcyBpcyBhIHRlc3Q='" + + +def test_list(): + exp = stix2.InComparisonExpression("process:name", + ['proccy', 'proximus', 'badproc']) + assert str(exp) == "process:name IN ('proccy', 'proximus', 'badproc')" + + +def test_list2(): + # alternate way to construct an "IN" Comparison Expression + exp = stix2.EqualityComparisonExpression("process:name", + ['proccy', 'proximus', 'badproc']) + assert str(exp) == "process:name IN ('proccy', 'proximus', 'badproc')" + + +def test_invalid_constant_type(): + with pytest.raises(ValueError) as excinfo: + stix2.EqualityComparisonExpression("artifact:payload_bin", + {'foo': 'bar'}) + assert 'Unable to create a constant' in str(excinfo) + + +def test_invalid_integer_constant(): + with pytest.raises(ValueError) as excinfo: + stix2.IntegerConstant('foo') + assert 'must be an integer' in str(excinfo) + + +def test_invalid_timestamp_constant(): + with pytest.raises(ValueError) as excinfo: + stix2.TimestampConstant('foo') + assert 'must be a datetime object or timestamp string' in str(excinfo) + + +def test_invalid_float_constant(): + with pytest.raises(ValueError) as excinfo: + stix2.FloatConstant('foo') + assert 'must be a float' in str(excinfo) + + +@pytest.mark.parametrize("data, result", [ + (True, True), + (False, False), + ('True', True), + ('False', False), + ('true', True), + ('false', False), + ('t', True), + ('f', False), + ('T', True), + ('F', False), + (1, True), + (0, False), +]) +def test_boolean_constant(data, result): + boolean = stix2.BooleanConstant(data) + assert boolean.value == result + + +def test_invalid_boolean_constant(): + with pytest.raises(ValueError) as excinfo: + stix2.BooleanConstant('foo') + assert 'must be a boolean' in str(excinfo) + + +@pytest.mark.parametrize("hashtype, data", [ + ('MD5', 'zzz'), + ('ssdeep', 'zzz=='), +]) +def test_invalid_hash_constant(hashtype, data): + with pytest.raises(ValueError) as excinfo: + stix2.HashConstant(data, hashtype) + assert 'is not a valid {} hash'.format(hashtype) in str(excinfo) + + +def test_invalid_hex_constant(): + with pytest.raises(ValueError) as excinfo: + stix2.HexConstant('mm') + assert "must contain an even number of hexadecimal characters" in str(excinfo) + + +def test_invalid_binary_constant(): + with pytest.raises(ValueError) as excinfo: + stix2.BinaryConstant('foo') + assert 'must contain a base64' in str(excinfo) + + +def test_escape_quotes_and_backslashes(): + exp = stix2.MatchesComparisonExpression("file:name", + "^Final Report.+\.exe$") + assert str(exp) == "file:name MATCHES '^Final Report.+\\\\.exe$'" + + +def test_like(): + exp = stix2.LikeComparisonExpression("directory:path", + "C:\Windows\%\\foo") + assert str(exp) == "directory:path LIKE 'C:\\\\Windows\\\\%\\\\foo'" + + +def test_issuperset(): + exp = stix2.IsSupersetComparisonExpression("ipv4-addr:value", + "198.51.100.0/24") + assert str(exp) == "ipv4-addr:value ISSUPERSET '198.51.100.0/24'" + + +def test_repeat_qualifier(): + qual = stix2.RepeatQualifier(stix2.IntegerConstant(5)) + assert str(qual) == 'REPEATS 5 TIMES' + + +def test_invalid_repeat_qualifier(): + with pytest.raises(ValueError) as excinfo: + stix2.RepeatQualifier('foo') + assert 'is not a valid argument for a Repeat Qualifier' in str(excinfo) + + +def test_invalid_within_qualifier(): + with pytest.raises(ValueError) as excinfo: + stix2.WithinQualifier('foo') + assert 'is not a valid argument for a Within Qualifier' in str(excinfo) + + +def test_startstop_qualifier(): + qual = stix2.StartStopQualifier(stix2.TimestampConstant('2016-06-01T00:00:00Z'), + datetime.datetime(2017, 3, 12, 8, 30, 0)) + assert str(qual) == "START t'2016-06-01T00:00:00Z' STOP t'2017-03-12T08:30:00Z'" + + qual2 = stix2.StartStopQualifier(datetime.date(2016, 6, 1), + stix2.TimestampConstant('2016-07-01T00:00:00Z')) + assert str(qual2) == "START t'2016-06-01T00:00:00Z' STOP t'2016-07-01T00:00:00Z'" + + +def test_invalid_startstop_qualifier(): + with pytest.raises(ValueError) as excinfo: + stix2.StartStopQualifier('foo', + stix2.TimestampConstant('2016-06-01T00:00:00Z')) + assert 'is not a valid argument for a Start/Stop Qualifier' in str(excinfo) + + with pytest.raises(ValueError) as excinfo: + stix2.StartStopQualifier(datetime.date(2016, 6, 1), + 'foo') + assert 'is not a valid argument for a Start/Stop Qualifier' in str(excinfo) From dd8f0f5c7287f5d79a409cfc045c7c3c97470c85 Mon Sep 17 00:00:00 2001 From: Chris Lenk Date: Mon, 2 Apr 2018 16:44:57 -0400 Subject: [PATCH 24/61] Increase code coverage slightly An Environment will always have a CompositeDataSource, so there was no way those exceptions could get raised. --- stix2/environment.py | 10 ++-------- stix2/test/test_properties.py | 2 ++ 2 files changed, 4 insertions(+), 8 deletions(-) diff --git a/stix2/environment.py b/stix2/environment.py index eb5583e..dcf2449 100644 --- a/stix2/environment.py +++ b/stix2/environment.py @@ -114,16 +114,10 @@ class Environment(DataStoreMixin): create.__doc__ = ObjectFactory.create.__doc__ def add_filters(self, *args, **kwargs): - try: - return self.source.filters.update(*args, **kwargs) - except AttributeError: - raise AttributeError('Environment has no data source') + return self.source.filters.update(*args, **kwargs) def add_filter(self, *args, **kwargs): - try: - return self.source.filters.add(*args, **kwargs) - except AttributeError: - raise AttributeError('Environment has no data source') + return self.source.filters.add(*args, **kwargs) def parse(self, *args, **kwargs): return _parse(*args, **kwargs) diff --git a/stix2/test/test_properties.py b/stix2/test/test_properties.py index 6bd1888..34edc96 100644 --- a/stix2/test/test_properties.py +++ b/stix2/test/test_properties.py @@ -16,6 +16,8 @@ def test_property(): p = Property() assert p.required is False + assert p.clean('foo') == 'foo' + assert p.clean(3) == 3 def test_basic_clean(): From d5bcc902cc8980024eb6d3215bfb7e073a427b9c Mon Sep 17 00:00:00 2001 From: Robin Cover Date: Tue, 3 Apr 2018 11:20:43 -0500 Subject: [PATCH 25/61] fixup program name w/ 'TC' to OASIS TC Open Repo... --- CONTRIBUTING.md | 14 ++--- README.rst | 150 +++++++++++++++++++++++++++++++----------------- 2 files changed, 105 insertions(+), 59 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 4238e94..5b1f699 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,25 +1,25 @@

Public Participation Invited

-

This OASIS Open Repository ( github.com/oasis-open/cti-python-stix2 ) is a community public repository that supports participation by anyone, whether affiliated with OASIS or not. Substantive contributions (repository "code") and related feedback is invited from all parties, following the common conventions for participation in GitHub public repository projects. Participation is expected to be consistent with the OASIS Open Repository Guidelines and Procedures, the LICENSE designated for this particular repository (BSD-3-Clause License), and the requirement for an Individual Contributor License Agreement. Please see the repository README document for other details.

+

This OASIS TC Open Repository ( github.com/oasis-open/cti-python-stix2 ) is a community public repository that supports participation by anyone, whether affiliated with OASIS or not. Substantive contributions (repository "code") and related feedback is invited from all parties, following the common conventions for participation in GitHub public repository projects. Participation is expected to be consistent with the OASIS TC Open Repository Guidelines and Procedures, the LICENSE designated for this particular repository (BSD-3-Clause License), and the requirement for an Individual Contributor License Agreement. Please see the repository README document for other details.

Governance Distinct from OASIS TC Process

-

Content accepted as "contributions" to this Open Repository, as defined below, are distinct from any Contributions made to the associated OASIS Cyber Threat Intelligence (CTI) TC itself. Participation in the associated Technical Committee is governed by the OASIS Bylaws, OASIS TC Process, IPR Policy, and related policies. This Open Repository is not subject to the OASIS TC-related policies. Open Repository governance is defined by separate participation and contribution guidelines as referenced in the OASIS Open Repositories Overview.

+

Content accepted as "contributions" to this TC Open Repository, as defined below, are distinct from any Contributions made to the associated OASIS Cyber Threat Intelligence (CTI) TC itself. Participation in the associated Technical Committee is governed by the OASIS Bylaws, OASIS TC Process, IPR Policy, and related policies. This TC Open Repository is not subject to the OASIS TC-related policies. TC Open Repository governance is defined by separate participation and contribution guidelines as referenced in the OASIS TC Open Repositories Overview.

Licensing Distinct from OASIS IPR Policy

-

Because different licenses apply to the OASIS TC's specification work, and this Open Repository, there is no guarantee that the licensure of specific repository material will be compatible with licensing requirements of an implementation of a TC's specification. Please refer to the LICENSE file for the terms of this material, and to the OASIS IPR Policy for the terms applicable to the TC's specifications, including any applicable declarations.

+

Because different licenses apply to the OASIS TC's specification work, and this TC Open Repository, there is no guarantee that the licensure of specific repository material will be compatible with licensing requirements of an implementation of a TC's specification. Please refer to the LICENSE file for the terms of this material, and to the OASIS IPR Policy for the terms applicable to the TC's specifications, including any applicable declarations.

Contributions Subject to Individual CLA

-

Formally, "contribution" to this Open Repository refers to content merged into the "Code" repository (repository changes represented by code commits), following the GitHub definition of contributor: "someone who has contributed to a project by having a pull request merged but does not have collaborator [i.e., direct write] access." Anyone who signs the Open Repository Individual Contributor License Agreement (CLA), signifying agreement with the licensing requirement, may contribute substantive content — subject to evaluation of a GitHub pull request. The main web page for this repository, as with any GitHub public repository, displays a link to a document listing contributions to the repository's default branch (filtered by Commits, Additions, and Deletions).

+

Formally, "contribution" to this TC Open Repository refers to content merged into the "Code" repository (repository changes represented by code commits), following the GitHub definition of contributor: "someone who has contributed to a project by having a pull request merged but does not have collaborator [i.e., direct write] access." Anyone who signs the TC Open Repository Individual Contributor License Agreement (CLA), signifying agreement with the licensing requirement, may contribute substantive content — subject to evaluation of a GitHub pull request. The main web page for this repository, as with any GitHub public repository, displays a link to a document listing contributions to the repository's default branch (filtered by Commits, Additions, and Deletions).

-

This Open Repository, as with GitHub public repositories generally, also accepts public feedback from any GitHub user. Public feedback includes opening issues, authoring and editing comments, participating in conversations, making wiki edits, creating repository stars, and making suggestions via pull requests. Such feedback does not constitute an OASIS Open Repository contribution. Some details are presented under "Read permissions" in the table of permission levels for a GitHub organization. Technical content intended as a substantive contribution (repository "Code") to an Open Repository is subject to evaluation, and requires a signed Individual CLA.

+

This TC Open Repository, as with GitHub public repositories generally, also accepts public feedback from any GitHub user. Public feedback includes opening issues, authoring and editing comments, participating in conversations, making wiki edits, creating repository stars, and making suggestions via pull requests. Such feedback does not constitute an OASIS TC Open Repository contribution. Some details are presented under "Read permissions" in the table of permission levels for a GitHub organization. Technical content intended as a substantive contribution (repository "Code") to an TC Open Repository is subject to evaluation, and requires a signed Individual CLA.

@@ -27,12 +27,12 @@

Fork-and-Pull Collaboration Model

-

OASIS Open Repositories use the familiar fork-and-pull collaboration model supported by GitHub and other distributed version-control systems. Any GitHub user wishing to contribute should fork the repository, make additions or other modifications, and then submit a pull request. GitHub pull requests should be accompanied by supporting comments and/or issues. Community conversations about pull requests, supported by GitHub notifications, will provide the basis for a consensus determination to merge, modify, close, or take other action, as communicated by the repository Maintainers.

+

OASIS TC Open Repositories use the familiar fork-and-pull collaboration model supported by GitHub and other distributed version-control systems. Any GitHub user wishing to contribute should fork the repository, make additions or other modifications, and then submit a pull request. GitHub pull requests should be accompanied by supporting comments and/or issues. Community conversations about pull requests, supported by GitHub notifications, will provide the basis for a consensus determination to merge, modify, close, or take other action, as communicated by the repository Maintainers.

Feedback

-

Questions or comments about this Open Repository's activities should be composed as GitHub issues or comments. If use of an issue/comment is not possible or appropriate, questions may be directed by email to the repository Maintainer(s). Please send general questions about Open Repository participation to OASIS Staff at repository-admin@oasis-open.org and any specific CLA-related questions to repository-cla@oasis-open.org.

+

Questions or comments about this TC Open Repository's activities should be composed as GitHub issues or comments. If use of an issue/comment is not possible or appropriate, questions may be directed by email to the repository Maintainer(s). Please send general questions about TC Open Repository participation to OASIS Staff at repository-admin@oasis-open.org and any specific CLA-related questions to repository-cla@oasis-open.org.

diff --git a/README.rst b/README.rst index faacc53..ffd7b40 100644 --- a/README.rst +++ b/README.rst @@ -3,11 +3,13 @@ cti-python-stix2 ================ -This is an `OASIS Open -Repository `__. +This is an `OASIS TC Open +Repository `__. See the `Governance <#governance>`__ section for more information. -This repository provides Python APIs for serializing and de-serializing +This repository provides Python APIs for serializing and de- +serializing STIX 2 JSON content, along with higher-level APIs for common tasks, including data markings, versioning, and for resolving STIX IDs across multiple data sources. @@ -29,8 +31,10 @@ Usage ----- To create a STIX object, provide keyword arguments to the type's -constructor. Certain required attributes of all objects, such as ``type`` or -``id``, will be set automatically if not provided as keyword arguments. +constructor. Certain required attributes of all objects, such as +``type`` or +``id``, will be set automatically if not provided as keyword +arguments. .. code:: python @@ -38,9 +42,11 @@ constructor. Certain required attributes of all objects, such as ``type`` or indicator = Indicator(name="File hash for malware variant", labels=["malicious-activity"], - pattern="[file:hashes.md5 = 'd41d8cd98f00b204e9800998ecf8427e']") + pattern="[file:hashes.md5 = + 'd41d8cd98f00b204e9800998ecf8427e']") -To parse a STIX JSON string into a Python STIX object, use ``parse()``: +To parse a STIX JSON string into a Python STIX object, use +``parse()``: .. code:: python @@ -55,21 +61,28 @@ To parse a STIX JSON string into a Python STIX object, use ``parse()``: "malicious-activity" ], "name": "File hash for malware variant", - "pattern": "[file:hashes.md5 = 'd41d8cd98f00b204e9800998ecf8427e']", + "pattern": "[file:hashes.md5 = + 'd41d8cd98f00b204e9800998ecf8427e']", "valid_from": "2017-09-26T23:33:39.829952Z" }""") print(indicator) -For more in-depth documentation, please see `https://stix2.readthedocs.io/ `__. +For more in-depth documentation, please see +`https://stix2.readthedocs.io/ `__. STIX 2.X Technical Specification Support ---------------------------------------- -This version of python-stix2 supports STIX 2.0 by default. Although, the -`stix2` Python library is built to support multiple versions of the STIX -Technical Specification. With every major release of stix2 the ``import stix2`` -statement will automatically load the SDO/SROs equivalent to the most recent -supported 2.X Technical Specification. Please see the library documentation +This version of python-stix2 supports STIX 2.0 by default. Although, +the +`stix2` Python library is built to support multiple versions of the +STIX +Technical Specification. With every major release of stix2 the +``import stix2`` +statement will automatically load the SDO/SROs equivalent to the most +recent +supported 2.X Technical Specification. Please see the library +documentation for more details. Governance @@ -77,66 +90,87 @@ Governance This GitHub public repository ( **https://github.com/oasis-open/cti-python-stix2** ) was -`proposed `__ +`proposed `__ and -`approved `__ +`approved `__ [`bis `__] by the `OASIS Cyber Threat Intelligence (CTI) -TC `__ as an `OASIS Open -Repository `__ +TC `__ as an `OASIS TC +Open +Repository `__ to support development of open source resources related to Technical Committee work. -While this Open Repository remains associated with the sponsor TC, its +While this TC Open Repository remains associated with the sponsor TC, +its development priorities, leadership, intellectual property terms, participation rules, and other matters of governance are `separate and -distinct `__ +distinct `__ from the OASIS TC Process and related policies. -All contributions made to this Open Repository are subject to open +All contributions made to this TC Open Repository are subject to open source license terms expressed in the `BSD-3-Clause -License `__. +License `__. That license was selected as the declared `"Applicable -License" `__ -when the Open Repository was created. +License" `__ +when the TC Open Repository was created. As documented in `"Public Participation -Invited `__", -contributions to this OASIS Open Repository are invited from all -parties, whether affiliated with OASIS or not. Participants must have a +Invited `__", +contributions to this OASIS TC Open Repository are invited from all +parties, whether affiliated with OASIS or not. Participants must have +a GitHub account, but no fees or OASIS membership obligations are required. Participation is expected to be consistent with the `OASIS -Open Repository Guidelines and -Procedures `__, +TC Open Repository Guidelines and +Procedures `__, the open source -`LICENSE `__ +`LICENSE `__ designated for this particular repository, and the requirement for an `Individual Contributor License -Agreement `__ +Agreement `__ that governs intellectual property. Maintainers ~~~~~~~~~~~ -Open Repository -`Maintainers `__ +TC Open Repository +`Maintainers `__ are responsible for oversight of this project's community development activities, including evaluation of GitHub `pull -requests `__ +requests `__ and -`preserving `__ +`preserving `__ open source principles of openness and fairness. Maintainers are recognized and trusted experts who serve to implement community goals and consensus design preferences. -Initially, the associated TC members have designated one or more persons -to serve as Maintainer(s); subsequently, participating community members +Initially, the associated TC members have designated one or more +persons +to serve as Maintainer(s); subsequently, participating community +members may select additional or substitute Maintainers, per `consensus -agreements `__. +agreements `__. .. _currentMaintainers: -**Current Maintainers of this Open Repository** +**Current Maintainers of this TC Open Repository** - `Greg Back `__; GitHub ID: https://github.com/gtback/; WWW: `MITRE @@ -145,34 +179,46 @@ agreements `__ -About OASIS Open Repositories +About OASIS TC Open Repositories ----------------------------- -- `Open Repositories: Overview and - Resources `__ +- `TC Open Repositories: Overview and + Resources `__ - `Frequently Asked - Questions `__ + Questions `__ - `Open Source - Licenses `__ + Licenses `__ - `Contributor License Agreements - (CLAs) `__ + (CLAs) `__ - `Maintainers' Guidelines and - Agreement `__ + Agreement `__ Feedback -------- -Questions or comments about this Open Repository's activities should be -composed as GitHub issues or comments. If use of an issue/comment is not +Questions or comments about this TC Open Repository's activities +should be +composed as GitHub issues or comments. If use of an issue/comment is +not possible or appropriate, questions may be directed by email to the Maintainer(s) `listed above <#currentmaintainers>`__. Please send -general questions about Open Repository participation to OASIS Staff at +general questions about TC Open Repository participation to OASIS +Staff at repository-admin@oasis-open.org and any specific CLA-related questions to repository-cla@oasis-open.org. -.. |Build_Status| image:: https://travis-ci.org/oasis-open/cti-python-stix2.svg?branch=master +.. |Build_Status| image:: https://travis-ci.org/oasis-open/cti-python- +stix2.svg?branch=master :target: https://travis-ci.org/oasis-open/cti-python-stix2 -.. |Coverage| image:: https://codecov.io/gh/oasis-open/cti-python-stix2/branch/master/graph/badge.svg +.. |Coverage| image:: https://codecov.io/gh/oasis-open/cti-python- +stix2/branch/master/graph/badge.svg :target: https://codecov.io/gh/oasis-open/cti-python-stix2 -.. |Version| image:: https://img.shields.io/pypi/v/stix2.svg?maxAge=3600 +.. |Version| image:: https://img.shields.io/pypi/v/stix2.svg?maxAge= +3600 :target: https://pypi.python.org/pypi/stix2/ + From fe1852d41e090f9e0bf33998b1905d658ffd33fb Mon Sep 17 00:00:00 2001 From: Emmanuelle Vargas-Gonzalez Date: Wed, 4 Apr 2018 05:48:32 -0400 Subject: [PATCH 26/61] Update README.rst Update broken banners for Build_Status, Coverage and Version --- README.rst | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/README.rst b/README.rst index ffd7b40..6b9f407 100644 --- a/README.rst +++ b/README.rst @@ -212,13 +212,9 @@ Staff at repository-admin@oasis-open.org and any specific CLA-related questions to repository-cla@oasis-open.org. -.. |Build_Status| image:: https://travis-ci.org/oasis-open/cti-python- -stix2.svg?branch=master +.. |Build_Status| image:: https://travis-ci.org/oasis-open/cti-python-stix2.svg?branch=master :target: https://travis-ci.org/oasis-open/cti-python-stix2 -.. |Coverage| image:: https://codecov.io/gh/oasis-open/cti-python- -stix2/branch/master/graph/badge.svg +.. |Coverage| image:: https://codecov.io/gh/oasis-open/cti-python-stix2/branch/master/graph/badge.svg :target: https://codecov.io/gh/oasis-open/cti-python-stix2 -.. |Version| image:: https://img.shields.io/pypi/v/stix2.svg?maxAge= -3600 +.. |Version| image:: https://img.shields.io/pypi/v/stix2.svg?maxAge=3600 :target: https://pypi.python.org/pypi/stix2/ - From a1af05a14eb4e5863afb43cd6aef65bf6a7ae9b1 Mon Sep 17 00:00:00 2001 From: Chris Lenk Date: Wed, 4 Apr 2018 09:47:48 -0400 Subject: [PATCH 27/61] Warn against using workbench with the rest of lib Doing so may cause issues because the workbench overwrites the STIX Object mapping. --- docs/guide/workbench.ipynb | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/docs/guide/workbench.ipynb b/docs/guide/workbench.ipynb index bc7942a..9cb099a 100644 --- a/docs/guide/workbench.ipynb +++ b/docs/guide/workbench.ipynb @@ -53,7 +53,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## Using A Workbench" + "## Using The Workbench" ] }, { @@ -446,6 +446,19 @@ "source": [ "Defaults can also be set for the [created timestamp](../api/datastore/stix2.workbench.rst#stix2.workbench.set_default_created), [external references](../api/datastore/stix2.workbench.rst#stix2.workbench.set_default_external_refs) and [object marking references](../api/datastore/stix2.workbench.rst#stix2.workbench.set_default_object_marking_refs)." ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "
\n", + "\n", + "**Warning:**\n", + "\n", + "The workbench layer replaces STIX Object classes with special versions of them that use \"wrappers\" to provide extra functionality. Because of this, we recommend that you **either use the workbench layer or the rest of the library, but not both**. In other words, don't import from both ``stix2.workbench`` and any other submodules of ``stix2``.\n", + "\n", + "
" + ] } ], "metadata": { From 9a50f54ec4882438c195302f185997dd6d3b01bf Mon Sep 17 00:00:00 2001 From: Chris Lenk Date: Wed, 4 Apr 2018 12:12:09 -0400 Subject: [PATCH 28/61] Update README.rst Fix line break in usage example --- README.rst | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/README.rst b/README.rst index 6b9f407..46e8164 100644 --- a/README.rst +++ b/README.rst @@ -42,8 +42,7 @@ arguments. indicator = Indicator(name="File hash for malware variant", labels=["malicious-activity"], - pattern="[file:hashes.md5 = - 'd41d8cd98f00b204e9800998ecf8427e']") + pattern="[file:hashes.md5 = 'd41d8cd98f00b204e9800998ecf8427e']") To parse a STIX JSON string into a Python STIX object, use ``parse()``: From f951b9b09e23f68edf9b06b6115cafd4e12ad4fb Mon Sep 17 00:00:00 2001 From: Chris Lenk Date: Wed, 4 Apr 2018 13:21:25 -0400 Subject: [PATCH 29/61] Factor out dupl. code for creating list of filters --- stix2/datastore/__init__.py | 17 +++-------------- stix2/datastore/filters.py | 23 +++++++++++++++++++++++ 2 files changed, 26 insertions(+), 14 deletions(-) diff --git a/stix2/datastore/__init__.py b/stix2/datastore/__init__.py index 890ac45..16a0a9e 100644 --- a/stix2/datastore/__init__.py +++ b/stix2/datastore/__init__.py @@ -16,7 +16,7 @@ import uuid from six import with_metaclass -from stix2.datastore.filters import Filter +from stix2.datastore.filters import Filter, _assemble_filters from stix2.utils import deduplicate @@ -312,13 +312,7 @@ class DataSource(with_metaclass(ABCMeta)): list: The STIX objects that matched the query. """ - filter_list = [Filter('type', '=', obj_type)] - if filters: - if isinstance(filters, list): - filter_list.extend(filters) - else: - filter_list.append(filters) - + filter_list = _assemble_filters(filters, [Filter('type', '=', obj_type)]) return self.query(filter_list) def creator_of(self, obj): @@ -421,12 +415,7 @@ class DataSource(with_metaclass(ABCMeta)): ids.discard(obj_id) # Assemble filters - filter_list = [] - if filters: - if isinstance(filters, list): - filter_list.extend(filters) - else: - filter_list.append(filters) + filter_list = _assemble_filters(filters) for i in ids: results.extend(self.query(filter_list + [Filter('id', '=', i)])) diff --git a/stix2/datastore/filters.py b/stix2/datastore/filters.py index 9065b61..a116507 100644 --- a/stix2/datastore/filters.py +++ b/stix2/datastore/filters.py @@ -44,6 +44,29 @@ def _check_filter_components(prop, op, value): return True +def _assemble_filters(filter_arg, filters=[]): + """Assemble a list of filters. + + This can be used to allow certain functions to work correctly no matter if + the user provides a single filter or a list of them. + + Args: + filter_arg (Filter or list): The single Filter or list of Filters to be + coerced into a list of Filters. + filters (list, optional): A list of Filters to be automatically appended. + + Returns: + List of Filters. + + """ + if isinstance(filter_arg, list): + filters.extend(filter_arg) + else: + filters.append(filter_arg) + + return filters + + class Filter(collections.namedtuple("Filter", ['property', 'op', 'value'])): """STIX 2 filters that support the querying functionality of STIX 2 DataStores and DataSources. From 589c00064bc0079f490908b595a577d4cf4479d3 Mon Sep 17 00:00:00 2001 From: Chris Lenk Date: Wed, 4 Apr 2018 14:02:39 -0400 Subject: [PATCH 30/61] Remove query_by_type It's not that much of a shortcut and we can add it back in later if it makes sense. --- stix2/datastore/__init__.py | 19 +--------- stix2/environment.py | 1 - stix2/test/test_environment.py | 4 --- stix2/workbench.py | 63 ++++++++++++++++++++-------------- 4 files changed, 38 insertions(+), 49 deletions(-) diff --git a/stix2/datastore/__init__.py b/stix2/datastore/__init__.py index 16a0a9e..4e53b17 100644 --- a/stix2/datastore/__init__.py +++ b/stix2/datastore/__init__.py @@ -298,23 +298,6 @@ class DataSource(with_metaclass(ABCMeta)): """ - def query_by_type(self, obj_type, filters=None): - """Retrieve all objects of the given STIX object type. - - This helper function is a shortcut that calls query() under the hood. - - Args: - obj_type (str): The STIX object type to retrieve. - filters (list, optional): A list of additional filters to apply to - the query. - - Returns: - list: The STIX objects that matched the query. - - """ - filter_list = _assemble_filters(filters, [Filter('type', '=', obj_type)]) - return self.query(filter_list) - def creator_of(self, obj): """Retrieve the Identity refered to by the object's `created_by_ref`. @@ -376,7 +359,7 @@ class DataSource(with_metaclass(ABCMeta)): return results - def related_to(self, obj, relationship_type=None, source_only=False, target_only=False, filters=None): + def related_to(self, obj, relationship_type=None, source_only=False, target_only=False, filters=[]): """Retrieve STIX Objects that have a Relationship involving the given STIX object. diff --git a/stix2/environment.py b/stix2/environment.py index 9f55a7e..e40e991 100644 --- a/stix2/environment.py +++ b/stix2/environment.py @@ -114,7 +114,6 @@ class Environment(DataStoreMixin): .. automethod:: get .. automethod:: all_versions .. automethod:: query - .. automethod:: query_by_type .. automethod:: creator_of .. automethod:: relationships .. automethod:: related_to diff --git a/stix2/test/test_environment.py b/stix2/test/test_environment.py index 8764e25..176d3f0 100644 --- a/stix2/test/test_environment.py +++ b/stix2/test/test_environment.py @@ -164,10 +164,6 @@ def test_environment_no_datastore(): env.query(INDICATOR_ID) assert 'Environment has no data source' in str(excinfo.value) - with pytest.raises(AttributeError) as excinfo: - env.query_by_type('indicator') - assert 'Environment has no data source' in str(excinfo.value) - with pytest.raises(AttributeError) as excinfo: env.relationships(INDICATOR_ID) assert 'Environment has no data source' in str(excinfo.value) diff --git a/stix2/workbench.py b/stix2/workbench.py index 0338353..61e99af 100644 --- a/stix2/workbench.py +++ b/stix2/workbench.py @@ -8,7 +8,6 @@ .. autofunction:: get .. autofunction:: all_versions .. autofunction:: query -.. autofunction:: query_by_type .. autofunction:: creator_of .. autofunction:: relationships .. autofunction:: related_to @@ -49,6 +48,7 @@ from . import (AlternateDataStream, ArchiveExt, Artifact, AutonomousSystem, # n WindowsPEOptionalHeaderType, WindowsPESection, WindowsProcessExt, WindowsRegistryKey, WindowsRegistryValueType, WindowsServiceExt, X509Certificate, X509V3ExtenstionsType) +from .datastore.filters import _assemble_filters # Use an implicit MemoryStore _environ = Environment(store=MemoryStore()) @@ -61,7 +61,6 @@ set_default_object_marking_refs = _environ.set_default_object_marking_refs get = _environ.get all_versions = _environ.all_versions query = _environ.query -query_by_type = _environ.query_by_type creator_of = _environ.creator_of relationships = _environ.relationships related_to = _environ.related_to @@ -149,7 +148,7 @@ _setup_workbench() # Functions to get all objects of a specific type -def attack_patterns(filters=None): +def attack_patterns(filters=[]): """Retrieve all Attack Pattern objects. Args: @@ -157,10 +156,11 @@ def attack_patterns(filters=None): the query. """ - return query_by_type('attack-pattern', filters) + filter_list = _assemble_filters(filters, [Filter('type', '=', 'attack-pattern')]) + return query(filter_list) -def campaigns(filters=None): +def campaigns(filters=[]): """Retrieve all Campaign objects. Args: @@ -168,10 +168,11 @@ def campaigns(filters=None): the query. """ - return query_by_type('campaign', filters) + filter_list = _assemble_filters(filters, [Filter('type', '=', 'campaign')]) + return query(filter_list) -def courses_of_action(filters=None): +def courses_of_action(filters=[]): """Retrieve all Course of Action objects. Args: @@ -179,10 +180,11 @@ def courses_of_action(filters=None): the query. """ - return query_by_type('course-of-action', filters) + filter_list = _assemble_filters(filters, [Filter('type', '=', 'course-of-action')]) + return query(filter_list) -def identities(filters=None): +def identities(filters=[]): """Retrieve all Identity objects. Args: @@ -190,10 +192,11 @@ def identities(filters=None): the query. """ - return query_by_type('identity', filters) + filter_list = _assemble_filters(filters, [Filter('type', '=', 'identity')]) + return query(filter_list) -def indicators(filters=None): +def indicators(filters=[]): """Retrieve all Indicator objects. Args: @@ -201,10 +204,11 @@ def indicators(filters=None): the query. """ - return query_by_type('indicator', filters) + filter_list = _assemble_filters(filters, [Filter('type', '=', 'indicator')]) + return query(filter_list) -def intrusion_sets(filters=None): +def intrusion_sets(filters=[]): """Retrieve all Intrusion Set objects. Args: @@ -212,10 +216,11 @@ def intrusion_sets(filters=None): the query. """ - return query_by_type('intrusion-set', filters) + filter_list = _assemble_filters(filters, [Filter('type', '=', 'intrusion-set')]) + return query(filter_list) -def malware(filters=None): +def malware(filters=[]): """Retrieve all Malware objects. Args: @@ -223,10 +228,11 @@ def malware(filters=None): the query. """ - return query_by_type('malware', filters) + filter_list = _assemble_filters(filters, [Filter('type', '=', 'malware')]) + return query(filter_list) -def observed_data(filters=None): +def observed_data(filters=[]): """Retrieve all Observed Data objects. Args: @@ -234,10 +240,11 @@ def observed_data(filters=None): the query. """ - return query_by_type('observed-data', filters) + filter_list = _assemble_filters(filters, [Filter('type', '=', 'observed-data')]) + return query(filter_list) -def reports(filters=None): +def reports(filters=[]): """Retrieve all Report objects. Args: @@ -245,10 +252,11 @@ def reports(filters=None): the query. """ - return query_by_type('report', filters) + filter_list = _assemble_filters(filters, [Filter('type', '=', 'report')]) + return query(filter_list) -def threat_actors(filters=None): +def threat_actors(filters=[]): """Retrieve all Threat Actor objects. Args: @@ -256,10 +264,11 @@ def threat_actors(filters=None): the query. """ - return query_by_type('threat-actor', filters) + filter_list = _assemble_filters(filters, [Filter('type', '=', 'threat-actor')]) + return query(filter_list) -def tools(filters=None): +def tools(filters=[]): """Retrieve all Tool objects. Args: @@ -267,10 +276,11 @@ def tools(filters=None): the query. """ - return query_by_type('tool', filters) + filter_list = _assemble_filters(filters, [Filter('type', '=', 'tool')]) + return query(filter_list) -def vulnerabilities(filters=None): +def vulnerabilities(filters=[]): """Retrieve all Vulnerability objects. Args: @@ -278,4 +288,5 @@ def vulnerabilities(filters=None): the query. """ - return query_by_type('vulnerability', filters) + filter_list = _assemble_filters(filters, [Filter('type', '=', 'vulnerability')]) + return query(filter_list) From e3bbc39353fb4e536035f0973dbd8c2c9b12bd24 Mon Sep 17 00:00:00 2001 From: Chris Lenk Date: Thu, 5 Apr 2018 10:07:35 -0400 Subject: [PATCH 31/61] Fix bug with mutable default parameter --- stix2/datastore/__init__.py | 2 +- stix2/datastore/filters.py | 24 ++++++++++++++++-------- stix2/test/test_datastore.py | 11 ++++++++++- stix2/workbench.py | 24 ++++++++++++------------ 4 files changed, 39 insertions(+), 22 deletions(-) diff --git a/stix2/datastore/__init__.py b/stix2/datastore/__init__.py index 4e53b17..e0de6fe 100644 --- a/stix2/datastore/__init__.py +++ b/stix2/datastore/__init__.py @@ -359,7 +359,7 @@ class DataSource(with_metaclass(ABCMeta)): return results - def related_to(self, obj, relationship_type=None, source_only=False, target_only=False, filters=[]): + def related_to(self, obj, relationship_type=None, source_only=False, target_only=False, filters=None): """Retrieve STIX Objects that have a Relationship involving the given STIX object. diff --git a/stix2/datastore/filters.py b/stix2/datastore/filters.py index a116507..10bbeee 100644 --- a/stix2/datastore/filters.py +++ b/stix2/datastore/filters.py @@ -44,27 +44,35 @@ def _check_filter_components(prop, op, value): return True -def _assemble_filters(filter_arg, filters=[]): +def _assemble_filters(filters1=None, filters2=None): """Assemble a list of filters. This can be used to allow certain functions to work correctly no matter if the user provides a single filter or a list of them. Args: - filter_arg (Filter or list): The single Filter or list of Filters to be - coerced into a list of Filters. - filters (list, optional): A list of Filters to be automatically appended. + filters1 (Filter or list, optional): The single Filter or list of Filters to + coerce into a list of Filters. + filters2 (Filter or list, optional): The single Filter or list of Filters to + append to the list of Filters. Returns: List of Filters. """ - if isinstance(filter_arg, list): - filters.extend(filter_arg) + if filters1 is None: + filter_list = [] + elif not isinstance(filters1, list): + filter_list = [filters1] else: - filters.append(filter_arg) + filter_list = filters1 - return filters + if isinstance(filters2, list): + filter_list.extend(filters2) + elif filters2 is not None: + filter_list.append(filters2) + + return filter_list class Filter(collections.namedtuple("Filter", ['property', 'op', 'value'])): diff --git a/stix2/test/test_datastore.py b/stix2/test/test_datastore.py index e80e8d8..8f40401 100644 --- a/stix2/test/test_datastore.py +++ b/stix2/test/test_datastore.py @@ -4,7 +4,7 @@ from taxii2client import Collection from stix2 import Filter, MemorySink, MemorySource from stix2.datastore import (CompositeDataSource, DataSink, DataSource, make_id, taxii) -from stix2.datastore.filters import apply_common_filters +from stix2.datastore.filters import _assemble_filters, apply_common_filters from stix2.utils import deduplicate COLLECTION_URL = 'https://example.com/api1/collections/91a7b528-80eb-42ed-a74d-c6fbd5a26116/' @@ -473,6 +473,15 @@ def test_filters7(): assert len(resp) == 1 +def test_assemble_filters(): + filter1 = Filter("name", "=", "Malicious site hosting downloader") + filter2 = Filter("modified", ">", "2017-01-28T13:49:53.935Z") + result = _assemble_filters(filter1, filter2) + assert len(result) == 2 + assert result[0].property == 'name' + assert result[1].property == 'modified' + + def test_deduplicate(): unique = deduplicate(STIX_OBJS1) diff --git a/stix2/workbench.py b/stix2/workbench.py index 61e99af..9e31b50 100644 --- a/stix2/workbench.py +++ b/stix2/workbench.py @@ -148,7 +148,7 @@ _setup_workbench() # Functions to get all objects of a specific type -def attack_patterns(filters=[]): +def attack_patterns(filters=None): """Retrieve all Attack Pattern objects. Args: @@ -160,7 +160,7 @@ def attack_patterns(filters=[]): return query(filter_list) -def campaigns(filters=[]): +def campaigns(filters=None): """Retrieve all Campaign objects. Args: @@ -172,7 +172,7 @@ def campaigns(filters=[]): return query(filter_list) -def courses_of_action(filters=[]): +def courses_of_action(filters=None): """Retrieve all Course of Action objects. Args: @@ -184,7 +184,7 @@ def courses_of_action(filters=[]): return query(filter_list) -def identities(filters=[]): +def identities(filters=None): """Retrieve all Identity objects. Args: @@ -196,7 +196,7 @@ def identities(filters=[]): return query(filter_list) -def indicators(filters=[]): +def indicators(filters=None): """Retrieve all Indicator objects. Args: @@ -208,7 +208,7 @@ def indicators(filters=[]): return query(filter_list) -def intrusion_sets(filters=[]): +def intrusion_sets(filters=None): """Retrieve all Intrusion Set objects. Args: @@ -220,7 +220,7 @@ def intrusion_sets(filters=[]): return query(filter_list) -def malware(filters=[]): +def malware(filters=None): """Retrieve all Malware objects. Args: @@ -232,7 +232,7 @@ def malware(filters=[]): return query(filter_list) -def observed_data(filters=[]): +def observed_data(filters=None): """Retrieve all Observed Data objects. Args: @@ -244,7 +244,7 @@ def observed_data(filters=[]): return query(filter_list) -def reports(filters=[]): +def reports(filters=None): """Retrieve all Report objects. Args: @@ -256,7 +256,7 @@ def reports(filters=[]): return query(filter_list) -def threat_actors(filters=[]): +def threat_actors(filters=None): """Retrieve all Threat Actor objects. Args: @@ -268,7 +268,7 @@ def threat_actors(filters=[]): return query(filter_list) -def tools(filters=[]): +def tools(filters=None): """Retrieve all Tool objects. Args: @@ -280,7 +280,7 @@ def tools(filters=[]): return query(filter_list) -def vulnerabilities(filters=[]): +def vulnerabilities(filters=None): """Retrieve all Vulnerability objects. Args: From e6e72856b3e9b7adf93ce07a1d4218b59456044d Mon Sep 17 00:00:00 2001 From: Chris Lenk Date: Thu, 5 Apr 2018 11:22:50 -0400 Subject: [PATCH 32/61] Remove query_by_type() Missed these earlier. --- stix2/datastore/__init__.py | 48 ------------------------------------- 1 file changed, 48 deletions(-) diff --git a/stix2/datastore/__init__.py b/stix2/datastore/__init__.py index e0de6fe..442a242 100644 --- a/stix2/datastore/__init__.py +++ b/stix2/datastore/__init__.py @@ -99,25 +99,6 @@ class DataStoreMixin(object): except AttributeError: raise AttributeError('%s has no data source to query' % self.__class__.__name__) - def query_by_type(self, *args, **kwargs): - """Retrieve all objects of the given STIX object type. - - Translate query_by_type() call to the appropriate DataSource call. - - Args: - obj_type (str): The STIX object type to retrieve. - filters (list, optional): A list of additional filters to apply to - the query. - - Returns: - list: The STIX objects that matched the query. - - """ - try: - return self.source.query_by_type(*args, **kwargs) - except AttributeError: - raise AttributeError('%s has no data source to query' % self.__class__.__name__) - def creator_of(self, *args, **kwargs): """Retrieve the Identity refered to by the object's `created_by_ref`. @@ -568,35 +549,6 @@ class CompositeDataSource(DataSource): return all_data - def query_by_type(self, *args, **kwargs): - """Retrieve all objects of the given STIX object type. - - Federate the query to all DataSources attached to the - Composite Data Source. - - Args: - obj_type (str): The STIX object type to retrieve. - filters (list, optional): A list of additional filters to apply to - the query. - - Returns: - list: The STIX objects that matched the query. - - """ - if not self.has_data_sources(): - raise AttributeError('CompositeDataSource has no data sources') - - results = [] - for ds in self.data_sources: - results.extend(ds.query_by_type(*args, **kwargs)) - - # remove exact duplicates (where duplicates are STIX 2.0 - # objects with the same 'id' and 'modified' values) - if len(results) > 0: - results = deduplicate(results) - - return results - def relationships(self, *args, **kwargs): """Retrieve Relationships involving the given STIX object. From 5791810906fce96e82280e297cf384e911c83491 Mon Sep 17 00:00:00 2001 From: Chris Lenk Date: Thu, 5 Apr 2018 16:44:44 -0400 Subject: [PATCH 33/61] Ensure all guide doc output cells have [Out] label Fixes #105. --- docs/guide/creating.ipynb | 92 ++-- docs/guide/custom.ipynb | 658 +++++++++++++++++++++---- docs/guide/datastore.ipynb | 111 ++--- docs/guide/environment.ipynb | 370 +++++++------- docs/guide/filesystem.ipynb | 926 ++++++++++++++++++++++++----------- docs/guide/markings.ipynb | 414 ++++++++-------- docs/guide/memory.ipynb | 188 ++----- docs/guide/parsing.ipynb | 303 ++++++++++-- docs/guide/serializing.ipynb | 38 +- docs/guide/taxii.ipynb | 20 +- docs/guide/ts_support.ipynb | 37 +- docs/guide/versioning.ipynb | 72 +-- docs/guide/workbench.ipynb | 376 ++++++++++++-- 13 files changed, 2422 insertions(+), 1183 deletions(-) diff --git a/docs/guide/creating.ipynb b/docs/guide/creating.ipynb index 3e22061..d9464e7 100644 --- a/docs/guide/creating.ipynb +++ b/docs/guide/creating.ipynb @@ -4,7 +4,6 @@ "cell_type": "code", "execution_count": 1, "metadata": { - "collapsed": true, "nbsphinx": "hidden" }, "outputs": [], @@ -25,7 +24,6 @@ "cell_type": "code", "execution_count": 2, "metadata": { - "collapsed": true, "nbsphinx": "hidden" }, "outputs": [], @@ -146,15 +144,15 @@ ".highlight .vm { color: #19177C } /* Name.Variable.Magic */\n", ".highlight .il { color: #666666 } /* Literal.Number.Integer.Long */
{\n",
        "    "type": "indicator",\n",
-       "    "id": "indicator--dbcbd659-c927-4f9a-994f-0a2632274394",\n",
-       "    "created": "2017-09-26T23:33:39.829Z",\n",
-       "    "modified": "2017-09-26T23:33:39.829Z",\n",
-       "    "labels": [\n",
-       "        "malicious-activity"\n",
-       "    ],\n",
+       "    "id": "indicator--548af3be-39d7-4a3e-93c2-1a63cccf8951",\n",
+       "    "created": "2018-04-05T18:32:24.193Z",\n",
+       "    "modified": "2018-04-05T18:32:24.193Z",\n",
        "    "name": "File hash for malware variant",\n",
        "    "pattern": "[file:hashes.md5 = 'd41d8cd98f00b204e9800998ecf8427e']",\n",
-       "    "valid_from": "2017-09-26T23:33:39.829952Z"\n",
+       "    "valid_from": "2018-04-05T18:32:24.193659Z",\n",
+       "    "labels": [\n",
+       "        "malicious-activity"\n",
+       "    ]\n",
        "}\n",
        "
\n" ], @@ -188,9 +186,7 @@ { "cell_type": "code", "execution_count": 4, - "metadata": { - "collapsed": true - }, + "metadata": {}, "outputs": [], "source": [ "indicator2 = Indicator(type='indicator',\n", @@ -295,7 +291,7 @@ { "data": { "text/plain": [ - "u'File hash for malware variant'" + "'File hash for malware variant'" ] }, "execution_count": 8, @@ -322,7 +318,7 @@ { "data": { "text/plain": [ - "u'File hash for malware variant'" + "'File hash for malware variant'" ] }, "execution_count": 9, @@ -469,9 +465,9 @@ ".highlight .vm { color: #19177C } /* Name.Variable.Magic */\n", ".highlight .il { color: #666666 } /* Literal.Number.Integer.Long */
{\n",
        "    "type": "malware",\n",
-       "    "id": "malware--d7fd675d-94eb-4d95-b0bc-b3c5e28e8ed2",\n",
-       "    "created": "2017-09-26T23:33:56.908Z",\n",
-       "    "modified": "2017-09-26T23:33:56.908Z",\n",
+       "    "id": "malware--3d7f0c1c-616a-4868-aa7b-150821d2a429",\n",
+       "    "created": "2018-04-05T18:32:46.584Z",\n",
+       "    "modified": "2018-04-05T18:32:46.584Z",\n",
        "    "name": "Poison Ivy",\n",
        "    "labels": [\n",
        "        "remote-access-trojan"\n",
@@ -592,12 +588,12 @@
        ".highlight .vm { color: #19177C } /* Name.Variable.Magic */\n",
        ".highlight .il { color: #666666 } /* Literal.Number.Integer.Long */
{\n",
        "    "type": "relationship",\n",
-       "    "id": "relationship--637aa3b1-d4b8-4bc4-85e7-77cc82b198a3",\n",
-       "    "created": "2017-09-26T23:34:01.765Z",\n",
-       "    "modified": "2017-09-26T23:34:01.765Z",\n",
+       "    "id": "relationship--34ddc7b4-4965-4615-b286-1c8bbaa1e7db",\n",
+       "    "created": "2018-04-05T18:32:49.474Z",\n",
+       "    "modified": "2018-04-05T18:32:49.474Z",\n",
        "    "relationship_type": "indicates",\n",
-       "    "source_ref": "indicator--dbcbd659-c927-4f9a-994f-0a2632274394",\n",
-       "    "target_ref": "malware--d7fd675d-94eb-4d95-b0bc-b3c5e28e8ed2"\n",
+       "    "source_ref": "indicator--548af3be-39d7-4a3e-93c2-1a63cccf8951",\n",
+       "    "target_ref": "malware--3d7f0c1c-616a-4868-aa7b-150821d2a429"\n",
        "}\n",
        "
\n" ], @@ -704,12 +700,12 @@ ".highlight .vm { color: #19177C } /* Name.Variable.Magic */\n", ".highlight .il { color: #666666 } /* Literal.Number.Integer.Long */
{\n",
        "    "type": "relationship",\n",
-       "    "id": "relationship--70fe77c2-ab00-4181-a2dc-fe5567d971ca",\n",
-       "    "created": "2017-09-26T23:34:03.923Z",\n",
-       "    "modified": "2017-09-26T23:34:03.923Z",\n",
+       "    "id": "relationship--0a646403-f7e7-4cfd-b945-cab5cde05857",\n",
+       "    "created": "2018-04-05T18:32:51.417Z",\n",
+       "    "modified": "2018-04-05T18:32:51.417Z",\n",
        "    "relationship_type": "indicates",\n",
-       "    "source_ref": "indicator--dbcbd659-c927-4f9a-994f-0a2632274394",\n",
-       "    "target_ref": "malware--d7fd675d-94eb-4d95-b0bc-b3c5e28e8ed2"\n",
+       "    "source_ref": "indicator--548af3be-39d7-4a3e-93c2-1a63cccf8951",\n",
+       "    "target_ref": "malware--3d7f0c1c-616a-4868-aa7b-150821d2a429"\n",
        "}\n",
        "
\n" ], @@ -814,26 +810,26 @@ ".highlight .vm { color: #19177C } /* Name.Variable.Magic */\n", ".highlight .il { color: #666666 } /* Literal.Number.Integer.Long */
{\n",
        "    "type": "bundle",\n",
-       "    "id": "bundle--2536c43d-c874-418e-886c-20a22120d8cb",\n",
+       "    "id": "bundle--f83477e5-f853-47e1-a267-43f3aa1bd5b0",\n",
        "    "spec_version": "2.0",\n",
        "    "objects": [\n",
        "        {\n",
        "            "type": "indicator",\n",
-       "            "id": "indicator--dbcbd659-c927-4f9a-994f-0a2632274394",\n",
-       "            "created": "2017-09-26T23:33:39.829Z",\n",
-       "            "modified": "2017-09-26T23:33:39.829Z",\n",
-       "            "labels": [\n",
-       "                "malicious-activity"\n",
-       "            ],\n",
+       "            "id": "indicator--548af3be-39d7-4a3e-93c2-1a63cccf8951",\n",
+       "            "created": "2018-04-05T18:32:24.193Z",\n",
+       "            "modified": "2018-04-05T18:32:24.193Z",\n",
        "            "name": "File hash for malware variant",\n",
        "            "pattern": "[file:hashes.md5 = 'd41d8cd98f00b204e9800998ecf8427e']",\n",
-       "            "valid_from": "2017-09-26T23:33:39.829952Z"\n",
+       "            "valid_from": "2018-04-05T18:32:24.193659Z",\n",
+       "            "labels": [\n",
+       "                "malicious-activity"\n",
+       "            ]\n",
        "        },\n",
        "        {\n",
        "            "type": "malware",\n",
-       "            "id": "malware--d7fd675d-94eb-4d95-b0bc-b3c5e28e8ed2",\n",
-       "            "created": "2017-09-26T23:33:56.908Z",\n",
-       "            "modified": "2017-09-26T23:33:56.908Z",\n",
+       "            "id": "malware--3d7f0c1c-616a-4868-aa7b-150821d2a429",\n",
+       "            "created": "2018-04-05T18:32:46.584Z",\n",
+       "            "modified": "2018-04-05T18:32:46.584Z",\n",
        "            "name": "Poison Ivy",\n",
        "            "labels": [\n",
        "                "remote-access-trojan"\n",
@@ -841,12 +837,12 @@
        "        },\n",
        "        {\n",
        "            "type": "relationship",\n",
-       "            "id": "relationship--637aa3b1-d4b8-4bc4-85e7-77cc82b198a3",\n",
-       "            "created": "2017-09-26T23:34:01.765Z",\n",
-       "            "modified": "2017-09-26T23:34:01.765Z",\n",
+       "            "id": "relationship--34ddc7b4-4965-4615-b286-1c8bbaa1e7db",\n",
+       "            "created": "2018-04-05T18:32:49.474Z",\n",
+       "            "modified": "2018-04-05T18:32:49.474Z",\n",
        "            "relationship_type": "indicates",\n",
-       "            "source_ref": "indicator--dbcbd659-c927-4f9a-994f-0a2632274394",\n",
-       "            "target_ref": "malware--d7fd675d-94eb-4d95-b0bc-b3c5e28e8ed2"\n",
+       "            "source_ref": "indicator--548af3be-39d7-4a3e-93c2-1a63cccf8951",\n",
+       "            "target_ref": "malware--3d7f0c1c-616a-4868-aa7b-150821d2a429"\n",
        "        }\n",
        "    ]\n",
        "}\n",
@@ -871,21 +867,21 @@
  ],
  "metadata": {
   "kernelspec": {
-   "display_name": "Python 2",
+   "display_name": "Python 3",
    "language": "python",
-   "name": "python2"
+   "name": "python3"
   },
   "language_info": {
    "codemirror_mode": {
     "name": "ipython",
-    "version": 2
+    "version": 3
    },
    "file_extension": ".py",
    "mimetype": "text/x-python",
    "name": "python",
    "nbconvert_exporter": "python",
-   "pygments_lexer": "ipython2",
-   "version": "2.7.12"
+   "pygments_lexer": "ipython3",
+   "version": "3.6.3"
   }
  },
  "nbformat": 4,
diff --git a/docs/guide/custom.ipynb b/docs/guide/custom.ipynb
index 7f30401..bc19749 100644
--- a/docs/guide/custom.ipynb
+++ b/docs/guide/custom.ipynb
@@ -4,7 +4,6 @@
    "cell_type": "code",
    "execution_count": 1,
    "metadata": {
-    "collapsed": true,
     "nbsphinx": "hidden"
    },
    "outputs": [],
@@ -23,9 +22,8 @@
   },
   {
    "cell_type": "code",
-   "execution_count": 1,
+   "execution_count": 2,
    "metadata": {
-    "collapsed": true,
     "nbsphinx": "hidden"
    },
    "outputs": [],
@@ -33,23 +31,25 @@
     "# JSON output syntax highlighting\n",
     "from __future__ import print_function\n",
     "from pygments import highlight\n",
-    "from pygments.lexers import JsonLexer\n",
+    "from pygments.lexers import JsonLexer, TextLexer\n",
     "from pygments.formatters import HtmlFormatter\n",
-    "from IPython.display import HTML\n",
+    "from IPython.display import display, HTML\n",
+    "from IPython.core.interactiveshell import InteractiveShell\n",
     "\n",
-    "original_print = print\n",
+    "InteractiveShell.ast_node_interactivity = \"all\"\n",
     "\n",
     "def json_print(inpt):\n",
     "    string = str(inpt)\n",
+    "    formatter = HtmlFormatter()\n",
     "    if string[0] == '{':\n",
-    "        formatter = HtmlFormatter()\n",
-    "        return HTML('{}'.format(\n",
-    "                    formatter.get_style_defs('.highlight'),\n",
-    "                    highlight(string, JsonLexer(), formatter)))\n",
+    "        lexer = JsonLexer()\n",
     "    else:\n",
-    "        original_print(inpt)\n",
+    "        lexer = TextLexer()\n",
+    "    return HTML('{}'.format(\n",
+    "                formatter.get_style_defs('.highlight'),\n",
+    "                highlight(string, lexer, formatter)))\n",
     "\n",
-    "print = json_print"
+    "globals()['print'] = json_print"
    ]
   },
   {
@@ -70,7 +70,7 @@
   },
   {
    "cell_type": "code",
-   "execution_count": 4,
+   "execution_count": 3,
    "metadata": {},
    "outputs": [
     {
@@ -99,7 +99,7 @@
   },
   {
    "cell_type": "code",
-   "execution_count": 2,
+   "execution_count": 4,
    "metadata": {},
    "outputs": [
     {
@@ -175,9 +175,9 @@
        ".highlight .vm { color: #19177C } /* Name.Variable.Magic */\n",
        ".highlight .il { color: #666666 } /* Literal.Number.Integer.Long */
{\n",
        "    "type": "identity",\n",
-       "    "id": "identity--00c5743f-2d5e-4d66-88f1-1842584f4519",\n",
-       "    "created": "2017-11-09T16:17:44.596Z",\n",
-       "    "modified": "2017-11-09T16:17:44.596Z",\n",
+       "    "id": "identity--87aac643-341b-413a-b702-ea5820416155",\n",
+       "    "created": "2018-04-05T18:38:10.269Z",\n",
+       "    "modified": "2018-04-05T18:38:10.269Z",\n",
        "    "name": "John Smith",\n",
        "    "identity_class": "individual",\n",
        "    "x_foo": "bar"\n",
@@ -188,7 +188,7 @@
        ""
       ]
      },
-     "execution_count": 2,
+     "execution_count": 4,
      "metadata": {},
      "output_type": "execute_result"
     }
@@ -211,6 +211,117 @@
     "Alternatively, setting ``allow_custom`` to ``True`` will allow custom properties without requiring a ``custom_properties`` dictionary."
    ]
   },
+  {
+   "cell_type": "code",
+   "execution_count": 5,
+   "metadata": {},
+   "outputs": [
+    {
+     "data": {
+      "text/html": [
+       "
{\n",
+       "    "type": "identity",\n",
+       "    "id": "identity--a1ad0a6f-39ab-4642-9a72-aaa198b1eee2",\n",
+       "    "created": "2018-04-05T18:38:12.270Z",\n",
+       "    "modified": "2018-04-05T18:38:12.270Z",\n",
+       "    "name": "John Smith",\n",
+       "    "identity_class": "individual",\n",
+       "    "x_foo": "bar"\n",
+       "}\n",
+       "
\n" + ], + "text/plain": [ + "" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "identity2 = Identity(name=\"John Smith\",\n", + " identity_class=\"individual\",\n", + " x_foo=\"bar\",\n", + " allow_custom=True)\n", + "print(identity2)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Likewise, when parsing STIX content with custom properties, pass ``allow_custom=True`` to [parse()](../api/stix2.core.rst#stix2.core.parse):" + ] + }, { "cell_type": "code", "execution_count": 6, @@ -287,15 +398,7 @@ ".highlight .vg { color: #19177C } /* Name.Variable.Global */\n", ".highlight .vi { color: #19177C } /* Name.Variable.Instance */\n", ".highlight .vm { color: #19177C } /* Name.Variable.Magic */\n", - ".highlight .il { color: #666666 } /* Literal.Number.Integer.Long */
{\n",
-       "    "x_foo": "bar",\n",
-       "    "type": "identity",\n",
-       "    "id": "identity--1e8188eb-245f-400b-839d-7f612169c514",\n",
-       "    "created": "2017-09-26T21:02:22.708Z",\n",
-       "    "modified": "2017-09-26T21:02:22.708Z",\n",
-       "    "name": "John Smith",\n",
-       "    "identity_class": "individual"\n",
-       "}\n",
+       ".highlight .il { color: #666666 } /* Literal.Number.Integer.Long */
bar\n",
        "
\n" ], "text/plain": [ @@ -307,34 +410,6 @@ "output_type": "execute_result" } ], - "source": [ - "identity2 = Identity(name=\"John Smith\",\n", - " identity_class=\"individual\",\n", - " x_foo=\"bar\",\n", - " allow_custom=True)\n", - "print(identity2)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Likewise, when parsing STIX content with custom properties, pass ``allow_custom=True`` to [parse()](../api/stix2.core.rst#stix2.core.parse):" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "bar\n" - ] - } - ], "source": [ "from stix2 import parse\n", "\n", @@ -364,10 +439,8 @@ }, { "cell_type": "code", - "execution_count": 8, - "metadata": { - "collapsed": true - }, + "execution_count": 7, + "metadata": {}, "outputs": [], "source": [ "from stix2 import CustomObject, properties\n", @@ -391,7 +464,7 @@ }, { "cell_type": "code", - "execution_count": 9, + "execution_count": 8, "metadata": {}, "outputs": [ { @@ -467,9 +540,9 @@ ".highlight .vm { color: #19177C } /* Name.Variable.Magic */\n", ".highlight .il { color: #666666 } /* Literal.Number.Integer.Long */
{\n",
        "    "type": "x-animal",\n",
-       "    "id": "x-animal--caebdf17-9d2a-4c84-8864-7406326618f0",\n",
-       "    "created": "2017-09-26T21:02:34.724Z",\n",
-       "    "modified": "2017-09-26T21:02:34.724Z",\n",
+       "    "id": "x-animal--b1e4fe7f-7985-451d-855c-6ba5c265b22a",\n",
+       "    "created": "2018-04-05T18:38:19.790Z",\n",
+       "    "modified": "2018-04-05T18:38:19.790Z",\n",
        "    "species": "lion",\n",
        "    "animal_class": "mammal"\n",
        "}\n",
@@ -479,7 +552,7 @@
        ""
       ]
      },
-     "execution_count": 9,
+     "execution_count": 8,
      "metadata": {},
      "output_type": "execute_result"
     }
@@ -499,7 +572,7 @@
   },
   {
    "cell_type": "code",
-   "execution_count": 10,
+   "execution_count": 9,
    "metadata": {},
    "outputs": [
     {
@@ -525,15 +598,90 @@
   },
   {
    "cell_type": "code",
-   "execution_count": 11,
+   "execution_count": 10,
    "metadata": {},
    "outputs": [
     {
-     "name": "stdout",
-     "output_type": "stream",
-     "text": [
-      "shark\n"
-     ]
+     "data": {
+      "text/html": [
+       "
shark\n",
+       "
\n" + ], + "text/plain": [ + "" + ] + }, + "execution_count": 10, + "metadata": {}, + "output_type": "execute_result" } ], "source": [ @@ -558,7 +706,7 @@ }, { "cell_type": "code", - "execution_count": 12, + "execution_count": 11, "metadata": {}, "outputs": [ { @@ -593,7 +741,7 @@ }, { "cell_type": "code", - "execution_count": 13, + "execution_count": 12, "metadata": {}, "outputs": [ { @@ -678,7 +826,7 @@ "" ] }, - "execution_count": 13, + "execution_count": 12, "metadata": {}, "output_type": "execute_result" } @@ -709,16 +857,172 @@ }, { "cell_type": "code", - "execution_count": 14, + "execution_count": 13, "metadata": {}, "outputs": [ { - "name": "stdout", - "output_type": "stream", - "text": [ - "foobaz\n", - "5\n" - ] + "data": { + "text/html": [ + "
foobaz\n",
+       "
\n" + ], + "text/plain": [ + "" + ] + }, + "execution_count": 13, + "metadata": {}, + "output_type": "execute_result" + }, + { + "data": { + "text/html": [ + "
5\n",
+       "
\n" + ], + "text/plain": [ + "" + ] + }, + "execution_count": 13, + "metadata": {}, + "output_type": "execute_result" } ], "source": [ @@ -759,7 +1063,7 @@ }, { "cell_type": "code", - "execution_count": 15, + "execution_count": 16, "metadata": {}, "outputs": [ { @@ -843,7 +1147,7 @@ "" ] }, - "execution_count": 15, + "execution_count": 16, "metadata": {}, "output_type": "execute_result" } @@ -851,10 +1155,10 @@ "source": [ "from stix2 import File, CustomExtension\n", "\n", - "@CustomExtension(File, 'x-new-ext', [\n", - " ('property1', properties.StringProperty(required=True)),\n", - " ('property2', properties.IntegerProperty()),\n", - "])\n", + "@CustomExtension(File, 'x-new-ext', {\n", + " 'property1': properties.StringProperty(required=True),\n", + " 'property2': properties.IntegerProperty(),\n", + "})\n", "class NewExtension():\n", " pass\n", "\n", @@ -872,16 +1176,172 @@ }, { "cell_type": "code", - "execution_count": 16, + "execution_count": 17, "metadata": {}, "outputs": [ { - "name": "stdout", - "output_type": "stream", - "text": [ - "bla\n", - "50\n" - ] + "data": { + "text/html": [ + "
bla\n",
+       "
\n" + ], + "text/plain": [ + "" + ] + }, + "execution_count": 17, + "metadata": {}, + "output_type": "execute_result" + }, + { + "data": { + "text/html": [ + "
50\n",
+       "
\n" + ], + "text/plain": [ + "" + ] + }, + "execution_count": 17, + "metadata": {}, + "output_type": "execute_result" } ], "source": [ @@ -918,21 +1378,21 @@ ], "metadata": { "kernelspec": { - "display_name": "Python 2", + "display_name": "Python 3", "language": "python", - "name": "python2" + "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", - "version": 2 + "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", - "pygments_lexer": "ipython2", - "version": "2.7.12" + "pygments_lexer": "ipython3", + "version": "3.6.3" } }, "nbformat": 4, diff --git a/docs/guide/datastore.ipynb b/docs/guide/datastore.ipynb index ac27a82..474c719 100644 --- a/docs/guide/datastore.ipynb +++ b/docs/guide/datastore.ipynb @@ -4,7 +4,6 @@ "cell_type": "code", "execution_count": 1, "metadata": { - "collapsed": true, "nbsphinx": "hidden" }, "outputs": [], @@ -23,9 +22,8 @@ }, { "cell_type": "code", - "execution_count": 40, + "execution_count": 2, "metadata": { - "collapsed": true, "nbsphinx": "hidden" }, "outputs": [], @@ -33,36 +31,25 @@ "# JSON output syntax highlighting\n", "from __future__ import print_function\n", "from pygments import highlight\n", - "from pygments.lexers import JsonLexer\n", + "from pygments.lexers import JsonLexer, TextLexer\n", "from pygments.formatters import HtmlFormatter\n", - "from IPython.display import HTML\n", + "from IPython.display import display, HTML\n", + "from IPython.core.interactiveshell import InteractiveShell\n", "\n", - "original_print = print\n", + "InteractiveShell.ast_node_interactivity = \"all\"\n", "\n", "def json_print(inpt):\n", " string = str(inpt)\n", + " formatter = HtmlFormatter()\n", " if string[0] == '{':\n", - " formatter = HtmlFormatter()\n", - " return HTML('{}'.format(\n", - " formatter.get_style_defs('.highlight'),\n", - " highlight(string, JsonLexer(), formatter)))\n", + " lexer = JsonLexer()\n", " else:\n", - " original_print(inpt)\n", + " lexer = TextLexer()\n", + " return HTML('{}'.format(\n", + " formatter.get_style_defs('.highlight'),\n", + " highlight(string, lexer, formatter)))\n", "\n", - "print = json_print" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "metadata": { - "collapsed": true - }, - "outputs": [], - "source": [ - "# without this configuration, only last print() call is outputted in cells\n", - "from IPython.core.interactiveshell import InteractiveShell\n", - "InteractiveShell.ast_node_interactivity = \"all\"" + "globals()['print'] = json_print" ] }, { @@ -328,10 +315,10 @@ "from stix2 import CompositeDataSource, FileSystemSource, TAXIICollectionSource\n", "\n", "# create FileSystemStore\n", - "fs = FileSystemSource(\"/home/michael/cti-python-stix2/stix2/test/stix2_data/\")\n", + "fs = FileSystemSource(\"/tmp/stix2_source\")\n", "\n", "# create TAXIICollectionSource\n", - "colxn = Collection('https://test.freetaxii.com:8000/osint/collections/a9c22eaf-0f3e-482c-8bb4-45ae09e75d9b/')\n", + "colxn = Collection('http://127.0.0.1:5000/trustgroup1/collections/91a7b528-80eb-42ed-a74d-c6fbd5a26116/')\n", "ts = TAXIICollectionSource(colxn)\n", "\n", "# add them both to the CompositeDataSource\n", @@ -344,7 +331,7 @@ "\n", "# get an object that is only in the TAXII collection\n", "ind = cs.get('indicator--02b90f02-a96a-43ee-88f1-1e87297941f2')\n", - "print(ind)\n" + "print(ind)" ] }, { @@ -389,10 +376,8 @@ }, { "cell_type": "code", - "execution_count": 5, - "metadata": { - "collapsed": true - }, + "execution_count": 7, + "metadata": {}, "outputs": [], "source": [ "import sys\n", @@ -423,16 +408,14 @@ }, { "cell_type": "code", - "execution_count": 6, - "metadata": { - "collapsed": true - }, + "execution_count": 9, + "metadata": {}, "outputs": [], "source": [ "from stix2 import MemoryStore, FileSystemStore, FileSystemSource\n", "\n", - "fs = FileSystemStore(\"/home/michael/Desktop/sample_stix2_data\")\n", - "fs_source = FileSystemSource(\"/home/michael/Desktop/sample_stix2_data\")\n", + "fs = FileSystemStore(\"/tmp/stix2_store\")\n", + "fs_source = FileSystemSource(\"/tmp/stix2_source\")\n", "\n", "# attach filter to FileSystemStore\n", "fs.source.filters.add(f)\n", @@ -466,7 +449,7 @@ }, { "cell_type": "code", - "execution_count": 13, + "execution_count": 10, "metadata": {}, "outputs": [], "source": [ @@ -492,7 +475,7 @@ }, { "cell_type": "code", - "execution_count": 14, + "execution_count": 11, "metadata": {}, "outputs": [ { @@ -568,9 +551,9 @@ ".highlight .vm { color: #19177C } /* Name.Variable.Magic */\n", ".highlight .il { color: #666666 } /* Literal.Number.Integer.Long */
{\n",
        "    "type": "identity",\n",
-       "    "id": "identity--be3baac0-9aba-48a8-81e4-4408b1c379a8",\n",
-       "    "created": "2017-11-21T22:14:45.213Z",\n",
-       "    "modified": "2017-11-21T22:14:45.213Z",\n",
+       "    "id": "identity--b67cf8d4-cc1a-4bb7-9402-fffcff17c9a9",\n",
+       "    "created": "2018-04-05T20:43:54.117Z",\n",
+       "    "modified": "2018-04-05T20:43:54.117Z",\n",
        "    "name": "John Doe",\n",
        "    "identity_class": "individual"\n",
        "}\n",
@@ -580,7 +563,7 @@
        ""
       ]
      },
-     "execution_count": 14,
+     "execution_count": 11,
      "metadata": {},
      "output_type": "execute_result"
     }
@@ -598,7 +581,7 @@
   },
   {
    "cell_type": "code",
-   "execution_count": 15,
+   "execution_count": 12,
    "metadata": {},
    "outputs": [
     {
@@ -607,7 +590,7 @@
        "3"
       ]
      },
-     "execution_count": 15,
+     "execution_count": 12,
      "metadata": {},
      "output_type": "execute_result"
     }
@@ -626,16 +609,16 @@
   },
   {
    "cell_type": "code",
-   "execution_count": 27,
+   "execution_count": 13,
    "metadata": {},
    "outputs": [
     {
      "data": {
       "text/plain": [
-       "[Relationship(type='relationship', id='relationship--bd6fd399-c907-4feb-b1da-b90f15942f1d', created='2017-11-21T22:14:45.214Z', modified='2017-11-21T22:14:45.214Z', relationship_type=u'indicates', source_ref='indicator--5ee33ff0-c50d-456b-a8dd-b5d1b69a66e8', target_ref='malware--66c0bc78-4e27-4d80-a565-a07e6eb6fba4')]"
+       "[Relationship(type='relationship', id='relationship--3b9cb248-5c2c-425d-85d0-680bfef6e69d', created='2018-04-05T20:43:54.134Z', modified='2018-04-05T20:43:54.134Z', relationship_type='indicates', source_ref='indicator--61deb2a5-305a-490e-83b3-9839a9677368', target_ref='malware--9fe343d8-edf7-4f4a-bb6c-a221fb75142d')]"
       ]
      },
-     "execution_count": 27,
+     "execution_count": 13,
      "metadata": {},
      "output_type": "execute_result"
     }
@@ -653,16 +636,16 @@
   },
   {
    "cell_type": "code",
-   "execution_count": 28,
+   "execution_count": 14,
    "metadata": {},
    "outputs": [
     {
      "data": {
       "text/plain": [
-       "[Relationship(type='relationship', id='relationship--7eb7f5cd-8bf2-4f7c-8756-84c0b5693b9a', created='2017-11-21T22:14:45.215Z', modified='2017-11-21T22:14:45.215Z', relationship_type=u'targets', source_ref='malware--66c0bc78-4e27-4d80-a565-a07e6eb6fba4', target_ref='identity--be3baac0-9aba-48a8-81e4-4408b1c379a8')]"
+       "[Relationship(type='relationship', id='relationship--8d322508-423b-4d51-be85-a95ad083f8af', created='2018-04-05T20:43:54.134Z', modified='2018-04-05T20:43:54.134Z', relationship_type='targets', source_ref='malware--9fe343d8-edf7-4f4a-bb6c-a221fb75142d', target_ref='identity--b67cf8d4-cc1a-4bb7-9402-fffcff17c9a9')]"
       ]
      },
-     "execution_count": 28,
+     "execution_count": 14,
      "metadata": {},
      "output_type": "execute_result"
     }
@@ -680,17 +663,17 @@
   },
   {
    "cell_type": "code",
-   "execution_count": 30,
+   "execution_count": 15,
    "metadata": {},
    "outputs": [
     {
      "data": {
       "text/plain": [
-       "[Relationship(type='relationship', id='relationship--bd6fd399-c907-4feb-b1da-b90f15942f1d', created='2017-11-21T22:14:45.214Z', modified='2017-11-21T22:14:45.214Z', relationship_type=u'indicates', source_ref='indicator--5ee33ff0-c50d-456b-a8dd-b5d1b69a66e8', target_ref='malware--66c0bc78-4e27-4d80-a565-a07e6eb6fba4'),\n",
-       " Relationship(type='relationship', id='relationship--3c759d40-c92a-430e-aab6-77d5c5763302', created='2017-11-21T22:14:45.215Z', modified='2017-11-21T22:14:45.215Z', relationship_type=u'uses', source_ref='campaign--82ab7aa4-d13b-4e99-8a09-ebcba30668a7', target_ref='malware--66c0bc78-4e27-4d80-a565-a07e6eb6fba4')]"
+       "[Relationship(type='relationship', id='relationship--3b9cb248-5c2c-425d-85d0-680bfef6e69d', created='2018-04-05T20:43:54.134Z', modified='2018-04-05T20:43:54.134Z', relationship_type='indicates', source_ref='indicator--61deb2a5-305a-490e-83b3-9839a9677368', target_ref='malware--9fe343d8-edf7-4f4a-bb6c-a221fb75142d'),\n",
+       " Relationship(type='relationship', id='relationship--93e5afe0-d1fb-4315-8d08-10951f7a99b6', created='2018-04-05T20:43:54.134Z', modified='2018-04-05T20:43:54.134Z', relationship_type='uses', source_ref='campaign--edfd885c-bc31-4051-9bc2-08e057542d56', target_ref='malware--9fe343d8-edf7-4f4a-bb6c-a221fb75142d')]"
       ]
      },
-     "execution_count": 30,
+     "execution_count": 15,
      "metadata": {},
      "output_type": "execute_result"
     }
@@ -708,16 +691,16 @@
   },
   {
    "cell_type": "code",
-   "execution_count": 42,
+   "execution_count": 16,
    "metadata": {},
    "outputs": [
     {
      "data": {
       "text/plain": [
-       "[Campaign(type='campaign', id='campaign--82ab7aa4-d13b-4e99-8a09-ebcba30668a7', created='2017-11-21T22:14:45.213Z', modified='2017-11-21T22:14:45.213Z', name=u'Charge', description=u'Attack!')]"
+       "[Campaign(type='campaign', id='campaign--edfd885c-bc31-4051-9bc2-08e057542d56', created='2018-04-05T20:43:54.117Z', modified='2018-04-05T20:43:54.117Z', name='Charge', description='Attack!')]"
       ]
      },
-     "execution_count": 42,
+     "execution_count": 16,
      "metadata": {},
      "output_type": "execute_result"
     }
@@ -729,21 +712,21 @@
  ],
  "metadata": {
   "kernelspec": {
-   "display_name": "cti-python-stix2",
+   "display_name": "Python 3",
    "language": "python",
-   "name": "cti-python-stix2"
+   "name": "python3"
   },
   "language_info": {
    "codemirror_mode": {
     "name": "ipython",
-    "version": 2
+    "version": 3
    },
    "file_extension": ".py",
    "mimetype": "text/x-python",
    "name": "python",
    "nbconvert_exporter": "python",
-   "pygments_lexer": "ipython2",
-   "version": "2.7.12"
+   "pygments_lexer": "ipython3",
+   "version": "3.6.3"
   }
  },
  "nbformat": 4,
diff --git a/docs/guide/environment.ipynb b/docs/guide/environment.ipynb
index 3ece7c4..fdc57c8 100644
--- a/docs/guide/environment.ipynb
+++ b/docs/guide/environment.ipynb
@@ -4,7 +4,6 @@
    "cell_type": "code",
    "execution_count": 1,
    "metadata": {
-    "collapsed": true,
     "nbsphinx": "hidden"
    },
    "outputs": [],
@@ -25,7 +24,6 @@
    "cell_type": "code",
    "execution_count": 2,
    "metadata": {
-    "collapsed": true,
     "nbsphinx": "hidden"
    },
    "outputs": [],
@@ -33,23 +31,25 @@
     "# JSON output syntax highlighting\n",
     "from __future__ import print_function\n",
     "from pygments import highlight\n",
-    "from pygments.lexers import JsonLexer\n",
+    "from pygments.lexers import JsonLexer, TextLexer\n",
     "from pygments.formatters import HtmlFormatter\n",
-    "from IPython.display import HTML\n",
+    "from IPython.display import display, HTML\n",
+    "from IPython.core.interactiveshell import InteractiveShell\n",
     "\n",
-    "original_print = print\n",
+    "InteractiveShell.ast_node_interactivity = \"all\"\n",
     "\n",
     "def json_print(inpt):\n",
     "    string = str(inpt)\n",
+    "    formatter = HtmlFormatter()\n",
     "    if string[0] == '{':\n",
-    "        formatter = HtmlFormatter()\n",
-    "        return HTML('{}'.format(\n",
-    "                    formatter.get_style_defs('.highlight'),\n",
-    "                    highlight(string, JsonLexer(), formatter)))\n",
+    "        lexer = JsonLexer()\n",
     "    else:\n",
-    "        original_print(inpt)\n",
+    "        lexer = TextLexer()\n",
+    "    return HTML('{}'.format(\n",
+    "                formatter.get_style_defs('.highlight'),\n",
+    "                highlight(string, lexer, formatter)))\n",
     "\n",
-    "print = json_print"
+    "globals()['print'] = json_print"
    ]
   },
   {
@@ -68,9 +68,7 @@
   {
    "cell_type": "code",
    "execution_count": 3,
-   "metadata": {
-    "collapsed": true
-   },
+   "metadata": {},
    "outputs": [],
    "source": [
     "from stix2 import Environment, MemoryStore\n",
@@ -87,18 +85,16 @@
   },
   {
    "cell_type": "code",
-   "execution_count": 4,
-   "metadata": {
-    "collapsed": true
-   },
+   "execution_count": 6,
+   "metadata": {},
    "outputs": [],
    "source": [
     "from stix2 import CompositeDataSource, FileSystemSink, FileSystemSource, MemorySource\n",
     "\n",
     "src = CompositeDataSource()\n",
-    "src.add_data_sources([MemorySource(), FileSystemSource(\"/tmp/stix_source\")])\n",
+    "src.add_data_sources([MemorySource(), FileSystemSource(\"/tmp/stix2_source\")])\n",
     "env2 = Environment(source=src,\n",
-    "                   sink=FileSystemSink(\"/tmp/stix_sink\"))"
+    "                   sink=FileSystemSink(\"/tmp/stix2_sink\"))"
    ]
   },
   {
@@ -110,10 +106,8 @@
   },
   {
    "cell_type": "code",
-   "execution_count": 5,
-   "metadata": {
-    "collapsed": true
-   },
+   "execution_count": 7,
+   "metadata": {},
    "outputs": [],
    "source": [
     "from stix2 import Indicator\n",
@@ -131,139 +125,6 @@
     "You can retrieve STIX objects from the [DataSources](../api/stix2.datastore.rst#stix2.datastore.DataSource) in the [Environment](../api/stix2.environment.rst#stix2.environment.Environment) with [get()](../api/stix2.environment.rst#stix2.environment.Environment.get), [query()](../api/stix2.environment.rst#stix2.environment.Environment.query), [all_versions()](../api/stix2.environment.rst#stix2.environment.Environment.all_versions), [creator_of()](../api/stix2.datastore.rst#stix2.datastore.DataSource.creator_of), [related_to()](../api/stix2.datastore.rst#stix2.datastore.DataSource.related_to), and [relationships()](../api/stix2.datastore.rst#stix2.datastore.DataSource.relationships) just as you would for a [DataSource](../api/stix2.datastore.rst#stix2.datastore.DataSource)."
    ]
   },
-  {
-   "cell_type": "code",
-   "execution_count": 6,
-   "metadata": {},
-   "outputs": [
-    {
-     "data": {
-      "text/html": [
-       "
{\n",
-       "    "type": "indicator",\n",
-       "    "id": "indicator--01234567-89ab-cdef-0123-456789abcdef",\n",
-       "    "created": "2017-10-02T13:20:39.373Z",\n",
-       "    "modified": "2017-10-02T13:20:39.373Z",\n",
-       "    "labels": [\n",
-       "        "malicious-activity"\n",
-       "    ],\n",
-       "    "pattern": "[file:hashes.md5 = 'd41d8cd98f00b204e9800998ecf8427e']",\n",
-       "    "valid_from": "2017-10-02T13:20:39.3737Z"\n",
-       "}\n",
-       "
\n" - ], - "text/plain": [ - "" - ] - }, - "execution_count": 6, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "print(env.get(\"indicator--01234567-89ab-cdef-0123-456789abcdef\"))" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Creating STIX Objects With Defaults\n", - "\n", - "To create STIX objects with default values for certain properties, use an [ObjectFactory](../api/stix2.environment.rst#stix2.environment.ObjectFactory). For instance, say we want all objects we create to have a ``created_by_ref`` property pointing to the ``Identity`` object representing our organization." - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "metadata": { - "collapsed": true - }, - "outputs": [], - "source": [ - "from stix2 import Indicator, ObjectFactory\n", - "\n", - "factory = ObjectFactory(created_by_ref=\"identity--311b2d2d-f010-5473-83ec-1edf84858f4c\")" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "collapsed": true - }, - "source": [ - "Once you've set up the [ObjectFactory](../api/stix2.environment.rst#stix2.environment.ObjectFactory), use its [create()](../api/stix2.environment.rst#stix2.environment.ObjectFactory.create) method, passing in the class for the type of object you wish to create, followed by the other properties and their values for the object." - ] - }, { "cell_type": "code", "execution_count": 8, @@ -342,15 +203,14 @@ ".highlight .vm { color: #19177C } /* Name.Variable.Magic */\n", ".highlight .il { color: #666666 } /* Literal.Number.Integer.Long */
{\n",
        "    "type": "indicator",\n",
-       "    "id": "indicator--c92ad60d-449d-4adf-86b3-4e5951a8f480",\n",
-       "    "created_by_ref": "identity--311b2d2d-f010-5473-83ec-1edf84858f4c",\n",
-       "    "created": "2017-10-02T13:23:00.607Z",\n",
-       "    "modified": "2017-10-02T13:23:00.607Z",\n",
+       "    "id": "indicator--01234567-89ab-cdef-0123-456789abcdef",\n",
+       "    "created": "2018-04-05T19:27:53.923Z",\n",
+       "    "modified": "2018-04-05T19:27:53.923Z",\n",
+       "    "pattern": "[file:hashes.md5 = 'd41d8cd98f00b204e9800998ecf8427e']",\n",
+       "    "valid_from": "2018-04-05T19:27:53.923548Z",\n",
        "    "labels": [\n",
        "        "malicious-activity"\n",
-       "    ],\n",
-       "    "pattern": "[file:hashes.md5 = 'd41d8cd98f00b204e9800998ecf8427e']",\n",
-       "    "valid_from": "2017-10-02T13:23:00.607216Z"\n",
+       "    ]\n",
        "}\n",
        "
\n" ], @@ -363,6 +223,138 @@ "output_type": "execute_result" } ], + "source": [ + "print(env.get(\"indicator--01234567-89ab-cdef-0123-456789abcdef\"))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Creating STIX Objects With Defaults\n", + "\n", + "To create STIX objects with default values for certain properties, use an [ObjectFactory](../api/stix2.environment.rst#stix2.environment.ObjectFactory). For instance, say we want all objects we create to have a ``created_by_ref`` property pointing to the ``Identity`` object representing our organization." + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [], + "source": [ + "from stix2 import Indicator, ObjectFactory\n", + "\n", + "factory = ObjectFactory(created_by_ref=\"identity--311b2d2d-f010-5473-83ec-1edf84858f4c\")" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "Once you've set up the [ObjectFactory](../api/stix2.environment.rst#stix2.environment.ObjectFactory), use its [create()](../api/stix2.environment.rst#stix2.environment.ObjectFactory.create) method, passing in the class for the type of object you wish to create, followed by the other properties and their values for the object." + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
{\n",
+       "    "type": "indicator",\n",
+       "    "id": "indicator--c1b421c0-9c6b-4276-9b73-1b8684a5a0d2",\n",
+       "    "created_by_ref": "identity--311b2d2d-f010-5473-83ec-1edf84858f4c",\n",
+       "    "created": "2018-04-05T19:28:48.776Z",\n",
+       "    "modified": "2018-04-05T19:28:48.776Z",\n",
+       "    "pattern": "[file:hashes.md5 = 'd41d8cd98f00b204e9800998ecf8427e']",\n",
+       "    "valid_from": "2018-04-05T19:28:48.776442Z",\n",
+       "    "labels": [\n",
+       "        "malicious-activity"\n",
+       "    ]\n",
+       "}\n",
+       "
\n" + ], + "text/plain": [ + "" + ] + }, + "execution_count": 14, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "ind = factory.create(Indicator,\n", " labels=[\"malicious-activity\"],\n", @@ -388,7 +380,7 @@ }, { "cell_type": "code", - "execution_count": 9, + "execution_count": 15, "metadata": {}, "outputs": [ { @@ -464,14 +456,14 @@ ".highlight .vm { color: #19177C } /* Name.Variable.Magic */\n", ".highlight .il { color: #666666 } /* Literal.Number.Integer.Long */
{\n",
        "    "type": "indicator",\n",
-       "    "id": "indicator--ae206b9f-8723-4fcf-beb7-8b1b9a2570ab",\n",
+       "    "id": "indicator--30a3b39c-5f57-4e7f-9eaf-e1abcb643da4",\n",
        "    "created": "2017-09-25T18:07:46.255Z",\n",
        "    "modified": "2017-09-25T18:07:46.255Z",\n",
+       "    "pattern": "[file:hashes.md5 = 'd41d8cd98f00b204e9800998ecf8427e']",\n",
+       "    "valid_from": "2018-04-05T19:28:53.268567Z",\n",
        "    "labels": [\n",
        "        "malicious-activity"\n",
-       "    ],\n",
-       "    "pattern": "[file:hashes.md5 = 'd41d8cd98f00b204e9800998ecf8427e']",\n",
-       "    "valid_from": "2017-10-02T13:23:05.790562Z"\n",
+       "    ]\n",
        "}\n",
        "
\n" ], @@ -479,7 +471,7 @@ "" ] }, - "execution_count": 9, + "execution_count": 15, "metadata": {}, "output_type": "execute_result" } @@ -498,7 +490,7 @@ }, { "cell_type": "code", - "execution_count": 10, + "execution_count": 16, "metadata": {}, "outputs": [ { @@ -574,15 +566,15 @@ ".highlight .vm { color: #19177C } /* Name.Variable.Magic */\n", ".highlight .il { color: #666666 } /* Literal.Number.Integer.Long */
{\n",
        "    "type": "indicator",\n",
-       "    "id": "indicator--a8e2be68-b496-463f-9ff4-f620046e7cf2",\n",
+       "    "id": "indicator--6c5bbaaf-6dac-44b0-a0df-86c27b3f6ecb",\n",
        "    "created_by_ref": "identity--962cabe5-f7f3-438a-9169-585a8c971d12",\n",
        "    "created": "2017-09-25T18:07:46.255Z",\n",
        "    "modified": "2017-09-25T18:07:46.255Z",\n",
+       "    "pattern": "[file:hashes.md5 = 'd41d8cd98f00b204e9800998ecf8427e']",\n",
+       "    "valid_from": "2018-04-05T19:29:56.55129Z",\n",
        "    "labels": [\n",
        "        "malicious-activity"\n",
-       "    ],\n",
-       "    "pattern": "[file:hashes.md5 = 'd41d8cd98f00b204e9800998ecf8427e']",\n",
-       "    "valid_from": "2017-10-02T13:23:08.32424Z"\n",
+       "    ]\n",
        "}\n",
        "
\n" ], @@ -590,7 +582,7 @@ "" ] }, - "execution_count": 10, + "execution_count": 16, "metadata": {}, "output_type": "execute_result" } @@ -614,7 +606,7 @@ }, { "cell_type": "code", - "execution_count": 11, + "execution_count": 17, "metadata": {}, "outputs": [ { @@ -690,15 +682,15 @@ ".highlight .vm { color: #19177C } /* Name.Variable.Magic */\n", ".highlight .il { color: #666666 } /* Literal.Number.Integer.Long */
{\n",
        "    "type": "indicator",\n",
-       "    "id": "indicator--89ba04ea-cce9-47a3-acd3-b6379ce51581",\n",
+       "    "id": "indicator--d1b8c3f6-1de1-44c1-b079-3df307224a0d",\n",
        "    "created_by_ref": "identity--311b2d2d-f010-5473-83ec-1edf84858f4c",\n",
-       "    "created": "2017-10-02T13:23:29.629Z",\n",
-       "    "modified": "2017-10-02T13:23:29.629Z",\n",
+       "    "created": "2018-04-05T19:29:59.605Z",\n",
+       "    "modified": "2018-04-05T19:29:59.605Z",\n",
+       "    "pattern": "[file:hashes.md5 = 'd41d8cd98f00b204e9800998ecf8427e']",\n",
+       "    "valid_from": "2018-04-05T19:29:59.605463Z",\n",
        "    "labels": [\n",
        "        "malicious-activity"\n",
-       "    ],\n",
-       "    "pattern": "[file:hashes.md5 = 'd41d8cd98f00b204e9800998ecf8427e']",\n",
-       "    "valid_from": "2017-10-02T13:23:29.629857Z"\n",
+       "    ]\n",
        "}\n",
        "
\n" ], @@ -706,7 +698,7 @@ "" ] }, - "execution_count": 11, + "execution_count": 17, "metadata": {}, "output_type": "execute_result" } @@ -725,21 +717,21 @@ ], "metadata": { "kernelspec": { - "display_name": "Python 2", + "display_name": "Python 3", "language": "python", - "name": "python2" + "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", - "version": 2 + "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", - "pygments_lexer": "ipython2", - "version": "2.7.12" + "pygments_lexer": "ipython3", + "version": "3.6.3" } }, "nbformat": 4, diff --git a/docs/guide/filesystem.ipynb b/docs/guide/filesystem.ipynb index cff73d6..28a1843 100644 --- a/docs/guide/filesystem.ipynb +++ b/docs/guide/filesystem.ipynb @@ -4,7 +4,6 @@ "cell_type": "code", "execution_count": 1, "metadata": { - "collapsed": true, "nbsphinx": "hidden" }, "outputs": [], @@ -25,7 +24,6 @@ "cell_type": "code", "execution_count": 2, "metadata": { - "collapsed": true, "nbsphinx": "hidden" }, "outputs": [], @@ -33,23 +31,25 @@ "# JSON output syntax highlighting\n", "from __future__ import print_function\n", "from pygments import highlight\n", - "from pygments.lexers import JsonLexer\n", + "from pygments.lexers import JsonLexer, TextLexer\n", "from pygments.formatters import HtmlFormatter\n", - "from IPython.display import HTML\n", + "from IPython.display import display, HTML\n", + "from IPython.core.interactiveshell import InteractiveShell\n", "\n", - "original_print = print\n", + "InteractiveShell.ast_node_interactivity = \"all\"\n", "\n", "def json_print(inpt):\n", " string = str(inpt)\n", + " formatter = HtmlFormatter()\n", " if string[0] == '{':\n", - " formatter = HtmlFormatter()\n", - " return HTML('{}'.format(\n", - " formatter.get_style_defs('.highlight'),\n", - " highlight(string, JsonLexer(), formatter)))\n", + " lexer = JsonLexer()\n", " else:\n", - " original_print(inpt)\n", + " lexer = TextLexer()\n", + " return HTML('{}'.format(\n", + " formatter.get_style_defs('.highlight'),\n", + " highlight(string, lexer, formatter)))\n", "\n", - "print = json_print" + "globals()['print'] = json_print" ] }, { @@ -120,57 +120,129 @@ "### FileSystem Examples\n", "\n", "#### FileSystemStore\n", - " " + "\n", + "Use the FileSystemStore when you want to both retrieve STIX content from the file system and push STIX content to it, too." ] }, { "cell_type": "code", - "execution_count": 10, + "execution_count": 4, "metadata": {}, "outputs": [ { - "name": "stdout", - "output_type": "stream", - "text": [ - "{\n", - " \"type\": \"malware\",\n", - " \"id\": \"malware--00c3bfcb-99bd-4767-8c03-b08f585f5c8a\",\n", - " \"created_by_ref\": \"identity--c78cb6e5-0c4b-4611-8297-d1b8b55e40b5\",\n", - " \"created\": \"2017-05-31T21:33:19.746Z\",\n", - " \"modified\": \"2017-05-31T21:33:19.746Z\",\n", - " \"name\": \"PowerDuke\",\n", - " \"description\": \"PowerDuke is a backdoor that was used by APT29 in 2016. It has primarily been delivered through Microsoft Word or Excel attachments containing malicious macros.[[Citation: Volexity PowerDuke November 2016]]\",\n", - " \"labels\": [\n", - " \"malware\"\n", - " ],\n", - " \"external_references\": [\n", - " {\n", - " \"source_name\": \"mitre-attack\",\n", - " \"url\": \"https://attack.mitre.org/wiki/Software/S0139\",\n", - " \"external_id\": \"S0139\"\n", - " },\n", - " {\n", - " \"source_name\": \"Volexity PowerDuke November 2016\",\n", - " \"description\": \"Adair, S.. (2016, November 9). PowerDuke: Widespread Post-Election Spear Phishing Campaigns Targeting Think Tanks and NGOs. Retrieved January 11, 2017.\",\n", - " \"url\": \"https://www.volexity.com/blog/2016/11/09/powerduke-post-election-spear-phishing-campaigns-targeting-think-tanks-and-ngos/\"\n", - " }\n", - " ],\n", - " \"object_marking_refs\": [\n", - " \"marking-definition--fa42a846-8d90-4e51-bc29-71d5b4802168\"\n", - " ]\n", - "}\n" - ] + "data": { + "text/html": [ + "
{\n",
+       "    "type": "malware",\n",
+       "    "id": "malware--00c3bfcb-99bd-4767-8c03-b08f585f5c8a",\n",
+       "    "created_by_ref": "identity--c78cb6e5-0c4b-4611-8297-d1b8b55e40b5",\n",
+       "    "created": "2017-05-31T21:33:19.746Z",\n",
+       "    "modified": "2017-05-31T21:33:19.746Z",\n",
+       "    "name": "PowerDuke",\n",
+       "    "description": "PowerDuke is a backdoor that was used by APT29 in 2016. It has primarily been delivered through Microsoft Word or Excel attachments containing malicious macros.[[Citation: Volexity PowerDuke November 2016]]",\n",
+       "    "labels": [\n",
+       "        "malware"\n",
+       "    ],\n",
+       "    "external_references": [\n",
+       "        {\n",
+       "            "source_name": "mitre-attack",\n",
+       "            "url": "https://attack.mitre.org/wiki/Software/S0139",\n",
+       "            "external_id": "S0139"\n",
+       "        },\n",
+       "        {\n",
+       "            "source_name": "Volexity PowerDuke November 2016",\n",
+       "            "description": "Adair, S.. (2016, November 9). PowerDuke: Widespread Post-Election Spear Phishing Campaigns Targeting Think Tanks and NGOs. Retrieved January 11, 2017.",\n",
+       "            "url": "https://www.volexity.com/blog/2016/11/09/powerduke-post-election-spear-phishing-campaigns-targeting-think-tanks-and-ngos/"\n",
+       "        }\n",
+       "    ],\n",
+       "    "object_marking_refs": [\n",
+       "        "marking-definition--fa42a846-8d90-4e51-bc29-71d5b4802168"\n",
+       "    ]\n",
+       "}\n",
+       "
\n" + ], + "text/plain": [ + "" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" } ], "source": [ "from stix2 import FileSystemStore\n", "\n", - "\"\"\"\n", - "Working with the FileSystemStore, where STIX content can be retrieved and pushed to a file system.\n", - "\"\"\"\n", - "\n", "# create FileSystemStore\n", - "fs = FileSystemStore(\"/home/michael/Desktop/sample_stix2_data\")\n", + "fs = FileSystemStore(\"/tmp/stix2_store\")\n", "\n", "# retrieve STIX2 content from FileSystemStore\n", "ap = fs.get(\"attack-pattern--00d0b012-8a03-410e-95de-5826bf542de6\")\n", @@ -221,54 +293,128 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "#### FileSystemSource - (if STIX content is only to be retrieved from FileSystem)" + "#### FileSystemSource\n", + "\n", + "Use the FileSystemSource when you only want to retrieve STIX content from the file system." ] }, { "cell_type": "code", - "execution_count": 4, + "execution_count": 6, "metadata": {}, "outputs": [ { - "name": "stdout", - "output_type": "stream", - "text": [ - "{\n", - " \"type\": \"attack-pattern\",\n", - " \"id\": \"attack-pattern--00d0b012-8a03-410e-95de-5826bf542de6\",\n", - " \"created_by_ref\": \"identity--c78cb6e5-0c4b-4611-8297-d1b8b55e40b5\",\n", - " \"created\": \"2017-05-31T21:30:54.176Z\",\n", - " \"modified\": \"2017-05-31T21:30:54.176Z\",\n", - " \"name\": \"Indicator Removal from Tools\",\n", - " \"description\": \"If a malicious...command-line parameters, Process monitoring\",\n", - " \"kill_chain_phases\": [\n", - " {\n", - " \"kill_chain_name\": \"mitre-attack\",\n", - " \"phase_name\": \"defense-evasion\"\n", - " }\n", - " ],\n", - " \"external_references\": [\n", - " {\n", - " \"source_name\": \"mitre-attack\",\n", - " \"url\": \"https://attack.mitre.org/wiki/Technique/T1066\",\n", - " \"external_id\": \"T1066\"\n", - " }\n", - " ],\n", - " \"object_marking_refs\": [\n", - " \"marking-definition--fa42a846-8d90-4e51-bc29-71d5b4802168\"\n", - " ]\n", - "}\n" - ] + "data": { + "text/html": [ + "
{\n",
+       "    "type": "attack-pattern",\n",
+       "    "id": "attack-pattern--00d0b012-8a03-410e-95de-5826bf542de6",\n",
+       "    "created_by_ref": "identity--c78cb6e5-0c4b-4611-8297-d1b8b55e40b5",\n",
+       "    "created": "2017-05-31T21:30:54.176Z",\n",
+       "    "modified": "2017-05-31T21:30:54.176Z",\n",
+       "    "name": "Indicator Removal from Tools",\n",
+       "    "description": "If a malicious...command-line parameters, Process monitoring",\n",
+       "    "kill_chain_phases": [\n",
+       "        {\n",
+       "            "kill_chain_name": "mitre-attack",\n",
+       "            "phase_name": "defense-evasion"\n",
+       "        }\n",
+       "    ],\n",
+       "    "external_references": [\n",
+       "        {\n",
+       "            "source_name": "mitre-attack",\n",
+       "            "url": "https://attack.mitre.org/wiki/Technique/T1066",\n",
+       "            "external_id": "T1066"\n",
+       "        }\n",
+       "    ],\n",
+       "    "object_marking_refs": [\n",
+       "        "marking-definition--fa42a846-8d90-4e51-bc29-71d5b4802168"\n",
+       "    ]\n",
+       "}\n",
+       "
\n" + ], + "text/plain": [ + "" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" } ], "source": [ "from stix2 import FileSystemSource\n", - "\"\"\"\n", - "Working with FileSystemSource for retrieving STIX content.\n", - "\"\"\"\n", "\n", "# create FileSystemSource\n", - "fs_source = FileSystemSource(\"/home/michael/Desktop/sample_stix2_data\")\n", + "fs_source = FileSystemSource(\"/tmp/stix2_source\")\n", "\n", "# retrieve STIX 2 objects\n", "ap = fs_source.get(\"attack-pattern--00d0b012-8a03-410e-95de-5826bf542de6\")\n", @@ -279,149 +425,336 @@ }, { "cell_type": "code", - "execution_count": 5, + "execution_count": 7, "metadata": {}, "outputs": [ { - "name": "stdout", - "output_type": "stream", - "text": [ - "{\n", - " \"type\": \"malware\",\n", - " \"id\": \"malware--0f862b01-99da-47cc-9bdb-db4a86a95bb1\",\n", - " \"created_by_ref\": \"identity--c78cb6e5-0c4b-4611-8297-d1b8b55e40b5\",\n", - " \"created\": \"2017-05-31T21:32:54.772Z\",\n", - " \"modified\": \"2017-05-31T21:32:54.772Z\",\n", - " \"name\": \"Emissary\",\n", - " \"description\": \"Emissary is a Trojan that has been used by Lotus Blossom. It shares code with Elise, with both Trojans being part of a malware group referred to as LStudio.[[Citation: Lotus Blossom Dec 2015]]\",\n", - " \"labels\": [\n", - " \"malware\"\n", - " ],\n", - " \"external_references\": [\n", - " {\n", - " \"source_name\": \"mitre-attack\",\n", - " \"url\": \"https://attack.mitre.org/wiki/Software/S0082\",\n", - " \"external_id\": \"S0082\"\n", - " },\n", - " {\n", - " \"source_name\": \"Lotus Blossom Dec 2015\",\n", - " \"description\": \"Falcone, R. and Miller-Osborn, J.. (2015, December 18). Attack on French Diplomat Linked to Operation Lotus Blossom. Retrieved February 15, 2016.\",\n", - " \"url\": \"http://researchcenter.paloaltonetworks.com/2015/12/attack-on-french-diplomat-linked-to-operation-lotus-blossom/\"\n", - " }\n", - " ],\n", - " \"object_marking_refs\": [\n", - " \"marking-definition--fa42a846-8d90-4e51-bc29-71d5b4802168\"\n", - " ]\n", - "}\n", - "{\n", - " \"type\": \"malware\",\n", - " \"id\": \"malware--2a6f4c7b-e690-4cc7-ab6b-1f821fb6b80b\",\n", - " \"created_by_ref\": \"identity--c78cb6e5-0c4b-4611-8297-d1b8b55e40b5\",\n", - " \"created\": \"2017-05-31T21:32:33.348Z\",\n", - " \"modified\": \"2017-05-31T21:32:33.348Z\",\n", - " \"name\": \"LOWBALL\",\n", - " \"description\": \"LOWBALL is malware used by admin@338. It was used in August 2015 in email messages targeting Hong Kong-based media organizations.[[Citation: FireEye admin@338]]\",\n", - " \"labels\": [\n", - " \"malware\"\n", - " ],\n", - " \"external_references\": [\n", - " {\n", - " \"source_name\": \"mitre-attack\",\n", - " \"url\": \"https://attack.mitre.org/wiki/Software/S0042\",\n", - " \"external_id\": \"S0042\"\n", - " },\n", - " {\n", - " \"source_name\": \"FireEye admin@338\",\n", - " \"description\": \"FireEye Threat Intelligence. (2015, December 1). China-based Cyber Threat Group Uses Dropbox for Malware Communications and Targets Hong Kong Media Outlets. Retrieved December 4, 2015.\",\n", - " \"url\": \"https://www.fireeye.com/blog/threat-research/2015/11/china-based-threat.html\"\n", - " }\n", - " ],\n", - " \"object_marking_refs\": [\n", - " \"marking-definition--fa42a846-8d90-4e51-bc29-71d5b4802168\"\n", - " ]\n", - "}\n", - "{\n", - " \"type\": \"malware\",\n", - " \"id\": \"malware--00c3bfcb-99bd-4767-8c03-b08f585f5c8a\",\n", - " \"created_by_ref\": \"identity--c78cb6e5-0c4b-4611-8297-d1b8b55e40b5\",\n", - " \"created\": \"2017-05-31T21:33:19.746Z\",\n", - " \"modified\": \"2017-05-31T21:33:19.746Z\",\n", - " \"name\": \"PowerDuke\",\n", - " \"description\": \"PowerDuke is a backdoor that was used by APT29 in 2016. It has primarily been delivered through Microsoft Word or Excel attachments containing malicious macros.[[Citation: Volexity PowerDuke November 2016]]\",\n", - " \"labels\": [\n", - " \"malware\"\n", - " ],\n", - " \"external_references\": [\n", - " {\n", - " \"source_name\": \"mitre-attack\",\n", - " \"url\": \"https://attack.mitre.org/wiki/Software/S0139\",\n", - " \"external_id\": \"S0139\"\n", - " },\n", - " {\n", - " \"source_name\": \"Volexity PowerDuke November 2016\",\n", - " \"description\": \"Adair, S.. (2016, November 9). PowerDuke: Widespread Post-Election Spear Phishing Campaigns Targeting Think Tanks and NGOs. Retrieved January 11, 2017.\",\n", - " \"url\": \"https://www.volexity.com/blog/2016/11/09/powerduke-post-election-spear-phishing-campaigns-targeting-think-tanks-and-ngos/\"\n", - " }\n", - " ],\n", - " \"object_marking_refs\": [\n", - " \"marking-definition--fa42a846-8d90-4e51-bc29-71d5b4802168\"\n", - " ]\n", - "}\n", - "{\n", - " \"type\": \"malware\",\n", - " \"id\": \"malware--0db09158-6e48-4e7c-8ce7-2b10b9c0c039\",\n", - " \"created_by_ref\": \"identity--c78cb6e5-0c4b-4611-8297-d1b8b55e40b5\",\n", - " \"created\": \"2017-05-31T21:32:55.126Z\",\n", - " \"modified\": \"2017-05-31T21:32:55.126Z\",\n", - " \"name\": \"Misdat\",\n", - " \"description\": \"Misdat is a backdoor that was used by Dust Storm from 2010 to 2011.[[Citation: Cylance Dust Storm]]\",\n", - " \"labels\": [\n", - " \"malware\"\n", - " ],\n", - " \"external_references\": [\n", - " {\n", - " \"source_name\": \"mitre-attack\",\n", - " \"url\": \"https://attack.mitre.org/wiki/Software/S0083\",\n", - " \"external_id\": \"S0083\"\n", - " },\n", - " {\n", - " \"source_name\": \"Cylance Dust Storm\",\n", - " \"description\": \"Gross, J. (2016, February 23). Operation Dust Storm. Retrieved February 25, 2016.\",\n", - " \"url\": \"https://www.cylance.com/hubfs/2015%20cylance%20website/assets/operation-dust-storm/Op%20Dust%20Storm%20Report.pdf?t=1456259131512\"\n", - " }\n", - " ],\n", - " \"object_marking_refs\": [\n", - " \"marking-definition--fa42a846-8d90-4e51-bc29-71d5b4802168\"\n", - " ]\n", - "}\n", - "{\n", - " \"type\": \"malware\",\n", - " \"id\": \"malware--1d808f62-cf63-4063-9727-ff6132514c22\",\n", - " \"created_by_ref\": \"identity--c78cb6e5-0c4b-4611-8297-d1b8b55e40b5\",\n", - " \"created\": \"2017-05-31T21:33:06.433Z\",\n", - " \"modified\": \"2017-05-31T21:33:06.433Z\",\n", - " \"name\": \"WEBC2\",\n", - " \"description\": \"WEBC2 is a backdoor used by APT1 to retrieve a Web page from a predetermined C2 server.[[Citation: Mandiant APT1 Appendix]]\",\n", - " \"labels\": [\n", - " \"malware\"\n", - " ],\n", - " \"external_references\": [\n", - " {\n", - " \"source_name\": \"mitre-attack\",\n", - " \"url\": \"https://attack.mitre.org/wiki/Software/S0109\",\n", - " \"external_id\": \"S0109\"\n", - " },\n", - " {\n", - " \"source_name\": \"Mandiant APT1 Appendix\",\n", - " \"description\": \"Mandiant. (n.d.). Appendix C (Digital) - The Malware Arsenal. Retrieved July 18, 2016.\",\n", - " \"url\": \"https://www.fireeye.com/content/dam/fireeye-www/services/pdfs/mandiant-apt1-report-appendix.zip\"\n", - " }\n", - " ],\n", - " \"object_marking_refs\": [\n", - " \"marking-definition--fa42a846-8d90-4e51-bc29-71d5b4802168\"\n", - " ]\n", - "}\n" - ] + "data": { + "text/html": [ + "
malware--96b08451-b27a-4ff6-893f-790e26393a8e\n",
+       "
\n" + ], + "text/plain": [ + "" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + }, + { + "data": { + "text/html": [ + "
malware--b42378e0-f147-496f-992a-26a49705395b\n",
+       "
\n" + ], + "text/plain": [ + "" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + }, + { + "data": { + "text/html": [ + "
malware--6b616fc1-1505-48e3-8b2c-0d19337bff38\n",
+       "
\n" + ], + "text/plain": [ + "" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + }, + { + "data": { + "text/html": [ + "
malware--92ec0cbd-2c30-44a2-b270-73f4ec949841\n",
+       "
\n" + ], + "text/plain": [ + "" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" } ], "source": [ @@ -434,46 +767,95 @@ "mals = fs_source.query(query)\n", "\n", "for mal in mals:\n", - " print(mal)" + " print(mal.id)" ] }, { "cell_type": "code", - "execution_count": 6, + "execution_count": 8, "metadata": {}, "outputs": [ { - "name": "stdout", - "output_type": "stream", - "text": [ - "{\n", - " \"type\": \"malware\",\n", - " \"id\": \"malware--00c3bfcb-99bd-4767-8c03-b08f585f5c8a\",\n", - " \"created_by_ref\": \"identity--c78cb6e5-0c4b-4611-8297-d1b8b55e40b5\",\n", - " \"created\": \"2017-05-31T21:33:19.746Z\",\n", - " \"modified\": \"2017-05-31T21:33:19.746Z\",\n", - " \"name\": \"PowerDuke\",\n", - " \"description\": \"PowerDuke is a backdoor that was used by APT29 in 2016. It has primarily been delivered through Microsoft Word or Excel attachments containing malicious macros.[[Citation: Volexity PowerDuke November 2016]]\",\n", - " \"labels\": [\n", - " \"malware\"\n", - " ],\n", - " \"external_references\": [\n", - " {\n", - " \"source_name\": \"mitre-attack\",\n", - " \"url\": \"https://attack.mitre.org/wiki/Software/S0139\",\n", - " \"external_id\": \"S0139\"\n", - " },\n", - " {\n", - " \"source_name\": \"Volexity PowerDuke November 2016\",\n", - " \"description\": \"Adair, S.. (2016, November 9). PowerDuke: Widespread Post-Election Spear Phishing Campaigns Targeting Think Tanks and NGOs. Retrieved January 11, 2017.\",\n", - " \"url\": \"https://www.volexity.com/blog/2016/11/09/powerduke-post-election-spear-phishing-campaigns-targeting-think-tanks-and-ngos/\"\n", - " }\n", - " ],\n", - " \"object_marking_refs\": [\n", - " \"marking-definition--fa42a846-8d90-4e51-bc29-71d5b4802168\"\n", - " ]\n", - "}\n" - ] + "data": { + "text/html": [ + "
malware--92ec0cbd-2c30-44a2-b270-73f4ec949841\n",
+       "
\n" + ], + "text/plain": [ + "" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" } ], "source": [ @@ -484,30 +866,28 @@ "\n", "# for visual purposes\n", "for mal in mals:\n", - " print(mal)" + " print(mal.id)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "#### FileSystemSink - (if STIX content is only to be pushed to FileSystem)" + "#### FileSystemSink\n", + "\n", + "Use the FileSystemSink when you only want to push STIX content to the file system." ] }, { "cell_type": "code", - "execution_count": 7, - "metadata": { - "collapsed": true - }, + "execution_count": 10, + "metadata": {}, "outputs": [], "source": [ - "from stix2 import FileSystemSink, Campaign\n", - "\"\"\"\n", - "Working with FileSystemSink for pushing STIX content.\n", - "\"\"\"\n", + "from stix2 import FileSystemSink, Campaign, Indicator\n", + "\n", "# create FileSystemSink\n", - "fs_sink = FileSystemSink(\"/home/michael/Desktop/sample_stix2_data\")\n", + "fs_sink = FileSystemSink(\"/tmp/stix2_sink\")\n", "\n", "# create STIX objects and add to sink\n", "camp = Campaign(name=\"The Crusades\",\n", @@ -532,21 +912,21 @@ ], "metadata": { "kernelspec": { - "display_name": "Python 2", + "display_name": "Python 3", "language": "python", - "name": "python2" + "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", - "version": 2 + "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", - "pygments_lexer": "ipython2", - "version": "2.7.12" + "pygments_lexer": "ipython3", + "version": "3.6.3" } }, "nbformat": 4, diff --git a/docs/guide/markings.ipynb b/docs/guide/markings.ipynb index fcacf47..8230daf 100644 --- a/docs/guide/markings.ipynb +++ b/docs/guide/markings.ipynb @@ -2,9 +2,8 @@ "cells": [ { "cell_type": "code", - "execution_count": 1, + "execution_count": 6, "metadata": { - "collapsed": true, "nbsphinx": "hidden" }, "outputs": [], @@ -23,9 +22,8 @@ }, { "cell_type": "code", - "execution_count": 2, + "execution_count": 5, "metadata": { - "collapsed": true, "nbsphinx": "hidden" }, "outputs": [], @@ -33,23 +31,25 @@ "# JSON output syntax highlighting\n", "from __future__ import print_function\n", "from pygments import highlight\n", - "from pygments.lexers import JsonLexer\n", + "from pygments.lexers import JsonLexer, TextLexer\n", "from pygments.formatters import HtmlFormatter\n", - "from IPython.display import HTML\n", + "from IPython.display import display, HTML\n", + "from IPython.core.interactiveshell import InteractiveShell\n", "\n", - "original_print = print\n", + "InteractiveShell.ast_node_interactivity = \"all\"\n", "\n", "def json_print(inpt):\n", " string = str(inpt)\n", + " formatter = HtmlFormatter()\n", " if string[0] == '{':\n", - " formatter = HtmlFormatter()\n", - " return HTML('{}'.format(\n", - " formatter.get_style_defs('.highlight'),\n", - " highlight(string, JsonLexer(), formatter)))\n", + " lexer = JsonLexer()\n", " else:\n", - " original_print(inpt)\n", + " lexer = TextLexer()\n", + " return HTML('{}'.format(\n", + " formatter.get_style_defs('.highlight'),\n", + " highlight(string, lexer, formatter)))\n", "\n", - "print = json_print" + "globals()['print'] = json_print" ] }, { @@ -68,127 +68,127 @@ "To create an object with a (predefined) TLP marking to an object, just provide it as a keyword argument to the constructor. The TLP markings can easily be imported from python-stix2." ] }, - { - "cell_type": "code", - "execution_count": 3, - "metadata": {}, - "outputs": [ - { - "data": { - "text/html": [ - "
{\n",
-       "    "type": "indicator",\n",
-       "    "id": "indicator--65ff0082-bb92-4812-9b74-b144b858297f",\n",
-       "    "created": "2017-11-13T14:42:14.641Z",\n",
-       "    "modified": "2017-11-13T14:42:14.641Z",\n",
-       "    "pattern": "[file:hashes.md5 = 'd41d8cd98f00b204e9800998ecf8427e']",\n",
-       "    "valid_from": "2017-11-13T14:42:14.641818Z",\n",
-       "    "labels": [\n",
-       "        "malicious-activity"\n",
-       "    ],\n",
-       "    "object_marking_refs": [\n",
-       "        "marking-definition--f88d31f6-486f-44da-b317-01333bde0b82"\n",
-       "    ]\n",
-       "}\n",
-       "
\n" - ], - "text/plain": [ - "" - ] - }, - "execution_count": 3, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "from stix2 import Indicator, TLP_AMBER\n", - "\n", - "indicator = Indicator(labels=[\"malicious-activity\"],\n", - " pattern=\"[file:hashes.md5 = 'd41d8cd98f00b204e9800998ecf8427e']\",\n", - " object_marking_refs=TLP_AMBER)\n", - "print(indicator)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "If you’re creating your own marking (for example, a ``Statement`` marking), first create the statement marking:" - ] - }, { "cell_type": "code", "execution_count": 7, "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
{\n",
+       "    "type": "indicator",\n",
+       "    "id": "indicator--95a71cff-fad0-4ffb-a641-8a6eaa642290",\n",
+       "    "created": "2018-04-05T19:49:47.924Z",\n",
+       "    "modified": "2018-04-05T19:49:47.924Z",\n",
+       "    "pattern": "[file:hashes.md5 = 'd41d8cd98f00b204e9800998ecf8427e']",\n",
+       "    "valid_from": "2018-04-05T19:49:47.924708Z",\n",
+       "    "labels": [\n",
+       "        "malicious-activity"\n",
+       "    ],\n",
+       "    "object_marking_refs": [\n",
+       "        "marking-definition--f88d31f6-486f-44da-b317-01333bde0b82"\n",
+       "    ]\n",
+       "}\n",
+       "
\n" + ], + "text/plain": [ + "" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "from stix2 import Indicator, TLP_AMBER\n", + "\n", + "indicator = Indicator(labels=[\"malicious-activity\"],\n", + " pattern=\"[file:hashes.md5 = 'd41d8cd98f00b204e9800998ecf8427e']\",\n", + " object_marking_refs=TLP_AMBER)\n", + "print(indicator)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "If you’re creating your own marking (for example, a ``Statement`` marking), first create the statement marking:" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, "outputs": [ { "data": { @@ -263,8 +263,8 @@ ".highlight .vm { color: #19177C } /* Name.Variable.Magic */\n", ".highlight .il { color: #666666 } /* Literal.Number.Integer.Long */
{\n",
        "    "type": "marking-definition",\n",
-       "    "id": "marking-definition--d16f0975-c5dd-4b25-a41d-af4afcc5da92",\n",
-       "    "created": "2017-11-13T14:43:30.558058Z",\n",
+       "    "id": "marking-definition--13680b12-3d19-4b42-abe6-0d31effe5368",\n",
+       "    "created": "2018-04-05T19:49:53.98008Z",\n",
        "    "definition_type": "statement",\n",
        "    "definition": {\n",
        "        "statement": "Copyright 2017, Example Corp"\n",
@@ -276,7 +276,7 @@
        ""
       ]
      },
-     "execution_count": 7,
+     "execution_count": 8,
      "metadata": {},
      "output_type": "execute_result"
     }
@@ -300,7 +300,7 @@
   },
   {
    "cell_type": "code",
-   "execution_count": 5,
+   "execution_count": 9,
    "metadata": {},
    "outputs": [
     {
@@ -376,16 +376,16 @@
        ".highlight .vm { color: #19177C } /* Name.Variable.Magic */\n",
        ".highlight .il { color: #666666 } /* Literal.Number.Integer.Long */
{\n",
        "    "type": "indicator",\n",
-       "    "id": "indicator--526cda4e-6745-4cd6-852f-0750c6a79784",\n",
-       "    "created": "2017-10-04T14:43:09.586Z",\n",
-       "    "modified": "2017-10-04T14:43:09.586Z",\n",
+       "    "id": "indicator--7caeab49-2472-41bb-a988-2f990aea99bd",\n",
+       "    "created": "2018-04-05T19:49:55.763Z",\n",
+       "    "modified": "2018-04-05T19:49:55.763Z",\n",
+       "    "pattern": "[file:hashes.md5 = 'd41d8cd98f00b204e9800998ecf8427e']",\n",
+       "    "valid_from": "2018-04-05T19:49:55.763364Z",\n",
        "    "labels": [\n",
        "        "malicious-activity"\n",
        "    ],\n",
-       "    "pattern": "[file:hashes.md5 = 'd41d8cd98f00b204e9800998ecf8427e']",\n",
-       "    "valid_from": "2017-10-04T14:43:09.586133Z",\n",
        "    "object_marking_refs": [\n",
-       "        "marking-definition--030bb5c6-c5eb-4e9c-8e7a-b9aab08ded53"\n",
+       "        "marking-definition--13680b12-3d19-4b42-abe6-0d31effe5368"\n",
        "    ]\n",
        "}\n",
        "
\n" @@ -394,7 +394,7 @@ "" ] }, - "execution_count": 5, + "execution_count": 9, "metadata": {}, "output_type": "execute_result" } @@ -408,7 +408,7 @@ }, { "cell_type": "code", - "execution_count": 6, + "execution_count": 10, "metadata": {}, "outputs": [ { @@ -484,14 +484,14 @@ ".highlight .vm { color: #19177C } /* Name.Variable.Magic */\n", ".highlight .il { color: #666666 } /* Literal.Number.Integer.Long */
{\n",
        "    "type": "indicator",\n",
-       "    "id": "indicator--1505b789-fcd2-48ee-bea9-3b20627a4abd",\n",
-       "    "created": "2017-10-04T14:43:20.049Z",\n",
-       "    "modified": "2017-10-04T14:43:20.049Z",\n",
+       "    "id": "indicator--4eb21bbe-b8a9-4348-86cf-1ed52f9abdd7",\n",
+       "    "created": "2018-04-05T19:49:57.248Z",\n",
+       "    "modified": "2018-04-05T19:49:57.248Z",\n",
+       "    "pattern": "[file:hashes.md5 = 'd41d8cd98f00b204e9800998ecf8427e']",\n",
+       "    "valid_from": "2018-04-05T19:49:57.248658Z",\n",
        "    "labels": [\n",
        "        "malicious-activity"\n",
        "    ],\n",
-       "    "pattern": "[file:hashes.md5 = 'd41d8cd98f00b204e9800998ecf8427e']",\n",
-       "    "valid_from": "2017-10-04T14:43:20.049166Z",\n",
        "    "object_marking_refs": [\n",
        "        "marking-definition--f88d31f6-486f-44da-b317-01333bde0b82"\n",
        "    ]\n",
@@ -502,7 +502,7 @@
        ""
       ]
      },
-     "execution_count": 6,
+     "execution_count": 10,
      "metadata": {},
      "output_type": "execute_result"
     }
@@ -523,7 +523,7 @@
   },
   {
    "cell_type": "code",
-   "execution_count": 8,
+   "execution_count": 11,
    "metadata": {},
    "outputs": [
     {
@@ -599,9 +599,9 @@
        ".highlight .vm { color: #19177C } /* Name.Variable.Magic */\n",
        ".highlight .il { color: #666666 } /* Literal.Number.Integer.Long */
{\n",
        "    "type": "malware",\n",
-       "    "id": "malware--f7128008-f6ab-4d43-a8a2-a681651268f8",\n",
-       "    "created": "2017-11-13T14:43:34.857Z",\n",
-       "    "modified": "2017-11-13T14:43:34.857Z",\n",
+       "    "id": "malware--ef1eddbb-b5a5-47e0-b607-75b9870d8d91",\n",
+       "    "created": "2018-04-05T19:49:59.103Z",\n",
+       "    "modified": "2018-04-05T19:49:59.103Z",\n",
        "    "name": "Poison Ivy",\n",
        "    "description": "A ransomware related to ...",\n",
        "    "labels": [\n",
@@ -609,7 +609,7 @@
        "    ],\n",
        "    "granular_markings": [\n",
        "        {\n",
-       "            "marking_ref": "marking-definition--d16f0975-c5dd-4b25-a41d-af4afcc5da92",\n",
+       "            "marking_ref": "marking-definition--13680b12-3d19-4b42-abe6-0d31effe5368",\n",
        "            "selectors": [\n",
        "                "description"\n",
        "            ]\n",
@@ -628,7 +628,7 @@
        ""
       ]
      },
-     "execution_count": 8,
+     "execution_count": 11,
      "metadata": {},
      "output_type": "execute_result"
     }
@@ -661,7 +661,7 @@
   },
   {
    "cell_type": "code",
-   "execution_count": 8,
+   "execution_count": 12,
    "metadata": {},
    "outputs": [
     {
@@ -705,7 +705,7 @@
   },
   {
    "cell_type": "code",
-   "execution_count": 21,
+   "execution_count": 13,
    "metadata": {},
    "outputs": [
     {
@@ -781,17 +781,17 @@
        ".highlight .vm { color: #19177C } /* Name.Variable.Magic */\n",
        ".highlight .il { color: #666666 } /* Literal.Number.Integer.Long */
{\n",
        "    "type": "indicator",\n",
-       "    "id": "indicator--409a0b15-1108-4251-8aee-a08995976561",\n",
-       "    "created": "2017-10-04T14:42:54.685Z",\n",
-       "    "modified": "2017-10-04T15:03:46.599Z",\n",
+       "    "id": "indicator--95a71cff-fad0-4ffb-a641-8a6eaa642290",\n",
+       "    "created": "2018-04-05T19:49:47.924Z",\n",
+       "    "modified": "2018-04-05T19:50:03.387Z",\n",
+       "    "pattern": "[file:hashes.md5 = 'd41d8cd98f00b204e9800998ecf8427e']",\n",
+       "    "valid_from": "2018-04-05T19:49:47.924708Z",\n",
        "    "labels": [\n",
        "        "malicious-activity"\n",
        "    ],\n",
-       "    "pattern": "[file:hashes.md5 = 'd41d8cd98f00b204e9800998ecf8427e']",\n",
-       "    "valid_from": "2017-10-04T14:42:54.685184Z",\n",
        "    "object_marking_refs": [\n",
-       "        "marking-definition--f88d31f6-486f-44da-b317-01333bde0b82",\n",
-       "        "marking-definition--030bb5c6-c5eb-4e9c-8e7a-b9aab08ded53"\n",
+       "        "marking-definition--13680b12-3d19-4b42-abe6-0d31effe5368",\n",
+       "        "marking-definition--f88d31f6-486f-44da-b317-01333bde0b82"\n",
        "    ]\n",
        "}\n",
        "
\n" @@ -800,7 +800,7 @@ "" ] }, - "execution_count": 21, + "execution_count": 13, "metadata": {}, "output_type": "execute_result" } @@ -819,7 +819,7 @@ }, { "cell_type": "code", - "execution_count": 22, + "execution_count": 14, "metadata": {}, "outputs": [ { @@ -895,14 +895,14 @@ ".highlight .vm { color: #19177C } /* Name.Variable.Magic */\n", ".highlight .il { color: #666666 } /* Literal.Number.Integer.Long */
{\n",
        "    "type": "indicator",\n",
-       "    "id": "indicator--409a0b15-1108-4251-8aee-a08995976561",\n",
-       "    "created": "2017-10-04T14:42:54.685Z",\n",
-       "    "modified": "2017-10-04T15:03:54.290Z",\n",
+       "    "id": "indicator--95a71cff-fad0-4ffb-a641-8a6eaa642290",\n",
+       "    "created": "2018-04-05T19:49:47.924Z",\n",
+       "    "modified": "2018-04-05T19:50:05.109Z",\n",
+       "    "pattern": "[file:hashes.md5 = 'd41d8cd98f00b204e9800998ecf8427e']",\n",
+       "    "valid_from": "2018-04-05T19:49:47.924708Z",\n",
        "    "labels": [\n",
        "        "malicious-activity"\n",
        "    ],\n",
-       "    "pattern": "[file:hashes.md5 = 'd41d8cd98f00b204e9800998ecf8427e']",\n",
-       "    "valid_from": "2017-10-04T14:42:54.685184Z",\n",
        "    "object_marking_refs": [\n",
        "        "marking-definition--f88d31f6-486f-44da-b317-01333bde0b82"\n",
        "    ]\n",
@@ -913,7 +913,7 @@
        ""
       ]
      },
-     "execution_count": 22,
+     "execution_count": 14,
      "metadata": {},
      "output_type": "execute_result"
     }
@@ -932,7 +932,7 @@
   },
   {
    "cell_type": "code",
-   "execution_count": 23,
+   "execution_count": 15,
    "metadata": {},
    "outputs": [
     {
@@ -1008,17 +1008,17 @@
        ".highlight .vm { color: #19177C } /* Name.Variable.Magic */\n",
        ".highlight .il { color: #666666 } /* Literal.Number.Integer.Long */
{\n",
        "    "type": "indicator",\n",
-       "    "id": "indicator--409a0b15-1108-4251-8aee-a08995976561",\n",
-       "    "created": "2017-10-04T14:42:54.685Z",\n",
-       "    "modified": "2017-10-04T15:04:04.218Z",\n",
+       "    "id": "indicator--95a71cff-fad0-4ffb-a641-8a6eaa642290",\n",
+       "    "created": "2018-04-05T19:49:47.924Z",\n",
+       "    "modified": "2018-04-05T19:50:06.773Z",\n",
+       "    "pattern": "[file:hashes.md5 = 'd41d8cd98f00b204e9800998ecf8427e']",\n",
+       "    "valid_from": "2018-04-05T19:49:47.924708Z",\n",
        "    "labels": [\n",
        "        "malicious-activity"\n",
        "    ],\n",
-       "    "pattern": "[file:hashes.md5 = 'd41d8cd98f00b204e9800998ecf8427e']",\n",
-       "    "valid_from": "2017-10-04T14:42:54.685184Z",\n",
        "    "object_marking_refs": [\n",
-       "        "marking-definition--34098fce-860f-48ae-8e50-ebd3cc5e41da",\n",
-       "        "marking-definition--030bb5c6-c5eb-4e9c-8e7a-b9aab08ded53"\n",
+       "        "marking-definition--13680b12-3d19-4b42-abe6-0d31effe5368",\n",
+       "        "marking-definition--34098fce-860f-48ae-8e50-ebd3cc5e41da"\n",
        "    ]\n",
        "}\n",
        "
\n" @@ -1027,7 +1027,7 @@ "" ] }, - "execution_count": 23, + "execution_count": 15, "metadata": {}, "output_type": "execute_result" } @@ -1048,7 +1048,7 @@ }, { "cell_type": "code", - "execution_count": 12, + "execution_count": 16, "metadata": {}, "outputs": [ { @@ -1124,14 +1124,14 @@ ".highlight .vm { color: #19177C } /* Name.Variable.Magic */\n", ".highlight .il { color: #666666 } /* Literal.Number.Integer.Long */
{\n",
        "    "type": "indicator",\n",
-       "    "id": "indicator--409a0b15-1108-4251-8aee-a08995976561",\n",
-       "    "created": "2017-10-04T14:42:54.685Z",\n",
-       "    "modified": "2017-10-04T14:54:39.331Z",\n",
+       "    "id": "indicator--95a71cff-fad0-4ffb-a641-8a6eaa642290",\n",
+       "    "created": "2018-04-05T19:49:47.924Z",\n",
+       "    "modified": "2018-04-05T19:50:08.616Z",\n",
+       "    "pattern": "[file:hashes.md5 = 'd41d8cd98f00b204e9800998ecf8427e']",\n",
+       "    "valid_from": "2018-04-05T19:49:47.924708Z",\n",
        "    "labels": [\n",
        "        "malicious-activity"\n",
-       "    ],\n",
-       "    "pattern": "[file:hashes.md5 = 'd41d8cd98f00b204e9800998ecf8427e']",\n",
-       "    "valid_from": "2017-10-04T14:42:54.685184Z"\n",
+       "    ]\n",
        "}\n",
        "
\n" ], @@ -1139,7 +1139,7 @@ "" ] }, - "execution_count": 12, + "execution_count": 16, "metadata": {}, "output_type": "execute_result" } @@ -1167,17 +1167,17 @@ }, { "cell_type": "code", - "execution_count": 19, + "execution_count": 17, "metadata": {}, "outputs": [ { "data": { "text/plain": [ - "['marking-definition--34098fce-860f-48ae-8e50-ebd3cc5e41da',\n", - " 'marking-definition--030bb5c6-c5eb-4e9c-8e7a-b9aab08ded53']" + "['marking-definition--13680b12-3d19-4b42-abe6-0d31effe5368',\n", + " 'marking-definition--34098fce-860f-48ae-8e50-ebd3cc5e41da']" ] }, - "execution_count": 19, + "execution_count": 17, "metadata": {}, "output_type": "execute_result" } @@ -1195,7 +1195,7 @@ }, { "cell_type": "code", - "execution_count": 9, + "execution_count": 18, "metadata": {}, "outputs": [ { @@ -1204,7 +1204,7 @@ "['marking-definition--613f2e26-407d-48c7-9eca-b8e91df99dc9']" ] }, - "execution_count": 9, + "execution_count": 18, "metadata": {}, "output_type": "execute_result" } @@ -1224,7 +1224,7 @@ }, { "cell_type": "code", - "execution_count": 14, + "execution_count": 19, "metadata": {}, "outputs": [ { @@ -1233,7 +1233,7 @@ "['marking-definition--613f2e26-407d-48c7-9eca-b8e91df99dc9']" ] }, - "execution_count": 14, + "execution_count": 19, "metadata": {}, "output_type": "execute_result" } @@ -1251,7 +1251,7 @@ }, { "cell_type": "code", - "execution_count": 16, + "execution_count": 20, "metadata": {}, "outputs": [ { @@ -1260,7 +1260,7 @@ "True" ] }, - "execution_count": 16, + "execution_count": 20, "metadata": {}, "output_type": "execute_result" } @@ -1271,7 +1271,7 @@ }, { "cell_type": "code", - "execution_count": 17, + "execution_count": 21, "metadata": {}, "outputs": [ { @@ -1280,7 +1280,7 @@ "True" ] }, - "execution_count": 17, + "execution_count": 21, "metadata": {}, "output_type": "execute_result" } @@ -1291,7 +1291,7 @@ }, { "cell_type": "code", - "execution_count": 18, + "execution_count": 22, "metadata": { "scrolled": true }, @@ -1302,7 +1302,7 @@ "False" ] }, - "execution_count": 18, + "execution_count": 22, "metadata": {}, "output_type": "execute_result" } @@ -1314,21 +1314,21 @@ ], "metadata": { "kernelspec": { - "display_name": "Python 2", + "display_name": "Python 3", "language": "python", - "name": "python2" + "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", - "version": 2 + "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", - "pygments_lexer": "ipython2", - "version": "2.7.12" + "pygments_lexer": "ipython3", + "version": "3.6.3" } }, "nbformat": 4, diff --git a/docs/guide/memory.ipynb b/docs/guide/memory.ipynb index 79a8f33..6b6d5cb 100644 --- a/docs/guide/memory.ipynb +++ b/docs/guide/memory.ipynb @@ -4,7 +4,6 @@ "cell_type": "code", "execution_count": 1, "metadata": { - "collapsed": true, "nbsphinx": "hidden" }, "outputs": [], @@ -25,7 +24,6 @@ "cell_type": "code", "execution_count": 2, "metadata": { - "collapsed": true, "nbsphinx": "hidden" }, "outputs": [], @@ -33,23 +31,25 @@ "# JSON output syntax highlighting\n", "from __future__ import print_function\n", "from pygments import highlight\n", - "from pygments.lexers import JsonLexer\n", + "from pygments.lexers import JsonLexer, TextLexer\n", "from pygments.formatters import HtmlFormatter\n", - "from IPython.display import HTML\n", + "from IPython.display import display, HTML\n", + "from IPython.core.interactiveshell import InteractiveShell\n", "\n", - "original_print = print\n", + "InteractiveShell.ast_node_interactivity = \"all\"\n", "\n", "def json_print(inpt):\n", " string = str(inpt)\n", + " formatter = HtmlFormatter()\n", " if string[0] == '{':\n", - " formatter = HtmlFormatter()\n", - " return HTML('{}'.format(\n", - " formatter.get_style_defs('.highlight'),\n", - " highlight(string, JsonLexer(), formatter)))\n", + " lexer = JsonLexer()\n", " else:\n", - " original_print(inpt)\n", + " lexer = TextLexer()\n", + " return HTML('{}'.format(\n", + " formatter.get_style_defs('.highlight'),\n", + " highlight(string, lexer, formatter)))\n", "\n", - "print = json_print" + "globals()['print'] = json_print" ] }, { @@ -151,12 +151,12 @@ ".highlight .vm { color: #19177C } /* Name.Variable.Magic */\n", ".highlight .il { color: #666666 } /* Literal.Number.Integer.Long */
{\n",
        "    "type": "indicator",\n",
-       "    "id": "indicator--2f61e4e7-0891-4e09-b79a-66f5e594fec0",\n",
-       "    "created": "2017-11-17T17:01:31.590Z",\n",
-       "    "modified": "2017-11-17T17:01:31.590Z",\n",
+       "    "id": "indicator--41a960c7-a6d4-406d-9156-0069cb3bd40d",\n",
+       "    "created": "2018-04-05T19:50:41.222Z",\n",
+       "    "modified": "2018-04-05T19:50:41.222Z",\n",
        "    "description": "Crusades C2 implant",\n",
        "    "pattern": "[file:hashes.'SHA-256' = '54b7e05e39a59428743635242e4a867c932140a999f52a1e54fa7ee6a440c73b']",\n",
-       "    "valid_from": "2017-11-17T17:01:31.590939Z",\n",
+       "    "valid_from": "2018-04-05T19:50:41.222522Z",\n",
        "    "labels": [\n",
        "        "malicious-activity"\n",
        "    ]\n",
@@ -267,12 +267,12 @@
        ".highlight .vm { color: #19177C } /* Name.Variable.Magic */\n",
        ".highlight .il { color: #666666 } /* Literal.Number.Integer.Long */
{\n",
        "    "type": "indicator",\n",
-       "    "id": "indicator--ddb765ba-ff1e-4285-bf33-1f6d08f583d6",\n",
-       "    "created": "2017-11-17T17:01:31.799Z",\n",
-       "    "modified": "2017-11-17T17:01:31.799Z",\n",
+       "    "id": "indicator--ba2a7acb-a3ac-420b-9288-09988aa99408",\n",
+       "    "created": "2018-04-05T19:50:43.343Z",\n",
+       "    "modified": "2018-04-05T19:50:43.343Z",\n",
        "    "description": "Crusades stage 2 implant variant",\n",
        "    "pattern": "[file:hashes.'SHA-256' = '31a45e777e4d58b97f4c43e38006f8cd6580ddabc4037905b2fad734712b582c']",\n",
-       "    "valid_from": "2017-11-17T17:01:31.799228Z",\n",
+       "    "valid_from": "2018-04-05T19:50:43.343298Z",\n",
        "    "labels": [\n",
        "        "malicious-activity"\n",
        "    ]\n",
@@ -386,9 +386,9 @@
        ".highlight .vm { color: #19177C } /* Name.Variable.Magic */\n",
        ".highlight .il { color: #666666 } /* Literal.Number.Integer.Long */
{\n",
        "    "type": "malware",\n",
-       "    "id": "malware--e8170e70-522f-4ec3-aa22-afb55bfad0b0",\n",
-       "    "created": "2017-11-17T17:01:31.806Z",\n",
-       "    "modified": "2017-11-17T17:01:31.806Z",\n",
+       "    "id": "malware--9e9b87ce-2b2b-455a-8d5b-26384ccc8d52",\n",
+       "    "created": "2018-04-05T19:50:43.346Z",\n",
+       "    "modified": "2018-04-05T19:50:43.346Z",\n",
        "    "name": "Alexios",\n",
        "    "labels": [\n",
        "        "rootkit"\n",
@@ -412,120 +412,6 @@
     "print(mal)"
    ]
   },
-  {
-   "cell_type": "code",
-   "execution_count": 6,
-   "metadata": {},
-   "outputs": [
-    {
-     "data": {
-      "text/html": [
-       "
{\n",
-       "    "type": "report",\n",
-       "    "id": "report--2add14d6-bbf3-4308-bb8e-226d314a08e4",\n",
-       "    "created": "2017-05-08T18:34:08.042Z",\n",
-       "    "modified": "2017-05-08T18:34:08.042Z",\n",
-       "    "name": "The Crusades: Looking into the relentless infiltration of Israels digital infrastructure.",\n",
-       "    "published": "2017-05-08T10:24:11.011Z",\n",
-       "    "object_refs": [\n",
-       "        "malware--2daa14d6-cbf3-4308-bb8e-226d324a08e4"\n",
-       "    ],\n",
-       "    "labels": [\n",
-       "        "threat-report"\n",
-       "    ]\n",
-       "}\n",
-       "
\n" - ], - "text/plain": [ - "" - ] - }, - "execution_count": 6, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "from stix2 import Filter\n", - "\n", - "# add json formatted string to MemoryStore\n", - "# Again, would NOT manually create json-formatted string\n", - "# but taken as an output form from another source\n", - "report = '{\"type\": \"report\",\"id\": \"report--2add14d6-bbf3-4308-bb8e-226d314a08e4\",\"labels\": [\"threat-report\"], \"name\": \"The Crusades: Looking into the relentless infiltration of Israels digital infrastructure.\", \"published\": \"2017-05-08T10:24:11.011Z\", \"object_refs\":[\"malware--2daa14d6-cbf3-4308-bb8e-226d324a08e4\"], \"created\": \"2017-05-08T18:34:08.042Z\", \"modified\": \"2017-05-08T18:34:08.042Z\"}'\n", - "\n", - "mem.add(report)\n", - "\n", - "print(mem.get(\"report--2add14d6-bbf3-4308-bb8e-226d314a08e4\"))" - ] - }, { "cell_type": "markdown", "metadata": {}, @@ -610,17 +496,13 @@ ".highlight .vi { color: #19177C } /* Name.Variable.Instance */\n", ".highlight .vm { color: #19177C } /* Name.Variable.Magic */\n", ".highlight .il { color: #666666 } /* Literal.Number.Integer.Long */
{\n",
-       "    "type": "report",\n",
-       "    "id": "report--2add14d6-bbf3-4308-bb8e-226d314a08e4",\n",
-       "    "created": "2017-05-08T18:34:08.042Z",\n",
-       "    "modified": "2017-05-08T18:34:08.042Z",\n",
-       "    "name": "The Crusades: Looking into the relentless infiltration of Israels digital infrastructure.",\n",
-       "    "published": "2017-05-08T10:24:11.011Z",\n",
-       "    "object_refs": [\n",
-       "        "malware--2daa14d6-cbf3-4308-bb8e-226d324a08e4"\n",
-       "    ],\n",
+       "    "type": "malware",\n",
+       "    "id": "malware--9e9b87ce-2b2b-455a-8d5b-26384ccc8d52",\n",
+       "    "created": "2018-04-05T19:50:43.346Z",\n",
+       "    "modified": "2018-04-05T19:50:43.346Z",\n",
+       "    "name": "Alexios",\n",
        "    "labels": [\n",
-       "        "threat-report"\n",
+       "        "rootkit"\n",
        "    ]\n",
        "}\n",
        "
\n" @@ -643,30 +525,30 @@ "# load(add) STIX content from json file into MemoryStore\n", "mem_2.load_from_file(\"path_to_target_file.json\")\n", "\n", - "report = mem_2.get(\"report--2add14d6-bbf3-4308-bb8e-226d314a08e4\")\n", + "report = mem_2.get(\"malware--9e9b87ce-2b2b-455a-8d5b-26384ccc8d52\")\n", "\n", - "# for visualpurposes\n", + "# for visual purposes\n", "print(report)" ] } ], "metadata": { "kernelspec": { - "display_name": "cti-python-stix2", + "display_name": "Python 3", "language": "python", - "name": "cti-python-stix2" + "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", - "version": 2 + "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", - "pygments_lexer": "ipython2", - "version": "2.7.12" + "pygments_lexer": "ipython3", + "version": "3.6.3" } }, "nbformat": 4, diff --git a/docs/guide/parsing.ipynb b/docs/guide/parsing.ipynb index b3460b3..284125e 100644 --- a/docs/guide/parsing.ipynb +++ b/docs/guide/parsing.ipynb @@ -4,7 +4,6 @@ "cell_type": "code", "execution_count": 1, "metadata": { - "collapsed": true, "nbsphinx": "hidden" }, "outputs": [], @@ -25,7 +24,6 @@ "cell_type": "code", "execution_count": 2, "metadata": { - "collapsed": true, "nbsphinx": "hidden" }, "outputs": [], @@ -33,23 +31,25 @@ "# JSON output syntax highlighting\n", "from __future__ import print_function\n", "from pygments import highlight\n", - "from pygments.lexers import JsonLexer\n", + "from pygments.lexers import JsonLexer, TextLexer\n", "from pygments.formatters import HtmlFormatter\n", - "from IPython.display import HTML\n", + "from IPython.display import display, HTML\n", + "from IPython.core.interactiveshell import InteractiveShell\n", "\n", - "original_print = print\n", + "InteractiveShell.ast_node_interactivity = \"all\"\n", "\n", "def json_print(inpt):\n", " string = str(inpt)\n", + " formatter = HtmlFormatter()\n", " if string[0] == '{':\n", - " formatter = HtmlFormatter()\n", - " return HTML('{}'.format(\n", - " formatter.get_style_defs('.highlight'),\n", - " highlight(string, JsonLexer(), formatter)))\n", + " lexer = JsonLexer()\n", " else:\n", - " original_print(inpt)\n", + " lexer = TextLexer()\n", + " return HTML('{}'.format(\n", + " formatter.get_style_defs('.highlight'),\n", + " highlight(string, lexer, formatter)))\n", "\n", - "print = json_print" + "globals()['print'] = json_print" ] }, { @@ -70,15 +70,90 @@ }, { "cell_type": "code", - "execution_count": 10, + "execution_count": 3, "metadata": {}, "outputs": [ { - "name": "stdout", - "output_type": "stream", - "text": [ - "\n" - ] + "data": { + "text/html": [ + "
<class 'stix2.v20.sdo.ObservedData'>\n",
+       "
\n" + ], + "text/plain": [ + "" + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" }, { "data": { @@ -174,7 +249,7 @@ "" ] }, - "execution_count": 10, + "execution_count": 3, "metadata": {}, "output_type": "execute_result" } @@ -214,15 +289,90 @@ }, { "cell_type": "code", - "execution_count": 7, + "execution_count": 4, "metadata": {}, "outputs": [ { - "name": "stdout", - "output_type": "stream", - "text": [ - "\n" - ] + "data": { + "text/html": [ + "
<class 'stix2.v20.sdo.Identity'>\n",
+       "
\n" + ], + "text/plain": [ + "" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" }, { "data": { @@ -309,7 +459,7 @@ "" ] }, - "execution_count": 7, + "execution_count": 4, "metadata": {}, "output_type": "execute_result" } @@ -338,15 +488,90 @@ }, { "cell_type": "code", - "execution_count": 8, + "execution_count": 5, "metadata": {}, "outputs": [ { - "name": "stdout", - "output_type": "stream", - "text": [ - "\n" - ] + "data": { + "text/html": [ + "
<class 'stix2.v20.sdo.CourseOfAction'>\n",
+       "
\n" + ], + "text/plain": [ + "" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" }, { "data": { @@ -434,13 +659,13 @@ "" ] }, - "execution_count": 8, + "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ - "file_handle = open(\"/home/michael/cti-python-stix2/stix2/test/stix2_data/course-of-action/course-of-action--d9727aee-48b8-4fdb-89e2-4c49746ba4dd.json\")\n", + "file_handle = open(\"/tmp/stix2_store/course-of-action/course-of-action--d9727aee-48b8-4fdb-89e2-4c49746ba4dd.json\")\n", "\n", "obj = parse(file_handle)\n", "print(type(obj))\n", @@ -486,27 +711,27 @@ "\n", "# create TAXIICollectionSource\n", "colxn = Collection('http://taxii_url')\n", - "ts = TAXIICollectionSource(colxn, allow_custom=True)\n" + "ts = TAXIICollectionSource(colxn, allow_custom=True)" ] } ], "metadata": { "kernelspec": { - "display_name": "Python 2", + "display_name": "Python 3", "language": "python", - "name": "python2" + "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", - "version": 2 + "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", - "pygments_lexer": "ipython2", - "version": "2.7.12" + "pygments_lexer": "ipython3", + "version": "3.6.3" } }, "nbformat": 4, diff --git a/docs/guide/serializing.ipynb b/docs/guide/serializing.ipynb index 1046d9f..e58302e 100644 --- a/docs/guide/serializing.ipynb +++ b/docs/guide/serializing.ipynb @@ -31,23 +31,25 @@ "# JSON output syntax highlighting\n", "from __future__ import print_function\n", "from pygments import highlight\n", - "from pygments.lexers import JsonLexer\n", + "from pygments.lexers import JsonLexer, TextLexer\n", "from pygments.formatters import HtmlFormatter\n", - "from IPython.display import HTML\n", + "from IPython.display import display, HTML\n", + "from IPython.core.interactiveshell import InteractiveShell\n", "\n", - "original_print = print\n", + "InteractiveShell.ast_node_interactivity = \"all\"\n", "\n", "def json_print(inpt):\n", " string = str(inpt)\n", + " formatter = HtmlFormatter()\n", " if string[0] == '{':\n", - " formatter = HtmlFormatter()\n", - " return HTML('{}'.format(\n", - " formatter.get_style_defs('.highlight'),\n", - " highlight(string, JsonLexer(), formatter)))\n", + " lexer = JsonLexer()\n", " else:\n", - " original_print(inpt)\n", + " lexer = TextLexer()\n", + " return HTML('{}'.format(\n", + " formatter.get_style_defs('.highlight'),\n", + " highlight(string, lexer, formatter)))\n", "\n", - "print = json_print" + "globals()['print'] = json_print" ] }, { @@ -142,12 +144,12 @@ ".highlight .vm { color: #19177C } /* Name.Variable.Magic */\n", ".highlight .il { color: #666666 } /* Literal.Number.Integer.Long */
{\n",
        "    "type": "indicator",\n",
-       "    "id": "indicator--85773ceb-c768-45f6-bb04-b4d813809e48",\n",
-       "    "created": "2018-03-13T19:49:53.392Z",\n",
-       "    "modified": "2018-03-13T19:49:53.392Z",\n",
+       "    "id": "indicator--4336ace8-d985-413a-8e32-f749ba268dc3",\n",
+       "    "created": "2018-04-05T20:01:20.012Z",\n",
+       "    "modified": "2018-04-05T20:01:20.012Z",\n",
        "    "name": "File hash for malware variant",\n",
        "    "pattern": "[file:hashes.md5 = 'd41d8cd98f00b204e9800998ecf8427e']",\n",
-       "    "valid_from": "2018-03-13T19:49:53.392627Z",\n",
+       "    "valid_from": "2018-04-05T20:01:20.012209Z",\n",
        "    "labels": [\n",
        "        "malicious-activity"\n",
        "    ]\n",
@@ -256,7 +258,7 @@
        ".highlight .vg { color: #19177C } /* Name.Variable.Global */\n",
        ".highlight .vi { color: #19177C } /* Name.Variable.Instance */\n",
        ".highlight .vm { color: #19177C } /* Name.Variable.Magic */\n",
-       ".highlight .il { color: #666666 } /* Literal.Number.Integer.Long */
{"name": "File hash for malware variant", "labels": ["malicious-activity"], "pattern": "[file:hashes.md5 = 'd41d8cd98f00b204e9800998ecf8427e']", "type": "indicator", "id": "indicator--85773ceb-c768-45f6-bb04-b4d813809e48", "created": "2018-03-13T19:49:53.392Z", "modified": "2018-03-13T19:49:53.392Z", "valid_from": "2018-03-13T19:49:53.392627Z"}\n",
+       ".highlight .il { color: #666666 } /* Literal.Number.Integer.Long */
{"name": "File hash for malware variant", "labels": ["malicious-activity"], "pattern": "[file:hashes.md5 = 'd41d8cd98f00b204e9800998ecf8427e']", "type": "indicator", "id": "indicator--4336ace8-d985-413a-8e32-f749ba268dc3", "created": "2018-04-05T20:01:20.012Z", "modified": "2018-04-05T20:01:20.012Z", "valid_from": "2018-04-05T20:01:20.012209Z"}\n",
        "
\n" ], "text/plain": [ @@ -362,10 +364,10 @@ " ],\n", " "pattern": "[file:hashes.md5 = 'd41d8cd98f00b204e9800998ecf8427e']",\n", " "type": "indicator",\n", - " "id": "indicator--85773ceb-c768-45f6-bb04-b4d813809e48",\n", - " "created": "2018-03-13T19:49:53.392Z",\n", - " "modified": "2018-03-13T19:49:53.392Z",\n", - " "valid_from": "2018-03-13T19:49:53.392627Z"\n", + " "id": "indicator--4336ace8-d985-413a-8e32-f749ba268dc3",\n", + " "created": "2018-04-05T20:01:20.012Z",\n", + " "modified": "2018-04-05T20:01:20.012Z",\n", + " "valid_from": "2018-04-05T20:01:20.012209Z"\n", "}\n", "
\n" ], diff --git a/docs/guide/taxii.ipynb b/docs/guide/taxii.ipynb index 4045a98..4e81388 100644 --- a/docs/guide/taxii.ipynb +++ b/docs/guide/taxii.ipynb @@ -33,23 +33,25 @@ "# JSON output syntax highlighting\n", "from __future__ import print_function\n", "from pygments import highlight\n", - "from pygments.lexers import JsonLexer\n", + "from pygments.lexers import JsonLexer, TextLexer\n", "from pygments.formatters import HtmlFormatter\n", - "from IPython.display import HTML\n", + "from IPython.display import display, HTML\n", + "from IPython.core.interactiveshell import InteractiveShell\n", "\n", - "original_print = print\n", + "InteractiveShell.ast_node_interactivity = \"all\"\n", "\n", "def json_print(inpt):\n", " string = str(inpt)\n", + " formatter = HtmlFormatter()\n", " if string[0] == '{':\n", - " formatter = HtmlFormatter()\n", - " return HTML('{}'.format(\n", - " formatter.get_style_defs('.highlight'),\n", - " highlight(string, JsonLexer(), formatter)))\n", + " lexer = JsonLexer()\n", " else:\n", - " original_print(inpt)\n", + " lexer = TextLexer()\n", + " return HTML('{}'.format(\n", + " formatter.get_style_defs('.highlight'),\n", + " highlight(string, lexer, formatter)))\n", "\n", - "print = json_print" + "globals()['print'] = json_print" ] }, { diff --git a/docs/guide/ts_support.ipynb b/docs/guide/ts_support.ipynb index 6ceef99..2264eb5 100644 --- a/docs/guide/ts_support.ipynb +++ b/docs/guide/ts_support.ipynb @@ -23,9 +23,8 @@ }, { "cell_type": "code", - "execution_count": 2, + "execution_count": 1, "metadata": { - "collapsed": true, "nbsphinx": "hidden" }, "outputs": [], @@ -33,23 +32,25 @@ "# JSON output syntax highlighting\n", "from __future__ import print_function\n", "from pygments import highlight\n", - "from pygments.lexers import JsonLexer\n", + "from pygments.lexers import JsonLexer, TextLexer\n", "from pygments.formatters import HtmlFormatter\n", - "from IPython.display import HTML\n", + "from IPython.display import display, HTML\n", + "from IPython.core.interactiveshell import InteractiveShell\n", "\n", - "original_print = print\n", + "InteractiveShell.ast_node_interactivity = \"all\"\n", "\n", "def json_print(inpt):\n", " string = str(inpt)\n", + " formatter = HtmlFormatter()\n", " if string[0] == '{':\n", - " formatter = HtmlFormatter()\n", - " return HTML('{}'.format(\n", - " formatter.get_style_defs('.highlight'),\n", - " highlight(string, JsonLexer(), formatter)))\n", + " lexer = JsonLexer()\n", " else:\n", - " original_print(inpt)\n", + " lexer = TextLexer()\n", + " return HTML('{}'.format(\n", + " formatter.get_style_defs('.highlight'),\n", + " highlight(string, lexer, formatter)))\n", "\n", - "print = json_print" + "globals()['print'] = json_print" ] }, { @@ -236,7 +237,7 @@ }, { "cell_type": "code", - "execution_count": 3, + "execution_count": 2, "metadata": {}, "outputs": [ { @@ -328,7 +329,7 @@ "" ] }, - "execution_count": 3, + "execution_count": 2, "metadata": {}, "output_type": "execute_result" } @@ -396,21 +397,21 @@ ], "metadata": { "kernelspec": { - "display_name": "Python 2", + "display_name": "Python 3", "language": "python", - "name": "python2" + "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", - "version": 2 + "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", - "pygments_lexer": "ipython2", - "version": "2.7.12" + "pygments_lexer": "ipython3", + "version": "3.6.3" } }, "nbformat": 4, diff --git a/docs/guide/versioning.ipynb b/docs/guide/versioning.ipynb index fb3b866..6074d00 100644 --- a/docs/guide/versioning.ipynb +++ b/docs/guide/versioning.ipynb @@ -2,9 +2,8 @@ "cells": [ { "cell_type": "code", - "execution_count": 1, + "execution_count": 2, "metadata": { - "collapsed": true, "nbsphinx": "hidden" }, "outputs": [], @@ -23,9 +22,8 @@ }, { "cell_type": "code", - "execution_count": 2, + "execution_count": 3, "metadata": { - "collapsed": true, "nbsphinx": "hidden" }, "outputs": [], @@ -33,23 +31,25 @@ "# JSON output syntax highlighting\n", "from __future__ import print_function\n", "from pygments import highlight\n", - "from pygments.lexers import JsonLexer\n", + "from pygments.lexers import JsonLexer, TextLexer\n", "from pygments.formatters import HtmlFormatter\n", - "from IPython.display import HTML\n", + "from IPython.display import display, HTML\n", + "from IPython.core.interactiveshell import InteractiveShell\n", "\n", - "original_print = print\n", + "InteractiveShell.ast_node_interactivity = \"all\"\n", "\n", "def json_print(inpt):\n", " string = str(inpt)\n", + " formatter = HtmlFormatter()\n", " if string[0] == '{':\n", - " formatter = HtmlFormatter()\n", - " return HTML('{}'.format(\n", - " formatter.get_style_defs('.highlight'),\n", - " highlight(string, JsonLexer(), formatter)))\n", + " lexer = JsonLexer()\n", " else:\n", - " original_print(inpt)\n", + " lexer = TextLexer()\n", + " return HTML('{}'.format(\n", + " formatter.get_style_defs('.highlight'),\n", + " highlight(string, lexer, formatter)))\n", "\n", - "print = json_print" + "globals()['print'] = json_print" ] }, { @@ -68,7 +68,7 @@ }, { "cell_type": "code", - "execution_count": 3, + "execution_count": 4, "metadata": {}, "outputs": [ { @@ -144,15 +144,15 @@ ".highlight .vm { color: #19177C } /* Name.Variable.Magic */\n", ".highlight .il { color: #666666 } /* Literal.Number.Integer.Long */
{\n",
        "    "type": "indicator",\n",
-       "    "id": "indicator--92bb1ae4-db9c-4d6e-8ded-ef7280b4439a",\n",
+       "    "id": "indicator--dd052ff6-e404-444b-beb9-eae96d1e79ea",\n",
        "    "created": "2016-01-01T08:00:00.000Z",\n",
-       "    "modified": "2017-09-26T23:39:07.149Z",\n",
-       "    "labels": [\n",
-       "        "malicious-activity"\n",
-       "    ],\n",
+       "    "modified": "2018-04-05T20:02:51.161Z",\n",
        "    "name": "File hash for Foobar malware",\n",
        "    "pattern": "[file:hashes.md5 = 'd41d8cd98f00b204e9800998ecf8427e']",\n",
-       "    "valid_from": "2017-09-26T23:39:07.132129Z"\n",
+       "    "valid_from": "2018-04-05T20:02:51.138312Z",\n",
+       "    "labels": [\n",
+       "        "malicious-activity"\n",
+       "    ]\n",
        "}\n",
        "
\n" ], @@ -160,7 +160,7 @@ "" ] }, - "execution_count": 3, + "execution_count": 4, "metadata": {}, "output_type": "execute_result" } @@ -187,7 +187,7 @@ }, { "cell_type": "code", - "execution_count": 4, + "execution_count": 5, "metadata": { "scrolled": true }, @@ -216,7 +216,7 @@ }, { "cell_type": "code", - "execution_count": 5, + "execution_count": 6, "metadata": {}, "outputs": [ { @@ -292,16 +292,16 @@ ".highlight .vm { color: #19177C } /* Name.Variable.Magic */\n", ".highlight .il { color: #666666 } /* Literal.Number.Integer.Long */
{\n",
        "    "type": "indicator",\n",
-       "    "id": "indicator--92bb1ae4-db9c-4d6e-8ded-ef7280b4439a",\n",
+       "    "id": "indicator--dd052ff6-e404-444b-beb9-eae96d1e79ea",\n",
        "    "created": "2016-01-01T08:00:00.000Z",\n",
-       "    "modified": "2017-09-26T23:39:09.463Z",\n",
-       "    "labels": [\n",
-       "        "malicious-activity"\n",
-       "    ],\n",
+       "    "modified": "2018-04-05T20:02:54.704Z",\n",
        "    "name": "File hash for Foobar malware",\n",
        "    "pattern": "[file:hashes.md5 = 'd41d8cd98f00b204e9800998ecf8427e']",\n",
-       "    "valid_from": "2017-09-26T23:39:07.132129Z",\n",
-       "    "revoked": true\n",
+       "    "valid_from": "2018-04-05T20:02:51.138312Z",\n",
+       "    "revoked": true,\n",
+       "    "labels": [\n",
+       "        "malicious-activity"\n",
+       "    ]\n",
        "}\n",
        "
\n" ], @@ -309,7 +309,7 @@ "" ] }, - "execution_count": 5, + "execution_count": 6, "metadata": {}, "output_type": "execute_result" } @@ -322,21 +322,21 @@ ], "metadata": { "kernelspec": { - "display_name": "Python 2", + "display_name": "Python 3", "language": "python", - "name": "python2" + "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", - "version": 2 + "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", - "pygments_lexer": "ipython2", - "version": "2.7.12" + "pygments_lexer": "ipython3", + "version": "3.6.3" } }, "nbformat": 4, diff --git a/docs/guide/workbench.ipynb b/docs/guide/workbench.ipynb index 9cb099a..6594841 100644 --- a/docs/guide/workbench.ipynb +++ b/docs/guide/workbench.ipynb @@ -22,7 +22,7 @@ }, { "cell_type": "code", - "execution_count": 16, + "execution_count": 2, "metadata": { "nbsphinx": "hidden" }, @@ -31,20 +31,23 @@ "# JSON output syntax highlighting\n", "from __future__ import print_function\n", "from pygments import highlight\n", - "from pygments.lexers import JsonLexer\n", + "from pygments.lexers import JsonLexer, TextLexer\n", "from pygments.formatters import HtmlFormatter\n", - "from six.moves import builtins\n", "from IPython.display import display, HTML\n", + "from IPython.core.interactiveshell import InteractiveShell\n", + "\n", + "InteractiveShell.ast_node_interactivity = \"all\"\n", "\n", "def json_print(inpt):\n", " string = str(inpt)\n", + " formatter = HtmlFormatter()\n", " if string[0] == '{':\n", - " formatter = HtmlFormatter()\n", - " display(HTML('{}'.format(\n", - " formatter.get_style_defs('.highlight'),\n", - " highlight(string, JsonLexer(), formatter))))\n", + " lexer = JsonLexer()\n", " else:\n", - " builtins.print(inpt)\n", + " lexer = TextLexer()\n", + " return HTML('{}'.format(\n", + " formatter.get_style_defs('.highlight'),\n", + " highlight(string, lexer, formatter)))\n", "\n", "globals()['print'] = json_print" ] @@ -65,7 +68,7 @@ }, { "cell_type": "code", - "execution_count": 11, + "execution_count": 3, "metadata": {}, "outputs": [], "source": [ @@ -83,7 +86,7 @@ }, { "cell_type": "code", - "execution_count": 12, + "execution_count": 4, "metadata": { "scrolled": true }, @@ -141,17 +144,254 @@ }, { "cell_type": "code", - "execution_count": 18, + "execution_count": 7, "metadata": {}, "outputs": [ { - "name": "stdout", - "output_type": "stream", - "text": [ - "indicator--a932fcc6-e032-176c-126f-cb970a5a1ade\n", - "indicates\n", - "malware--fdd60b30-b67c-11e3-b0b9-f01faf20d111\n" - ] + "data": { + "text/html": [ + "
indicator--a932fcc6-e032-176c-126f-cb970a5a1ade\n",
+       "
\n" + ], + "text/plain": [ + "" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + }, + { + "data": { + "text/html": [ + "
indicates\n",
+       "
\n" + ], + "text/plain": [ + "" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + }, + { + "data": { + "text/html": [ + "
malware--fdd60b30-b67c-11e3-b0b9-f01faf20d111\n",
+       "
\n" + ], + "text/plain": [ + "" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" } ], "source": [ @@ -164,7 +404,7 @@ }, { "cell_type": "code", - "execution_count": 17, + "execution_count": 8, "metadata": {}, "outputs": [ { @@ -255,8 +495,9 @@ "" ] }, + "execution_count": 8, "metadata": {}, - "output_type": "display_data" + "output_type": "execute_result" } ], "source": [ @@ -274,7 +515,7 @@ }, { "cell_type": "code", - "execution_count": 5, + "execution_count": 9, "metadata": {}, "outputs": [ { @@ -366,7 +607,7 @@ "" ] }, - "execution_count": 5, + "execution_count": 9, "metadata": {}, "output_type": "execute_result" } @@ -388,7 +629,7 @@ }, { "cell_type": "code", - "execution_count": 4, + "execution_count": 10, "metadata": {}, "outputs": [], "source": [ @@ -405,7 +646,7 @@ }, { "cell_type": "code", - "execution_count": 5, + "execution_count": 11, "metadata": {}, "outputs": [], "source": [ @@ -421,15 +662,90 @@ }, { "cell_type": "code", - "execution_count": 9, + "execution_count": 12, "metadata": {}, "outputs": [ { - "name": "stdout", - "output_type": "stream", - "text": [ - "ACME Threat Intel Co.\n" - ] + "data": { + "text/html": [ + "
ACME Threat Intel Co.\n",
+       "
\n" + ], + "text/plain": [ + "" + ] + }, + "execution_count": 12, + "metadata": {}, + "output_type": "execute_result" } ], "source": [ From 1d06e642a4a9b5c202af20af87f3bd3cabaa2c6c Mon Sep 17 00:00:00 2001 From: Chris Lenk Date: Mon, 9 Apr 2018 09:55:29 -0400 Subject: [PATCH 34/61] Bump and pin nbsphinx version --- requirements.txt | 2 +- stix2/workbench.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/requirements.txt b/requirements.txt index d6abb63..32e08f2 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,6 +1,6 @@ bumpversion ipython -nbsphinx>=0.3.0 +nbsphinx==0.3.2 pre-commit pytest pytest-cov diff --git a/stix2/workbench.py b/stix2/workbench.py index 9e31b50..b47968e 100644 --- a/stix2/workbench.py +++ b/stix2/workbench.py @@ -131,7 +131,7 @@ def _setup_workbench(): for obj_type in STIX_OBJS: new_class_dict = { '__new__': _constructor_wrapper(obj_type), - '__doc__': 'Workbench wrapper around the `{0} `__ object. {1}'.format(obj_type.__name__, STIX_OBJ_DOCS) + '__doc__': 'Workbench wrapper around the `{0} `__ object. {1}'.format(obj_type.__name__, STIX_OBJ_DOCS) } new_class = type(obj_type.__name__, (), new_class_dict) From f83d9a56b56a77c505397f63efb68655ada80791 Mon Sep 17 00:00:00 2001 From: Chris Lenk Date: Mon, 9 Apr 2018 13:29:53 -0400 Subject: [PATCH 35/61] Clean up documentation --- docs/api_ref.rst | 2 +- docs/datastore_api.rst | 39 ------------------------------------- docs/guide.rst | 3 +++ docs/guide/creating.ipynb | 2 +- docs/guide/datastore.ipynb | 15 ++++++++++---- docs/guide/filesystem.ipynb | 12 ++++++------ docs/guide/parsing.ipynb | 10 +++++----- docs/guide/ts_support.ipynb | 6 +++--- docs/index.rst | 19 ++++++++++++++---- docs/overview.rst | 25 ++++++++++-------------- docs/roadmap.rst | 17 ---------------- stix2/datastore/__init__.py | 2 +- stix2/environment.py | 3 +++ stix2/utils.py | 4 ++-- stix2/v20/sdo.py | 3 ++- 15 files changed, 63 insertions(+), 99 deletions(-) delete mode 100644 docs/datastore_api.rst delete mode 100644 docs/roadmap.rst diff --git a/docs/api_ref.rst b/docs/api_ref.rst index ffc328c..dc66401 100644 --- a/docs/api_ref.rst +++ b/docs/api_ref.rst @@ -7,6 +7,6 @@ functions in the ``stix2`` API, as given by the package's docstrings. .. note:: All the classes and functions detailed in the pages below are importable directly from `stix2`. See also: - :ref:`How imports will work `. + :ref:`How imports work `. .. automodule:: stix2 diff --git a/docs/datastore_api.rst b/docs/datastore_api.rst deleted file mode 100644 index 5ecf09f..0000000 --- a/docs/datastore_api.rst +++ /dev/null @@ -1,39 +0,0 @@ -.. _datastore_api: - -DataStore API -============= - -.. warning:: - - The DataStore API is still in the planning stages and may be subject to - major changes. We encourage anyone with feedback to contact the maintainers - to help ensure the API meets a large variety of use cases. - -One prominent feature of python-stix2 will be an interface for connecting -different backend data stores containing STIX content. This will allow a uniform -interface for querying and saving STIX content, and allow higher level code to -be written without regard to the underlying data storage format. python-stix2 -will define the API and contain some default implementations of this API, but -developers are encouraged to write their own implementations. - -Potential functions of the API include: - -* get a STIX Object by ID (returns the most recent version). -* get all versions of a STIX object by ID. -* get all relationships involving a given object, and all related objects. -* save an object. -* query for objects that match certain criteria (query syntax TBD). - -For all queries, the API will include a "filter" interface that can be used to -either explicitly include or exclude results with certain criteria. For example, - -* only trust content from a set of object creators. -* exclude content from certain (untrusted) object creators. -* only include content with a confidence above a certain threshold (once - confidence is added to STIX). -* only return content that can be shared with external parties (in other words, - that has TLP:GREEN markings). - -Additionally, the python-stix2 library will contain a "composite" data store, -which implements the DataStore API while delegating functionality to one or more -"child" data stores. diff --git a/docs/guide.rst b/docs/guide.rst index 80d2fb3..b722be3 100644 --- a/docs/guide.rst +++ b/docs/guide.rst @@ -1,6 +1,9 @@ User's Guide ============ +This section of documentation contains guides and tutorials on how to use the +``stix2`` library. + .. toctree:: :glob: diff --git a/docs/guide/creating.ipynb b/docs/guide/creating.ipynb index d9464e7..61bbe15 100644 --- a/docs/guide/creating.ipynb +++ b/docs/guide/creating.ipynb @@ -377,7 +377,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "To update the properties of an object, see the [Versioning](guide/versioning.ipynb) section." + "To update the properties of an object, see the [Versioning](versioning.ipynb) section." ] }, { diff --git a/docs/guide/datastore.ipynb b/docs/guide/datastore.ipynb index 474c719..7d40930 100644 --- a/docs/guide/datastore.ipynb +++ b/docs/guide/datastore.ipynb @@ -58,9 +58,9 @@ "source": [ "# DataStore API\n", "\n", - "CTI Python STIX2 features a new interface for pulling and pushing STIX2 content. The new interface consists of [DataStore](../api/stix2.datastore.rst#stix2.datastore.DataStoreMixin), [DataSource](../api/stix2.datastore.rst#stix2.datastore.DataSource) and [DataSink](../api/stix2.datastore.rst#stix2.datastore.DataSink) constructs: a [DataSource](../api/stix2.datastore.rst#stix2.datastore.DataSource) for pulling STIX2 content, a [DataSink](../api/stix2.datastore.rst#stix2.datastore.DataSink) for pushing STIX2 content, and a [DataStore](../api/stix2.datastore.rst#stix2.datastore.DataStoreMixin) for both pulling and pushing.\n", + "The ``stix2`` library features an interface for pulling and pushing STIX 2 content. This interface consists of [DataStore](../api/stix2.datastore.rst#stix2.datastore.DataStoreMixin), [DataSource](../api/stix2.datastore.rst#stix2.datastore.DataSource) and [DataSink](../api/stix2.datastore.rst#stix2.datastore.DataSink) constructs: a [DataSource](../api/stix2.datastore.rst#stix2.datastore.DataSource) for pulling STIX 2 content, a [DataSink](../api/stix2.datastore.rst#stix2.datastore.DataSink) for pushing STIX 2 content, and a [DataStore](../api/stix2.datastore.rst#stix2.datastore.DataStoreMixin) for both pulling and pushing.\n", "\n", - "The DataStore, [DataSource](../api/stix2.datastore.rst#stix2.datastore.DataSource), [DataSink](../api/stix2.datastore.rst#stix2.datastore.DataSink) (collectively referred to as the \"DataStore suite\") APIs are not referenced directly by a user but are used as base classes, which are then subclassed by real DataStore suites. CTI Python STIX2 provides the DataStore suites of [FileSystem](../api/datastore/stix2.datastore.filesystem.rst), [Memory](../api/datastore/stix2.datastore.memory.rst), and [TAXII](../api/datastore/stix2.datastore.taxii.rst). Users are also encouraged to subclass the base classes and create their own custom DataStore suites." + "The DataStore, [DataSource](../api/stix2.datastore.rst#stix2.datastore.DataSource), [DataSink](../api/stix2.datastore.rst#stix2.datastore.DataSink) (collectively referred to as the \"DataStore suite\") APIs are not referenced directly by a user but are used as base classes, which are then subclassed by real DataStore suites. The ``stix2`` library provides the DataStore suites of [FileSystem](../api/datastore/stix2.datastore.filesystem.rst), [Memory](../api/datastore/stix2.datastore.memory.rst), and [TAXII](../api/datastore/stix2.datastore.taxii.rst). Users are also encouraged to subclass the base classes and create their own custom DataStore suites." ] }, { @@ -340,9 +340,16 @@ "source": [ "## Filters\n", "\n", - "The CTI Python STIX2 DataStore suites - [FileSystem](../api/datastore/stix2.datastore.filesystem.rst), [Memory](../api/datastore/stix2.datastore.memory.rst), and [TAXII](../api/datastore/stix2.datastore.taxii.rst) - all use the [Filters](../api/datastore/stix2.datastore.filters.rst) module to allow for the querying of STIX content. The basic functionality is that filters can be created and supplied everytime to calls to `query()`, and/or attached to a [DataStore](../api/stix2.datastore.rst#stix2.datastore.DataStoreMixin) so that every future query placed to that [DataStore](../api/stix2.datastore.rst#stix2.datastore.DataStoreMixin) is evaluated against the attached filters, supplemented with any further filters supplied with the query call. Attached filters can also be removed from [DataStores](../api/stix2.datastore.rst#stix2.datastore.DataStoreMixin).\n", + "The ``stix2`` DataStore suites - [FileSystem](../api/datastore/stix2.datastore.filesystem.rst), [Memory](../api/datastore/stix2.datastore.memory.rst), and [TAXII](../api/datastore/stix2.datastore.taxii.rst) - all use the [Filters](../api/datastore/stix2.datastore.filters.rst) module to allow for the querying of STIX content. Filters can be used to explicitly include or exclude results with certain criteria. For example:\n", "\n", - "Filters are very simple, as they consist of a field name, comparison operator and an object property value (i.e. value to compare to). All properties of STIX2 objects can be filtered on. In addition, TAXII2 Filtering parameters for fields can also be used in filters.\n", + "* only trust content from a set of object creators\n", + "* exclude content from certain (untrusted) object creators\n", + "* only include content with a confidence above a certain threshold (once confidence is added to STIX 2)\n", + "* only return content that can be shared with external parties (e.g. only content that has TLP:GREEN markings)\n", + "\n", + "Filters can be created and supplied with every call to `query()`, and/or attached to a [DataStore](../api/stix2.datastore.rst#stix2.datastore.DataStoreMixin) so that every future query placed to that [DataStore](../api/stix2.datastore.rst#stix2.datastore.DataStoreMixin) is evaluated against the attached filters, supplemented with any further filters supplied with the query call. Attached filters can also be removed from [DataStores](../api/stix2.datastore.rst#stix2.datastore.DataStoreMixin).\n", + "\n", + "Filters are very simple, as they consist of a field name, comparison operator and an object property value (i.e. value to compare to). All properties of STIX 2 objects can be filtered on. In addition, TAXII 2 Filtering parameters for fields can also be used in filters.\n", "\n", "TAXII2 filter fields:\n", "\n", diff --git a/docs/guide/filesystem.ipynb b/docs/guide/filesystem.ipynb index 28a1843..b3aca88 100644 --- a/docs/guide/filesystem.ipynb +++ b/docs/guide/filesystem.ipynb @@ -58,9 +58,9 @@ "source": [ "## FileSystem \n", "\n", - "The FileSystem suite contains [FileSystemStore](../api/datastore/stix2.datastore.filesystem.rst#stix2.datastore.filesystem.FileSystemStore), [FileSystemSource](../api/datastore/stix2.datastore.filesystem.rst#stix2.datastore.filesystem.FileSystemSource) and [FileSystemSink](../api/datastore/stix2.datastore.filesystem.rst#stix2.datastore.filesystem.FileSystemSink). Under the hood, all FileSystem objects point to a file directory (on disk) that contains STIX2 content. \n", + "The FileSystem suite contains [FileSystemStore](../api/datastore/stix2.datastore.filesystem.rst#stix2.datastore.filesystem.FileSystemStore), [FileSystemSource](../api/datastore/stix2.datastore.filesystem.rst#stix2.datastore.filesystem.FileSystemSource) and [FileSystemSink](../api/datastore/stix2.datastore.filesystem.rst#stix2.datastore.filesystem.FileSystemSink). Under the hood, all FileSystem objects point to a file directory (on disk) that contains STIX 2 content. \n", "\n", - "The directory and file structure of the intended STIX2 content should be:\n", + "The directory and file structure of the intended STIX 2 content should be:\n", "\n", "```\n", "stix2_content/\n", @@ -82,7 +82,7 @@ " /STIX2 Domain Object type\n", "```\n", "\n", - "The master STIX2 content directory contains subdirectories, each of which aligns to a STIX2 domain object type (i.e. \"attack-pattern\", \"campaign\", \"malware\", etc.). Within each STIX2 domain object subdirectory are JSON files that are STIX2 domain objects of the specified type. The name of the json files correspond to the ID of the STIX2 domain object found within that file. A real example of the FileSystem directory structure:\n", + "The master STIX 2 content directory contains subdirectories, each of which aligns to a STIX 2 domain object type (i.e. \"attack-pattern\", \"campaign\", \"malware\", etc.). Within each STIX 2 domain object subdirectory are JSON files that are STIX 2 domain objects of the specified type. The name of the json files correspond to the ID of the STIX 2 domain object found within that file. A real example of the FileSystem directory structure:\n", "\n", "```\n", "stix2_content/\n", @@ -107,13 +107,13 @@ " /vulnerability\n", "```\n", "\n", - "[FileSystemStore](../api/datastore/stix2.datastore.filesystem.rst#stix2.datastore.filesystem.FileSystemStore) is intended for use cases where STIX2 content is retrieved and pushed to the same file directory. As [FileSystemStore](../api/datastore/stix2.datastore.filesystem.rst#stix2.datastore.filesystem.FileSystemStore) is just a wrapper around a paired [FileSystemSource](../api/datastore/stix2.datastore.filesystem.rst#stix2.datastore.filesystem.FileSystemSource) and [FileSystemSink](../api/datastore/stix2.datastore.filesystem.rst#stix2.datastore.filesystem.FileSystemSink) that point the same file directory.\n", + "[FileSystemStore](../api/datastore/stix2.datastore.filesystem.rst#stix2.datastore.filesystem.FileSystemStore) is intended for use cases where STIX 2 content is retrieved and pushed to the same file directory. As [FileSystemStore](../api/datastore/stix2.datastore.filesystem.rst#stix2.datastore.filesystem.FileSystemStore) is just a wrapper around a paired [FileSystemSource](../api/datastore/stix2.datastore.filesystem.rst#stix2.datastore.filesystem.FileSystemSource) and [FileSystemSink](../api/datastore/stix2.datastore.filesystem.rst#stix2.datastore.filesystem.FileSystemSink) that point the same file directory.\n", "\n", - "For use cases where STIX2 content will only be retrieved or pushed, then a [FileSystemSource](../api/datastore/stix2.datastore.filesystem.rst#stix2.datastore.filesystem.FileSystemSource) and [FileSystemSink](../api/datastore/stix2.datastore.filesystem.rst#stix2.datastore.filesystem.FileSystemSink) can be used individually. They can also be used individually when STIX2 content will be retrieved from one distinct file directory and pushed to another.\n", + "For use cases where STIX 2 content will only be retrieved or pushed, then a [FileSystemSource](../api/datastore/stix2.datastore.filesystem.rst#stix2.datastore.filesystem.FileSystemSource) and [FileSystemSink](../api/datastore/stix2.datastore.filesystem.rst#stix2.datastore.filesystem.FileSystemSink) can be used individually. They can also be used individually when STIX 2 content will be retrieved from one distinct file directory and pushed to another.\n", "\n", "### FileSystem API\n", "\n", - "A note on [get()](../api/datastore/stix2.datastore.filesystem.rst#stix2.datastore.filesystem.FileSystemSource.get), [all_versions()](../api/datastore/stix2.datastore.filesystem.rst#stix2.datastore.filesystem.FileSystemSource.all_versions), and [query()](../api/datastore/stix2.datastore.filesystem.rst#stix2.datastore.filesystem.FileSystemSource.query): The format of the STIX2 content targeted by the FileSystem suite is JSON files. When the [FileSystemStore](../api/datastore/stix2.datastore.filesystem.rst#stix2.datastore.filesystem.FileSystemStore) retrieves STIX2 content (in JSON) from disk, it will attempt to parse the content into full-featured python-stix2 objects and returned as such. \n", + "A note on [get()](../api/datastore/stix2.datastore.filesystem.rst#stix2.datastore.filesystem.FileSystemSource.get), [all_versions()](../api/datastore/stix2.datastore.filesystem.rst#stix2.datastore.filesystem.FileSystemSource.all_versions), and [query()](../api/datastore/stix2.datastore.filesystem.rst#stix2.datastore.filesystem.FileSystemSource.query): The format of the STIX2 content targeted by the FileSystem suite is JSON files. When the [FileSystemStore](../api/datastore/stix2.datastore.filesystem.rst#stix2.datastore.filesystem.FileSystemStore) retrieves STIX 2 content (in JSON) from disk, it will attempt to parse the content into full-featured python-stix2 objects and returned as such. \n", "\n", "A note on [add()](../api/datastore/stix2.datastore.filesystem.rst#stix2.datastore.filesystem.FileSystemSink.add): When STIX content is added (pushed) to the file system, the STIX content can be supplied in the following forms: Python STIX objects, Python dictionaries (of valid STIX objects or Bundles), JSON-encoded strings (of valid STIX objects or Bundles), or a (Python) list of any of the previously listed types. Any of the previous STIX content forms will be converted to a STIX JSON object (in a STIX Bundle) and written to disk. \n", "\n", diff --git a/docs/guide/parsing.ipynb b/docs/guide/parsing.ipynb index 284125e..4bd026f 100644 --- a/docs/guide/parsing.ipynb +++ b/docs/guide/parsing.ipynb @@ -676,20 +676,20 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## Parsing Custom STIX Content" + "### Parsing Custom STIX Content" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "Parsing custom STIX objects and/or STIX objects with custom properties is also completed easily with [parse()](../api/stix2.core.rst#stix2.core.parse). Just supply the keyword argument *allow_custom=True*. When *allow_custom* is specified, [parse()](../api/stix2.core.rst#stix2.core.parse) will attempt to convert the supplied STIX content to known STIX2 domain objects and/or previously defined custom defined STIX2 objects. If the conversion cannot be completed (and *allow_custom* is specified), [parse()](../api/stix2.core.rst#stix2.core.parse) will treat the supplied STIX2 content as valid STIX2 objects and return them. **Warning: Specifying *allow_custom* may lead to critical errors if further processing (searching, filtering, modifying etc...) of the custom STIX2 content occurs where the custom STIX2 content supplied is not valid STIX2**. This is an axiomatic possibility as the STIX2 library cannot guarantee proper processing of unknown custom STIX2 objects that were explicitly flagged to be allowed, and thus may not be valid.\n", + "Parsing custom STIX objects and/or STIX objects with custom properties is also completed easily with [parse()](../api/stix2.core.rst#stix2.core.parse). Just supply the keyword argument ``allow_custom=True``. When ``allow_custom`` is specified, [parse()](../api/stix2.core.rst#stix2.core.parse) will attempt to convert the supplied STIX content to known STIX 2 domain objects and/or previously defined [custom STIX 2 objects](custom.ipynb). If the conversion cannot be completed (and ``allow_custom`` is specified), [parse()](../api/stix2.core.rst#stix2.core.parse) will treat the supplied STIX 2 content as valid STIX 2 objects and return them. **Warning: Specifying allow_custom may lead to critical errors if further processing (searching, filtering, modifying etc...) of the custom content occurs where the custom content supplied is not valid STIX 2**. This is an axiomatic possibility as the ``stix2`` library cannot guarantee proper processing of unknown custom STIX 2 objects that were explicitly flagged to be allowed, and thus may not be valid.\n", "\n", - "For examples on parsing STIX2 objects with custom STIX properties, see [Custom STIX Content:Custom Properties](custom.ipynb#Custom-Properties)\n", + "For examples of parsing STIX 2 objects with custom STIX properties, see [Custom STIX Content: Custom Properties](custom.ipynb#Custom-Properties)\n", "\n", - "For examples on parsing defined custom STIX2 objects, see [Custom STIX Content: Custom STIX Object Types](custom.ipynb#Custom-STIX-Object-Types)\n", + "For examples of parsing defined custom STIX 2 objects, see [Custom STIX Content: Custom STIX Object Types](custom.ipynb#Custom-STIX-Object-Types)\n", "\n", - "For the case where it is desired to retrieve STIX2 content from a source (e.g. file system, TAXII) that may possibly have custom STIX2 content unknown to the user, the user can create a STIX2 DataStore/Source with the flag *allow_custom=True*. As aforementioned this will configure the DataStore/Source to allow for unknown STIX2 content to be returned (albeit not converted to full STIX2 domain objects and properties); notable processing capabilites of the STIX2 library may be precluded by the unknown STIX2 content, if the content is not valid or actual STIX2 domain objects and properties." + "For retrieving STIX 2 content from a source (e.g. file system, TAXII) that may possibly have custom STIX 2 content unknown to the user, the user can create a STIX 2 DataStore/Source with the flag ``allow_custom=True``. As mentioned, this will configure the DataStore/Source to allow for unknown STIX 2 content to be returned (albeit not converted to full STIX 2 domain objects and properties); the ``stix2`` library may preclude processing the unknown content, if the content is not valid or actual STIX 2 domain objects and properties." ] }, { diff --git a/docs/guide/ts_support.ipynb b/docs/guide/ts_support.ipynb index 2264eb5..445e263 100644 --- a/docs/guide/ts_support.ipynb +++ b/docs/guide/ts_support.ipynb @@ -59,7 +59,7 @@ "source": [ "## Technical Specification Support\n", "\n", - "### How imports will work\n", + "### How imports work\n", "\n", "Imports can be used in different ways depending on the use case and support levels.\n", "\n", @@ -229,7 +229,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### How parsing will work\n", + "### How parsing works\n", "If the ``version`` positional argument is not provided. The data will be parsed using the latest version of STIX 2.X supported by the `stix2` library.\n", "\n", "You can lock your [parse()](../api/stix2.core.rst#stix2.core.parse) method to a specific STIX version by:" @@ -363,7 +363,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### How will custom content work\n", + "### How custom content works\n", "\n", "[CustomObject](../api/stix2.v20.sdo.rst#stix2.v20.sdo.CustomObject), [CustomObservable](../api/stix2.v20.observables.rst#stix2.v20.observables.CustomObservable), [CustomMarking](../api/stix2.v20.common.rst#stix2.v20.common.CustomMarking) and [CustomExtension](../api/stix2.v20.observables.rst#stix2.v20.observables.CustomExtension) must be registered explicitly by STIX version. This is a design decision since properties or requirements may change as the STIX Technical Specification advances.\n", "\n", diff --git a/docs/index.rst b/docs/index.rst index 62d07ff..dd39903 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -3,8 +3,21 @@ You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. -Welcome to stix2's documentation! -================================= +STIX 2 Python API Documentation +=============================== + +.. warning:: + + Prior to version 1.0, all APIs are considered unstable and subject to change. + +Welcome to the STIX 2 Python API's documentation. This library is designed to +help you work with STIX 2 content. For more information about STIX 2, see the +`website `_ of the OASIS Cyber Threat Intelligence +Technical Committee. + +Get started with an `overview `_ of the library, then take a look +at the `guides and tutorials `_ to see how to use it. For information +about a specific class or function, see the `API reference `_. .. toctree:: :maxdepth: 3 @@ -13,8 +26,6 @@ Welcome to stix2's documentation! overview guide api_ref - datastore_api - roadmap contributing diff --git a/docs/overview.rst b/docs/overview.rst index 0306a22..0396ee8 100644 --- a/docs/overview.rst +++ b/docs/overview.rst @@ -4,7 +4,7 @@ Overview Goals ----- -High level goals/principles of the python-stix2 library: +High level goals/principles of the Python ``stix2`` library: 1. It should be as easy as possible (but no easier!) to perform common tasks of producing, consuming, and processing STIX 2 content. @@ -17,22 +17,22 @@ Design Decisions ---------------- To accomplish these goals, and to incorporate lessons learned while developing -python-stix (for STIX 1.x), several decisions influenced the design of -python-stix2: +``python-stix`` (for STIX 1.x), several decisions influenced the design of the +``stix2`` library: 1. All data structures are immutable by default. In contrast to python-stix, where users would create an object and then assign attributes to it, in - python-stix2 all properties must be provided when creating the object. + ``stix2`` all properties must be provided when creating the object. 2. Where necessary, library objects should act like ``dict``'s. When treated as a ``str``, the JSON reprentation of the object should be used. 3. Core Python data types (including numeric types, ``datetime``) should be used when appropriate, and serialized to the correct format in JSON as specified - in the STIX 2.0 spec. + in the STIX 2 spec. Architecture ------------ -The `stix2` library APIs are divided into three logical layers, representing +The ``stix2`` library is divided into three logical layers, representing different levels of abstraction useful in different types of scripts and larger applications. It is possible to combine multiple layers in the same program, and the higher levels build on the layers below. @@ -41,7 +41,7 @@ and the higher levels build on the layers below. Object Layer ^^^^^^^^^^^^ -The lowest layer, **Object Layer**, is where Python objects representing STIX 2 +The lowest layer, the **Object Layer**, is where Python objects representing STIX 2 data types (such as SDOs, SROs, and Cyber Observable Objects, as well as non-top-level objects like External References, Kill Chain phases, and Cyber Observable extensions) are created, and can be serialized and deserialized @@ -57,8 +57,6 @@ not implemented as references between the Python objects themselves, but by simply having the same values in ``id`` and reference properties. There is no referential integrity maintained by the ``stix2`` library. -*This layer is mostly complete.* - Environment Layer ^^^^^^^^^^^^^^^^^ @@ -79,8 +77,7 @@ intelligence ecosystem. Each of these components can be used individually, or combined as part of an ``Environment``. These ``Environment`` objects allow different settings to be used by different users of a multi-user application (such as a web application). - -*This layer is mostly complete.* +For more information, check out `this Environment tutorial `_. Workbench Layer ^^^^^^^^^^^^^^^ @@ -89,9 +86,7 @@ The highest layer of the ``stix2`` APIs is the **Workbench Layer**, designed for a single user in a highly-interactive analytical environment (such as a `Jupyter Notebook `_). It builds on the lower layers of the API, while hiding most of their complexity. Unlike the other layers, this layer is -designed to be used directly by end users. For users who are comfortable with, +designed to be used directly by end users. For users who are comfortable with Python, the Workbench Layer makes it easy to quickly interact with STIX data from a variety of sources without needing to write and run one-off Python -scripts. - -*This layer is currently being developed.* +scripts. For more information, check out `this Workbench tutorial `_. diff --git a/docs/roadmap.rst b/docs/roadmap.rst deleted file mode 100644 index 7fb9d8b..0000000 --- a/docs/roadmap.rst +++ /dev/null @@ -1,17 +0,0 @@ -Development Roadmap -=================== - -.. warning:: - - Prior to version 1.0, all APIs are considered unstable and subject to - change. - -This is a list of (planned) features before version 1.0 is released. - -* Serialization of all STIX and Cyber Observable objects to JSON. -* De-serialization (parsing) of all STIX and Cyber Observable objects. -* APIs for versioning (revising and revoking) STIX objects. -* APIs for marking STIX objects and interpreting markings of STIX objects. -* :ref:`datastore_api`, providing a common interface for querying sources - of STIX content (such as objects in memory, on a filesystem, in a database, or - via a TAXII feed). diff --git a/stix2/datastore/__init__.py b/stix2/datastore/__init__.py index 442a242..4ca9d5f 100644 --- a/stix2/datastore/__init__.py +++ b/stix2/datastore/__init__.py @@ -1,4 +1,4 @@ -"""Python STIX 2.0 DataStore API +"""Python STIX 2.0 DataStore API. .. autosummary:: :toctree: datastore diff --git a/stix2/environment.py b/stix2/environment.py index e40e991..a456e95 100644 --- a/stix2/environment.py +++ b/stix2/environment.py @@ -1,3 +1,6 @@ +"""Python STIX 2.0 Environment API. +""" + import copy from .core import parse as _parse diff --git a/stix2/utils.py b/stix2/utils.py index 37ff166..9febd78 100644 --- a/stix2/utils.py +++ b/stix2/utils.py @@ -263,11 +263,11 @@ def get_class_hierarchy_names(obj): def remove_custom_stix(stix_obj): - """remove any custom STIX objects or properties + """Remove any custom STIX objects or properties. Warning: This function is a best effort utility, in that it will remove custom objects and properties based on the - type names; i.e. if "x-" prefixes object types, and "x_" + type names; i.e. if "x-" prefixes object types, and "x\\_" prefixes property types. According to the STIX2 spec, those naming conventions are a SHOULDs not MUSTs, meaning that valid custom STIX content may ignore those conventions diff --git a/stix2/v20/sdo.py b/stix2/v20/sdo.py index 7ccc3e3..060b9f0 100644 --- a/stix2/v20/sdo.py +++ b/stix2/v20/sdo.py @@ -1,4 +1,5 @@ -"""STIX 2.0 Domain Objects""" +"""STIX 2.0 Domain Objects. +""" from collections import OrderedDict From b851afba01e77ed972238a89fc3da1a32930067c Mon Sep 17 00:00:00 2001 From: Chris Lenk Date: Mon, 9 Apr 2018 14:58:52 -0400 Subject: [PATCH 36/61] Req. custom extension properties as list of tuples --- docs/guide/custom.ipynb | 8 +++---- stix2/test/test_custom.py | 50 +++++++++++++++++++++++---------------- stix2/v20/observables.py | 4 ++-- 3 files changed, 35 insertions(+), 27 deletions(-) diff --git a/docs/guide/custom.ipynb b/docs/guide/custom.ipynb index bc19749..e651084 100644 --- a/docs/guide/custom.ipynb +++ b/docs/guide/custom.ipynb @@ -1155,10 +1155,10 @@ "source": [ "from stix2 import File, CustomExtension\n", "\n", - "@CustomExtension(File, 'x-new-ext', {\n", - " 'property1': properties.StringProperty(required=True),\n", - " 'property2': properties.IntegerProperty(),\n", - "})\n", + "@CustomExtension(File, 'x-new-ext', [\n", + " ('property1', properties.StringProperty(required=True)),\n", + " ('property2', properties.IntegerProperty()),\n", + "])\n", "class NewExtension():\n", " pass\n", "\n", diff --git a/stix2/test/test_custom.py b/stix2/test/test_custom.py index cc8b32b..918c7f0 100644 --- a/stix2/test/test_custom.py +++ b/stix2/test/test_custom.py @@ -435,10 +435,10 @@ def test_observed_data_with_custom_observable_object(): assert ob_data.objects['0'].property1 == 'something' -@stix2.observables.CustomExtension(stix2.DomainName, 'x-new-ext', { - 'property1': stix2.properties.StringProperty(required=True), - 'property2': stix2.properties.IntegerProperty(), -}) +@stix2.observables.CustomExtension(stix2.DomainName, 'x-new-ext', [ + ('property1', stix2.properties.StringProperty(required=True)), + ('property2', stix2.properties.IntegerProperty()), +]) class NewExtension(): def __init__(self, property2=None, **kwargs): if property2 and property2 < 10: @@ -485,9 +485,9 @@ def test_custom_extension_invalid_observable(): class Foo(object): pass with pytest.raises(ValueError) as excinfo: - @stix2.observables.CustomExtension(Foo, 'x-new-ext', { - 'property1': stix2.properties.StringProperty(required=True), - }) + @stix2.observables.CustomExtension(Foo, 'x-new-ext', [ + ('property1', stix2.properties.StringProperty(required=True)), + ]) class FooExtension(): pass # pragma: no cover assert str(excinfo.value) == "'observable' must be a valid Observable class!" @@ -495,9 +495,9 @@ def test_custom_extension_invalid_observable(): class Bar(stix2.observables._Observable): pass with pytest.raises(ValueError) as excinfo: - @stix2.observables.CustomExtension(Bar, 'x-new-ext', { - 'property1': stix2.properties.StringProperty(required=True), - }) + @stix2.observables.CustomExtension(Bar, 'x-new-ext', [ + ('property1', stix2.properties.StringProperty(required=True)), + ]) class BarExtension(): pass assert "Unknown observable type" in str(excinfo.value) @@ -506,9 +506,9 @@ def test_custom_extension_invalid_observable(): class Baz(stix2.observables._Observable): _type = 'Baz' with pytest.raises(ValueError) as excinfo: - @stix2.observables.CustomExtension(Baz, 'x-new-ext', { - 'property1': stix2.properties.StringProperty(required=True), - }) + @stix2.observables.CustomExtension(Baz, 'x-new-ext', [ + ('property1', stix2.properties.StringProperty(required=True)), + ]) class BazExtension(): pass assert "Unknown observable type" in str(excinfo.value) @@ -520,21 +520,29 @@ def test_custom_extension_no_properties(): @stix2.observables.CustomExtension(stix2.DomainName, 'x-new-ext2', None) class BarExtension(): pass - assert "'properties' must be a dict!" in str(excinfo.value) + assert "Must supply a list, containing tuples." in str(excinfo.value) def test_custom_extension_empty_properties(): + with pytest.raises(ValueError) as excinfo: + @stix2.observables.CustomExtension(stix2.DomainName, 'x-new-ext2', []) + class BarExtension(): + pass + assert "Must supply a list, containing tuples." in str(excinfo.value) + + +def test_custom_extension_dict_properties(): with pytest.raises(ValueError) as excinfo: @stix2.observables.CustomExtension(stix2.DomainName, 'x-new-ext2', {}) class BarExtension(): pass - assert "'properties' must be a dict!" in str(excinfo.value) + assert "Must supply a list, containing tuples." in str(excinfo.value) def test_custom_extension_no_init_1(): - @stix2.observables.CustomExtension(stix2.DomainName, 'x-new-extension', { - 'property1': stix2.properties.StringProperty(required=True), - }) + @stix2.observables.CustomExtension(stix2.DomainName, 'x-new-extension', [ + ('property1', stix2.properties.StringProperty(required=True)), + ]) class NewExt(): pass @@ -543,9 +551,9 @@ def test_custom_extension_no_init_1(): def test_custom_extension_no_init_2(): - @stix2.observables.CustomExtension(stix2.DomainName, 'x-new-ext2', { - 'property1': stix2.properties.StringProperty(required=True), - }) + @stix2.observables.CustomExtension(stix2.DomainName, 'x-new-ext2', [ + ('property1', stix2.properties.StringProperty(required=True)), + ]) class NewExt2(object): pass diff --git a/stix2/v20/observables.py b/stix2/v20/observables.py index 83600b0..dc1289b 100644 --- a/stix2/v20/observables.py +++ b/stix2/v20/observables.py @@ -1034,8 +1034,8 @@ def CustomExtension(observable=None, type='x-custom-observable', properties=None 'extensions': ExtensionsProperty(enclosing_type=_type), } - if not isinstance(properties, dict) or not properties: - raise ValueError("'properties' must be a dict!") + if not properties or not isinstance(properties, list): + raise ValueError("Must supply a list, containing tuples. For example, [('property1', IntegerProperty())]") _properties.update(properties) From 5c5ca1f21cd4887db271bd7d97c975c962a909c0 Mon Sep 17 00:00:00 2001 From: Chris Lenk Date: Mon, 9 Apr 2018 15:18:29 -0400 Subject: [PATCH 37/61] Move 'extensions' property to custom Observables ... from custom Observable extensions (an extension doesn't need an 'extensions' property). --- stix2/test/test_custom.py | 5 +++++ stix2/v20/observables.py | 7 ++++--- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/stix2/test/test_custom.py b/stix2/test/test_custom.py index 918c7f0..a14503f 100644 --- a/stix2/test/test_custom.py +++ b/stix2/test/test_custom.py @@ -602,3 +602,8 @@ def test_register_custom_object(): stix2._register_type(CustomObject2) # Note that we will always check against newest OBJ_MAP. assert (CustomObject2._type, CustomObject2) in stix2.OBJ_MAP.items() + + +def test_extension_property_location(): + assert 'extensions' in stix2.v20.observables.OBJ_MAP_OBSERVABLE['x-new-observable']._properties + assert 'extensions' not in stix2.v20.observables.EXT_MAP['domain-name']['x-new-ext']._properties diff --git a/stix2/v20/observables.py b/stix2/v20/observables.py index dc1289b..39a8f19 100644 --- a/stix2/v20/observables.py +++ b/stix2/v20/observables.py @@ -979,6 +979,9 @@ def CustomObservable(type='x-custom-observable', properties=None): "is not a ListProperty containing ObjectReferenceProperty." % prop_name) _properties.update(properties) + _properties.update([ + ('extensions', ExtensionsProperty(enclosing_type=_type)), + ]) def __init__(self, **kwargs): _Observable.__init__(self, **kwargs) @@ -1030,9 +1033,7 @@ def CustomExtension(observable=None, type='x-custom-observable', properties=None class _Custom(cls, _Extension): _type = type - _properties = { - 'extensions': ExtensionsProperty(enclosing_type=_type), - } + _properties = OrderedDict() if not properties or not isinstance(properties, list): raise ValueError("Must supply a list, containing tuples. For example, [('property1', IntegerProperty())]") From b633fd37856ccd15257d7d6bae3223411a90e9ef Mon Sep 17 00:00:00 2001 From: Chris Lenk Date: Tue, 10 Apr 2018 12:54:27 -0400 Subject: [PATCH 38/61] WIP: Allow custom observables, extensions --- stix2/test/test_custom.py | 31 +++++++++++++++++++++++++++++++ stix2/v20/observables.py | 15 +++++++++++---- 2 files changed, 42 insertions(+), 4 deletions(-) diff --git a/stix2/test/test_custom.py b/stix2/test/test_custom.py index cc8b32b..a50819b 100644 --- a/stix2/test/test_custom.py +++ b/stix2/test/test_custom.py @@ -363,6 +363,7 @@ def test_parse_custom_observable_object(): }""" nt = stix2.parse_observable(nt_string, []) + assert isinstance(nt, stix2.core._STIXBase) assert nt.property1 == 'something' @@ -376,6 +377,32 @@ def test_parse_unregistered_custom_observable_object(): stix2.parse_observable(nt_string) assert "Can't parse unknown observable type" in str(excinfo.value) + parsed_custom = stix2.parse_observable(nt_string, allow_custom=True) + assert parsed_custom['property1'] == 'something' + with pytest.raises(AttributeError) as excinfo: + assert parsed_custom.property1 == 'something' + assert not isinstance(parsed_custom, stix2.core._STIXBase) + + +def test_parse_observed_data_with_custom_observable(): + input_str = """{ + "type": "observed-data", + "id": "observed-data--dc20c4ca-a2a3-4090-a5d5-9558c3af4758", + "created": "2016-04-06T19:58:16.000Z", + "modified": "2016-04-06T19:58:16.000Z", + "first_observed": "2015-12-21T19:00:00Z", + "last_observed": "2015-12-21T19:00:00Z", + "number_observed": 1, + "objects": { + "0": { + "type": "x-foobar-observable", + "property1": "something" + } + } + }""" + parsed = stix2.parse(input_str, allow_custom=True) + assert parsed.objects['0']['property1'] == 'something' + def test_parse_invalid_custom_observable_object(): nt_string = """{ @@ -585,6 +612,10 @@ def test_parse_observable_with_unregistered_custom_extension(): stix2.parse_observable(input_str) assert "Can't parse Unknown extension type" in str(excinfo.value) + parsed_ob = stix2.parse_observable(input_str, allow_custom=True) + assert parsed_ob['extensions']['x-foobar-ext']['property1'] == 'foo' + assert not isinstance(parsed_ob['extensions']['x-foobar-ext'], stix2.core._STIXBase) + def test_register_custom_object(): # Not the way to register custom object. diff --git a/stix2/v20/observables.py b/stix2/v20/observables.py index 83600b0..4449527 100644 --- a/stix2/v20/observables.py +++ b/stix2/v20/observables.py @@ -923,15 +923,22 @@ def parse_observable(data, _valid_refs=None, allow_custom=False): try: obj_class = OBJ_MAP_OBSERVABLE[obj['type']] except KeyError: + if allow_custom: + # flag allows for unknown custom objects too, but will not + # be parsed into STIX observable object, just returned as is + return obj raise ParseError("Can't parse unknown observable type '%s'! For custom observables, " "use the CustomObservable decorator." % obj['type']) if 'extensions' in obj and obj['type'] in EXT_MAP: for name, ext in obj['extensions'].items(): - if name not in EXT_MAP[obj['type']]: - raise ParseError("Can't parse Unknown extension type '%s' for observable type '%s'!" % (name, obj['type'])) - ext_class = EXT_MAP[obj['type']][name] - obj['extensions'][name] = ext_class(allow_custom=allow_custom, **obj['extensions'][name]) + try: + ext_class = EXT_MAP[obj['type']][name] + except KeyError: + if not allow_custom: + raise ParseError("Can't parse Unknown extension type '%s' for observable type '%s'!" % (name, obj['type'])) + else: # extension was found + obj['extensions'][name] = ext_class(allow_custom=allow_custom, **obj['extensions'][name]) return obj_class(allow_custom=allow_custom, **obj) From 27647091a5a59f91e86bf38490900f14964b5289 Mon Sep 17 00:00:00 2001 From: = Date: Wed, 11 Apr 2018 13:36:52 -0400 Subject: [PATCH 39/61] WIP - just at stash point --- stix2/datastore/__init__.py | 33 +++++++++++----------- stix2/datastore/filesystem.py | 25 ++++++----------- stix2/datastore/filters.py | 53 +++++++++++++++++++++++++++++++++++ stix2/datastore/memory.py | 20 ++++++------- stix2/datastore/taxii.py | 37 ++++++++++-------------- 5 files changed, 102 insertions(+), 66 deletions(-) diff --git a/stix2/datastore/__init__.py b/stix2/datastore/__init__.py index 78f7555..c43f309 100644 --- a/stix2/datastore/__init__.py +++ b/stix2/datastore/__init__.py @@ -16,7 +16,7 @@ import uuid from six import with_metaclass -from stix2.datastore.filters import Filter +from stix2.datastore.filters import Filter, FilterSet from stix2.utils import deduplicate @@ -220,13 +220,13 @@ class DataSource(with_metaclass(ABCMeta)): Attributes: id (str): A unique UUIDv4 to identify this DataSource. - filters (set): A collection of filters attached to this DataSource. + filters (FilterSet): A collection of filters attached to this DataSource. """ def __init__(self): super(DataSource, self).__init__() self.id = make_id() - self.filters = set() + self.filters = FilterSet() @abstractmethod def get(self, stix_id): @@ -420,7 +420,7 @@ class CompositeDataSource(DataSource): Args: stix_id (str): the id of the STIX object to retrieve. - _composite_filters (list): a list of filters passed from a + _composite_filters (FilterSet): a collection of filters passed from a CompositeDataSource (i.e. if this CompositeDataSource is attached to another parent CompositeDataSource), not user supplied. @@ -432,11 +432,12 @@ class CompositeDataSource(DataSource): raise AttributeError('CompositeDataSource has no data sources') all_data = [] - all_filters = set() - all_filters.update(self.filters) + all_filters = FilterSet() + + all_filters.add(self.filters) if _composite_filters: - all_filters.update(_composite_filters) + all_filters.add(_composite_filters) # for every configured Data Source, call its retrieve handler for ds in self.data_sources: @@ -466,7 +467,7 @@ class CompositeDataSource(DataSource): Args: stix_id (str): id of the STIX objects to retrieve. - _composite_filters (list): a list of filters passed from a + _composite_filters (FilterSet): a collection of filters passed from a CompositeDataSource (i.e. if this CompositeDataSource is attached to a parent CompositeDataSource), not user supplied. @@ -478,12 +479,12 @@ class CompositeDataSource(DataSource): raise AttributeError('CompositeDataSource has no data sources') all_data = [] - all_filters = set() + all_filters = FilterSet() - all_filters.update(self.filters) + all_filters.add(self.filters) if _composite_filters: - all_filters.update(_composite_filters) + all_filters.add(_composite_filters) # retrieve STIX objects from all configured data sources for ds in self.data_sources: @@ -505,7 +506,7 @@ class CompositeDataSource(DataSource): Args: query (list): list of filters to search on. - _composite_filters (list): a list of filters passed from a + _composite_filters (FilterSet): a collection of filters passed from a CompositeDataSource (i.e. if this CompositeDataSource is attached to a parent CompositeDataSource), not user supplied. @@ -517,17 +518,17 @@ class CompositeDataSource(DataSource): raise AttributeError('CompositeDataSource has no data sources') if not query: - # don't mess with the query (i.e. convert to a set, as that's done + # don't mess with the query (i.e. deduplicate, as that's done # within the specific DataSources that are called) query = [] all_data = [] + all_filters = FilterSet() - all_filters = set() - all_filters.update(self.filters) + all_filters.add(self.filters) if _composite_filters: - all_filters.update(_composite_filters) + all_filters.add(_composite_filters) # federate query to all attached data sources, # pass composite filters to id diff --git a/stix2/datastore/filesystem.py b/stix2/datastore/filesystem.py index a6f31cf..c13b02c 100644 --- a/stix2/datastore/filesystem.py +++ b/stix2/datastore/filesystem.py @@ -8,7 +8,7 @@ import os from stix2.core import Bundle, parse from stix2.datastore import DataSink, DataSource, DataStoreMixin -from stix2.datastore.filters import Filter, apply_common_filters +from stix2.datastore.filters import Filter, FilterSet, apply_common_filters from stix2.utils import deduplicate, get_class_hierarchy_names @@ -165,7 +165,7 @@ class FileSystemSource(DataSource): Args: stix_id (str): The STIX ID of the STIX object to be retrieved. - _composite_filters (set): set of filters passed from the parent + _composite_filters (FilterSet): collection of filters passed from the parent CompositeDataSource, not user supplied version (str): Which STIX2 version to use. (e.g. "2.0", "2.1"). If None, use latest version. @@ -195,7 +195,7 @@ class FileSystemSource(DataSource): Args: stix_id (str): The STIX ID of the STIX objects to be retrieved. - _composite_filters (set): set of filters passed from the parent + _composite_filters (FilterSet): collection of filters passed from the parent CompositeDataSource, not user supplied version (str): Which STIX2 version to use. (e.g. "2.0", "2.1"). If None, use latest version. @@ -217,7 +217,7 @@ class FileSystemSource(DataSource): Args: query (list): list of filters to search on - _composite_filters (set): set of filters passed from the + _composite_filters (FilterSet): collection of filters passed from the CompositeDataSource, not user supplied version (str): Which STIX2 version to use. (e.g. "2.0", "2.1"). If None, use latest version. @@ -231,20 +231,13 @@ class FileSystemSource(DataSource): all_data = [] - if query is None: - query = set() - else: - if not isinstance(query, list): - # make sure dont make set from a Filter object, - # need to make a set from a list of Filter objects (even if just one Filter) - query = [query] - query = set(query) + query = FilterSet(query) # combine all query filters if self.filters: - query.update(self.filters) + query.add(self.filters) if _composite_filters: - query.update(_composite_filters) + query.add(_composite_filters) # extract any filters that are for "type" or "id" , as we can then do # filtering before reading in the STIX objects. A STIX 'type' filter @@ -343,8 +336,8 @@ class FileSystemSource(DataSource): search space of a FileSystemStore (or FileSystemSink). """ - file_filters = set() + file_filters = [] for filter_ in query: if filter_.property == "id" or filter_.property == "type": - file_filters.add(filter_) + file_filters.append(filter_) return file_filters diff --git a/stix2/datastore/filters.py b/stix2/datastore/filters.py index 9065b61..0946694 100644 --- a/stix2/datastore/filters.py +++ b/stix2/datastore/filters.py @@ -17,6 +17,23 @@ except NameError: pass +def deduplicate_filters(filters): + """utility for deduplicating list of filters, this + is used when 'set()' cannot be used as one of the + filter values is a dict (or non-hashable type) + + Args: + filters (list): a list of filters + + Returns: list of unique filters + """ + unique_filters = [] + for filter_ in filters: + if filter_ not in unique_filters: + unique_filters.append(filter_) + return unique_filters + + def _check_filter_components(prop, op, value): """Check that filter meets minimum validity. @@ -168,3 +185,39 @@ def _check_filter(filter_, stix_obj): else: # Check if property matches return filter_._check_property(stix_obj[prop]) + + +class FilterSet(object): + """ """ + + def __init__(self, filters=None): + """ """ + self._filters = [] + if filters: + self.add(filters) + + def __iter__(self): + """ """ + for f in self._filters: + yield f + + def add(self, filters): + """ """ + if not isinstance(filters, FilterSet) and not isinstance(filters, list): + filters = [filters] + + for f in filters: + if f not in self._filters: + self._filters.append(f) + + return + + def remove(self, filters): + """ """ + if not isinstance(filters, FilterSet) and not isinstance(filters, list): + filters = [filters] + + for f in filters: + self._filters.remove(f) + + return diff --git a/stix2/datastore/memory.py b/stix2/datastore/memory.py index e057271..e6f0fd2 100644 --- a/stix2/datastore/memory.py +++ b/stix2/datastore/memory.py @@ -18,7 +18,7 @@ import os from stix2.base import _STIXBase from stix2.core import Bundle, parse from stix2.datastore import DataSink, DataSource, DataStoreMixin -from stix2.datastore.filters import Filter, apply_common_filters +from stix2.datastore.filters import Filter, FilterSet, apply_common_filters def _add(store, stix_data=None, version=None): @@ -197,7 +197,7 @@ class MemorySource(DataSource): Args: stix_id (str): The STIX ID of the STIX object to be retrieved. - _composite_filters (set): set of filters passed from the parent + _composite_filters (FilterSet): collection of filters passed from the parent CompositeDataSource, not user supplied Returns: @@ -236,7 +236,7 @@ class MemorySource(DataSource): Args: stix_id (str): The STIX ID of the STIX 2 object to retrieve. - _composite_filters (set): set of filters passed from the parent + _composite_filters (FilterSet): collection of filters passed from the parent CompositeDataSource, not user supplied Returns: @@ -258,7 +258,7 @@ class MemorySource(DataSource): Args: query (list): list of filters to search on - _composite_filters (set): set of filters passed from the + _composite_filters (FilterSet): collection of filters passed from the CompositeDataSource, not user supplied Returns: @@ -269,19 +269,15 @@ class MemorySource(DataSource): """ if query is None: - query = set() + query = FilterSet() else: - if not isinstance(query, list): - # make sure don't make set from a Filter object, - # need to make a set from a list of Filter objects (even if just one Filter) - query = [query] - query = set(query) + query = FilterSet(query) # combine all query filters if self.filters: - query.update(self.filters) + query.add(self.filters) if _composite_filters: - query.update(_composite_filters) + query.add(_composite_filters) # Apply STIX common property filters. all_data = list(apply_common_filters(self._data.values(), query)) diff --git a/stix2/datastore/taxii.py b/stix2/datastore/taxii.py index 0a58763..faa2669 100644 --- a/stix2/datastore/taxii.py +++ b/stix2/datastore/taxii.py @@ -6,7 +6,7 @@ from requests.exceptions import HTTPError from stix2.base import _STIXBase from stix2.core import Bundle, parse from stix2.datastore import DataSink, DataSource, DataStoreMixin -from stix2.datastore.filters import Filter, apply_common_filters +from stix2.datastore.filters import Filter, FilterSet, apply_common_filters from stix2.utils import deduplicate TAXII_FILTERS = ['added_after', 'id', 'type', 'version'] @@ -120,7 +120,7 @@ class TAXIICollectionSource(DataSource): Args: stix_id (str): The STIX ID of the STIX object to be retrieved. - _composite_filters (set): set of filters passed from the parent + _composite_filters (FilterSet): collection of filters passed from the parent CompositeDataSource, not user supplied version (str): Which STIX2 version to use. (e.g. "2.0", "2.1"). If None, use latest version. @@ -132,11 +132,12 @@ class TAXIICollectionSource(DataSource): """ # combine all query filters - query = set() + query = FilterSet() + if self.filters: - query.update(self.filters) + query.add(self.filters) if _composite_filters: - query.update(_composite_filters) + query.add(_composite_filters) # dont extract TAXII filters from query (to send to TAXII endpoint) # as directly retrieveing a STIX object by ID @@ -164,7 +165,7 @@ class TAXIICollectionSource(DataSource): Args: stix_id (str): The STIX ID of the STIX objects to be retrieved. - _composite_filters (set): set of filters passed from the parent + _composite_filters (FilterSet): collection of filters passed from the parent CompositeDataSource, not user supplied version (str): Which STIX2 version to use. (e.g. "2.0", "2.1"). If None, use latest version. @@ -198,7 +199,7 @@ class TAXIICollectionSource(DataSource): Args: query (list): list of filters to search on - _composite_filters (set): set of filters passed from the + _composite_filters (FilterSet): collection of filters passed from the CompositeDataSource, not user supplied version (str): Which STIX2 version to use. (e.g. "2.0", "2.1"). If None, use latest version. @@ -209,20 +210,13 @@ class TAXIICollectionSource(DataSource): parsed into python STIX objects and then returned. """ - if query is None: - query = set() - else: - if not isinstance(query, list): - # make sure dont make set from a Filter object, - # need to make a set from a list of Filter objects (even if just one Filter) - query = [query] - query = set(query) + query = FilterSet(query) # combine all query filters if self.filters: - query.update(self.filters) + query.add(self.filters) if _composite_filters: - query.update(_composite_filters) + query.add(_composite_filters) # parse taxii query params (that can be applied remotely) taxii_filters = self._parse_taxii_filters(query) @@ -268,17 +262,16 @@ class TAXIICollectionSource(DataSource): Args: - query (set): set of filters to extract which ones are TAXII + query (list): list of filters to extract which ones are TAXII specific. - Returns: - taxii_filters (set): set of the TAXII filters + Returns: a list of the TAXII filters """ - taxii_filters = set() + taxii_filters = [] for filter_ in query: if filter_.property in TAXII_FILTERS: - taxii_filters.add(filter_) + taxii_filters.append(filter_) return taxii_filters From 76f1474a8b6a5d11dbec170f29ed9219e5721128 Mon Sep 17 00:00:00 2001 From: Chris Lenk Date: Wed, 11 Apr 2018 14:43:44 -0400 Subject: [PATCH 40/61] Pin sphinx version for ReadTheDocs See also: https://github.com/rtfd/readthedocs.org/issues/3148 --- requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index 32e08f2..5ac0b37 100644 --- a/requirements.txt +++ b/requirements.txt @@ -4,7 +4,7 @@ nbsphinx==0.3.2 pre-commit pytest pytest-cov -sphinx +sphinx<1.6 sphinx-prompt tox From 1d22c757ef79a02a0ea0b22962a5009ee8e82ce8 Mon Sep 17 00:00:00 2001 From: Chris Lenk Date: Wed, 11 Apr 2018 15:40:52 -0400 Subject: [PATCH 41/61] Improve Tox test harness - No need for both pycodestyle and flake8; flake8 includes the former. - Use the proper pytest invocation. --- tox.ini | 21 ++++++++------------- 1 file changed, 8 insertions(+), 13 deletions(-) diff --git a/tox.ini b/tox.ini index ac4e89f..86cd4ee 100644 --- a/tox.ini +++ b/tox.ini @@ -1,5 +1,5 @@ [tox] -envlist = py27,py34,py35,py36,pycodestyle,isort-check +envlist = py27,py34,py35,py36,style,isort-check [testenv] deps = @@ -10,22 +10,17 @@ deps = coverage taxii2-client commands = - py.test --ignore=stix2/test/test_workbench.py --cov=stix2 stix2/test/ --cov-report term-missing - py.test stix2/test/test_workbench.py --cov=stix2 --cov-report term-missing --cov-append + pytest --ignore=stix2/test/test_workbench.py --cov=stix2 stix2/test/ --cov-report term-missing + pytest stix2/test/test_workbench.py --cov=stix2 --cov-report term-missing --cov-append passenv = CI TRAVIS TRAVIS_* -[testenv:pycodestyle] +[testenv:style] deps = flake8 - pycodestyle commands = - pycodestyle ./stix2 flake8 -[pycodestyle] -max-line-length=160 - [flake8] max-line-length=160 @@ -37,7 +32,7 @@ commands = [travis] python = - 2.7: py27, pycodestyle - 3.4: py34, pycodestyle - 3.5: py35, pycodestyle - 3.6: py36, pycodestyle + 2.7: py27, style + 3.4: py34, style + 3.5: py35, style + 3.6: py36, style From 3e048ef325ba129a71c03708c2f07c953e26c5de Mon Sep 17 00:00:00 2001 From: Chris Lenk Date: Wed, 11 Apr 2018 15:46:17 -0400 Subject: [PATCH 42/61] Fix deprecated 3.6 backslash-character pairs (https://docs.python.org/3/whatsnew/3.6.html#deprecated-python-behavior) --- stix2/test/test_external_reference.py | 4 ++-- stix2/test/test_malware.py | 2 +- stix2/test/test_pattern_expressions.py | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/stix2/test/test_external_reference.py b/stix2/test/test_external_reference.py index 2b79f01..9b90998 100644 --- a/stix2/test/test_external_reference.py +++ b/stix2/test/test_external_reference.py @@ -42,7 +42,7 @@ def test_external_reference_capec(): ) assert str(ref) == CAPEC - assert re.match("ExternalReference\(source_name=u?'capec', external_id=u?'CAPEC-550'\)", repr(ref)) + assert re.match("ExternalReference\\(source_name=u?'capec', external_id=u?'CAPEC-550'\\)", repr(ref)) CAPEC_URL = """{ @@ -109,7 +109,7 @@ def test_external_reference_offline(): ) assert str(ref) == OFFLINE - assert re.match("ExternalReference\(source_name=u?'ACME Threat Intel', description=u?'Threat report'\)", repr(ref)) + assert re.match("ExternalReference\\(source_name=u?'ACME Threat Intel', description=u?'Threat report'\\)", repr(ref)) # Yikes! This works assert eval("stix2." + repr(ref)) == ref diff --git a/stix2/test/test_malware.py b/stix2/test/test_malware.py index 8c565cd..2228885 100644 --- a/stix2/test/test_malware.py +++ b/stix2/test/test_malware.py @@ -126,7 +126,7 @@ def test_parse_malware(data): def test_parse_malware_invalid_labels(): - data = re.compile('\[.+\]', re.DOTALL).sub('1', EXPECTED_MALWARE) + data = re.compile('\\[.+\\]', re.DOTALL).sub('1', EXPECTED_MALWARE) with pytest.raises(ValueError) as excinfo: stix2.parse(data) assert "Invalid value for Malware 'labels'" in str(excinfo.value) diff --git a/stix2/test/test_pattern_expressions.py b/stix2/test/test_pattern_expressions.py index 363458a..74a7d0f 100644 --- a/stix2/test/test_pattern_expressions.py +++ b/stix2/test/test_pattern_expressions.py @@ -319,13 +319,13 @@ def test_invalid_binary_constant(): def test_escape_quotes_and_backslashes(): exp = stix2.MatchesComparisonExpression("file:name", - "^Final Report.+\.exe$") + "^Final Report.+\\.exe$") assert str(exp) == "file:name MATCHES '^Final Report.+\\\\.exe$'" def test_like(): exp = stix2.LikeComparisonExpression("directory:path", - "C:\Windows\%\\foo") + "C:\\Windows\\%\\foo") assert str(exp) == "directory:path LIKE 'C:\\\\Windows\\\\%\\\\foo'" From ba6fa595c6e459303cdc712304bb84b6ff4c9d03 Mon Sep 17 00:00:00 2001 From: = Date: Wed, 11 Apr 2018 20:54:16 -0400 Subject: [PATCH 43/61] WIP - finding more issues with allowing dicts as filters --- stix2/datastore/filters.py | 15 +++- stix2/environment.py | 2 +- stix2/test/test_datastore.py | 144 ++++++++++++++++++++++++++++++++--- 3 files changed, 147 insertions(+), 14 deletions(-) diff --git a/stix2/datastore/filters.py b/stix2/datastore/filters.py index 0946694..f0028cb 100644 --- a/stix2/datastore/filters.py +++ b/stix2/datastore/filters.py @@ -5,11 +5,13 @@ Filters for Python STIX 2.0 DataSources, DataSinks, DataStores import collections +from stix2.utils import STIXdatetime + """Supported filter operations""" FILTER_OPS = ['=', '!=', 'in', '>', '<', '>=', '<='] """Supported filter value types""" -FILTER_VALUE_TYPES = [bool, dict, float, int, list, str, tuple] +FILTER_VALUE_TYPES = [bool, dict, float, int, list, str, tuple, STIXdatetime] try: FILTER_VALUE_TYPES.append(unicode) except NameError: @@ -169,19 +171,26 @@ def _check_filter(filter_, stix_obj): # Check embedded properties, from e.g. granular_markings or external_references sub_property = filter_.property.split(".", 1)[1] sub_filter = filter_._replace(property=sub_property) + if isinstance(stix_obj[prop], list): for elem in stix_obj[prop]: if _check_filter(sub_filter, elem) is True: return True return False + + elif isinstance(stix_obj[prop], dict): + return _check_filter(sub_filter, stix_obj[prop]) + else: return _check_filter(sub_filter, stix_obj[prop]) + elif isinstance(stix_obj[prop], list): # Check each item in list property to see if it matches for elem in stix_obj[prop]: if filter_._check_property(elem) is True: return True return False + else: # Check if property matches return filter_._check_property(stix_obj[prop]) @@ -201,6 +210,10 @@ class FilterSet(object): for f in self._filters: yield f + def __len__(self): + """ """ + return len(self._filters) + def add(self, filters): """ """ if not isinstance(filters, FilterSet) and not isinstance(filters, list): diff --git a/stix2/environment.py b/stix2/environment.py index eb5583e..30f2802 100644 --- a/stix2/environment.py +++ b/stix2/environment.py @@ -115,7 +115,7 @@ class Environment(DataStoreMixin): def add_filters(self, *args, **kwargs): try: - return self.source.filters.update(*args, **kwargs) + return self.source.filters.add(*args, **kwargs) except AttributeError: raise AttributeError('Environment has no data source') diff --git a/stix2/test/test_datastore.py b/stix2/test/test_datastore.py index e80e8d8..01304b9 100644 --- a/stix2/test/test_datastore.py +++ b/stix2/test/test_datastore.py @@ -2,10 +2,11 @@ import pytest from taxii2client import Collection from stix2 import Filter, MemorySink, MemorySource +from stix2.core import parse from stix2.datastore import (CompositeDataSource, DataSink, DataSource, make_id, taxii) from stix2.datastore.filters import apply_common_filters -from stix2.utils import deduplicate +from stix2.utils import deduplicate, parse_into_datetime COLLECTION_URL = 'https://example.com/api1/collections/91a7b528-80eb-42ed-a74d-c6fbd5a26116/' @@ -120,6 +121,9 @@ IND8 = { STIX_OBJS2 = [IND6, IND7, IND8] STIX_OBJS1 = [IND1, IND2, IND3, IND4, IND5] +REAL_STIX_OBJS2 = [parse(IND6), parse(IND7), parse(IND8)] +REAL_STIX_OBJS1 = [parse(IND1), parse(IND2), parse(IND3), parse(IND4), parse(IND5)] + def test_ds_abstract_class_smoke(): with pytest.raises(TypeError): @@ -148,12 +152,12 @@ def test_parse_taxii_filters(): Filter("created_by_ref", "=", "Bane"), ] - taxii_filters_expected = set([ + taxii_filters_expected = [ Filter("added_after", "=", "2016-02-01T00:00:01.000Z"), Filter("id", "=", "taxii stix object ID"), Filter("type", "=", "taxii stix object ID"), Filter("version", "=", "first") - ]) + ] ds = taxii.TAXIICollectionSource(collection) @@ -177,7 +181,7 @@ def test_add_get_remove_filter(): ds.filters.add(valid_filters[0]) assert len(ds.filters) == 1 - # Addin the same filter again will have no effect since `filters` uses a set + # Addin the same filter again will have no effect since `filters` acts like a set ds.filters.add(valid_filters[0]) assert len(ds.filters) == 1 @@ -186,14 +190,14 @@ def test_add_get_remove_filter(): ds.filters.add(valid_filters[2]) assert len(ds.filters) == 3 - assert set(valid_filters) == ds.filters + assert valid_filters == [f for f in ds.filters] # remove ds.filters.remove(valid_filters[0]) assert len(ds.filters) == 2 - ds.filters.update(valid_filters) + ds.filters.add(valid_filters) def test_filter_ops_check(): @@ -297,9 +301,32 @@ def test_apply_common_filters(): } ], "labels": ["heartbleed", "has-logo"] + }, + { + "type": "observed-data", + "id": "observed-data--b67d30ff-02ac-498a-92f9-32f845f448cf", + "created_by_ref": "identity--f431f809-377b-45e0-aa1c-6a4751cae5ff", + "created": "2016-04-06T19:58:16.000Z", + "modified": "2016-04-06T19:58:16.000Z", + "first_observed": "2015-12-21T19:00:00Z", + "last_observed": "2015-12-21T19:00:00Z", + "number_observed": 1, + "objects": { + "0": { + "type": "file", + "name": "HAL 9000.exe" + } + } + } ] + # same as above objects but converted to real Python STIX2 objects + # to test filters against true Python STIX2 objects + print(stix_objs) + real_stix_objs = [parse(stix_obj) for stix_obj in stix_objs] + print("after\n\n") + print(stix_objs) filters = [ Filter("type", "!=", "relationship"), Filter("id", "=", "relationship--2f9a9aa9-108a-4333-83e2-4fb25add0463"), @@ -315,6 +342,7 @@ def test_apply_common_filters(): Filter("object_marking_refs", "=", "marking-definition--613f2e26-0000-0000-0000-b8e91df99dc9"), Filter("granular_markings.selectors", "in", "description"), Filter("external_references.source_name", "=", "CVE"), + Filter("objects", "=", {"0": {"type": "file", "name": "HAL 9000.exe"}}) ] # "Return any object whose type is not relationship" @@ -323,66 +351,125 @@ def test_apply_common_filters(): assert stix_objs[0]['id'] in ids assert stix_objs[1]['id'] in ids assert stix_objs[3]['id'] in ids - assert len(ids) == 3 + assert len(ids) == 4 + + resp = list(apply_common_filters(real_stix_objs, [filters[0]])) + ids = [r.id for r in resp] + assert real_stix_objs[0].id in ids + assert real_stix_objs[1].id in ids + assert real_stix_objs[3].id in ids + assert len(ids) == 4 # "Return any object that matched id relationship--2f9a9aa9-108a-4333-83e2-4fb25add0463" resp = list(apply_common_filters(stix_objs, [filters[1]])) assert resp[0]['id'] == stix_objs[2]['id'] assert len(resp) == 1 + resp = list(apply_common_filters(real_stix_objs, [filters[1]])) + assert resp[0].id == real_stix_objs[2].id + assert len(resp) == 1 + # "Return any object that contains remote-access-trojan in labels" resp = list(apply_common_filters(stix_objs, [filters[2]])) assert resp[0]['id'] == stix_objs[0]['id'] assert len(resp) == 1 + resp = list(apply_common_filters(real_stix_objs, [filters[2]])) + assert resp[0].id == real_stix_objs[0].id + assert len(resp) == 1 + # "Return any object created after 2015-01-01T01:00:00.000Z" resp = list(apply_common_filters(stix_objs, [filters[3]])) assert resp[0]['id'] == stix_objs[0]['id'] - assert len(resp) == 2 + assert len(resp) == 3 # "Return any revoked object" resp = list(apply_common_filters(stix_objs, [filters[4]])) assert resp[0]['id'] == stix_objs[2]['id'] assert len(resp) == 1 + resp = list(apply_common_filters(real_stix_objs, [filters[4]])) + assert resp[0].id == real_stix_objs[2].id + assert len(resp) == 1 + # "Return any object whose not revoked" # Note that if 'revoked' property is not present in object. # Currently we can't use such an expression to filter for... :( resp = list(apply_common_filters(stix_objs, [filters[5]])) assert len(resp) == 0 + resp = list(apply_common_filters(real_stix_objs, [filters[5]])) + assert len(resp) == 0 + # "Return any object that matches marking-definition--613f2e26-407d-48c7-9eca-b8e91df99dc9 in object_marking_refs" resp = list(apply_common_filters(stix_objs, [filters[6]])) assert resp[0]['id'] == stix_objs[2]['id'] assert len(resp) == 1 + resp = list(apply_common_filters(real_stix_objs, [filters[6]])) + assert resp[0].id == real_stix_objs[2].id + assert len(resp) == 1 + # "Return any object that contains relationship_type in their selectors AND # also has marking-definition--5e57c739-391a-4eb3-b6be-7d15ca92d5ed in marking_ref" resp = list(apply_common_filters(stix_objs, [filters[7], filters[8]])) assert resp[0]['id'] == stix_objs[2]['id'] assert len(resp) == 1 + resp = list(apply_common_filters(real_stix_objs, [filters[7], filters[8]])) + assert resp[0].id == real_stix_objs[2].id + assert len(resp) == 1 + # "Return any object that contains CVE-2014-0160,CVE-2017-6608 in their external_id" resp = list(apply_common_filters(stix_objs, [filters[9]])) assert resp[0]['id'] == stix_objs[3]['id'] assert len(resp) == 1 + resp = list(apply_common_filters(real_stix_objs, [filters[9]])) + assert resp[0].id == real_stix_objs[3].id + assert len(resp) == 1 + # "Return any object that matches created_by_ref identity--00000000-0000-0000-0000-b8e91df99dc9" resp = list(apply_common_filters(stix_objs, [filters[10]])) assert len(resp) == 1 + resp = list(apply_common_filters(real_stix_objs, [filters[10]])) + assert len(resp) == 1 + # "Return any object that matches marking-definition--613f2e26-0000-0000-0000-b8e91df99dc9 in object_marking_refs" (None) resp = list(apply_common_filters(stix_objs, [filters[11]])) assert len(resp) == 0 + resp = list(apply_common_filters(real_stix_objs, [filters[11]])) + assert len(resp) == 0 + # "Return any object that contains description in its selectors" (None) resp = list(apply_common_filters(stix_objs, [filters[12]])) assert len(resp) == 0 - # "Return any object that object that matches CVE in source_name" (None, case sensitive) + resp = list(apply_common_filters(real_stix_objs, [filters[12]])) + assert len(resp) == 0 + + # "Return any object that matches CVE in source_name" (None, case sensitive) resp = list(apply_common_filters(stix_objs, [filters[13]])) assert len(resp) == 0 + resp = list(apply_common_filters(real_stix_objs, [filters[13]])) + assert len(resp) == 0 + + # Return any object that matches file object in "objects" + # BUG: This test is brokem , weird behavior, the file obj + # in stix_objs is being parsed into real python-stix2 obj even though + # it never goes through parse() --> BAD <_< + print(stix_objs) + resp = list(apply_common_filters(stix_objs, [filters[14]])) + assert resp[0]["id"] == stix_objs[14]["id"] + assert len(resp) == 1 + + resp = list(apply_common_filters(real_stix_objs, [filters[14]])) + assert resp[0].id == real_stix_objs[14].id + assert len(resp) == 1 + def test_filters0(): # "Return any object modified before 2017-01-28T13:49:53.935Z" @@ -390,6 +477,10 @@ def test_filters0(): assert resp[0]['id'] == STIX_OBJS2[1]['id'] assert len(resp) == 2 + resp = list(apply_common_filters(REAL_STIX_OBJS2, [Filter("modified", "<", parse_into_datetime("2017-01-28T13:49:53.935Z"))])) + assert resp[0].id == REAL_STIX_OBJS2[1].id + assert len(resp) == 2 + def test_filters1(): # "Return any object modified after 2017-01-28T13:49:53.935Z" @@ -397,6 +488,10 @@ def test_filters1(): assert resp[0]['id'] == STIX_OBJS2[0]['id'] assert len(resp) == 1 + resp = list(apply_common_filters(REAL_STIX_OBJS2, [Filter("modified", ">", parse_into_datetime("2017-01-28T13:49:53.935Z"))])) + assert resp[0].id == REAL_STIX_OBJS2[0].id + assert len(resp) == 1 + def test_filters2(): # "Return any object modified after or on 2017-01-28T13:49:53.935Z" @@ -404,6 +499,10 @@ def test_filters2(): assert resp[0]['id'] == STIX_OBJS2[0]['id'] assert len(resp) == 3 + resp = list(apply_common_filters(REAL_STIX_OBJS2, [Filter("modified", ">=", parse_into_datetime("2017-01-27T13:49:53.935Z"))])) + assert resp[0].id == REAL_STIX_OBJS2[0].id + assert len(resp) == 3 + def test_filters3(): # "Return any object modified before or on 2017-01-28T13:49:53.935Z" @@ -411,6 +510,11 @@ def test_filters3(): assert resp[0]['id'] == STIX_OBJS2[1]['id'] assert len(resp) == 2 + # "Return any object modified before or on 2017-01-28T13:49:53.935Z" + resp = list(apply_common_filters(REAL_STIX_OBJS2, [Filter("modified", "<=", parse_into_datetime("2017-01-27T13:49:53.935Z"))])) + assert resp[0].id == REAL_STIX_OBJS2[1].id + assert len(resp) == 2 + def test_filters4(): # Assert invalid Filter cannot be created @@ -426,6 +530,10 @@ def test_filters5(): assert resp[0]['id'] == STIX_OBJS2[0]['id'] assert len(resp) == 1 + resp = list(apply_common_filters(REAL_STIX_OBJS2, [Filter("id", "!=", "indicator--d81f86b8-975b-bc0b-775e-810c5ad45a4f")])) + assert resp[0].id == REAL_STIX_OBJS2[0].id + assert len(resp) == 1 + def test_filters6(): # Test filtering on non-common property @@ -433,10 +541,14 @@ def test_filters6(): assert resp[0]['id'] == STIX_OBJS2[0]['id'] assert len(resp) == 3 + resp = list(apply_common_filters(REAL_STIX_OBJS2, [Filter("name", "=", "Malicious site hosting downloader")])) + assert resp[0].id == REAL_STIX_OBJS2[0].id + assert len(resp) == 3 + def test_filters7(): # Test filtering on embedded property - stix_objects = list(STIX_OBJS2) + [{ + obsvd_data_obj = { "type": "observed-data", "id": "observed-data--b67d30ff-02ac-498a-92f9-32f845f448cf", "created_by_ref": "identity--f431f809-377b-45e0-aa1c-6a4751cae5ff", @@ -467,11 +579,19 @@ def test_filters7(): } } } - }] + } + + stix_objects = list(STIX_OBJS2) + [obsvd_data_obj] + real_stix_objects = list(REAL_STIX_OBJS2) + [parse(obsvd_data_obj)] + resp = list(apply_common_filters(stix_objects, [Filter("objects.0.extensions.pdf-ext.version", ">", "1.2")])) assert resp[0]['id'] == stix_objects[3]['id'] assert len(resp) == 1 + resp = list(apply_common_filters(real_stix_objects, [Filter("objects.0.extensions.pdf-ext.version", ">", "1.2")])) + assert resp[0].id == real_stix_objects[3].id + assert len(resp) == 1 + def test_deduplicate(): unique = deduplicate(STIX_OBJS1) @@ -548,7 +668,7 @@ def test_composite_datasource_operations(): Filter("valid_from", "=", "2017-01-27T13:49:53.935382Z") ] - cds1.filters.update(query2) + cds1.filters.add(query2) results = cds1.query(query1) From 31fc1c369a5303c3fdcbbca03b1e155f3da2a8a6 Mon Sep 17 00:00:00 2001 From: = Date: Thu, 12 Apr 2018 12:03:07 -0400 Subject: [PATCH 44/61] still WIP --- stix2/datastore/filters.py | 14 ++++++++++++-- stix2/environment.py | 2 +- stix2/test/test_datastore.py | 1 - 3 files changed, 13 insertions(+), 4 deletions(-) diff --git a/stix2/datastore/filters.py b/stix2/datastore/filters.py index 12f0cae..c0bed44 100644 --- a/stix2/datastore/filters.py +++ b/stix2/datastore/filters.py @@ -245,8 +245,13 @@ class FilterSet(object): """ """ return len(self._filters) - def add(self, filters): + def add(self, filters=None): """ """ + if not filters: + # so add() can be called blindly, useful for + # DataStore/Environment usage of filter operations + return + if not isinstance(filters, FilterSet) and not isinstance(filters, list): filters = [filters] @@ -256,8 +261,13 @@ class FilterSet(object): return - def remove(self, filters): + def remove(self, filters=None): """ """ + if not filters: + # so remove() can be called blindly, useful for + # DataStore/Environemnt usage of filter ops + return + if not isinstance(filters, FilterSet) and not isinstance(filters, list): filters = [filters] diff --git a/stix2/environment.py b/stix2/environment.py index a456e95..cc589ae 100644 --- a/stix2/environment.py +++ b/stix2/environment.py @@ -158,7 +158,7 @@ class Environment(DataStoreMixin): set_default_object_marking_refs.__doc__ = ObjectFactory.set_default_object_marking_refs.__doc__ def add_filters(self, *args, **kwargs): - return self.source.filters.update(*args, **kwargs) + return self.source.filters.add(*args, **kwargs) def add_filter(self, *args, **kwargs): return self.source.filters.add(*args, **kwargs) diff --git a/stix2/test/test_datastore.py b/stix2/test/test_datastore.py index e3f19bf..a989d89 100644 --- a/stix2/test/test_datastore.py +++ b/stix2/test/test_datastore.py @@ -461,7 +461,6 @@ def test_apply_common_filters(): # BUG: This test is brokem , weird behavior, the file obj # in stix_objs is being parsed into real python-stix2 obj even though # it never goes through parse() --> BAD <_< - print(stix_objs) resp = list(apply_common_filters(stix_objs, [filters[14]])) assert resp[0]["id"] == stix_objs[14]["id"] assert len(resp) == 1 From 9ef5b395a8b702eae048f4688e7b8d16eda61795 Mon Sep 17 00:00:00 2001 From: Chris Lenk Date: Thu, 12 Apr 2018 14:20:24 -0400 Subject: [PATCH 45/61] Fix allowing custom observables and extensions --- stix2/base.py | 16 +++++++++++----- stix2/test/test_custom.py | 17 +++++++++++++++++ stix2/v20/observables.py | 4 ++-- 3 files changed, 30 insertions(+), 7 deletions(-) diff --git a/stix2/base.py b/stix2/base.py index 898f489..7ca4740 100644 --- a/stix2/base.py +++ b/stix2/base.py @@ -10,7 +10,7 @@ from .exceptions import (AtLeastOnePropertyError, DependentPropertiesError, ExtraPropertiesError, ImmutableError, InvalidObjRefError, InvalidValueError, MissingPropertiesError, - MutuallyExclusivePropertiesError) + MutuallyExclusivePropertiesError, ParseError) from .markings.utils import validate from .utils import NOW, find_property_index, format_datetime, get_timestamp from .utils import new_version as _new_version @@ -49,7 +49,7 @@ class _STIXBase(collections.Mapping): return all_properties - def _check_property(self, prop_name, prop, kwargs): + def _check_property(self, prop_name, prop, kwargs, allow_custom=False): if prop_name not in kwargs: if hasattr(prop, 'default'): value = prop.default() @@ -61,6 +61,8 @@ class _STIXBase(collections.Mapping): try: kwargs[prop_name] = prop.clean(kwargs[prop_name]) except ValueError as exc: + if allow_custom and isinstance(exc, ParseError): + return raise InvalidValueError(self.__class__, prop_name, reason=str(exc)) # interproperty constraint methods @@ -125,7 +127,11 @@ class _STIXBase(collections.Mapping): raise MissingPropertiesError(cls, missing_kwargs) for prop_name, prop_metadata in cls._properties.items(): - self._check_property(prop_name, prop_metadata, setting_kwargs) + try: + self._check_property(prop_name, prop_metadata, setting_kwargs, allow_custom) + except ParseError as err: + if not allow_custom: + raise err self._inner = setting_kwargs @@ -244,8 +250,8 @@ class _Observable(_STIXBase): if ref_type not in allowed_types: raise InvalidObjRefError(self.__class__, prop_name, "object reference '%s' is of an invalid type '%s'" % (ref, ref_type)) - def _check_property(self, prop_name, prop, kwargs): - super(_Observable, self)._check_property(prop_name, prop, kwargs) + def _check_property(self, prop_name, prop, kwargs, allow_custom=False): + super(_Observable, self)._check_property(prop_name, prop, kwargs, allow_custom) if prop_name not in kwargs: return diff --git a/stix2/test/test_custom.py b/stix2/test/test_custom.py index a50819b..d46acd4 100644 --- a/stix2/test/test_custom.py +++ b/stix2/test/test_custom.py @@ -617,6 +617,23 @@ def test_parse_observable_with_unregistered_custom_extension(): assert not isinstance(parsed_ob['extensions']['x-foobar-ext'], stix2.core._STIXBase) +def test_parse_observable_with_unregistered_custom_extension_dict(): + input_dict = { + "type": "domain-name", + "value": "example.com", + "extensions": { + "x-foobar-ext": { + "property1": "foo", + "property2": 12 + } + } + } + + with pytest.raises(ValueError) as excinfo: + stix2.v20.observables.DomainName(**input_dict) + assert "Can't parse unknown extension type" in str(excinfo.value) + + def test_register_custom_object(): # Not the way to register custom object. class CustomObject2(object): diff --git a/stix2/v20/observables.py b/stix2/v20/observables.py index 4449527..7dc7c02 100644 --- a/stix2/v20/observables.py +++ b/stix2/v20/observables.py @@ -67,7 +67,7 @@ class ExtensionsProperty(DictionaryProperty): else: raise ValueError("Cannot determine extension type.") else: - raise ValueError("The key used in the extensions dictionary is not an extension type name") + raise ParseError("Can't parse unknown extension type: {}".format(key)) else: raise ValueError("The enclosing type '%s' has no extensions defined" % self.enclosing_type) return dictified @@ -936,7 +936,7 @@ def parse_observable(data, _valid_refs=None, allow_custom=False): ext_class = EXT_MAP[obj['type']][name] except KeyError: if not allow_custom: - raise ParseError("Can't parse Unknown extension type '%s' for observable type '%s'!" % (name, obj['type'])) + raise ParseError("Can't parse unknown extension type '%s' for observable type '%s'!" % (name, obj['type'])) else: # extension was found obj['extensions'][name] = ext_class(allow_custom=allow_custom, **obj['extensions'][name]) From 91376586d4e311f9e24c686b70de7a247772df7d Mon Sep 17 00:00:00 2001 From: Chris Lenk Date: Thu, 12 Apr 2018 16:33:08 -0400 Subject: [PATCH 46/61] Simplify allowing custom observables/extensions --- stix2/base.py | 15 ++++++--------- stix2/test/test_custom.py | 19 +------------------ 2 files changed, 7 insertions(+), 27 deletions(-) diff --git a/stix2/base.py b/stix2/base.py index 7ca4740..05afe3f 100644 --- a/stix2/base.py +++ b/stix2/base.py @@ -49,7 +49,7 @@ class _STIXBase(collections.Mapping): return all_properties - def _check_property(self, prop_name, prop, kwargs, allow_custom=False): + def _check_property(self, prop_name, prop, kwargs): if prop_name not in kwargs: if hasattr(prop, 'default'): value = prop.default() @@ -61,7 +61,7 @@ class _STIXBase(collections.Mapping): try: kwargs[prop_name] = prop.clean(kwargs[prop_name]) except ValueError as exc: - if allow_custom and isinstance(exc, ParseError): + if self.__allow_custom and isinstance(exc, ParseError): return raise InvalidValueError(self.__class__, prop_name, reason=str(exc)) @@ -99,6 +99,7 @@ class _STIXBase(collections.Mapping): def __init__(self, allow_custom=False, **kwargs): cls = self.__class__ + self.__allow_custom = allow_custom # Use the same timestamp for any auto-generated datetimes self.__now = get_timestamp() @@ -127,11 +128,7 @@ class _STIXBase(collections.Mapping): raise MissingPropertiesError(cls, missing_kwargs) for prop_name, prop_metadata in cls._properties.items(): - try: - self._check_property(prop_name, prop_metadata, setting_kwargs, allow_custom) - except ParseError as err: - if not allow_custom: - raise err + self._check_property(prop_name, prop_metadata, setting_kwargs) self._inner = setting_kwargs @@ -250,8 +247,8 @@ class _Observable(_STIXBase): if ref_type not in allowed_types: raise InvalidObjRefError(self.__class__, prop_name, "object reference '%s' is of an invalid type '%s'" % (ref, ref_type)) - def _check_property(self, prop_name, prop, kwargs, allow_custom=False): - super(_Observable, self)._check_property(prop_name, prop, kwargs, allow_custom) + def _check_property(self, prop_name, prop, kwargs): + super(_Observable, self)._check_property(prop_name, prop, kwargs) if prop_name not in kwargs: return diff --git a/stix2/test/test_custom.py b/stix2/test/test_custom.py index d46acd4..8da2a7a 100644 --- a/stix2/test/test_custom.py +++ b/stix2/test/test_custom.py @@ -610,30 +610,13 @@ def test_parse_observable_with_unregistered_custom_extension(): with pytest.raises(ValueError) as excinfo: stix2.parse_observable(input_str) - assert "Can't parse Unknown extension type" in str(excinfo.value) + assert "Can't parse unknown extension type" in str(excinfo.value) parsed_ob = stix2.parse_observable(input_str, allow_custom=True) assert parsed_ob['extensions']['x-foobar-ext']['property1'] == 'foo' assert not isinstance(parsed_ob['extensions']['x-foobar-ext'], stix2.core._STIXBase) -def test_parse_observable_with_unregistered_custom_extension_dict(): - input_dict = { - "type": "domain-name", - "value": "example.com", - "extensions": { - "x-foobar-ext": { - "property1": "foo", - "property2": 12 - } - } - } - - with pytest.raises(ValueError) as excinfo: - stix2.v20.observables.DomainName(**input_dict) - assert "Can't parse unknown extension type" in str(excinfo.value) - - def test_register_custom_object(): # Not the way to register custom object. class CustomObject2(object): From d08be151f713e020f502a5aea516b0859fd1679e Mon Sep 17 00:00:00 2001 From: Chris Lenk Date: Thu, 12 Apr 2018 21:26:48 -0400 Subject: [PATCH 47/61] Allow a ListProperty of DictionaryProperties --- stix2/properties.py | 2 ++ stix2/test/test_properties.py | 13 ++++++++++++- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/stix2/properties.py b/stix2/properties.py index ca7f04c..41841b6 100644 --- a/stix2/properties.py +++ b/stix2/properties.py @@ -129,6 +129,8 @@ class ListProperty(Property): # constructor again result.append(valid) continue + elif type(self.contained) is DictionaryProperty: + obj_type = dict else: obj_type = self.contained diff --git a/stix2/test/test_properties.py b/stix2/test/test_properties.py index 34edc96..16ff06a 100644 --- a/stix2/test/test_properties.py +++ b/stix2/test/test_properties.py @@ -1,6 +1,6 @@ import pytest -from stix2 import EmailMIMEComponent, ExtensionsProperty, TCPExt +from stix2 import CustomObject, EmailMIMEComponent, ExtensionsProperty, TCPExt from stix2.exceptions import AtLeastOnePropertyError, DictionaryKeyError from stix2.properties import (BinaryProperty, BooleanProperty, DictionaryProperty, EmbeddedObjectProperty, @@ -266,6 +266,17 @@ def test_dictionary_property_invalid(d): assert str(excinfo.value) == d[1] +def test_property_list_of_dictionary(): + @CustomObject('x-new-obj', [ + ('property1', ListProperty(DictionaryProperty(), required=True)), + ]) + class NewObj(): + pass + + test_obj = NewObj(property1=[{'foo': 'bar'}]) + assert test_obj.property1[0]['foo'] == 'bar' + + @pytest.mark.parametrize("value", [ {"sha256": "6db12788c37247f2316052e142f42f4b259d6561751e5f401a1ae2a6df9c674b"}, [('MD5', '2dfb1bcc980200c6706feee399d41b3f'), ('RIPEMD-160', 'b3a8cd8a27c90af79b3c81754f267780f443dfef')], From a8b7be88d03f4e548b241b89cc56a69b3a3819e2 Mon Sep 17 00:00:00 2001 From: Emmanuelle Vargas-Gonzalez Date: Fri, 13 Apr 2018 11:04:07 -0400 Subject: [PATCH 48/61] Add support for pretty print case list of dictionaries. --- stix2/test/test_custom.py | 21 +++++++++++++++++++++ stix2/utils.py | 7 ++++++- 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/stix2/test/test_custom.py b/stix2/test/test_custom.py index a14503f..b45670f 100644 --- a/stix2/test/test_custom.py +++ b/stix2/test/test_custom.py @@ -479,6 +479,27 @@ def test_custom_extension_wrong_observable_type(): assert 'Cannot determine extension type' in excinfo.value.reason +@pytest.mark.parametrize("data", [ + """{ + "keys": [ + { + "test123": 123, + "test345": "aaaa" + } + ] +}""", +]) +def test_custom_extension_with_list_and_dict_properties_observable_type(data): + @stix2.observables.CustomExtension(stix2.UserAccount, 'some-extension', [ + ('keys', stix2.properties.ListProperty(stix2.properties.DictionaryProperty, required=True)) + ]) + class SomeCustomExtension: + pass + + example = SomeCustomExtension(keys=[{'test123': 123, 'test345': 'aaaa'}]) + assert data == str(example) + + def test_custom_extension_invalid_observable(): # These extensions are being applied to improperly-created Observables. # The Observable classes should have been created with the CustomObservable decorator. diff --git a/stix2/utils.py b/stix2/utils.py index 9febd78..4ef3d23 100644 --- a/stix2/utils.py +++ b/stix2/utils.py @@ -166,7 +166,7 @@ def get_dict(data): def find_property_index(obj, properties, tuple_to_find): """Recursively find the property in the object model, return the index according to the _properties OrderedDict. If it's a list look for - individual objects. + individual objects. Returns and integer indicating its location """ from .base import _STIXBase try: @@ -183,6 +183,11 @@ def find_property_index(obj, properties, tuple_to_find): tuple_to_find) if val is not None: return val + elif isinstance(item, dict): + for idx, val in enumerate(sorted(item)): + if (tuple_to_find[0] == val and + item.get(val) == tuple_to_find[1]): + return idx elif isinstance(pv, dict): if pv.get(tuple_to_find[0]) is not None: try: From 1a1e5e161637dc47f1d9e9792fdec5fff2c0b513 Mon Sep 17 00:00:00 2001 From: = Date: Fri, 13 Apr 2018 11:08:03 -0400 Subject: [PATCH 49/61] WIP- getting close though --- stix2/__init__.py | 2 +- stix2/core.py | 6 +- stix2/datastore/__init__.py | 6 +- stix2/datastore/filters.py | 68 ++------ stix2/properties.py | 4 +- stix2/test/test_custom.py | 1 + stix2/test/test_datastore.py | 293 ++++++++++++++++++++--------------- stix2/test/test_utils.py | 4 +- stix2/utils.py | 2 +- stix2/v20/common.py | 4 +- stix2/v20/observables.py | 22 ++- stix2/workbench.py | 38 +++-- 12 files changed, 246 insertions(+), 204 deletions(-) diff --git a/stix2/__init__.py b/stix2/__init__.py index 17f2277..449be68 100644 --- a/stix2/__init__.py +++ b/stix2/__init__.py @@ -50,7 +50,7 @@ from .patterns import (AndBooleanExpression, AndObservationExpression, ReferenceObjectPathComponent, RepeatQualifier, StartStopQualifier, StringConstant, TimestampConstant, WithinQualifier) -from .utils import get_dict, new_version, revoke +from .utils import new_version, revoke from .v20 import * # This import will always be the latest STIX 2.X version from .version import __version__ diff --git a/stix2/core.py b/stix2/core.py index 7de7984..0b222a9 100644 --- a/stix2/core.py +++ b/stix2/core.py @@ -9,7 +9,7 @@ import stix2 from . import exceptions from .base import _STIXBase from .properties import IDProperty, ListProperty, Property, TypeProperty -from .utils import get_class_hierarchy_names, get_dict +from .utils import _get_dict, get_class_hierarchy_names class STIXObjectProperty(Property): @@ -25,7 +25,7 @@ class STIXObjectProperty(Property): for x in get_class_hierarchy_names(value)): return value try: - dictified = get_dict(value) + dictified = _get_dict(value) except ValueError: raise ValueError("This property may only contain a dictionary or object") if dictified == {}: @@ -95,7 +95,7 @@ def parse(data, allow_custom=False, version=None): """ # convert STIX object to dict, if not already - obj = get_dict(data) + obj = _get_dict(data) # convert dict to full python-stix2 obj obj = dict_to_stix2(obj, allow_custom, version) diff --git a/stix2/datastore/__init__.py b/stix2/datastore/__init__.py index ff50735..7fdf515 100644 --- a/stix2/datastore/__init__.py +++ b/stix2/datastore/__init__.py @@ -16,7 +16,7 @@ import uuid from six import with_metaclass -from stix2.datastore.filters import Filter, FilterSet, _assemble_filters +from stix2.datastore.filters import Filter, FilterSet from stix2.utils import deduplicate @@ -379,10 +379,10 @@ class DataSource(with_metaclass(ABCMeta)): ids.discard(obj_id) # Assemble filters - filter_list = _assemble_filters(filters) + filter_list = FilterSet(filters) for i in ids: - results.extend(self.query(filter_list + [Filter('id', '=', i)])) + results.extend(self.query([f for f in filter_list] + [Filter('id', '=', i)])) return results diff --git a/stix2/datastore/filters.py b/stix2/datastore/filters.py index c0bed44..3d2c5e8 100644 --- a/stix2/datastore/filters.py +++ b/stix2/datastore/filters.py @@ -4,14 +4,15 @@ Filters for Python STIX 2.0 DataSources, DataSinks, DataStores """ import collections +from datetime import datetime -from stix2.utils import STIXdatetime +from stix2.utils import format_datetime """Supported filter operations""" FILTER_OPS = ['=', '!=', 'in', '>', '<', '>=', '<='] """Supported filter value types""" -FILTER_VALUE_TYPES = [bool, dict, float, int, list, str, tuple, STIXdatetime] +FILTER_VALUE_TYPES = [bool, dict, float, int, list, str, tuple] try: FILTER_VALUE_TYPES.append(unicode) except NameError: @@ -19,23 +20,6 @@ except NameError: pass -def deduplicate_filters(filters): - """utility for deduplicating list of filters, this - is used when 'set()' cannot be used as one of the - filter values is a dict (or non-hashable type) - - Args: - filters (list): a list of filters - - Returns: list of unique filters - """ - unique_filters = [] - for filter_ in filters: - if filter_ not in unique_filters: - unique_filters.append(filter_) - return unique_filters - - def _check_filter_components(prop, op, value): """Check that filter meets minimum validity. @@ -63,37 +47,6 @@ def _check_filter_components(prop, op, value): return True -def _assemble_filters(filters1=None, filters2=None): - """Assemble a list of filters. - - This can be used to allow certain functions to work correctly no matter if - the user provides a single filter or a list of them. - - Args: - filters1 (Filter or list, optional): The single Filter or list of Filters to - coerce into a list of Filters. - filters2 (Filter or list, optional): The single Filter or list of Filters to - append to the list of Filters. - - Returns: - List of Filters. - - """ - if filters1 is None: - filter_list = [] - elif not isinstance(filters1, list): - filter_list = [filters1] - else: - filter_list = filters1 - - if isinstance(filters2, list): - filter_list.extend(filters2) - elif filters2 is not None: - filter_list.append(filters2) - - return filter_list - - class Filter(collections.namedtuple("Filter", ['property', 'op', 'value'])): """STIX 2 filters that support the querying functionality of STIX 2 DataStores and DataSources. @@ -116,6 +69,11 @@ class Filter(collections.namedtuple("Filter", ['property', 'op', 'value'])): if isinstance(value, list): value = tuple(value) + if isinstance(value, datetime): + # if value is a datetime obj, convert to str + dt_str = format_datetime(value) + value = dt_str # use temp variable to avoid deepcopy operation + _check_filter_components(prop, op, value) self = super(Filter, cls).__new__(cls, prop, op, value) @@ -131,6 +89,12 @@ class Filter(collections.namedtuple("Filter", ['property', 'op', 'value'])): True if property matches the filter, False otherwise. """ + if isinstance(stix_obj_property, datetime): + # if a datetime obj, convert to str before comparison + # NOTE: this check seems like it should be done upstream + # but will put here for now + stix_obj_property = format_datetime(stix_obj_property) + if self.op == "=": return stix_obj_property == self.value elif self.op == "!=": @@ -252,7 +216,7 @@ class FilterSet(object): # DataStore/Environment usage of filter operations return - if not isinstance(filters, FilterSet) and not isinstance(filters, list): + if not isinstance(filters, (FilterSet, list)): filters = [filters] for f in filters: @@ -268,7 +232,7 @@ class FilterSet(object): # DataStore/Environemnt usage of filter ops return - if not isinstance(filters, FilterSet) and not isinstance(filters, list): + if not isinstance(filters, (FilterSet, list)): filters = [filters] for f in filters: diff --git a/stix2/properties.py b/stix2/properties.py index ca7f04c..a650d55 100644 --- a/stix2/properties.py +++ b/stix2/properties.py @@ -12,7 +12,7 @@ from stix2patterns.validator import run_validator from .base import _STIXBase from .exceptions import DictionaryKeyError -from .utils import get_dict, parse_into_datetime +from .utils import _get_dict, parse_into_datetime class Property(object): @@ -232,7 +232,7 @@ class DictionaryProperty(Property): def clean(self, value): try: - dictified = get_dict(value) + dictified = _get_dict(value) except ValueError: raise ValueError("The dictionary property must contain a dictionary") if dictified == {}: diff --git a/stix2/test/test_custom.py b/stix2/test/test_custom.py index a14503f..417be00 100644 --- a/stix2/test/test_custom.py +++ b/stix2/test/test_custom.py @@ -80,6 +80,7 @@ def test_identity_custom_property_allowed(): def test_parse_identity_custom_property(data): with pytest.raises(stix2.exceptions.ExtraPropertiesError) as excinfo: identity = stix2.parse(data) + assert str(excinfo.value.cls) == str(stix2.Identity) assert excinfo.value.cls == stix2.Identity assert excinfo.value.properties == ['foo'] assert "Unexpected properties for" in str(excinfo.value) diff --git a/stix2/test/test_datastore.py b/stix2/test/test_datastore.py index a989d89..9ffa992 100644 --- a/stix2/test/test_datastore.py +++ b/stix2/test/test_datastore.py @@ -5,7 +5,7 @@ from stix2 import Filter, MemorySink, MemorySource from stix2.core import parse from stix2.datastore import (CompositeDataSource, DataSink, DataSource, make_id, taxii) -from stix2.datastore.filters import _assemble_filters, apply_common_filters +from stix2.datastore.filters import apply_common_filters from stix2.utils import deduplicate, parse_into_datetime COLLECTION_URL = 'https://example.com/api1/collections/91a7b528-80eb-42ed-a74d-c6fbd5a26116/' @@ -21,6 +21,108 @@ def collection(): return Collection(COLLECTION_URL, MockTAXIIClient()) +stix_objs = [ + { + "created": "2017-01-27T13:49:53.997Z", + "description": "\n\nTITLE:\n\tPoison Ivy", + "id": "malware--fdd60b30-b67c-11e3-b0b9-f01faf20d111", + "labels": [ + "remote-access-trojan" + ], + "modified": "2017-01-27T13:49:53.997Z", + "name": "Poison Ivy", + "type": "malware" + }, + { + "created": "2014-05-08T09:00:00.000Z", + "id": "indicator--a932fcc6-e032-176c-126f-cb970a5a1ade", + "labels": [ + "file-hash-watchlist" + ], + "modified": "2014-05-08T09:00:00.000Z", + "name": "File hash for Poison Ivy variant", + "pattern": "[file:hashes.'SHA-256' = 'ef537f25c895bfa782526529a9b63d97aa631564d5d789c2b765448c8635fb6c']", + "type": "indicator", + "valid_from": "2014-05-08T09:00:00.000000Z" + }, + { + "created": "2014-05-08T09:00:00.000Z", + "granular_markings": [ + { + "marking_ref": "marking-definition--5e57c739-391a-4eb3-b6be-7d15ca92d5ed", + "selectors": [ + "relationship_type" + ] + } + ], + "id": "relationship--2f9a9aa9-108a-4333-83e2-4fb25add0463", + "modified": "2014-05-08T09:00:00.000Z", + "object_marking_refs": [ + "marking-definition--613f2e26-407d-48c7-9eca-b8e91df99dc9" + ], + "relationship_type": "indicates", + "revoked": True, + "source_ref": "indicator--a932fcc6-e032-176c-126f-cb970a5a1ade", + "target_ref": "malware--fdd60b30-b67c-11e3-b0b9-f01faf20d111", + "type": "relationship" + }, + { + "id": "vulnerability--ee916c28-c7a4-4d0d-ad56-a8d357f89fef", + "created": "2016-02-14T00:00:00.000Z", + "created_by_ref": "identity--00000000-0000-0000-0000-b8e91df99dc9", + "modified": "2016-02-14T00:00:00.000Z", + "type": "vulnerability", + "name": "CVE-2014-0160", + "description": "The (1) TLS...", + "external_references": [ + { + "source_name": "cve", + "external_id": "CVE-2014-0160" + } + ], + "labels": ["heartbleed", "has-logo"] + }, + { + "type": "observed-data", + "id": "observed-data--b67d30ff-02ac-498a-92f9-32f845f448cf", + "created_by_ref": "identity--f431f809-377b-45e0-aa1c-6a4751cae5ff", + "created": "2016-04-06T19:58:16.000Z", + "modified": "2016-04-06T19:58:16.000Z", + "first_observed": "2015-12-21T19:00:00Z", + "last_observed": "2015-12-21T19:00:00Z", + "number_observed": 1, + "objects": { + "0": { + "type": "file", + "name": "HAL 9000.exe" + } + } + + } +] + +# same as above objects but converted to real Python STIX2 objects +# to test filters against true Python STIX2 objects +real_stix_objs = [parse(stix_obj) for stix_obj in stix_objs] + +filters = [ + Filter("type", "!=", "relationship"), + Filter("id", "=", "relationship--2f9a9aa9-108a-4333-83e2-4fb25add0463"), + Filter("labels", "in", "remote-access-trojan"), + Filter("created", ">", "2015-01-01T01:00:00.000Z"), + Filter("revoked", "=", True), + Filter("revoked", "!=", True), + Filter("object_marking_refs", "=", "marking-definition--613f2e26-407d-48c7-9eca-b8e91df99dc9"), + Filter("granular_markings.selectors", "in", "relationship_type"), + Filter("granular_markings.marking_ref", "=", "marking-definition--5e57c739-391a-4eb3-b6be-7d15ca92d5ed"), + Filter("external_references.external_id", "in", "CVE-2014-0160,CVE-2017-6608"), + Filter("created_by_ref", "=", "identity--00000000-0000-0000-0000-b8e91df99dc9"), + Filter("object_marking_refs", "=", "marking-definition--613f2e26-0000-0000-0000-b8e91df99dc9"), + Filter("granular_markings.selectors", "in", "description"), + Filter("external_references.source_name", "=", "CVE"), + Filter("objects", "=", {"0": {"type": "file", "name": "HAL 9000.exe"}}) +] + IND1 = { "created": "2017-01-27T13:49:53.935Z", "id": "indicator--d81f86b9-975b-bc0b-775e-810c5ad45a4f", @@ -240,111 +342,7 @@ def test_filter_type_underscore_check(): assert "Filter for property 'type' cannot have its value 'oh_underscore'" in str(excinfo.value) -def test_apply_common_filters(): - stix_objs = [ - { - "created": "2017-01-27T13:49:53.997Z", - "description": "\n\nTITLE:\n\tPoison Ivy", - "id": "malware--fdd60b30-b67c-11e3-b0b9-f01faf20d111", - "labels": [ - "remote-access-trojan" - ], - "modified": "2017-01-27T13:49:53.997Z", - "name": "Poison Ivy", - "type": "malware" - }, - { - "created": "2014-05-08T09:00:00.000Z", - "id": "indicator--a932fcc6-e032-176c-126f-cb970a5a1ade", - "labels": [ - "file-hash-watchlist" - ], - "modified": "2014-05-08T09:00:00.000Z", - "name": "File hash for Poison Ivy variant", - "pattern": "[file:hashes.'SHA-256' = 'ef537f25c895bfa782526529a9b63d97aa631564d5d789c2b765448c8635fb6c']", - "type": "indicator", - "valid_from": "2014-05-08T09:00:00.000000Z" - }, - { - "created": "2014-05-08T09:00:00.000Z", - "granular_markings": [ - { - "marking_ref": "marking-definition--5e57c739-391a-4eb3-b6be-7d15ca92d5ed", - "selectors": [ - "relationship_type" - ] - } - ], - "id": "relationship--2f9a9aa9-108a-4333-83e2-4fb25add0463", - "modified": "2014-05-08T09:00:00.000Z", - "object_marking_refs": [ - "marking-definition--613f2e26-407d-48c7-9eca-b8e91df99dc9" - ], - "relationship_type": "indicates", - "revoked": True, - "source_ref": "indicator--a932fcc6-e032-176c-126f-cb970a5a1ade", - "target_ref": "malware--fdd60b30-b67c-11e3-b0b9-f01faf20d111", - "type": "relationship" - }, - { - "id": "vulnerability--ee916c28-c7a4-4d0d-ad56-a8d357f89fef", - "created": "2016-02-14T00:00:00.000Z", - "created_by_ref": "identity--00000000-0000-0000-0000-b8e91df99dc9", - "modified": "2016-02-14T00:00:00.000Z", - "type": "vulnerability", - "name": "CVE-2014-0160", - "description": "The (1) TLS...", - "external_references": [ - { - "source_name": "cve", - "external_id": "CVE-2014-0160" - } - ], - "labels": ["heartbleed", "has-logo"] - }, - { - "type": "observed-data", - "id": "observed-data--b67d30ff-02ac-498a-92f9-32f845f448cf", - "created_by_ref": "identity--f431f809-377b-45e0-aa1c-6a4751cae5ff", - "created": "2016-04-06T19:58:16.000Z", - "modified": "2016-04-06T19:58:16.000Z", - "first_observed": "2015-12-21T19:00:00Z", - "last_observed": "2015-12-21T19:00:00Z", - "number_observed": 1, - "objects": { - "0": { - "type": "file", - "name": "HAL 9000.exe" - } - } - - } - ] - - # same as above objects but converted to real Python STIX2 objects - # to test filters against true Python STIX2 objects - print(stix_objs) - real_stix_objs = [parse(stix_obj) for stix_obj in stix_objs] - print("after\n\n") - print(stix_objs) - filters = [ - Filter("type", "!=", "relationship"), - Filter("id", "=", "relationship--2f9a9aa9-108a-4333-83e2-4fb25add0463"), - Filter("labels", "in", "remote-access-trojan"), - Filter("created", ">", "2015-01-01T01:00:00.000Z"), - Filter("revoked", "=", True), - Filter("revoked", "!=", True), - Filter("object_marking_refs", "=", "marking-definition--613f2e26-407d-48c7-9eca-b8e91df99dc9"), - Filter("granular_markings.selectors", "in", "relationship_type"), - Filter("granular_markings.marking_ref", "=", "marking-definition--5e57c739-391a-4eb3-b6be-7d15ca92d5ed"), - Filter("external_references.external_id", "in", "CVE-2014-0160,CVE-2017-6608"), - Filter("created_by_ref", "=", "identity--00000000-0000-0000-0000-b8e91df99dc9"), - Filter("object_marking_refs", "=", "marking-definition--613f2e26-0000-0000-0000-b8e91df99dc9"), - Filter("granular_markings.selectors", "in", "description"), - Filter("external_references.source_name", "=", "CVE"), - Filter("objects", "=", {"0": {"type": "file", "name": "HAL 9000.exe"}}) - ] - +def test_apply_common_filters0(): # "Return any object whose type is not relationship" resp = list(apply_common_filters(stix_objs, [filters[0]])) ids = [r['id'] for r in resp] @@ -360,6 +358,8 @@ def test_apply_common_filters(): assert real_stix_objs[3].id in ids assert len(ids) == 4 + +def test_apply_common_filters1(): # "Return any object that matched id relationship--2f9a9aa9-108a-4333-83e2-4fb25add0463" resp = list(apply_common_filters(stix_objs, [filters[1]])) assert resp[0]['id'] == stix_objs[2]['id'] @@ -369,6 +369,8 @@ def test_apply_common_filters(): assert resp[0].id == real_stix_objs[2].id assert len(resp) == 1 + +def test_apply_common_filters2(): # "Return any object that contains remote-access-trojan in labels" resp = list(apply_common_filters(stix_objs, [filters[2]])) assert resp[0]['id'] == stix_objs[0]['id'] @@ -378,11 +380,19 @@ def test_apply_common_filters(): assert resp[0].id == real_stix_objs[0].id assert len(resp) == 1 + +def test_apply_common_filters3(): # "Return any object created after 2015-01-01T01:00:00.000Z" resp = list(apply_common_filters(stix_objs, [filters[3]])) assert resp[0]['id'] == stix_objs[0]['id'] assert len(resp) == 3 + resp = list(apply_common_filters(real_stix_objs, [filters[3]])) + assert resp[0].id == real_stix_objs[0].id + assert len(resp) == 3 + + +def test_apply_common_filters4(): # "Return any revoked object" resp = list(apply_common_filters(stix_objs, [filters[4]])) assert resp[0]['id'] == stix_objs[2]['id'] @@ -392,6 +402,8 @@ def test_apply_common_filters(): assert resp[0].id == real_stix_objs[2].id assert len(resp) == 1 + +def test_apply_common_filters5(): # "Return any object whose not revoked" # Note that if 'revoked' property is not present in object. # Currently we can't use such an expression to filter for... :( @@ -401,6 +413,8 @@ def test_apply_common_filters(): resp = list(apply_common_filters(real_stix_objs, [filters[5]])) assert len(resp) == 0 + +def test_apply_common_filters6(): # "Return any object that matches marking-definition--613f2e26-407d-48c7-9eca-b8e91df99dc9 in object_marking_refs" resp = list(apply_common_filters(stix_objs, [filters[6]])) assert resp[0]['id'] == stix_objs[2]['id'] @@ -410,6 +424,8 @@ def test_apply_common_filters(): assert resp[0].id == real_stix_objs[2].id assert len(resp) == 1 + +def test_apply_common_filters7(): # "Return any object that contains relationship_type in their selectors AND # also has marking-definition--5e57c739-391a-4eb3-b6be-7d15ca92d5ed in marking_ref" resp = list(apply_common_filters(stix_objs, [filters[7], filters[8]])) @@ -420,6 +436,8 @@ def test_apply_common_filters(): assert resp[0].id == real_stix_objs[2].id assert len(resp) == 1 + +def test_apply_common_filters8(): # "Return any object that contains CVE-2014-0160,CVE-2017-6608 in their external_id" resp = list(apply_common_filters(stix_objs, [filters[9]])) assert resp[0]['id'] == stix_objs[3]['id'] @@ -429,6 +447,8 @@ def test_apply_common_filters(): assert resp[0].id == real_stix_objs[3].id assert len(resp) == 1 + +def test_apply_common_filters9(): # "Return any object that matches created_by_ref identity--00000000-0000-0000-0000-b8e91df99dc9" resp = list(apply_common_filters(stix_objs, [filters[10]])) assert len(resp) == 1 @@ -436,6 +456,8 @@ def test_apply_common_filters(): resp = list(apply_common_filters(real_stix_objs, [filters[10]])) assert len(resp) == 1 + +def test_apply_common_filters10(): # "Return any object that matches marking-definition--613f2e26-0000-0000-0000-b8e91df99dc9 in object_marking_refs" (None) resp = list(apply_common_filters(stix_objs, [filters[11]])) assert len(resp) == 0 @@ -443,6 +465,8 @@ def test_apply_common_filters(): resp = list(apply_common_filters(real_stix_objs, [filters[11]])) assert len(resp) == 0 + +def test_apply_common_filters11(): # "Return any object that contains description in its selectors" (None) resp = list(apply_common_filters(stix_objs, [filters[12]])) assert len(resp) == 0 @@ -450,6 +474,8 @@ def test_apply_common_filters(): resp = list(apply_common_filters(real_stix_objs, [filters[12]])) assert len(resp) == 0 + +def test_apply_common_filters12(): # "Return any object that matches CVE in source_name" (None, case sensitive) resp = list(apply_common_filters(stix_objs, [filters[13]])) assert len(resp) == 0 @@ -457,19 +483,51 @@ def test_apply_common_filters(): resp = list(apply_common_filters(real_stix_objs, [filters[13]])) assert len(resp) == 0 + +def test_apply_common_filters13(): # Return any object that matches file object in "objects" - # BUG: This test is brokem , weird behavior, the file obj - # in stix_objs is being parsed into real python-stix2 obj even though - # it never goes through parse() --> BAD <_< resp = list(apply_common_filters(stix_objs, [filters[14]])) - assert resp[0]["id"] == stix_objs[14]["id"] + assert resp[0]["id"] == stix_objs[4]["id"] assert len(resp) == 1 resp = list(apply_common_filters(real_stix_objs, [filters[14]])) - assert resp[0].id == real_stix_objs[14].id + assert resp[0].id == real_stix_objs[4].id assert len(resp) == 1 +def test_datetime_filter_behavior(): + """if a filter is initialized with its value being a datetime object + OR the STIX object property being filtered on is a datetime object, all + resulting comparisons executed are done on the string representations + of the datetime objects, as the Filter functionality will convert + all datetime objects to there string forms using format_datetim() + + This test makes sure all datetime comparisons are carried out correctly + """ + filter_with_dt_obj = Filter("created", "=", parse_into_datetime("2016-02-14T00:00:00.000Z", "millisecond")) + filter_with_str = Filter("created", "=", "2016-02-14T00:00:00.000Z") + + # compare datetime string to filter w/ datetime obj + resp = list(apply_common_filters(stix_objs, [filter_with_dt_obj])) + assert len(resp) == 1 + assert resp[0]["id"] == "vulnerability--ee916c28-c7a4-4d0d-ad56-a8d357f89fef" + + # compare datetime obj to filter w/ datetime obj + resp = list(apply_common_filters(real_stix_objs, [filter_with_dt_obj])) + assert len(resp) == 1 + assert resp[0]["id"] == "vulnerability--ee916c28-c7a4-4d0d-ad56-a8d357f89fef" + + # compare datetime string to filter w/ str + resp = list(apply_common_filters(stix_objs, [filter_with_str])) + assert len(resp) == 1 + assert resp[0]["id"] == "vulnerability--ee916c28-c7a4-4d0d-ad56-a8d357f89fef" + + # compare datetime obj to filter w/ str + resp = list(apply_common_filters(real_stix_objs, [filter_with_str])) + assert len(resp) == 1 + assert resp[0]["id"] == "vulnerability--ee916c28-c7a4-4d0d-ad56-a8d357f89fef" + + def test_filters0(): # "Return any object modified before 2017-01-28T13:49:53.935Z" resp = list(apply_common_filters(STIX_OBJS2, [Filter("modified", "<", "2017-01-28T13:49:53.935Z")])) @@ -510,7 +568,9 @@ def test_filters3(): assert len(resp) == 2 # "Return any object modified before or on 2017-01-28T13:49:53.935Z" - resp = list(apply_common_filters(REAL_STIX_OBJS2, [Filter("modified", "<=", parse_into_datetime("2017-01-27T13:49:53.935Z"))])) + fv = Filter("modified", "<=", parse_into_datetime("2017-01-27T13:49:53.935Z")) + print(fv) + resp = list(apply_common_filters(REAL_STIX_OBJS2, [fv])) assert resp[0].id == REAL_STIX_OBJS2[1].id assert len(resp) == 2 @@ -592,15 +652,6 @@ def test_filters7(): assert len(resp) == 1 -def test_assemble_filters(): - filter1 = Filter("name", "=", "Malicious site hosting downloader") - filter2 = Filter("modified", ">", "2017-01-28T13:49:53.935Z") - result = _assemble_filters(filter1, filter2) - assert len(result) == 2 - assert result[0].property == 'name' - assert result[1].property == 'modified' - - def test_deduplicate(): unique = deduplicate(STIX_OBJS1) diff --git a/stix2/test/test_utils.py b/stix2/test/test_utils.py index cbe5b0f..84b2476 100644 --- a/stix2/test/test_utils.py +++ b/stix2/test/test_utils.py @@ -62,7 +62,7 @@ def test_parse_datetime_invalid(ts): [("a", 1,)], ]) def test_get_dict(data): - assert stix2.utils.get_dict(data) + assert stix2.utils._get_dict(data) @pytest.mark.parametrize('data', [ @@ -73,7 +73,7 @@ def test_get_dict(data): ]) def test_get_dict_invalid(data): with pytest.raises(ValueError): - stix2.utils.get_dict(data) + stix2.utils._get_dict(data) @pytest.mark.parametrize('stix_id, typ', [ diff --git a/stix2/utils.py b/stix2/utils.py index 9febd78..fdb7679 100644 --- a/stix2/utils.py +++ b/stix2/utils.py @@ -140,7 +140,7 @@ def parse_into_datetime(value, precision=None): return STIXdatetime(ts, precision=precision) -def get_dict(data): +def _get_dict(data): """Return data as a dictionary. Input can be a dictionary, string, or file-like object. diff --git a/stix2/v20/common.py b/stix2/v20/common.py index e915df6..0bba3b1 100644 --- a/stix2/v20/common.py +++ b/stix2/v20/common.py @@ -7,7 +7,7 @@ from ..markings import _MarkingsMixin from ..properties import (HashesProperty, IDProperty, ListProperty, Property, ReferenceProperty, SelectorProperty, StringProperty, TimestampProperty, TypeProperty) -from ..utils import NOW, get_dict +from ..utils import NOW, _get_dict class ExternalReference(_STIXBase): @@ -125,7 +125,7 @@ class MarkingDefinition(_STIXBase, _MarkingsMixin): raise ValueError("definition_type must be a valid marking type") if not isinstance(kwargs['definition'], marking_type): - defn = get_dict(kwargs['definition']) + defn = _get_dict(kwargs['definition']) kwargs['definition'] = marking_type(**defn) super(MarkingDefinition, self).__init__(**kwargs) diff --git a/stix2/v20/observables.py b/stix2/v20/observables.py index 39a8f19..75887ee 100644 --- a/stix2/v20/observables.py +++ b/stix2/v20/observables.py @@ -6,6 +6,7 @@ Observable and do not have a ``_type`` attribute. """ from collections import OrderedDict +import copy from ..base import _Extension, _Observable, _STIXBase from ..exceptions import (AtLeastOnePropertyError, DependentPropertiesError, @@ -15,7 +16,7 @@ from ..properties import (BinaryProperty, BooleanProperty, DictionaryProperty, HashesProperty, HexProperty, IntegerProperty, ListProperty, ObjectReferenceProperty, Property, StringProperty, TimestampProperty, TypeProperty) -from ..utils import get_dict +from ..utils import _get_dict class ObservableProperty(Property): @@ -24,7 +25,11 @@ class ObservableProperty(Property): def clean(self, value): try: - dictified = get_dict(value) + dictified = _get_dict(value) + # get deep copy since we are going modify the dict and might + # modify the original dict as _get_dict() does not return new + # dict when passed a dict + dictified = copy.deepcopy(dictified) except ValueError: raise ValueError("The observable property must contain a dictionary") if dictified == {}: @@ -49,7 +54,11 @@ class ExtensionsProperty(DictionaryProperty): def clean(self, value): try: - dictified = get_dict(value) + dictified = _get_dict(value) + # get deep copy since we are going modify the dict and might + # modify the original dict as _get_dict() does not return new + # dict when passed a dict + dictified = copy.deepcopy(dictified) except ValueError: raise ValueError("The extensions property must contain a dictionary") if dictified == {}: @@ -915,7 +924,12 @@ def parse_observable(data, _valid_refs=None, allow_custom=False): An instantiated Python STIX Cyber Observable object. """ - obj = get_dict(data) + obj = _get_dict(data) + # get deep copy since we are going modify the dict and might + # modify the original dict as _get_dict() does not return new + # dict when passed a dict + obj = copy.deepcopy(obj) + obj['_valid_refs'] = _valid_refs or [] if 'type' not in obj: diff --git a/stix2/workbench.py b/stix2/workbench.py index b47968e..6654555 100644 --- a/stix2/workbench.py +++ b/stix2/workbench.py @@ -48,7 +48,7 @@ from . import (AlternateDataStream, ArchiveExt, Artifact, AutonomousSystem, # n WindowsPEOptionalHeaderType, WindowsPESection, WindowsProcessExt, WindowsRegistryKey, WindowsRegistryValueType, WindowsServiceExt, X509Certificate, X509V3ExtenstionsType) -from .datastore.filters import _assemble_filters +from .datastore.filters import FilterSet # Use an implicit MemoryStore _environ = Environment(store=MemoryStore()) @@ -156,7 +156,8 @@ def attack_patterns(filters=None): the query. """ - filter_list = _assemble_filters(filters, [Filter('type', '=', 'attack-pattern')]) + filter_list = FilterSet(filters) + filter_list.add(Filter('type', '=', 'attack-pattern')) return query(filter_list) @@ -168,7 +169,8 @@ def campaigns(filters=None): the query. """ - filter_list = _assemble_filters(filters, [Filter('type', '=', 'campaign')]) + filter_list = FilterSet(filters) + filter_list.add(Filter('type', '=', 'campaign')) return query(filter_list) @@ -180,7 +182,8 @@ def courses_of_action(filters=None): the query. """ - filter_list = _assemble_filters(filters, [Filter('type', '=', 'course-of-action')]) + filter_list = FilterSet(filters) + filter_list.add(Filter('type', '=', 'course-of-action')) return query(filter_list) @@ -192,7 +195,8 @@ def identities(filters=None): the query. """ - filter_list = _assemble_filters(filters, [Filter('type', '=', 'identity')]) + filter_list = FilterSet(filters) + filter_list.add(Filter('type', '=', 'identity')) return query(filter_list) @@ -204,7 +208,8 @@ def indicators(filters=None): the query. """ - filter_list = _assemble_filters(filters, [Filter('type', '=', 'indicator')]) + filter_list = FilterSet(filters) + filter_list.add(Filter('type', '=', 'indicator')) return query(filter_list) @@ -216,7 +221,8 @@ def intrusion_sets(filters=None): the query. """ - filter_list = _assemble_filters(filters, [Filter('type', '=', 'intrusion-set')]) + filter_list = FilterSet(filters) + filter_list.add(Filter('type', '=', 'intrusion-set')) return query(filter_list) @@ -228,7 +234,8 @@ def malware(filters=None): the query. """ - filter_list = _assemble_filters(filters, [Filter('type', '=', 'malware')]) + filter_list = FilterSet(filters) + filter_list.add(Filter('type', '=', 'malware')) return query(filter_list) @@ -240,7 +247,8 @@ def observed_data(filters=None): the query. """ - filter_list = _assemble_filters(filters, [Filter('type', '=', 'observed-data')]) + filter_list = FilterSet(filters) + filter_list.add(Filter('type', '=', 'observed-data')) return query(filter_list) @@ -252,7 +260,8 @@ def reports(filters=None): the query. """ - filter_list = _assemble_filters(filters, [Filter('type', '=', 'report')]) + filter_list = FilterSet(filters) + filter_list.add([Filter('type', '=', 'report')]) return query(filter_list) @@ -264,7 +273,8 @@ def threat_actors(filters=None): the query. """ - filter_list = _assemble_filters(filters, [Filter('type', '=', 'threat-actor')]) + filter_list = FilterSet(filters) + filter_list.add(Filter('type', '=', 'threat-actor')) return query(filter_list) @@ -276,7 +286,8 @@ def tools(filters=None): the query. """ - filter_list = _assemble_filters(filters, [Filter('type', '=', 'tool')]) + filter_list = FilterSet(filters) + filter_list.add(Filter('type', '=', 'tool')) return query(filter_list) @@ -288,5 +299,6 @@ def vulnerabilities(filters=None): the query. """ - filter_list = _assemble_filters(filters, [Filter('type', '=', 'vulnerability')]) + filter_list = FilterSet(filters) + filter_list.add(Filter('type', '=', 'vulnerability')) return query(filter_list) From fc6a33b23e2a7131249b89eb5a1b8394d328ca26 Mon Sep 17 00:00:00 2001 From: Chris Lenk Date: Fri, 13 Apr 2018 11:18:56 -0400 Subject: [PATCH 50/61] Disallow missing 'type' property with allow_custom There was a bug where if you allowed custom content the library would parse an object without the required 'type' property. --- stix2/base.py | 10 +++++----- stix2/exceptions.py | 7 +++++++ stix2/test/test_custom.py | 12 +++++++++++- stix2/v20/observables.py | 13 +++++++------ 4 files changed, 30 insertions(+), 12 deletions(-) diff --git a/stix2/base.py b/stix2/base.py index 05afe3f..3219007 100644 --- a/stix2/base.py +++ b/stix2/base.py @@ -6,11 +6,11 @@ import datetime as dt import simplejson as json -from .exceptions import (AtLeastOnePropertyError, DependentPropertiesError, - ExtraPropertiesError, ImmutableError, - InvalidObjRefError, InvalidValueError, +from .exceptions import (AtLeastOnePropertyError, CustomContentError, + DependentPropertiesError, ExtraPropertiesError, + ImmutableError, InvalidObjRefError, InvalidValueError, MissingPropertiesError, - MutuallyExclusivePropertiesError, ParseError) + MutuallyExclusivePropertiesError) from .markings.utils import validate from .utils import NOW, find_property_index, format_datetime, get_timestamp from .utils import new_version as _new_version @@ -61,7 +61,7 @@ class _STIXBase(collections.Mapping): try: kwargs[prop_name] = prop.clean(kwargs[prop_name]) except ValueError as exc: - if self.__allow_custom and isinstance(exc, ParseError): + if self.__allow_custom and isinstance(exc, CustomContentError): return raise InvalidValueError(self.__class__, prop_name, reason=str(exc)) diff --git a/stix2/exceptions.py b/stix2/exceptions.py index 841a8e9..79c5a81 100644 --- a/stix2/exceptions.py +++ b/stix2/exceptions.py @@ -163,6 +163,13 @@ class ParseError(STIXError, ValueError): super(ParseError, self).__init__(msg) +class CustomContentError(STIXError, ValueError): + """Custom STIX Content (SDO, Observable, Extension, etc.) detected.""" + + def __init__(self, msg): + super(CustomContentError, self).__init__(msg) + + class InvalidSelectorError(STIXError, AssertionError): """Granular Marking selector violation. The selector must resolve into an existing STIX object property.""" diff --git a/stix2/test/test_custom.py b/stix2/test/test_custom.py index 8da2a7a..d655e5d 100644 --- a/stix2/test/test_custom.py +++ b/stix2/test/test_custom.py @@ -373,7 +373,7 @@ def test_parse_unregistered_custom_observable_object(): "property1": "something" }""" - with pytest.raises(stix2.exceptions.ParseError) as excinfo: + with pytest.raises(stix2.exceptions.CustomContentError) as excinfo: stix2.parse_observable(nt_string) assert "Can't parse unknown observable type" in str(excinfo.value) @@ -384,6 +384,16 @@ def test_parse_unregistered_custom_observable_object(): assert not isinstance(parsed_custom, stix2.core._STIXBase) +def test_parse_unregistered_custom_observable_object_with_no_type(): + nt_string = """{ + "property1": "something" + }""" + + with pytest.raises(stix2.exceptions.ParseError) as excinfo: + stix2.parse_observable(nt_string, allow_custom=True) + assert "Can't parse observable with no 'type' property" in str(excinfo.value) + + def test_parse_observed_data_with_custom_observable(): input_str = """{ "type": "observed-data", diff --git a/stix2/v20/observables.py b/stix2/v20/observables.py index 7dc7c02..b5ffe49 100644 --- a/stix2/v20/observables.py +++ b/stix2/v20/observables.py @@ -8,8 +8,8 @@ Observable and do not have a ``_type`` attribute. from collections import OrderedDict from ..base import _Extension, _Observable, _STIXBase -from ..exceptions import (AtLeastOnePropertyError, DependentPropertiesError, - ParseError) +from ..exceptions import (AtLeastOnePropertyError, CustomContentError, + DependentPropertiesError, ParseError) from ..properties import (BinaryProperty, BooleanProperty, DictionaryProperty, EmbeddedObjectProperty, EnumProperty, FloatProperty, HashesProperty, HexProperty, IntegerProperty, @@ -67,7 +67,7 @@ class ExtensionsProperty(DictionaryProperty): else: raise ValueError("Cannot determine extension type.") else: - raise ParseError("Can't parse unknown extension type: {}".format(key)) + raise CustomContentError("Can't parse unknown extension type: {}".format(key)) else: raise ValueError("The enclosing type '%s' has no extensions defined" % self.enclosing_type) return dictified @@ -927,8 +927,8 @@ def parse_observable(data, _valid_refs=None, allow_custom=False): # flag allows for unknown custom objects too, but will not # be parsed into STIX observable object, just returned as is return obj - raise ParseError("Can't parse unknown observable type '%s'! For custom observables, " - "use the CustomObservable decorator." % obj['type']) + raise CustomContentError("Can't parse unknown observable type '%s'! For custom observables, " + "use the CustomObservable decorator." % obj['type']) if 'extensions' in obj and obj['type'] in EXT_MAP: for name, ext in obj['extensions'].items(): @@ -936,7 +936,8 @@ def parse_observable(data, _valid_refs=None, allow_custom=False): ext_class = EXT_MAP[obj['type']][name] except KeyError: if not allow_custom: - raise ParseError("Can't parse unknown extension type '%s' for observable type '%s'!" % (name, obj['type'])) + raise CustomContentError("Can't parse unknown extension type '%s'" + "for observable type '%s'!" % (name, obj['type'])) else: # extension was found obj['extensions'][name] = ext_class(allow_custom=allow_custom, **obj['extensions'][name]) From 61e091baf34d029aebf8b0bf3c88449dd87329e7 Mon Sep 17 00:00:00 2001 From: = Date: Fri, 13 Apr 2018 12:25:12 -0400 Subject: [PATCH 51/61] added FilterSet class for internal use; modified certain parsing processes to make deepcopies or suppled values(dicts) so as to taint original user passed data; added Filter logic to handle datetime objects; added/adjusted tests accordingly --- stix2/datastore/filters.py | 37 ++++++++++++++++++++++++++++++------ stix2/test/test_datastore.py | 1 - 2 files changed, 31 insertions(+), 7 deletions(-) diff --git a/stix2/datastore/filters.py b/stix2/datastore/filters.py index 3d2c5e8..21a156e 100644 --- a/stix2/datastore/filters.py +++ b/stix2/datastore/filters.py @@ -192,25 +192,43 @@ def _check_filter(filter_, stix_obj): class FilterSet(object): - """ """ + """Internal STIX2 class to facilitate the grouping of Filters + into sets. The primary motivation for this class came from the problem + that Filters that had a dict as a value could not be added to a Python + set as dicts are not hashable. Thus this class provides set functionality + but internally stores filters in a list. + """ def __init__(self, filters=None): - """ """ + """ + Args: + filters: see FilterSet.add() + """ self._filters = [] if filters: self.add(filters) def __iter__(self): - """ """ + """provide iteration functionality of FilterSet""" for f in self._filters: yield f def __len__(self): - """ """ + """provide built-in len() utility of FilterSet""" return len(self._filters) def add(self, filters=None): - """ """ + """add a Filter, FilterSet, or list of Filters to the FilterSet + + Operates like set, only adding unique stix2.Filters to the FilterSet + + NOTE: method designed to be very accomodating (i.e. even accepting filters=None) + as it allows for blind calls (very useful in DataStore) + + Args: + filters: stix2.Filter OR list of stix2.Filter OR stix2.FilterSet + + """ if not filters: # so add() can be called blindly, useful for # DataStore/Environment usage of filter operations @@ -226,7 +244,14 @@ class FilterSet(object): return def remove(self, filters=None): - """ """ + """remove a Filter, list of Filters, or FilterSet from the FilterSet + + NOTE: method designed to be very accomodating (i.e. even accepting filters=None) + as it allows for blind calls (very useful in DataStore) + + Args: + filters: stix2.Filter OR list of stix2.Filter or stix2.FilterSet + """ if not filters: # so remove() can be called blindly, useful for # DataStore/Environemnt usage of filter ops diff --git a/stix2/test/test_datastore.py b/stix2/test/test_datastore.py index 9ffa992..772c72e 100644 --- a/stix2/test/test_datastore.py +++ b/stix2/test/test_datastore.py @@ -569,7 +569,6 @@ def test_filters3(): # "Return any object modified before or on 2017-01-28T13:49:53.935Z" fv = Filter("modified", "<=", parse_into_datetime("2017-01-27T13:49:53.935Z")) - print(fv) resp = list(apply_common_filters(REAL_STIX_OBJS2, [fv])) assert resp[0].id == REAL_STIX_OBJS2[1].id assert len(resp) == 2 From eba1844535a8140751dfee6dfcdc81835ba94830 Mon Sep 17 00:00:00 2001 From: = Date: Fri, 13 Apr 2018 14:01:33 -0400 Subject: [PATCH 52/61] tweak to filter property checking to make sure original object property is not altered; added tests for this as well --- stix2/datastore/filters.py | 5 +++-- stix2/test/test_datastore.py | 10 +++++++++- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/stix2/datastore/filters.py b/stix2/datastore/filters.py index 21a156e..c260dcc 100644 --- a/stix2/datastore/filters.py +++ b/stix2/datastore/filters.py @@ -90,10 +90,11 @@ class Filter(collections.namedtuple("Filter", ['property', 'op', 'value'])): False otherwise. """ if isinstance(stix_obj_property, datetime): - # if a datetime obj, convert to str before comparison + # if a datetime obj, use str format before comparison # NOTE: this check seems like it should be done upstream # but will put here for now - stix_obj_property = format_datetime(stix_obj_property) + tmp = format_datetime(stix_obj_property) + stix_obj_property = tmp # use tmp variable to avoid deepcopy op if self.op == "=": return stix_obj_property == self.value diff --git a/stix2/test/test_datastore.py b/stix2/test/test_datastore.py index 772c72e..7ee4877 100644 --- a/stix2/test/test_datastore.py +++ b/stix2/test/test_datastore.py @@ -6,7 +6,7 @@ from stix2.core import parse from stix2.datastore import (CompositeDataSource, DataSink, DataSource, make_id, taxii) from stix2.datastore.filters import apply_common_filters -from stix2.utils import deduplicate, parse_into_datetime +from stix2.utils import STIXdatetime, deduplicate, parse_into_datetime COLLECTION_URL = 'https://example.com/api1/collections/91a7b528-80eb-42ed-a74d-c6fbd5a26116/' @@ -489,6 +489,9 @@ def test_apply_common_filters13(): resp = list(apply_common_filters(stix_objs, [filters[14]])) assert resp[0]["id"] == stix_objs[4]["id"] assert len(resp) == 1 + # important additional check to make sure original File dict was + # not converted to File object. (this was a deep bug found) + assert isinstance(resp[0]["objects"]["0"], dict) resp = list(apply_common_filters(real_stix_objs, [filters[14]])) assert resp[0].id == real_stix_objs[4].id @@ -507,6 +510,9 @@ def test_datetime_filter_behavior(): filter_with_dt_obj = Filter("created", "=", parse_into_datetime("2016-02-14T00:00:00.000Z", "millisecond")) filter_with_str = Filter("created", "=", "2016-02-14T00:00:00.000Z") + # check taht filter value is converted from datetime to str + assert isinstance(filter_with_dt_obj.value, str) + # compare datetime string to filter w/ datetime obj resp = list(apply_common_filters(stix_objs, [filter_with_dt_obj])) assert len(resp) == 1 @@ -516,6 +522,7 @@ def test_datetime_filter_behavior(): resp = list(apply_common_filters(real_stix_objs, [filter_with_dt_obj])) assert len(resp) == 1 assert resp[0]["id"] == "vulnerability--ee916c28-c7a4-4d0d-ad56-a8d357f89fef" + assert isinstance(resp[0].created, STIXdatetime) # make sure original object not altered # compare datetime string to filter w/ str resp = list(apply_common_filters(stix_objs, [filter_with_str])) @@ -526,6 +533,7 @@ def test_datetime_filter_behavior(): resp = list(apply_common_filters(real_stix_objs, [filter_with_str])) assert len(resp) == 1 assert resp[0]["id"] == "vulnerability--ee916c28-c7a4-4d0d-ad56-a8d357f89fef" + assert isinstance(resp[0].created, STIXdatetime) # make sure original object not altered def test_filters0(): From a614a78e22b95d1b2f46df2d8432ab8505a68f06 Mon Sep 17 00:00:00 2001 From: = Date: Fri, 13 Apr 2018 14:21:44 -0400 Subject: [PATCH 53/61] rm testing lines --- stix2/test/test_custom.py | 1 - stix2/workbench.py | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/stix2/test/test_custom.py b/stix2/test/test_custom.py index 5829e29..f9bb875 100644 --- a/stix2/test/test_custom.py +++ b/stix2/test/test_custom.py @@ -80,7 +80,6 @@ def test_identity_custom_property_allowed(): def test_parse_identity_custom_property(data): with pytest.raises(stix2.exceptions.ExtraPropertiesError) as excinfo: identity = stix2.parse(data) - assert str(excinfo.value.cls) == str(stix2.Identity) assert excinfo.value.cls == stix2.Identity assert excinfo.value.properties == ['foo'] assert "Unexpected properties for" in str(excinfo.value) diff --git a/stix2/workbench.py b/stix2/workbench.py index 6654555..3697c63 100644 --- a/stix2/workbench.py +++ b/stix2/workbench.py @@ -261,7 +261,7 @@ def reports(filters=None): """ filter_list = FilterSet(filters) - filter_list.add([Filter('type', '=', 'report')]) + filter_list.add(Filter('type', '=', 'report')) return query(filter_list) From a475fc6dbd422dc97ece318e2ba089370e03eead Mon Sep 17 00:00:00 2001 From: Chris Lenk Date: Fri, 13 Apr 2018 14:52:00 -0400 Subject: [PATCH 54/61] Disallow invalid type names in custom classes --- stix2/test/test_custom.py | 54 +++++++++++++++++++++++++++++++++++++++ stix2/utils.py | 2 ++ stix2/v20/observables.py | 15 ++++++++++- stix2/v20/sdo.py | 10 +++++++- 4 files changed, 79 insertions(+), 2 deletions(-) diff --git a/stix2/test/test_custom.py b/stix2/test/test_custom.py index 56e578f..0e004a8 100644 --- a/stix2/test/test_custom.py +++ b/stix2/test/test_custom.py @@ -197,6 +197,24 @@ def test_custom_object_no_init_2(): assert no2.property1 == 'something' +def test_custom_object_invalid_type_name(): + with pytest.raises(ValueError) as excinfo: + @stix2.sdo.CustomObject('x', [ + ('property1', stix2.properties.StringProperty(required=True)), + ]) + class NewObj(object): + pass # pragma: no cover + assert "Invalid type name 'x': " in str(excinfo.value) + + with pytest.raises(ValueError) as excinfo: + @stix2.sdo.CustomObject('x_new_object', [ + ('property1', stix2.properties.StringProperty(required=True)), + ]) + class NewObj2(object): + pass # pragma: no cover + assert "Invalid type name 'x_new_object':" in str(excinfo.value) + + def test_parse_custom_object_type(): nt_string = """{ "type": "x-new-type", @@ -295,6 +313,24 @@ def test_custom_observable_object_no_init_2(): assert no2.property1 == 'something' +def test_custom_observable_object_invalid_type_name(): + with pytest.raises(ValueError) as excinfo: + @stix2.observables.CustomObservable('x', [ + ('property1', stix2.properties.StringProperty()), + ]) + class NewObs(object): + pass # pragma: no cover + assert "Invalid observable type name 'x':" in str(excinfo.value) + + with pytest.raises(ValueError) as excinfo: + @stix2.observables.CustomObservable('x_new_obs', [ + ('property1', stix2.properties.StringProperty()), + ]) + class NewObs2(object): + pass # pragma: no cover + assert "Invalid observable type name 'x_new_obs':" in str(excinfo.value) + + def test_custom_observable_object_invalid_ref_property(): with pytest.raises(ValueError) as excinfo: @stix2.observables.CustomObservable('x-new-obs', [ @@ -573,6 +609,24 @@ def test_custom_extension_invalid_observable(): assert "Custom observables must be created with the @CustomObservable decorator." in str(excinfo.value) +def test_custom_extension_invalid_type_name(): + with pytest.raises(ValueError) as excinfo: + @stix2.observables.CustomExtension(stix2.File, 'x', { + 'property1': stix2.properties.StringProperty(required=True), + }) + class FooExtension(): + pass # pragma: no cover + assert "Invalid extension type name 'x':" in str(excinfo.value) + + with pytest.raises(ValueError) as excinfo: + @stix2.observables.CustomExtension(stix2.File, 'x_new_ext', { + 'property1': stix2.properties.StringProperty(required=True), + }) + class BlaExtension(): + pass # pragma: no cover + assert "Invalid extension type name 'x_new_ext':" in str(excinfo.value) + + def test_custom_extension_no_properties(): with pytest.raises(ValueError) as excinfo: @stix2.observables.CustomExtension(stix2.DomainName, 'x-new-ext2', None) diff --git a/stix2/utils.py b/stix2/utils.py index 4ef3d23..e693d08 100644 --- a/stix2/utils.py +++ b/stix2/utils.py @@ -18,6 +18,8 @@ NOW = object() # STIX object properties that cannot be modified STIX_UNMOD_PROPERTIES = ["created", "created_by_ref", "id", "type"] +TYPE_REGEX = r'^\-?[a-z0-9]+(-[a-z0-9]+)*\-?$' + class STIXdatetime(dt.datetime): def __new__(cls, *args, **kwargs): diff --git a/stix2/v20/observables.py b/stix2/v20/observables.py index f6bac2b..773611e 100644 --- a/stix2/v20/observables.py +++ b/stix2/v20/observables.py @@ -6,6 +6,7 @@ Observable and do not have a ``_type`` attribute. """ from collections import OrderedDict +import re from ..base import _Extension, _Observable, _STIXBase from ..exceptions import (AtLeastOnePropertyError, CustomContentError, @@ -15,7 +16,7 @@ from ..properties import (BinaryProperty, BooleanProperty, DictionaryProperty, HashesProperty, HexProperty, IntegerProperty, ListProperty, ObjectReferenceProperty, Property, StringProperty, TimestampProperty, TypeProperty) -from ..utils import get_dict +from ..utils import TYPE_REGEX, get_dict class ObservableProperty(Property): @@ -967,6 +968,12 @@ def CustomObservable(type='x-custom-observable', properties=None): class _Custom(cls, _Observable): + if not re.match(TYPE_REGEX, type): + raise ValueError("Invalid observable type name '%s': must only contain the " + "characters a-z (lowercase ASCII), 0-9, and hyphen (-)." % type) + elif len(type) < 3 or len(type) > 250: + raise ValueError("Invalid observable type name '%s': must be between 3 and 250 characters." % type) + _type = type _properties = OrderedDict() _properties.update([ @@ -1040,6 +1047,12 @@ def CustomExtension(observable=None, type='x-custom-observable', properties=None class _Custom(cls, _Extension): + if not re.match(TYPE_REGEX, type): + raise ValueError("Invalid extension type name '%s': must only contain the " + "characters a-z (lowercase ASCII), 0-9, and hyphen (-)." % type) + elif len(type) < 3 or len(type) > 250: + raise ValueError("Invalid extension type name '%s': must be between 3 and 250 characters." % type) + _type = type _properties = OrderedDict() diff --git a/stix2/v20/sdo.py b/stix2/v20/sdo.py index 060b9f0..ff024f5 100644 --- a/stix2/v20/sdo.py +++ b/stix2/v20/sdo.py @@ -2,6 +2,7 @@ """ from collections import OrderedDict +import re import stix2 @@ -10,7 +11,7 @@ from ..markings import _MarkingsMixin from ..properties import (BooleanProperty, IDProperty, IntegerProperty, ListProperty, PatternProperty, ReferenceProperty, StringProperty, TimestampProperty, TypeProperty) -from ..utils import NOW +from ..utils import NOW, TYPE_REGEX from .common import ExternalReference, GranularMarking, KillChainPhase from .observables import ObservableProperty @@ -357,6 +358,13 @@ def CustomObject(type='x-custom-type', properties=None): def custom_builder(cls): class _Custom(cls, STIXDomainObject): + + if not re.match(TYPE_REGEX, type): + raise ValueError("Invalid type name '%s': must only contain the " + "characters a-z (lowercase ASCII), 0-9, and hyphen (-)." % type) + elif len(type) < 3 or len(type) > 250: + raise ValueError("Invalid type name '%s': must be between 3 and 250 characters." % type) + _type = type _properties = OrderedDict() _properties.update([ From 47347111372d31af5050bde387fd8ba9e9d6d62c Mon Sep 17 00:00:00 2001 From: = Date: Fri, 13 Apr 2018 15:07:49 -0400 Subject: [PATCH 55/61] corresponding doc update --- docs/guide/datastore.ipynb | 30 ++++++++++++++++++------------ 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/docs/guide/datastore.ipynb b/docs/guide/datastore.ipynb index 7d40930..c3980a0 100644 --- a/docs/guide/datastore.ipynb +++ b/docs/guide/datastore.ipynb @@ -4,6 +4,7 @@ "cell_type": "code", "execution_count": 1, "metadata": { + "collapsed": true, "nbsphinx": "hidden" }, "outputs": [], @@ -24,6 +25,7 @@ "cell_type": "code", "execution_count": 2, "metadata": { + "collapsed": true, "nbsphinx": "hidden" }, "outputs": [], @@ -383,8 +385,10 @@ }, { "cell_type": "code", - "execution_count": 7, - "metadata": {}, + "execution_count": 3, + "metadata": { + "collapsed": true + }, "outputs": [], "source": [ "import sys\n", @@ -415,7 +419,7 @@ }, { "cell_type": "code", - "execution_count": 9, + "execution_count": 6, "metadata": {}, "outputs": [], "source": [ @@ -428,11 +432,11 @@ "fs.source.filters.add(f)\n", "\n", "# attach multiple filters to FileSystemStore\n", - "fs.source.filters.update([f1,f2])\n", + "fs.source.filters.add([f1,f2])\n", "\n", "# can also attach filters to a Source\n", "# attach multiple filters to FileSystemSource\n", - "fs_source.filters.update([f3, f4])\n", + "fs_source.filters.add([f3, f4])\n", "\n", "\n", "mem = MemoryStore()\n", @@ -442,7 +446,7 @@ "mem.source.filters.add(f)\n", "\n", "# attach multiple filters to a MemoryStore\n", - "mem.source.filters.update([f1,f2])" + "mem.source.filters.add([f1,f2])" ] }, { @@ -457,7 +461,9 @@ { "cell_type": "code", "execution_count": 10, - "metadata": {}, + "metadata": { + "collapsed": true + }, "outputs": [], "source": [ "from stix2 import Campaign, Identity, Indicator, Malware, Relationship\n", @@ -719,21 +725,21 @@ ], "metadata": { "kernelspec": { - "display_name": "Python 3", + "display_name": "cti-python-stix2", "language": "python", - "name": "python3" + "name": "cti-python-stix2" }, "language_info": { "codemirror_mode": { "name": "ipython", - "version": 3 + "version": 2 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.6.3" + "pygments_lexer": "ipython2", + "version": "2.7.12" } }, "nbformat": 4, From 6df23e72686b90b93eaf000d2cbb63139361de43 Mon Sep 17 00:00:00 2001 From: = Date: Fri, 13 Apr 2018 16:06:31 -0400 Subject: [PATCH 56/61] removed unecessary checks, (clearly I need to review python ref model) --- stix2/datastore/filters.py | 15 +++------------ stix2/test/test_datastore.py | 2 +- 2 files changed, 4 insertions(+), 13 deletions(-) diff --git a/stix2/datastore/filters.py b/stix2/datastore/filters.py index c260dcc..ab94e89 100644 --- a/stix2/datastore/filters.py +++ b/stix2/datastore/filters.py @@ -71,8 +71,7 @@ class Filter(collections.namedtuple("Filter", ['property', 'op', 'value'])): if isinstance(value, datetime): # if value is a datetime obj, convert to str - dt_str = format_datetime(value) - value = dt_str # use temp variable to avoid deepcopy operation + value = format_datetime(value) _check_filter_components(prop, op, value) @@ -90,11 +89,10 @@ class Filter(collections.namedtuple("Filter", ['property', 'op', 'value'])): False otherwise. """ if isinstance(stix_obj_property, datetime): - # if a datetime obj, use str format before comparison + # if a datetime obj, convert to str format before comparison # NOTE: this check seems like it should be done upstream # but will put here for now - tmp = format_datetime(stix_obj_property) - stix_obj_property = tmp # use tmp variable to avoid deepcopy op + stix_obj_property = format_datetime(stix_obj_property) if self.op == "=": return stix_obj_property == self.value @@ -174,9 +172,6 @@ def _check_filter(filter_, stix_obj): return True return False - elif isinstance(stix_obj[prop], dict): - return _check_filter(sub_filter, stix_obj[prop]) - else: return _check_filter(sub_filter, stix_obj[prop]) @@ -242,8 +237,6 @@ class FilterSet(object): if f not in self._filters: self._filters.append(f) - return - def remove(self, filters=None): """remove a Filter, list of Filters, or FilterSet from the FilterSet @@ -263,5 +256,3 @@ class FilterSet(object): for f in filters: self._filters.remove(f) - - return diff --git a/stix2/test/test_datastore.py b/stix2/test/test_datastore.py index 7ee4877..1c7fa43 100644 --- a/stix2/test/test_datastore.py +++ b/stix2/test/test_datastore.py @@ -510,7 +510,7 @@ def test_datetime_filter_behavior(): filter_with_dt_obj = Filter("created", "=", parse_into_datetime("2016-02-14T00:00:00.000Z", "millisecond")) filter_with_str = Filter("created", "=", "2016-02-14T00:00:00.000Z") - # check taht filter value is converted from datetime to str + # check that filter value is converted from datetime to str assert isinstance(filter_with_dt_obj.value, str) # compare datetime string to filter w/ datetime obj From 194672ee2bb4022f78e33a0169c33ba9dc76bc5a Mon Sep 17 00:00:00 2001 From: Chris Lenk Date: Fri, 13 Apr 2018 17:11:07 -0400 Subject: [PATCH 57/61] Tweak FilterSet docstrings style --- stix2/datastore/filters.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/stix2/datastore/filters.py b/stix2/datastore/filters.py index ab94e89..a32b14a 100644 --- a/stix2/datastore/filters.py +++ b/stix2/datastore/filters.py @@ -193,7 +193,7 @@ class FilterSet(object): that Filters that had a dict as a value could not be added to a Python set as dicts are not hashable. Thus this class provides set functionality but internally stores filters in a list. - """ + """ def __init__(self, filters=None): """ @@ -205,16 +205,16 @@ class FilterSet(object): self.add(filters) def __iter__(self): - """provide iteration functionality of FilterSet""" + """Provide iteration functionality of FilterSet.""" for f in self._filters: yield f def __len__(self): - """provide built-in len() utility of FilterSet""" + """Provide built-in len() utility of FilterSet.""" return len(self._filters) def add(self, filters=None): - """add a Filter, FilterSet, or list of Filters to the FilterSet + """Add a Filter, FilterSet, or list of Filters to the FilterSet. Operates like set, only adding unique stix2.Filters to the FilterSet @@ -238,7 +238,7 @@ class FilterSet(object): self._filters.append(f) def remove(self, filters=None): - """remove a Filter, list of Filters, or FilterSet from the FilterSet + """Remove a Filter, list of Filters, or FilterSet from the FilterSet. NOTE: method designed to be very accomodating (i.e. even accepting filters=None) as it allows for blind calls (very useful in DataStore) From 14dce03616d2d50c902cb3e825f878a8029e10bf Mon Sep 17 00:00:00 2001 From: Chris Lenk Date: Mon, 16 Apr 2018 14:37:07 -0400 Subject: [PATCH 58/61] Provide default for revoked, sighting:summary. This allows filter on un-revoked objects. Changes default JSONEncoder to drop optional properties with default values in the spec if set to the default value. They can be included by passing include_optional_defaults=True to serialize(). --- stix2/base.py | 54 ++++++++++++++++++++++++++++++--- stix2/test/test_bundle.py | 12 ++++---- stix2/test/test_datastore.py | 4 +-- stix2/test/test_indicator.py | 1 + stix2/test/test_relationship.py | 8 ++--- stix2/test/test_sighting.py | 2 +- stix2/test/test_tool.py | 27 +++++++++++++++++ stix2/v20/sdo.py | 26 ++++++++-------- stix2/v20/sro.py | 6 ++-- 9 files changed, 105 insertions(+), 35 deletions(-) diff --git a/stix2/base.py b/stix2/base.py index 3219007..e128d48 100644 --- a/stix2/base.py +++ b/stix2/base.py @@ -22,6 +22,33 @@ DEFAULT_ERROR = "{type} must have {property}='{expected}'." class STIXJSONEncoder(json.JSONEncoder): + """Custom JSONEncoder subclass for serializing Python ``stix2`` objects. + + If an optional property with a default value specified in the STIX 2 spec + is set to that default value, it will be left out of the serialized output. + + An example of this type of property include the ``revoked`` common property. + """ + + def default(self, obj): + if isinstance(obj, (dt.date, dt.datetime)): + return format_datetime(obj) + elif isinstance(obj, _STIXBase): + tmp_obj = dict(copy.deepcopy(obj)) + for prop_name in obj._defaulted_optional_properties: + del tmp_obj[prop_name] + return tmp_obj + else: + return super(STIXJSONEncoder, self).default(obj) + + +class STIXJSONIncludeOptionalDefaultsEncoder(json.JSONEncoder): + """Custom JSONEncoder subclass for serializing Python ``stix2`` objects. + + Differs from ``STIXJSONEncoder`` in that if an optional property with a default + value specified in the STIX 2 spec is set to that default value, it will be + included in the serialized output. + """ def default(self, obj): if isinstance(obj, (dt.date, dt.datetime)): @@ -122,14 +149,25 @@ class _STIXBase(collections.Mapping): setting_kwargs[prop_name] = prop_value # Detect any missing required properties - required_properties = get_required_properties(cls._properties) - missing_kwargs = set(required_properties) - set(setting_kwargs) + required_properties = set(get_required_properties(cls._properties)) + missing_kwargs = required_properties - set(setting_kwargs) if missing_kwargs: raise MissingPropertiesError(cls, missing_kwargs) for prop_name, prop_metadata in cls._properties.items(): self._check_property(prop_name, prop_metadata, setting_kwargs) + # Cache defaulted optional properties for serialization + defaulted = [] + for name, prop in cls._properties.items(): + try: + if (not prop.required and not hasattr(prop, '_fixed_value') and + prop.default() == setting_kwargs[name]): + defaulted.append(name) + except (AttributeError, KeyError): + continue + self._defaulted_optional_properties = defaulted + self._inner = setting_kwargs self._check_object_constraints() @@ -151,7 +189,7 @@ class _STIXBase(collections.Mapping): (self.__class__.__name__, name)) def __setattr__(self, name, value): - if name != '_inner' and not name.startswith("_STIXBase__"): + if not name.startswith("_"): raise ImmutableError(self.__class__, name) super(_STIXBase, self).__setattr__(name, value) @@ -170,6 +208,7 @@ class _STIXBase(collections.Mapping): if isinstance(self, _Observable): # Assume: valid references in the original object are still valid in the new version new_inner['_valid_refs'] = {'*': '*'} + new_inner['allow_custom'] = self.__allow_custom return cls(**new_inner) def properties_populated(self): @@ -183,7 +222,7 @@ class _STIXBase(collections.Mapping): def revoke(self): return _revoke(self) - def serialize(self, pretty=False, **kwargs): + def serialize(self, pretty=False, include_optional_defaults=False, **kwargs): """ Serialize a STIX object. @@ -191,6 +230,8 @@ class _STIXBase(collections.Mapping): pretty (bool): If True, output properties following the STIX specs formatting. This includes indentation. Refer to notes for more details. (Default: ``False``) + include_optional_defaults (bool): Determines whether to include + optional properties set to the default value defined in the spec. **kwargs: The arguments for a json.dumps() call. Returns: @@ -213,7 +254,10 @@ class _STIXBase(collections.Mapping): kwargs.update({'indent': 4, 'separators': (",", ": "), 'item_sort_key': sort_by}) - return json.dumps(self, cls=STIXJSONEncoder, **kwargs) + if include_optional_defaults: + return json.dumps(self, cls=STIXJSONIncludeOptionalDefaultsEncoder, **kwargs) + else: + return json.dumps(self, cls=STIXJSONEncoder, **kwargs) class _Observable(_STIXBase): diff --git a/stix2/test/test_bundle.py b/stix2/test/test_bundle.py index 8b14172..2d14654 100644 --- a/stix2/test/test_bundle.py +++ b/stix2/test/test_bundle.py @@ -6,7 +6,7 @@ import stix2 EXPECTED_BUNDLE = """{ "type": "bundle", - "id": "bundle--00000000-0000-0000-0000-000000000004", + "id": "bundle--00000000-0000-0000-0000-000000000007", "spec_version": "2.0", "objects": [ { @@ -22,7 +22,7 @@ EXPECTED_BUNDLE = """{ }, { "type": "malware", - "id": "malware--00000000-0000-0000-0000-000000000002", + "id": "malware--00000000-0000-0000-0000-000000000003", "created": "2017-01-01T12:34:56.000Z", "modified": "2017-01-01T12:34:56.000Z", "name": "Cryptolocker", @@ -32,7 +32,7 @@ EXPECTED_BUNDLE = """{ }, { "type": "relationship", - "id": "relationship--00000000-0000-0000-0000-000000000003", + "id": "relationship--00000000-0000-0000-0000-000000000005", "created": "2017-01-01T12:34:56.000Z", "modified": "2017-01-01T12:34:56.000Z", "relationship_type": "indicates", @@ -44,7 +44,7 @@ EXPECTED_BUNDLE = """{ EXPECTED_BUNDLE_DICT = { "type": "bundle", - "id": "bundle--00000000-0000-0000-0000-000000000004", + "id": "bundle--00000000-0000-0000-0000-000000000007", "spec_version": "2.0", "objects": [ { @@ -60,7 +60,7 @@ EXPECTED_BUNDLE_DICT = { }, { "type": "malware", - "id": "malware--00000000-0000-0000-0000-000000000002", + "id": "malware--00000000-0000-0000-0000-000000000003", "created": "2017-01-01T12:34:56.000Z", "modified": "2017-01-01T12:34:56.000Z", "name": "Cryptolocker", @@ -70,7 +70,7 @@ EXPECTED_BUNDLE_DICT = { }, { "type": "relationship", - "id": "relationship--00000000-0000-0000-0000-000000000003", + "id": "relationship--00000000-0000-0000-0000-000000000005", "created": "2017-01-01T12:34:56.000Z", "modified": "2017-01-01T12:34:56.000Z", "relationship_type": "indicates", diff --git a/stix2/test/test_datastore.py b/stix2/test/test_datastore.py index 1c7fa43..315aff5 100644 --- a/stix2/test/test_datastore.py +++ b/stix2/test/test_datastore.py @@ -405,13 +405,11 @@ def test_apply_common_filters4(): def test_apply_common_filters5(): # "Return any object whose not revoked" - # Note that if 'revoked' property is not present in object. - # Currently we can't use such an expression to filter for... :( resp = list(apply_common_filters(stix_objs, [filters[5]])) assert len(resp) == 0 resp = list(apply_common_filters(real_stix_objs, [filters[5]])) - assert len(resp) == 0 + assert len(resp) == 4 def test_apply_common_filters6(): diff --git a/stix2/test/test_indicator.py b/stix2/test/test_indicator.py index 78d1bf2..c9b6e56 100644 --- a/stix2/test/test_indicator.py +++ b/stix2/test/test_indicator.py @@ -45,6 +45,7 @@ def test_indicator_with_all_required_properties(): labels=['malicious-activity'], ) + assert ind.revoked is False assert str(ind) == EXPECTED_INDICATOR rep = re.sub(r"(\[|=| )u('|\"|\\\'|\\\")", r"\g<1>\g<2>", repr(ind)) assert rep == EXPECTED_INDICATOR_REPR diff --git a/stix2/test/test_relationship.py b/stix2/test/test_relationship.py index c6e2d6f..32ddf91 100644 --- a/stix2/test/test_relationship.py +++ b/stix2/test/test_relationship.py @@ -123,8 +123,8 @@ def test_create_relationship_from_objects_rather_than_ids(indicator, malware): assert rel.relationship_type == 'indicates' assert rel.source_ref == 'indicator--00000000-0000-0000-0000-000000000001' - assert rel.target_ref == 'malware--00000000-0000-0000-0000-000000000002' - assert rel.id == 'relationship--00000000-0000-0000-0000-000000000003' + assert rel.target_ref == 'malware--00000000-0000-0000-0000-000000000003' + assert rel.id == 'relationship--00000000-0000-0000-0000-000000000005' def test_create_relationship_with_positional_args(indicator, malware): @@ -132,8 +132,8 @@ def test_create_relationship_with_positional_args(indicator, malware): assert rel.relationship_type == 'indicates' assert rel.source_ref == 'indicator--00000000-0000-0000-0000-000000000001' - assert rel.target_ref == 'malware--00000000-0000-0000-0000-000000000002' - assert rel.id == 'relationship--00000000-0000-0000-0000-000000000003' + assert rel.target_ref == 'malware--00000000-0000-0000-0000-000000000003' + assert rel.id == 'relationship--00000000-0000-0000-0000-000000000005' @pytest.mark.parametrize("data", [ diff --git a/stix2/test/test_sighting.py b/stix2/test/test_sighting.py index ce1fab9..06f96b8 100644 --- a/stix2/test/test_sighting.py +++ b/stix2/test/test_sighting.py @@ -86,7 +86,7 @@ def test_create_sighting_from_objects_rather_than_ids(malware): # noqa: F811 rel = stix2.Sighting(sighting_of_ref=malware) assert rel.sighting_of_ref == 'malware--00000000-0000-0000-0000-000000000001' - assert rel.id == 'sighting--00000000-0000-0000-0000-000000000002' + assert rel.id == 'sighting--00000000-0000-0000-0000-000000000003' @pytest.mark.parametrize("data", [ diff --git a/stix2/test/test_tool.py b/stix2/test/test_tool.py index ce99fb8..9fc2c22 100644 --- a/stix2/test/test_tool.py +++ b/stix2/test/test_tool.py @@ -19,6 +19,19 @@ EXPECTED = """{ ] }""" +EXPECTED_WITH_REVOKED = """{ + "type": "tool", + "id": "tool--8e2e2d2b-17d4-4cbf-938f-98ee46b3cd3f", + "created_by_ref": "identity--f431f809-377b-45e0-aa1c-6a4751cae5ff", + "created": "2016-04-06T20:03:48.000Z", + "modified": "2016-04-06T20:03:48.000Z", + "name": "VNC", + "revoked": false, + "labels": [ + "remote-access" + ] +}""" + def test_tool_example(): tool = stix2.Tool( @@ -64,4 +77,18 @@ def test_tool_no_workbench_wrappers(): with pytest.raises(AttributeError): tool.created_by() + +def test_tool_serialize_with_defaults(): + tool = stix2.Tool( + id="tool--8e2e2d2b-17d4-4cbf-938f-98ee46b3cd3f", + created_by_ref="identity--f431f809-377b-45e0-aa1c-6a4751cae5ff", + created="2016-04-06T20:03:48.000Z", + modified="2016-04-06T20:03:48.000Z", + name="VNC", + labels=["remote-access"], + ) + + assert tool.serialize(pretty=True, include_optional_defaults=True) == EXPECTED_WITH_REVOKED + + # TODO: Add other examples diff --git a/stix2/v20/sdo.py b/stix2/v20/sdo.py index ff024f5..d7e9954 100644 --- a/stix2/v20/sdo.py +++ b/stix2/v20/sdo.py @@ -36,7 +36,7 @@ class AttackPattern(STIXDomainObject): ('name', StringProperty(required=True)), ('description', StringProperty()), ('kill_chain_phases', ListProperty(KillChainPhase)), - ('revoked', BooleanProperty()), + ('revoked', BooleanProperty(default=lambda: False)), ('labels', ListProperty(StringProperty)), ('external_references', ListProperty(ExternalReference)), ('object_marking_refs', ListProperty(ReferenceProperty(type="marking-definition"))), @@ -63,7 +63,7 @@ class Campaign(STIXDomainObject): ('first_seen', TimestampProperty()), ('last_seen', TimestampProperty()), ('objective', StringProperty()), - ('revoked', BooleanProperty()), + ('revoked', BooleanProperty(default=lambda: False)), ('labels', ListProperty(StringProperty)), ('external_references', ListProperty(ExternalReference)), ('object_marking_refs', ListProperty(ReferenceProperty(type="marking-definition"))), @@ -86,7 +86,7 @@ class CourseOfAction(STIXDomainObject): ('modified', TimestampProperty(default=lambda: NOW, precision='millisecond')), ('name', StringProperty(required=True)), ('description', StringProperty()), - ('revoked', BooleanProperty()), + ('revoked', BooleanProperty(default=lambda: False)), ('labels', ListProperty(StringProperty)), ('external_references', ListProperty(ExternalReference)), ('object_marking_refs', ListProperty(ReferenceProperty(type="marking-definition"))), @@ -112,7 +112,7 @@ class Identity(STIXDomainObject): ('identity_class', StringProperty(required=True)), ('sectors', ListProperty(StringProperty)), ('contact_information', StringProperty()), - ('revoked', BooleanProperty()), + ('revoked', BooleanProperty(default=lambda: False)), ('labels', ListProperty(StringProperty)), ('external_references', ListProperty(ExternalReference)), ('object_marking_refs', ListProperty(ReferenceProperty(type="marking-definition"))), @@ -139,7 +139,7 @@ class Indicator(STIXDomainObject): ('valid_from', TimestampProperty(default=lambda: NOW)), ('valid_until', TimestampProperty()), ('kill_chain_phases', ListProperty(KillChainPhase)), - ('revoked', BooleanProperty()), + ('revoked', BooleanProperty(default=lambda: False)), ('labels', ListProperty(StringProperty, required=True)), ('external_references', ListProperty(ExternalReference)), ('object_marking_refs', ListProperty(ReferenceProperty(type="marking-definition"))), @@ -169,7 +169,7 @@ class IntrusionSet(STIXDomainObject): ('resource_level', StringProperty()), ('primary_motivation', StringProperty()), ('secondary_motivations', ListProperty(StringProperty)), - ('revoked', BooleanProperty()), + ('revoked', BooleanProperty(default=lambda: False)), ('labels', ListProperty(StringProperty)), ('external_references', ListProperty(ExternalReference)), ('object_marking_refs', ListProperty(ReferenceProperty(type="marking-definition"))), @@ -193,7 +193,7 @@ class Malware(STIXDomainObject): ('name', StringProperty(required=True)), ('description', StringProperty()), ('kill_chain_phases', ListProperty(KillChainPhase)), - ('revoked', BooleanProperty()), + ('revoked', BooleanProperty(default=lambda: False)), ('labels', ListProperty(StringProperty, required=True)), ('external_references', ListProperty(ExternalReference)), ('object_marking_refs', ListProperty(ReferenceProperty(type="marking-definition"))), @@ -218,7 +218,7 @@ class ObservedData(STIXDomainObject): ('last_observed', TimestampProperty(required=True)), ('number_observed', IntegerProperty(required=True)), ('objects', ObservableProperty(required=True)), - ('revoked', BooleanProperty()), + ('revoked', BooleanProperty(default=lambda: False)), ('labels', ListProperty(StringProperty)), ('external_references', ListProperty(ExternalReference)), ('object_marking_refs', ListProperty(ReferenceProperty(type="marking-definition"))), @@ -243,7 +243,7 @@ class Report(STIXDomainObject): ('description', StringProperty()), ('published', TimestampProperty(required=True)), ('object_refs', ListProperty(ReferenceProperty, required=True)), - ('revoked', BooleanProperty()), + ('revoked', BooleanProperty(default=lambda: False)), ('labels', ListProperty(StringProperty, required=True)), ('external_references', ListProperty(ExternalReference)), ('object_marking_refs', ListProperty(ReferenceProperty(type="marking-definition"))), @@ -274,7 +274,7 @@ class ThreatActor(STIXDomainObject): ('primary_motivation', StringProperty()), ('secondary_motivations', ListProperty(StringProperty)), ('personal_motivations', ListProperty(StringProperty)), - ('revoked', BooleanProperty()), + ('revoked', BooleanProperty(default=lambda: False)), ('labels', ListProperty(StringProperty, required=True)), ('external_references', ListProperty(ExternalReference)), ('object_marking_refs', ListProperty(ReferenceProperty(type="marking-definition"))), @@ -299,7 +299,7 @@ class Tool(STIXDomainObject): ('description', StringProperty()), ('kill_chain_phases', ListProperty(KillChainPhase)), ('tool_version', StringProperty()), - ('revoked', BooleanProperty()), + ('revoked', BooleanProperty(default=lambda: False)), ('labels', ListProperty(StringProperty, required=True)), ('external_references', ListProperty(ExternalReference)), ('object_marking_refs', ListProperty(ReferenceProperty(type="marking-definition"))), @@ -322,7 +322,7 @@ class Vulnerability(STIXDomainObject): ('modified', TimestampProperty(default=lambda: NOW, precision='millisecond')), ('name', StringProperty(required=True)), ('description', StringProperty()), - ('revoked', BooleanProperty()), + ('revoked', BooleanProperty(default=lambda: False)), ('labels', ListProperty(StringProperty)), ('external_references', ListProperty(ExternalReference)), ('object_marking_refs', ListProperty(ReferenceProperty(type="marking-definition"))), @@ -382,7 +382,7 @@ def CustomObject(type='x-custom-type', properties=None): # This is to follow the general properties structure. _properties.update([ - ('revoked', BooleanProperty()), + ('revoked', BooleanProperty(default=lambda: False)), ('labels', ListProperty(StringProperty)), ('external_references', ListProperty(ExternalReference)), ('object_marking_refs', ListProperty(ReferenceProperty(type="marking-definition"))), diff --git a/stix2/v20/sro.py b/stix2/v20/sro.py index 7d7d3ae..e488229 100644 --- a/stix2/v20/sro.py +++ b/stix2/v20/sro.py @@ -32,7 +32,7 @@ class Relationship(STIXRelationshipObject): ('description', StringProperty()), ('source_ref', ReferenceProperty(required=True)), ('target_ref', ReferenceProperty(required=True)), - ('revoked', BooleanProperty()), + ('revoked', BooleanProperty(default=lambda: False)), ('labels', ListProperty(StringProperty)), ('external_references', ListProperty(ExternalReference)), ('object_marking_refs', ListProperty(ReferenceProperty(type="marking-definition"))), @@ -72,8 +72,8 @@ class Sighting(STIXRelationshipObject): ('sighting_of_ref', ReferenceProperty(required=True)), ('observed_data_refs', ListProperty(ReferenceProperty(type="observed-data"))), ('where_sighted_refs', ListProperty(ReferenceProperty(type="identity"))), - ('summary', BooleanProperty()), - ('revoked', BooleanProperty()), + ('summary', BooleanProperty(default=lambda: False)), + ('revoked', BooleanProperty(default=lambda: False)), ('labels', ListProperty(StringProperty)), ('external_references', ListProperty(ExternalReference)), ('object_marking_refs', ListProperty(ReferenceProperty(type="marking-definition"))), From f66fbb73d9b30b32d153f473c635bea7b79d9687 Mon Sep 17 00:00:00 2001 From: Chris Lenk Date: Mon, 16 Apr 2018 14:56:23 -0400 Subject: [PATCH 59/61] Update CHANGELOG, docs for v1.0.0 --- CHANGELOG | 17 +++++++++++++++++ docs/index.rst | 4 ---- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/CHANGELOG b/CHANGELOG index 7f77b25..f63f682 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,6 +1,23 @@ CHANGELOG ========= +1.0.0 - 2018-04-16 + +* Adds the Workbench layer API. +* Adds checks to ensure valid type names are provided. +* Supports parsing generic custom STIX 2 content without needing to create classes for them. +* Fixes "Not JSON serializable" error in TAXIICollectionStore. +* Fixes bug with parsing JSON files in FileSystemStore. +* Fixes bug with Filters in TAXIICollectionStore. +* Fixes minor bugs in the patterning API. +* Fixes bug with ListProperty containing DictionaryProperty. +* Fixes bug with parsing observables. +* Fixes bug involving optional properties with default values. +* Changes custom observable extensions to require properties to be defined as a list of tuples rather than a dictionary. +* Changes Filters to allow passing a dictionary as a filter value. +* Changes `get_dict` to a private function. +* `taxii2-client` is now an optional dependency. + 0.5.1 - 2018-03-06 * Fixes issue with PyPI. diff --git a/docs/index.rst b/docs/index.rst index dd39903..023400e 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -6,10 +6,6 @@ STIX 2 Python API Documentation =============================== -.. warning:: - - Prior to version 1.0, all APIs are considered unstable and subject to change. - Welcome to the STIX 2 Python API's documentation. This library is designed to help you work with STIX 2 content. For more information about STIX 2, see the `website `_ of the OASIS Cyber Threat Intelligence From 161e10ec4068243b6f8eb835bf708d3da9a00bba Mon Sep 17 00:00:00 2001 From: Chris Lenk Date: Mon, 16 Apr 2018 14:57:35 -0400 Subject: [PATCH 60/61] =?UTF-8?q?Bump=20version:=200.5.1=20=E2=86=92=201.0?= =?UTF-8?q?.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/conf.py | 4 ++-- setup.cfg | 2 +- stix2/version.py | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/conf.py b/docs/conf.py index 0764454..85c8b23 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -34,8 +34,8 @@ project = 'stix2' copyright = '2017, OASIS Open' author = 'OASIS Open' -version = '0.5.1' -release = '0.5.1' +version = '1.0.0' +release = '1.0.0' language = None exclude_patterns = ['_build', '_templates', 'Thumbs.db', '.DS_Store', 'guide/.ipynb_checkpoints'] diff --git a/setup.cfg b/setup.cfg index b252746..ac3e5d5 100644 --- a/setup.cfg +++ b/setup.cfg @@ -1,5 +1,5 @@ [bumpversion] -current_version = 0.5.1 +current_version = 1.0.0 commit = True tag = True diff --git a/stix2/version.py b/stix2/version.py index dd9b22c..5becc17 100644 --- a/stix2/version.py +++ b/stix2/version.py @@ -1 +1 @@ -__version__ = "0.5.1" +__version__ = "1.0.0" From 3373a66aef9105f6bc7fc1712bcb8b7ac2289573 Mon Sep 17 00:00:00 2001 From: Chris Lenk Date: Mon, 16 Apr 2018 15:47:25 -0400 Subject: [PATCH 61/61] Fix README for PyPI rendering Title underline too short. --- README.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.rst b/README.rst index 46e8164..0212eed 100644 --- a/README.rst +++ b/README.rst @@ -179,7 +179,7 @@ repositories/maintainers-guide#additionalMaintainers>`__. Corporation `__ About OASIS TC Open Repositories ------------------------------ +-------------------------------- - `TC Open Repositories: Overview and Resources