diff --git a/stix2/test/v20/conftest.py b/stix2/test/v20/conftest.py index c73eafb..a1ebe5f 100644 --- a/stix2/test/v20/conftest.py +++ b/stix2/test/v20/conftest.py @@ -35,17 +35,17 @@ def uuid4(monkeypatch): @pytest.fixture def indicator(uuid4, clock): - return stix2.Indicator(**INDICATOR_KWARGS) + return stix2.v20.Indicator(**INDICATOR_KWARGS) @pytest.fixture def malware(uuid4, clock): - return stix2.Malware(**MALWARE_KWARGS) + return stix2.v20.Malware(**MALWARE_KWARGS) @pytest.fixture def relationship(uuid4, clock): - return stix2.Relationship(**RELATIONSHIP_KWARGS) + return stix2.v20.Relationship(**RELATIONSHIP_KWARGS) @pytest.fixture @@ -156,4 +156,4 @@ def stix_objs2(): @pytest.fixture def real_stix_objs2(stix_objs2): - return [stix2.parse(x) for x in stix_objs2] + return [stix2.parse(x, version="2.0") for x in stix_objs2] diff --git a/stix2/test/v20/constants.py b/stix2/test/v20/constants.py index 49e4014..004df47 100644 --- a/stix2/test/v20/constants.py +++ b/stix2/test/v20/constants.py @@ -79,8 +79,7 @@ INTRUSION_SET_KWARGS = dict( MALWARE_KWARGS = dict( labels=['ransomware'], - name="Cryptolocker", - is_family=False + name="Cryptolocker" ) MALWARE_MORE_KWARGS = dict( @@ -90,8 +89,7 @@ MALWARE_MORE_KWARGS = dict( modified="2016-04-06T20:03:00.000Z", labels=['ransomware'], name="Cryptolocker", - description="A ransomware related to ...", - is_family=False + description="A ransomware related to ..." ) OBSERVED_DATA_KWARGS = dict( diff --git a/stix2/test/v20/test_attack_pattern.py b/stix2/test/v20/test_attack_pattern.py index 0be118c..835f36b 100644 --- a/stix2/test/v20/test_attack_pattern.py +++ b/stix2/test/v20/test_attack_pattern.py @@ -24,7 +24,7 @@ EXPECTED = """{ def test_attack_pattern_example(): - ap = stix2.AttackPattern( + ap = stix2.v20.AttackPattern( id="attack-pattern--0c7b5b88-8ff7-4a4d-aa9d-feb398cd0061", created="2016-05-12T08:17:27.000Z", modified="2016-05-12T08:17:27.000Z", @@ -57,7 +57,7 @@ def test_attack_pattern_example(): }, ]) def test_parse_attack_pattern(data): - ap = stix2.parse(data) + ap = stix2.parse(data, version="2.0") assert ap.type == 'attack-pattern' assert ap.id == ATTACK_PATTERN_ID @@ -71,7 +71,7 @@ def test_parse_attack_pattern(data): def test_attack_pattern_invalid_labels(): with pytest.raises(stix2.exceptions.InvalidValueError): - stix2.AttackPattern( + stix2.v20.AttackPattern( id="attack-pattern--0c7b5b88-8ff7-4a4d-aa9d-feb398cd0061", created="2016-05-12T08:17:27Z", modified="2016-05-12T08:17:27Z", diff --git a/stix2/test/v20/test_bundle.py b/stix2/test/v20/test_bundle.py index e5d0b92..98d9757 100644 --- a/stix2/test/v20/test_bundle.py +++ b/stix2/test/v20/test_bundle.py @@ -3,13 +3,11 @@ import json import pytest import stix2 -import stix2.v21.bundle -import stix2.v21.sdo EXPECTED_BUNDLE = """{ "type": "bundle", - "spec_version": "2.0", "id": "bundle--00000000-0000-0000-0000-000000000007", + "spec_version": "2.0", "objects": [ { "type": "indicator", @@ -24,19 +22,16 @@ EXPECTED_BUNDLE = """{ }, { "type": "malware", - "spec_version": "2.1", "id": "malware--00000000-0000-0000-0000-000000000003", "created": "2017-01-01T12:34:56.000Z", "modified": "2017-01-01T12:34:56.000Z", "name": "Cryptolocker", "labels": [ "ransomware" - ], - "is_family": false + ] }, { "type": "relationship", - "spec_version": "2.1", "id": "relationship--00000000-0000-0000-0000-000000000005", "created": "2017-01-01T12:34:56.000Z", "modified": "2017-01-01T12:34:56.000Z", @@ -49,8 +44,8 @@ EXPECTED_BUNDLE = """{ EXPECTED_BUNDLE_DICT = { "type": "bundle", - "spec_version": "2.0", "id": "bundle--00000000-0000-0000-0000-000000000007", + "spec_version": "2.0", "objects": [ { "type": "indicator", @@ -65,19 +60,16 @@ EXPECTED_BUNDLE_DICT = { }, { "type": "malware", - "spec_version": "2.1", "id": "malware--00000000-0000-0000-0000-000000000003", "created": "2017-01-01T12:34:56.000Z", "modified": "2017-01-01T12:34:56.000Z", "name": "Cryptolocker", "labels": [ "ransomware" - ], - "is_family": False + ] }, { "type": "relationship", - "spec_version": "2.1", "id": "relationship--00000000-0000-0000-0000-000000000005", "created": "2017-01-01T12:34:56.000Z", "modified": "2017-01-01T12:34:56.000Z", @@ -90,7 +82,7 @@ EXPECTED_BUNDLE_DICT = { def test_empty_bundle(): - bundle = stix2.Bundle() + bundle = stix2.v20.Bundle() assert bundle.type == "bundle" assert bundle.id.startswith("bundle--") @@ -100,9 +92,9 @@ def test_empty_bundle(): def test_bundle_with_wrong_type(): with pytest.raises(stix2.exceptions.InvalidValueError) as excinfo: - stix2.Bundle(type="not-a-bundle") + stix2.v20.Bundle(type="not-a-bundle") - assert excinfo.value.cls == stix2.Bundle + assert excinfo.value.cls == stix2.v20.Bundle assert excinfo.value.prop_name == "type" assert excinfo.value.reason == "must equal 'bundle'." assert str(excinfo.value) == "Invalid value for Bundle 'type': must equal 'bundle'." @@ -110,78 +102,78 @@ def test_bundle_with_wrong_type(): def test_bundle_id_must_start_with_bundle(): with pytest.raises(stix2.exceptions.InvalidValueError) as excinfo: - stix2.Bundle(id='my-prefix--') + stix2.v20.Bundle(id='my-prefix--') - assert excinfo.value.cls == stix2.Bundle + assert excinfo.value.cls == stix2.v20.Bundle assert excinfo.value.prop_name == "id" assert excinfo.value.reason == "must start with 'bundle--'." assert str(excinfo.value) == "Invalid value for Bundle 'id': must start with 'bundle--'." def test_create_bundle1(indicator, malware, relationship): - bundle = stix2.Bundle(objects=[indicator, malware, relationship]) + bundle = stix2.v20.Bundle(objects=[indicator, malware, relationship]) assert str(bundle) == EXPECTED_BUNDLE assert bundle.serialize(pretty=True) == EXPECTED_BUNDLE def test_create_bundle2(indicator, malware, relationship): - bundle = stix2.Bundle(objects=[indicator, malware, relationship]) + bundle = stix2.v20.Bundle(objects=[indicator, malware, relationship]) assert json.loads(bundle.serialize()) == EXPECTED_BUNDLE_DICT def test_create_bundle_with_positional_args(indicator, malware, relationship): - bundle = stix2.Bundle(indicator, malware, relationship) + bundle = stix2.v20.Bundle(indicator, malware, relationship) assert str(bundle) == EXPECTED_BUNDLE def test_create_bundle_with_positional_listarg(indicator, malware, relationship): - bundle = stix2.Bundle([indicator, malware, relationship]) + bundle = stix2.v20.Bundle([indicator, malware, relationship]) assert str(bundle) == EXPECTED_BUNDLE def test_create_bundle_with_listarg_and_positional_arg(indicator, malware, relationship): - bundle = stix2.Bundle([indicator, malware], relationship) + bundle = stix2.v20.Bundle([indicator, malware], relationship) assert str(bundle) == EXPECTED_BUNDLE def test_create_bundle_with_listarg_and_kwarg(indicator, malware, relationship): - bundle = stix2.Bundle([indicator, malware], objects=[relationship]) + bundle = stix2.v20.Bundle([indicator, malware], objects=[relationship]) assert str(bundle) == EXPECTED_BUNDLE def test_create_bundle_with_arg_listarg_and_kwarg(indicator, malware, relationship): - bundle = stix2.Bundle([indicator], malware, objects=[relationship]) + bundle = stix2.v20.Bundle([indicator], malware, objects=[relationship]) assert str(bundle) == EXPECTED_BUNDLE def test_create_bundle_invalid(indicator, malware, relationship): with pytest.raises(ValueError) as excinfo: - stix2.Bundle(objects=[1]) + stix2.v20.Bundle(objects=[1]) assert excinfo.value.reason == "This property may only contain a dictionary or object" with pytest.raises(ValueError) as excinfo: - stix2.Bundle(objects=[{}]) + stix2.v20.Bundle(objects=[{}]) assert excinfo.value.reason == "This property may only contain a non-empty dictionary or object" with pytest.raises(ValueError) as excinfo: - stix2.Bundle(objects=[{'type': 'bundle'}]) + stix2.v20.Bundle(objects=[{'type': 'bundle'}]) assert excinfo.value.reason == 'This property may not contain a Bundle object' -@pytest.mark.parametrize("version", ["2.1"]) +@pytest.mark.parametrize("version", ["2.0"]) def test_parse_bundle(version): bundle = stix2.parse(EXPECTED_BUNDLE, version=version) assert bundle.type == "bundle" assert bundle.id.startswith("bundle--") - assert type(bundle.objects[0]) is stix2.v21.sdo.Indicator + assert type(bundle.objects[0]) is stix2.v20.Indicator assert bundle.objects[0].type == 'indicator' assert bundle.objects[1].type == 'malware' assert bundle.objects[2].type == 'relationship' @@ -199,12 +191,12 @@ def test_parse_unknown_type(): } with pytest.raises(stix2.exceptions.ParseError) as excinfo: - stix2.parse(unknown) + stix2.parse(unknown, version="2.0") assert str(excinfo.value) == "Can't parse unknown object type 'other'! For custom types, use the CustomObject decorator." def test_stix_object_property(): - prop = stix2.v21.bundle.STIXObjectProperty() + prop = stix2.v20.bundle.STIXObjectProperty() - identity = stix2.Identity(name="test", identity_class="individual") + identity = stix2.v20.Identity(name="test", identity_class="individual") assert prop.clean(identity) is identity diff --git a/stix2/test/v20/test_campaign.py b/stix2/test/v20/test_campaign.py index b226478..96d01a5 100644 --- a/stix2/test/v20/test_campaign.py +++ b/stix2/test/v20/test_campaign.py @@ -19,7 +19,7 @@ EXPECTED = """{ def test_campaign_example(): - campaign = stix2.Campaign( + campaign = stix2.v20.Campaign( id="campaign--8e2e2d2b-17d4-4cbf-938f-98ee46b3cd3f", created_by_ref="identity--f431f809-377b-45e0-aa1c-6a4751cae5ff", created="2016-04-06T20:03:00Z", @@ -44,7 +44,7 @@ def test_campaign_example(): }, ]) def test_parse_campaign(data): - cmpn = stix2.parse(data) + cmpn = stix2.parse(data, version="2.0") assert cmpn.type == 'campaign' assert cmpn.id == CAMPAIGN_ID diff --git a/stix2/test/v20/test_course_of_action.py b/stix2/test/v20/test_course_of_action.py index e376f0d..9ba0286 100644 --- a/stix2/test/v20/test_course_of_action.py +++ b/stix2/test/v20/test_course_of_action.py @@ -19,7 +19,7 @@ EXPECTED = """{ def test_course_of_action_example(): - coa = stix2.CourseOfAction( + coa = stix2.v20.CourseOfAction( id="course-of-action--8e2e2d2b-17d4-4cbf-938f-98ee46b3cd3f", created_by_ref="identity--f431f809-377b-45e0-aa1c-6a4751cae5ff", created="2016-04-06T20:03:48.000Z", @@ -44,7 +44,7 @@ def test_course_of_action_example(): }, ]) def test_parse_course_of_action(data): - coa = stix2.parse(data) + coa = stix2.parse(data, version="2.0") assert coa.type == 'course-of-action' assert coa.id == COURSE_OF_ACTION_ID diff --git a/stix2/test/v20/test_custom.py b/stix2/test/v20/test_custom.py index df3edbc..8fda321 100644 --- a/stix2/test/v20/test_custom.py +++ b/stix2/test/v20/test_custom.py @@ -1,12 +1,10 @@ import pytest import stix2 -import stix2.base -import stix2.v21.sdo from .constants import FAKE_TIME, MARKING_DEFINITION_ID -IDENTITY_CUSTOM_PROP = stix2.Identity( +IDENTITY_CUSTOM_PROP = stix2.v20.Identity( name="John Smith", identity_class="individual", x_foo="bar", @@ -16,7 +14,7 @@ IDENTITY_CUSTOM_PROP = stix2.Identity( def test_identity_custom_property(): with pytest.raises(ValueError) as excinfo: - stix2.Identity( + stix2.v20.Identity( id="identity--311b2d2d-f010-5473-83ec-1edf84858f4c", created="2015-12-21T19:59:11Z", modified="2015-12-21T19:59:11Z", @@ -27,7 +25,7 @@ def test_identity_custom_property(): assert str(excinfo.value) == "'custom_properties' must be a dictionary" with pytest.raises(stix2.exceptions.ExtraPropertiesError) as excinfo: - stix2.Identity( + stix2.v20.Identity( id="identity--311b2d2d-f010-5473-83ec-1edf84858f4c", created="2015-12-21T19:59:11Z", modified="2015-12-21T19:59:11Z", @@ -40,7 +38,7 @@ def test_identity_custom_property(): ) assert "Unexpected properties for Identity" in str(excinfo.value) - identity = stix2.Identity( + identity = stix2.v20.Identity( id="identity--311b2d2d-f010-5473-83ec-1edf84858f4c", created="2015-12-21T19:59:11Z", modified="2015-12-21T19:59:11Z", @@ -55,7 +53,7 @@ def test_identity_custom_property(): def test_identity_custom_property_invalid(): with pytest.raises(stix2.exceptions.ExtraPropertiesError) as excinfo: - stix2.Identity( + stix2.v20.Identity( id="identity--311b2d2d-f010-5473-83ec-1edf84858f4c", created="2015-12-21T19:59:11Z", modified="2015-12-21T19:59:11Z", @@ -63,13 +61,13 @@ def test_identity_custom_property_invalid(): identity_class="individual", x_foo="bar", ) - assert excinfo.value.cls == stix2.Identity + assert excinfo.value.cls == stix2.v20.Identity assert excinfo.value.properties == ['x_foo'] assert "Unexpected properties for" in str(excinfo.value) def test_identity_custom_property_allowed(): - identity = stix2.Identity( + identity = stix2.v20.Identity( id="identity--311b2d2d-f010-5473-83ec-1edf84858f4c", created="2015-12-21T19:59:11Z", modified="2015-12-21T19:59:11Z", @@ -94,31 +92,31 @@ 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 excinfo.value.cls == stix2.v21.sdo.Identity + stix2.parse(data, version="2.0") + assert excinfo.value.cls == stix2.v20.Identity assert excinfo.value.properties == ['foo'] assert "Unexpected properties for" in str(excinfo.value) - identity = stix2.parse(data, allow_custom=True) + identity = stix2.parse(data, version="2.0", allow_custom=True) assert identity.foo == "bar" def test_custom_property_object_in_bundled_object(): - bundle = stix2.Bundle(IDENTITY_CUSTOM_PROP, allow_custom=True) + bundle = stix2.v20.Bundle(IDENTITY_CUSTOM_PROP, allow_custom=True) assert bundle.objects[0].x_foo == "bar" assert '"x_foo": "bar"' in str(bundle) def test_custom_properties_object_in_bundled_object(): - obj = stix2.Identity( + obj = stix2.v20.Identity( name="John Smith", identity_class="individual", custom_properties={ "x_foo": "bar", } ) - bundle = stix2.Bundle(obj, allow_custom=True) + bundle = stix2.v20.Bundle(obj, allow_custom=True) assert bundle.objects[0].x_foo == "bar" assert '"x_foo": "bar"' in str(bundle) @@ -134,9 +132,9 @@ def test_custom_property_dict_in_bundled_object(): 'x_foo': 'bar', } with pytest.raises(stix2.exceptions.ExtraPropertiesError): - bundle = stix2.Bundle(custom_identity) + stix2.v20.Bundle(custom_identity) - bundle = stix2.Bundle(custom_identity, allow_custom=True) + bundle = stix2.v20.Bundle(custom_identity, allow_custom=True) assert bundle.objects[0].x_foo == "bar" assert '"x_foo": "bar"' in str(bundle) @@ -152,19 +150,19 @@ def test_custom_properties_dict_in_bundled_object(): 'x_foo': 'bar', }, } - bundle = stix2.Bundle(custom_identity) + bundle = stix2.v20.Bundle(custom_identity) assert bundle.objects[0].x_foo == "bar" assert '"x_foo": "bar"' in str(bundle) def test_custom_property_in_observed_data(): - artifact = stix2.File( + artifact = stix2.v20.File( allow_custom=True, name='test', x_foo='bar' ) - observed_data = stix2.ObservedData( + observed_data = stix2.v20.ObservedData( allow_custom=True, first_observed="2015-12-21T19:00:00Z", last_observed="2015-12-21T19:00:00Z", @@ -177,16 +175,16 @@ def test_custom_property_in_observed_data(): def test_custom_property_object_in_observable_extension(): - ntfs = stix2.NTFSExt( + ntfs = stix2.v20.NTFSExt( allow_custom=True, sid=1, x_foo='bar', ) - artifact = stix2.File( + artifact = stix2.v20.File( name='test', extensions={'ntfs-ext': ntfs}, ) - observed_data = stix2.ObservedData( + observed_data = stix2.v20.ObservedData( allow_custom=True, first_observed="2015-12-21T19:00:00Z", last_observed="2015-12-21T19:00:00Z", @@ -200,7 +198,7 @@ def test_custom_property_object_in_observable_extension(): def test_custom_property_dict_in_observable_extension(): with pytest.raises(stix2.exceptions.ExtraPropertiesError): - artifact = stix2.File( + stix2.v20.File( name='test', extensions={ 'ntfs-ext': { @@ -210,7 +208,7 @@ def test_custom_property_dict_in_observable_extension(): }, ) - artifact = stix2.File( + artifact = stix2.v20.File( allow_custom=True, name='test', extensions={ @@ -221,7 +219,7 @@ def test_custom_property_dict_in_observable_extension(): } }, ) - observed_data = stix2.ObservedData( + observed_data = stix2.v20.ObservedData( allow_custom=True, first_observed="2015-12-21T19:00:00Z", last_observed="2015-12-21T19:00:00Z", @@ -239,15 +237,15 @@ def test_identity_custom_property_revoke(): def test_identity_custom_property_edit_markings(): - marking_obj = stix2.MarkingDefinition( + marking_obj = stix2.v20.MarkingDefinition( id=MARKING_DEFINITION_ID, definition_type="statement", - definition=stix2.StatementMarking(statement="Copyright 2016, Example Corp") + definition=stix2.v20.StatementMarking(statement="Copyright 2016, Example Corp") ) - marking_obj2 = stix2.MarkingDefinition( + marking_obj2 = stix2.v20.MarkingDefinition( id=MARKING_DEFINITION_ID, definition_type="statement", - definition=stix2.StatementMarking(statement="Another one") + definition=stix2.v20.StatementMarking(statement="Another one") ) # None of the following should throw exceptions @@ -260,8 +258,8 @@ def test_identity_custom_property_edit_markings(): def test_custom_marking_no_init_1(): - @stix2.CustomMarking('x-new-obj', [ - ('property1', stix2.properties.StringProperty(required=True)), + @stix2.v20.CustomMarking('x-new-obj', [ + ('property1', stix2.v20.properties.StringProperty(required=True)), ]) class NewObj(): pass @@ -271,8 +269,8 @@ def test_custom_marking_no_init_1(): def test_custom_marking_no_init_2(): - @stix2.CustomMarking('x-new-obj2', [ - ('property1', stix2.properties.StringProperty(required=True)), + @stix2.v20.CustomMarking('x-new-obj2', [ + ('property1', stix2.v20.properties.StringProperty(required=True)), ]) class NewObj2(object): pass @@ -281,9 +279,9 @@ def test_custom_marking_no_init_2(): assert no2.property1 == 'something' -@stix2.sdo.CustomObject('x-new-type', [ - ('property1', stix2.properties.StringProperty(required=True)), - ('property2', stix2.properties.IntegerProperty()), +@stix2.v20.CustomObject('x-new-type', [ + ('property1', stix2.v20.properties.StringProperty(required=True)), + ('property2', stix2.v20.properties.IntegerProperty()), ]) class NewType(object): def __init__(self, property2=None, **kwargs): @@ -314,8 +312,8 @@ def test_custom_object_type(): def test_custom_object_no_init_1(): - @stix2.sdo.CustomObject('x-new-obj', [ - ('property1', stix2.properties.StringProperty(required=True)), + @stix2.v20.CustomObject('x-new-obj', [ + ('property1', stix2.v20.properties.StringProperty(required=True)), ]) class NewObj(): pass @@ -325,8 +323,8 @@ def test_custom_object_no_init_1(): def test_custom_object_no_init_2(): - @stix2.sdo.CustomObject('x-new-obj2', [ - ('property1', stix2.properties.StringProperty(required=True)), + @stix2.v20.CustomObject('x-new-obj2', [ + ('property1', stix2.v20.properties.StringProperty(required=True)), ]) class NewObj2(object): pass @@ -337,16 +335,16 @@ def test_custom_object_no_init_2(): def test_custom_object_invalid_type_name(): with pytest.raises(ValueError) as excinfo: - @stix2.sdo.CustomObject('x', [ - ('property1', stix2.properties.StringProperty(required=True)), + @stix2.v20.CustomObject('x', [ + ('property1', stix2.v20.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)), + @stix2.v20.CustomObject('x_new_object', [ + ('property1', stix2.v20.properties.StringProperty(required=True)), ]) class NewObj2(object): pass # pragma: no cover @@ -360,7 +358,7 @@ def test_parse_custom_object_type(): "property1": "something" }""" - nt = stix2.parse(nt_string, allow_custom=True) + nt = stix2.parse(nt_string, version="2.0", allow_custom=True) assert nt["property1"] == 'something' @@ -372,7 +370,7 @@ def test_parse_unregistered_custom_object_type(): }""" with pytest.raises(stix2.exceptions.ParseError) as excinfo: - stix2.parse(nt_string) + stix2.parse(nt_string, version="2.0") assert "Can't parse unknown object type" in str(excinfo.value) assert "use the CustomObject decorator." in str(excinfo.value) @@ -387,14 +385,14 @@ def test_parse_unregistered_custom_object_type_w_allow_custom(): "property1": "something" }""" - custom_obj = stix2.parse(nt_string, allow_custom=True) + custom_obj = stix2.parse(nt_string, version="2.0", 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()), - ('x_property3', stix2.properties.BooleanProperty()), +@stix2.v20.CustomObservable('x-new-observable', [ + ('property1', stix2.v20.properties.StringProperty(required=True)), + ('property2', stix2.v20.properties.IntegerProperty()), + ('x_property3', stix2.v20.properties.BooleanProperty()), ]) class NewObservable(): def __init__(self, property2=None, **kwargs): @@ -430,8 +428,8 @@ def test_custom_observable_raises_exception(): def test_custom_observable_object_no_init_1(): - @stix2.observables.CustomObservable('x-new-observable', [ - ('property1', stix2.properties.StringProperty()), + @stix2.v20.CustomObservable('x-new-observable', [ + ('property1', stix2.v20.properties.StringProperty()), ]) class NewObs(): pass @@ -441,8 +439,8 @@ def test_custom_observable_object_no_init_1(): def test_custom_observable_object_no_init_2(): - @stix2.observables.CustomObservable('x-new-obs2', [ - ('property1', stix2.properties.StringProperty()), + @stix2.v20.CustomObservable('x-new-obs2', [ + ('property1', stix2.v20.properties.StringProperty()), ]) class NewObs2(object): pass @@ -453,16 +451,16 @@ def test_custom_observable_object_no_init_2(): def test_custom_observable_object_invalid_type_name(): with pytest.raises(ValueError) as excinfo: - @stix2.observables.CustomObservable('x', [ - ('property1', stix2.properties.StringProperty()), + @stix2.v20.CustomObservable('x', [ + ('property1', stix2.v20.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()), + @stix2.v20.CustomObservable('x_new_obs', [ + ('property1', stix2.v20.properties.StringProperty()), ]) class NewObs2(object): pass # pragma: no cover @@ -471,8 +469,8 @@ def test_custom_observable_object_invalid_type_name(): def test_custom_observable_object_invalid_ref_property(): with pytest.raises(ValueError) as excinfo: - @stix2.observables.CustomObservable('x-new-obs', [ - ('property_ref', stix2.properties.StringProperty()), + @stix2.v20.CustomObservable('x-new-obs', [ + ('property_ref', stix2.v20.properties.StringProperty()), ]) class NewObs(): pass @@ -481,8 +479,8 @@ def test_custom_observable_object_invalid_ref_property(): def test_custom_observable_object_invalid_refs_property(): with pytest.raises(ValueError) as excinfo: - @stix2.observables.CustomObservable('x-new-obs', [ - ('property_refs', stix2.properties.StringProperty()), + @stix2.v20.CustomObservable('x-new-obs', [ + ('property_refs', stix2.v20.properties.StringProperty()), ]) class NewObs(): pass @@ -491,8 +489,8 @@ def test_custom_observable_object_invalid_refs_property(): def test_custom_observable_object_invalid_refs_list_property(): with pytest.raises(ValueError) as excinfo: - @stix2.observables.CustomObservable('x-new-obs', [ - ('property_refs', stix2.properties.ListProperty(stix2.properties.StringProperty)), + @stix2.v20.CustomObservable('x-new-obs', [ + ('property_refs', stix2.v20.properties.ListProperty(stix2.v20.properties.StringProperty)), ]) class NewObs(): pass @@ -500,9 +498,9 @@ def test_custom_observable_object_invalid_refs_list_property(): def test_custom_observable_object_invalid_valid_refs(): - @stix2.observables.CustomObservable('x-new-obs', [ - ('property1', stix2.properties.StringProperty(required=True)), - ('property_ref', stix2.properties.ObjectReferenceProperty(valid_types='email-addr')), + @stix2.v20.CustomObservable('x-new-obs', [ + ('property1', stix2.v20.properties.StringProperty(required=True)), + ('property_ref', stix2.v20.properties.ObjectReferenceProperty(valid_types='email-addr')), ]) class NewObs(): pass @@ -517,7 +515,7 @@ def test_custom_observable_object_invalid_valid_refs(): def test_custom_no_properties_raises_exception(): with pytest.raises(ValueError): - @stix2.sdo.CustomObject('x-new-object-type') + @stix2.v20.CustomObject('x-new-object-type') class NewObject1(object): pass @@ -525,7 +523,7 @@ def test_custom_no_properties_raises_exception(): def test_custom_wrong_properties_arg_raises_exception(): with pytest.raises(ValueError): - @stix2.observables.CustomObservable('x-new-object-type', (("prop", stix2.properties.BooleanProperty()))) + @stix2.v20.CustomObservable('x-new-object-type', (("prop", stix2.v20.properties.BooleanProperty()))) class NewObject2(object): pass @@ -536,7 +534,7 @@ def test_parse_custom_observable_object(): "property1": "something" }""" - nt = stix2.parse_observable(nt_string, []) + nt = stix2.parse_observable(nt_string, [], version='2.0') assert isinstance(nt, stix2.base._STIXBase) assert nt.property1 == 'something' @@ -548,10 +546,10 @@ def test_parse_unregistered_custom_observable_object(): }""" with pytest.raises(stix2.exceptions.CustomContentError) as excinfo: - stix2.parse_observable(nt_string) + stix2.parse_observable(nt_string, version='2.0') assert "Can't parse unknown observable type" in str(excinfo.value) - parsed_custom = stix2.parse_observable(nt_string, allow_custom=True) + parsed_custom = stix2.parse_observable(nt_string, allow_custom=True, version='2.0') assert parsed_custom['property1'] == 'something' with pytest.raises(AttributeError) as excinfo: assert parsed_custom.property1 == 'something' @@ -564,7 +562,7 @@ def test_parse_unregistered_custom_observable_object_with_no_type(): }""" with pytest.raises(stix2.exceptions.ParseError) as excinfo: - stix2.parse_observable(nt_string, allow_custom=True) + stix2.parse_observable(nt_string, allow_custom=True, version='2.0') assert "Can't parse observable with no 'type' property" in str(excinfo.value) @@ -584,7 +582,7 @@ def test_parse_observed_data_with_custom_observable(): } } }""" - parsed = stix2.parse(input_str, allow_custom=True) + parsed = stix2.parse(input_str, version="2.0", allow_custom=True) assert parsed.objects['0']['property1'] == 'something' @@ -594,7 +592,7 @@ def test_parse_invalid_custom_observable_object(): }""" with pytest.raises(stix2.exceptions.ParseError) as excinfo: - stix2.parse_observable(nt_string) + stix2.parse_observable(nt_string, version='2.0') assert "Can't parse observable with no 'type' property" in str(excinfo.value) @@ -636,7 +634,7 @@ def test_observable_custom_property_allowed(): def test_observed_data_with_custom_observable_object(): no = NewObservable(property1='something') - ob_data = stix2.ObservedData( + ob_data = stix2.v20.ObservedData( first_observed=FAKE_TIME, last_observed=FAKE_TIME, number_observed=1, @@ -646,9 +644,9 @@ 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.v20.CustomExtension(stix2.v20.DomainName, 'x-new-ext', [ + ('property1', stix2.v20.properties.StringProperty(required=True)), + ('property2', stix2.v20.properties.IntegerProperty()), ]) class NewExtension(): def __init__(self, property2=None, **kwargs): @@ -683,10 +681,11 @@ def test_custom_extension_wrong_observable_type(): # NewExtension is an extension of DomainName, not File ext = NewExtension(property1='something') with pytest.raises(ValueError) as excinfo: - stix2.File(name="abc.txt", - extensions={ - "ntfs-ext": ext, - }) + stix2.v20.File( + name="abc.txt", + extensions={ + "ntfs-ext": ext, + }) assert 'Cannot determine extension type' in excinfo.value.reason @@ -702,8 +701,8 @@ def test_custom_extension_wrong_observable_type(): }""", ]) 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)) + @stix2.v20.CustomExtension(stix2.v20.UserAccount, 'some-extension', [ + ('keys', stix2.v20.properties.ListProperty(stix2.v20.properties.DictionaryProperty, required=True)) ]) class SomeCustomExtension: pass @@ -718,29 +717,29 @@ 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.v20.CustomExtension(Foo, 'x-new-ext', [ + ('property1', stix2.v20.properties.StringProperty(required=True)), ]) class FooExtension(): pass # pragma: no cover assert str(excinfo.value) == "'observable' must be a valid Observable class!" - class Bar(stix2.observables._Observable): + class Bar(stix2.v20.observables._Observable): pass with pytest.raises(ValueError) as excinfo: - @stix2.observables.CustomExtension(Bar, 'x-new-ext', [ - ('property1', stix2.properties.StringProperty(required=True)), + @stix2.v20.CustomExtension(Bar, 'x-new-ext', [ + ('property1', stix2.v20.properties.StringProperty(required=True)), ]) class BarExtension(): pass assert "Unknown observable type" in str(excinfo.value) assert "Custom observables must be created with the @CustomObservable decorator." in str(excinfo.value) - class Baz(stix2.observables._Observable): + class Baz(stix2.v20.observables._Observable): _type = 'Baz' with pytest.raises(ValueError) as excinfo: - @stix2.observables.CustomExtension(Baz, 'x-new-ext', [ - ('property1', stix2.properties.StringProperty(required=True)), + @stix2.v20.CustomExtension(Baz, 'x-new-ext', [ + ('property1', stix2.v20.properties.StringProperty(required=True)), ]) class BazExtension(): pass @@ -750,16 +749,16 @@ def test_custom_extension_invalid_observable(): 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), + @stix2.v20.CustomExtension(stix2.v20.File, 'x', { + 'property1': stix2.v20.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), + @stix2.v20.CustomExtension(stix2.File, 'x_new_ext', { + 'property1': stix2.v20.properties.StringProperty(required=True), }) class BlaExtension(): pass # pragma: no cover @@ -768,7 +767,7 @@ def test_custom_extension_invalid_type_name(): def test_custom_extension_no_properties(): with pytest.raises(ValueError) as excinfo: - @stix2.observables.CustomExtension(stix2.DomainName, 'x-new-ext2', None) + @stix2.v20.CustomExtension(stix2.v20.DomainName, 'x-new-ext2', None) class BarExtension(): pass assert "Must supply a list, containing tuples." in str(excinfo.value) @@ -776,7 +775,7 @@ def test_custom_extension_no_properties(): def test_custom_extension_empty_properties(): with pytest.raises(ValueError) as excinfo: - @stix2.observables.CustomExtension(stix2.DomainName, 'x-new-ext2', []) + @stix2.v20.CustomExtension(stix2.v20.DomainName, 'x-new-ext2', []) class BarExtension(): pass assert "Must supply a list, containing tuples." in str(excinfo.value) @@ -784,15 +783,15 @@ def test_custom_extension_empty_properties(): def test_custom_extension_dict_properties(): with pytest.raises(ValueError) as excinfo: - @stix2.observables.CustomExtension(stix2.DomainName, 'x-new-ext2', {}) + @stix2.v20.CustomExtension(stix2.v20.DomainName, 'x-new-ext2', {}) class BarExtension(): pass 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.v20.CustomExtension(stix2.v20.DomainName, 'x-new-extension', [ + ('property1', stix2.v20.properties.StringProperty(required=True)), ]) class NewExt(): pass @@ -802,8 +801,8 @@ 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.v20.CustomExtension(stix2.v20.DomainName, 'x-new-ext2', [ + ('property1', stix2.v20.properties.StringProperty(required=True)), ]) class NewExt2(object): pass @@ -824,7 +823,7 @@ def test_parse_observable_with_custom_extension(): } }""" - parsed = stix2.parse_observable(input_str) + parsed = stix2.parse_observable(input_str, version='2.0') assert parsed.extensions['x-new-ext'].property2 == 12 @@ -841,10 +840,10 @@ def test_parse_observable_with_unregistered_custom_extension(): }""" with pytest.raises(ValueError) as excinfo: - stix2.parse_observable(input_str) + stix2.parse_observable(input_str, version='2.0') assert "Can't parse unknown extension type" in str(excinfo.value) - parsed_ob = stix2.parse_observable(input_str, allow_custom=True) + parsed_ob = stix2.parse_observable(input_str, allow_custom=True, version='2.0') assert parsed_ob['extensions']['x-foobar-ext']['property1'] == 'foo' assert not isinstance(parsed_ob['extensions']['x-foobar-ext'], stix2.base._STIXBase) @@ -854,14 +853,14 @@ def test_register_custom_object(): class CustomObject2(object): _type = 'awesome-object' - stix2._register_type(CustomObject2) + stix2._register_object(CustomObject2, version="2.0") # Note that we will always check against newest OBJ_MAP. - assert (CustomObject2._type, CustomObject2) in stix2.OBJ_MAP.items() + assert (CustomObject2._type, CustomObject2) in stix2.v20.OBJ_MAP.items() def test_extension_property_location(): - assert 'extensions' in stix2.v21.observables.OBJ_MAP_OBSERVABLE['x-new-observable']._properties - assert 'extensions' not in stix2.v21.observables.EXT_MAP['domain-name']['x-new-ext']._properties + assert 'extensions' in stix2.v20.OBJ_MAP_OBSERVABLE['x-new-observable']._properties + assert 'extensions' not in stix2.v20.EXT_MAP['domain-name']['x-new-ext']._properties @pytest.mark.parametrize("data", [ @@ -879,8 +878,8 @@ def test_extension_property_location(): }""", ]) def test_custom_object_nested_dictionary(data): - @stix2.sdo.CustomObject('x-example', [ - ('dictionary', stix2.properties.DictionaryProperty()), + @stix2.v20.CustomObject('x-example', [ + ('dictionary', stix2.v20.properties.DictionaryProperty()), ]) class Example(object): def __init__(self, **kwargs): diff --git a/stix2/test/v20/test_datastore.py b/stix2/test/v20/test_datastore.py index 323365a..3c55d6b 100644 --- a/stix2/test/v20/test_datastore.py +++ b/stix2/test/v20/test_datastore.py @@ -3,7 +3,7 @@ import pytest from stix2.datastore import (CompositeDataSource, DataSink, DataSource, DataStoreMixin) from stix2.datastore.filters import Filter -from stix2.test.constants import CAMPAIGN_MORE_KWARGS +from stix2.test.v20.constants import CAMPAIGN_MORE_KWARGS def test_datasource_abstract_class_raises_error(): diff --git a/stix2/test/v20/test_datastore_filesystem.py b/stix2/test/v20/test_datastore_filesystem.py index 49cbcc1..c1d8f66 100644 --- a/stix2/test/v20/test_datastore_filesystem.py +++ b/stix2/test/v20/test_datastore_filesystem.py @@ -4,13 +4,12 @@ import shutil import pytest -from stix2 import (Bundle, Campaign, CustomObject, FileSystemSink, - FileSystemSource, FileSystemStore, Filter, Identity, - Indicator, Malware, Relationship, properties) -from stix2.test.constants import (CAMPAIGN_ID, CAMPAIGN_KWARGS, IDENTITY_ID, - IDENTITY_KWARGS, INDICATOR_ID, - INDICATOR_KWARGS, MALWARE_ID, MALWARE_KWARGS, - RELATIONSHIP_IDS) +import stix2 +from stix2.test.v20.constants import (CAMPAIGN_ID, CAMPAIGN_KWARGS, + IDENTITY_ID, IDENTITY_KWARGS, + INDICATOR_ID, INDICATOR_KWARGS, + MALWARE_ID, MALWARE_KWARGS, + RELATIONSHIP_IDS) FS_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), "stix2_data") @@ -18,7 +17,7 @@ FS_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), "stix2_data" @pytest.fixture def fs_store(): # create - yield FileSystemStore(FS_PATH) + yield stix2.FileSystemStore(FS_PATH) # remove campaign dir shutil.rmtree(os.path.join(FS_PATH, "campaign"), True) @@ -27,7 +26,7 @@ def fs_store(): @pytest.fixture def fs_source(): # create - fs = FileSystemSource(FS_PATH) + fs = stix2.FileSystemSource(FS_PATH) assert fs.stix_dir == FS_PATH yield fs @@ -38,7 +37,7 @@ def fs_source(): @pytest.fixture def fs_sink(): # create - fs = FileSystemSink(FS_PATH) + fs = stix2.FileSystemSink(FS_PATH) assert fs.stix_dir == FS_PATH yield fs @@ -83,15 +82,15 @@ def bad_stix_files(): @pytest.fixture(scope='module') def rel_fs_store(): - cam = Campaign(id=CAMPAIGN_ID, **CAMPAIGN_KWARGS) - idy = Identity(id=IDENTITY_ID, **IDENTITY_KWARGS) - ind = Indicator(id=INDICATOR_ID, **INDICATOR_KWARGS) - mal = Malware(id=MALWARE_ID, **MALWARE_KWARGS) - rel1 = Relationship(ind, 'indicates', mal, id=RELATIONSHIP_IDS[0]) - rel2 = Relationship(mal, 'targets', idy, id=RELATIONSHIP_IDS[1]) - rel3 = Relationship(cam, 'uses', mal, id=RELATIONSHIP_IDS[2]) + cam = stix2.v20.Campaign(id=CAMPAIGN_ID, **CAMPAIGN_KWARGS) + idy = stix2.v20.Identity(id=IDENTITY_ID, **IDENTITY_KWARGS) + ind = stix2.v20.Indicator(id=INDICATOR_ID, **INDICATOR_KWARGS) + mal = stix2.v20.Malware(id=MALWARE_ID, **MALWARE_KWARGS) + rel1 = stix2.v20.Relationship(ind, 'indicates', mal, id=RELATIONSHIP_IDS[0]) + rel2 = stix2.v20.Relationship(mal, 'targets', idy, id=RELATIONSHIP_IDS[1]) + rel3 = stix2.v20.Relationship(cam, 'uses', mal, id=RELATIONSHIP_IDS[2]) stix_objs = [cam, idy, ind, mal, rel1, rel2, rel3] - fs = FileSystemStore(FS_PATH) + fs = stix2.FileSystemStore(FS_PATH) for o in stix_objs: fs.add(o) yield fs @@ -102,13 +101,13 @@ def rel_fs_store(): def test_filesystem_source_nonexistent_folder(): with pytest.raises(ValueError) as excinfo: - FileSystemSource('nonexistent-folder') + stix2.FileSystemSource('nonexistent-folder') assert "for STIX data does not exist" in str(excinfo) def test_filesystem_sink_nonexistent_folder(): with pytest.raises(ValueError) as excinfo: - FileSystemSink('nonexistent-folder') + stix2.FileSystemSink('nonexistent-folder') assert "for STIX data does not exist" in str(excinfo) @@ -154,7 +153,7 @@ def test_filesytem_source_all_versions(fs_source): def test_filesytem_source_query_single(fs_source): # query2 - is_2 = fs_source.query([Filter("external_references.external_id", '=', "T1027")]) + is_2 = fs_source.query([stix2.Filter("external_references.external_id", '=', "T1027")]) assert len(is_2) == 1 is_2 = is_2[0] @@ -164,7 +163,7 @@ def test_filesytem_source_query_single(fs_source): def test_filesytem_source_query_multiple(fs_source): # query - intrusion_sets = fs_source.query([Filter("type", '=', "intrusion-set")]) + intrusion_sets = fs_source.query([stix2.Filter("type", '=', "intrusion-set")]) assert len(intrusion_sets) == 2 assert "intrusion-set--a653431d-6a5e-4600-8ad3-609b5af57064" in [is_.id for is_ in intrusion_sets] assert "intrusion-set--f3bdec95-3d62-42d9-a840-29630f6cdc1a" in [is_.id for is_ in intrusion_sets] @@ -176,9 +175,10 @@ def test_filesytem_source_query_multiple(fs_source): def test_filesystem_sink_add_python_stix_object(fs_sink, fs_source): # add python stix object - camp1 = Campaign(name="Hannibal", - objective="Targeting Italian and Spanish Diplomat internet accounts", - aliases=["War Elephant"]) + camp1 = stix2.v20.Campaign( + name="Hannibal", + objective="Targeting Italian and Spanish Diplomat internet accounts", + aliases=["War Elephant"]) fs_sink.add(camp1) @@ -278,9 +278,10 @@ def test_filesystem_sink_json_stix_bundle(fs_sink, fs_source): def test_filesystem_sink_add_objects_list(fs_sink, fs_source): # add list of objects - camp6 = Campaign(name="Comanche", - objective="US Midwest manufacturing firms, oil refineries, and businesses", - aliases=["Horse Warrior"]) + camp6 = stix2.v20.Campaign( + name="Comanche", + objective="US Midwest manufacturing firms, oil refineries, and businesses", + aliases=["Horse Warrior"]) camp7 = { "name": "Napolean", @@ -330,14 +331,14 @@ def test_filesystem_store_all_versions(fs_store): def test_filesystem_store_query(fs_store): # query() - tools = fs_store.query([Filter("labels", "in", "tool")]) + tools = fs_store.query([stix2.Filter("labels", "in", "tool")]) assert len(tools) == 2 assert "tool--242f3da3-4425-4d11-8f5c-b842886da966" in [tool.id for tool in tools] assert "tool--03342581-f790-4f03-ba41-e82e67392e23" in [tool.id for tool in tools] def test_filesystem_store_query_single_filter(fs_store): - query = Filter("labels", "in", "tool") + query = stix2.Filter("labels", "in", "tool") tools = fs_store.query(query) assert len(tools) == 2 assert "tool--242f3da3-4425-4d11-8f5c-b842886da966" in [tool.id for tool in tools] @@ -352,22 +353,23 @@ def test_filesystem_store_empty_query(fs_store): def test_filesystem_store_query_multiple_filters(fs_store): - fs_store.source.filters.add(Filter("labels", "in", "tool")) - tools = fs_store.query(Filter("id", "=", "tool--242f3da3-4425-4d11-8f5c-b842886da966")) + fs_store.source.filters.add(stix2.Filter("labels", "in", "tool")) + tools = fs_store.query(stix2.Filter("id", "=", "tool--242f3da3-4425-4d11-8f5c-b842886da966")) assert len(tools) == 1 assert tools[0].id == "tool--242f3da3-4425-4d11-8f5c-b842886da966" def test_filesystem_store_query_dont_include_type_folder(fs_store): - results = fs_store.query(Filter("type", "!=", "tool")) + results = fs_store.query(stix2.Filter("type", "!=", "tool")) assert len(results) == 24 def test_filesystem_store_add(fs_store): # add() - camp1 = Campaign(name="Great Heathen Army", - objective="Targeting the government of United Kingdom and insitutions affiliated with the Church Of England", - aliases=["Ragnar"]) + camp1 = stix2.v20.Campaign( + name="Great Heathen Army", + objective="Targeting the government of United Kingdom and insitutions affiliated with the Church Of England", + aliases=["Ragnar"]) fs_store.add(camp1) camp1_r = fs_store.get(camp1.id) @@ -379,11 +381,12 @@ def test_filesystem_store_add(fs_store): def test_filesystem_store_add_as_bundle(): - fs_store = FileSystemStore(FS_PATH, bundlify=True) + fs_store = stix2.FileSystemStore(FS_PATH, bundlify=True) - camp1 = Campaign(name="Great Heathen Army", - objective="Targeting the government of United Kingdom and insitutions affiliated with the Church Of England", - aliases=["Ragnar"]) + camp1 = stix2.v20.Campaign( + name="Great Heathen Army", + objective="Targeting the government of United Kingdom and insitutions affiliated with the Church Of England", + aliases=["Ragnar"]) fs_store.add(camp1) with open(os.path.join(FS_PATH, "campaign", camp1.id + ".json")) as bundle_file: @@ -397,7 +400,7 @@ def test_filesystem_store_add_as_bundle(): def test_filesystem_add_bundle_object(fs_store): - bundle = Bundle() + bundle = stix2.v20.Bundle() fs_store.add(bundle) @@ -412,10 +415,11 @@ def test_filesystem_store_add_invalid_object(fs_store): def test_filesystem_object_with_custom_property(fs_store): - camp = Campaign(name="Scipio Africanus", - objective="Defeat the Carthaginians", - x_empire="Roman", - allow_custom=True) + camp = stix2.v20.Campaign( + name="Scipio Africanus", + objective="Defeat the Carthaginians", + x_empire="Roman", + allow_custom=True) fs_store.add(camp, True) @@ -425,12 +429,13 @@ def test_filesystem_object_with_custom_property(fs_store): def test_filesystem_object_with_custom_property_in_bundle(fs_store): - camp = Campaign(name="Scipio Africanus", - objective="Defeat the Carthaginians", - x_empire="Roman", - allow_custom=True) + camp = stix2.v20.Campaign( + name="Scipio Africanus", + objective="Defeat the Carthaginians", + x_empire="Roman", + allow_custom=True) - bundle = Bundle(camp, allow_custom=True) + bundle = stix2.v20.Bundle(camp, allow_custom=True) fs_store.add(bundle) camp_r = fs_store.get(camp.id) @@ -439,8 +444,8 @@ def test_filesystem_object_with_custom_property_in_bundle(fs_store): def test_filesystem_custom_object(fs_store): - @CustomObject('x-new-obj', [ - ('property1', properties.StringProperty(required=True)), + @stix2.v20.CustomObject('x-new-obj', [ + ('property1', stix2.v20.properties.StringProperty(required=True)), ]) class NewObj(): pass diff --git a/stix2/test/v20/test_datastore_filters.py b/stix2/test/v20/test_datastore_filters.py index 8ed82f3..252b8eb 100644 --- a/stix2/test/v20/test_datastore_filters.py +++ b/stix2/test/v20/test_datastore_filters.py @@ -9,7 +9,6 @@ stix_objs = [ "created": "2017-01-27T13:49:53.997Z", "description": "\n\nTITLE:\n\tPoison Ivy", "id": "malware--fdd60b30-b67c-11e3-b0b9-f01faf20d111", - "spec_version": "2.1", "labels": [ "remote-access-trojan" ], diff --git a/stix2/test/v20/test_datastore_taxii.py b/stix2/test/v20/test_datastore_taxii.py index 8cc5033..5e8ea69 100644 --- a/stix2/test/v20/test_datastore_taxii.py +++ b/stix2/test/v20/test_datastore_taxii.py @@ -5,8 +5,7 @@ import pytest from requests.models import Response from taxii2client import Collection, _filter_kwargs_to_query_params -from stix2 import (Bundle, TAXIICollectionSink, TAXIICollectionSource, - TAXIICollectionStore, ThreatActor) +import stix2 from stix2.datastore import DataSourceError from stix2.datastore.filters import Filter @@ -39,7 +38,7 @@ class MockTAXIICollectionEndpoint(Collection): [] ) if objs: - return Bundle(objects=objs) + return stix2.v20.Bundle(objects=objs) else: resp = Response() resp.status_code = 404 @@ -59,7 +58,7 @@ class MockTAXIICollectionEndpoint(Collection): [] ) if objs: - return Bundle(objects=objs) + return stix2.v20.Bundle(objects=objs) else: resp = Response() resp.status_code = 404 @@ -101,78 +100,82 @@ def collection_no_rw_access(stix_objs1): def test_ds_taxii(collection): - ds = TAXIICollectionSource(collection) + ds = stix2.TAXIICollectionSource(collection) assert ds.collection is not None def test_add_stix2_object(collection): - tc_sink = TAXIICollectionSink(collection) + tc_sink = stix2.TAXIICollectionSink(collection) # create new STIX threat-actor - ta = ThreatActor(name="Teddy Bear", - labels=["nation-state"], - sophistication="innovator", - resource_level="government", - goals=[ - "compromising environment NGOs", - "water-hole attacks geared towards energy sector", - ]) + ta = stix2.v20.ThreatActor( + name="Teddy Bear", + labels=["nation-state"], + sophistication="innovator", + resource_level="government", + goals=[ + "compromising environment NGOs", + "water-hole attacks geared towards energy sector", + ]) tc_sink.add(ta) def test_add_stix2_with_custom_object(collection): - tc_sink = TAXIICollectionStore(collection, allow_custom=True) + tc_sink = stix2.TAXIICollectionStore(collection, allow_custom=True) # create new STIX threat-actor - ta = ThreatActor(name="Teddy Bear", - labels=["nation-state"], - sophistication="innovator", - resource_level="government", - goals=[ - "compromising environment NGOs", - "water-hole attacks geared towards energy sector", - ], - foo="bar", - allow_custom=True) + ta = stix2.v20.ThreatActor( + name="Teddy Bear", + labels=["nation-state"], + sophistication="innovator", + resource_level="government", + goals=[ + "compromising environment NGOs", + "water-hole attacks geared towards energy sector", + ], + foo="bar", + allow_custom=True) tc_sink.add(ta) def test_add_list_object(collection, indicator): - tc_sink = TAXIICollectionSink(collection) + tc_sink = stix2.TAXIICollectionSink(collection) # create new STIX threat-actor - ta = ThreatActor(name="Teddy Bear", - labels=["nation-state"], - sophistication="innovator", - resource_level="government", - goals=[ - "compromising environment NGOs", - "water-hole attacks geared towards energy sector", - ]) + ta = stix2.v20.ThreatActor( + name="Teddy Bear", + labels=["nation-state"], + sophistication="innovator", + resource_level="government", + goals=[ + "compromising environment NGOs", + "water-hole attacks geared towards energy sector", + ]) tc_sink.add([ta, indicator]) def test_add_stix2_bundle_object(collection): - tc_sink = TAXIICollectionSink(collection) + tc_sink = stix2.TAXIICollectionSink(collection) # create new STIX threat-actor - ta = ThreatActor(name="Teddy Bear", - labels=["nation-state"], - sophistication="innovator", - resource_level="government", - goals=[ - "compromising environment NGOs", - "water-hole attacks geared towards energy sector", - ]) + ta = stix2.v20.ThreatActor( + name="Teddy Bear", + labels=["nation-state"], + sophistication="innovator", + resource_level="government", + goals=[ + "compromising environment NGOs", + "water-hole attacks geared towards energy sector", + ]) - tc_sink.add(Bundle(objects=[ta])) + tc_sink.add(stix2.v20.Bundle(objects=[ta])) def test_add_str_object(collection): - tc_sink = TAXIICollectionSink(collection) + tc_sink = stix2.TAXIICollectionSink(collection) # create new STIX threat-actor ta = """{ @@ -196,7 +199,7 @@ def test_add_str_object(collection): def test_add_dict_object(collection): - tc_sink = TAXIICollectionSink(collection) + tc_sink = stix2.TAXIICollectionSink(collection) ta = { "type": "threat-actor", @@ -219,7 +222,7 @@ def test_add_dict_object(collection): def test_add_dict_bundle_object(collection): - tc_sink = TAXIICollectionSink(collection) + tc_sink = stix2.TAXIICollectionSink(collection) ta = { "type": "bundle", @@ -248,7 +251,7 @@ def test_add_dict_bundle_object(collection): def test_get_stix2_object(collection): - tc_sink = TAXIICollectionSource(collection) + tc_sink = stix2.TAXIICollectionSource(collection) objects = tc_sink.get("indicator--d81f86b9-975b-bc0b-775e-810c5ad45a4f") @@ -271,7 +274,7 @@ def test_parse_taxii_filters(collection): Filter("version", "=", "first") ] - ds = TAXIICollectionSource(collection) + ds = stix2.TAXIICollectionSource(collection) taxii_filters = ds._parse_taxii_filters(query) @@ -279,7 +282,7 @@ def test_parse_taxii_filters(collection): def test_add_get_remove_filter(collection): - ds = TAXIICollectionSource(collection) + ds = stix2.TAXIICollectionSource(collection) # First 3 filters are valid, remaining properties are erroneous in some way valid_filters = [ @@ -315,7 +318,7 @@ def test_add_get_remove_filter(collection): def test_get_all_versions(collection): - ds = TAXIICollectionStore(collection) + ds = stix2.TAXIICollectionStore(collection) indicators = ds.all_versions('indicator--d81f86b9-975b-bc0b-775e-810c5ad45a4f') # There are 3 indicators but 2 share the same 'modified' timestamp @@ -327,7 +330,7 @@ def test_can_read_error(collection_no_rw_access): instance that does not have read access, check ValueError exception is raised""" with pytest.raises(DataSourceError) as excinfo: - TAXIICollectionSource(collection_no_rw_access) + stix2.TAXIICollectionSource(collection_no_rw_access) assert "Collection object provided does not have read access" in str(excinfo.value) @@ -336,7 +339,7 @@ def test_can_write_error(collection_no_rw_access): instance that does not have write access, check ValueError exception is raised""" with pytest.raises(DataSourceError) as excinfo: - TAXIICollectionSink(collection_no_rw_access) + stix2.TAXIICollectionSink(collection_no_rw_access) assert "Collection object provided does not have write access" in str(excinfo.value) @@ -357,7 +360,7 @@ def test_get_404(): resp.status_code = 404 resp.raise_for_status() - ds = TAXIICollectionSource(TAXIICollection404()) + ds = stix2.TAXIICollectionSource(TAXIICollection404()) # this will raise 404 from mock TAXII Client but TAXIICollectionStore # should handle gracefully and return None @@ -369,7 +372,7 @@ def test_all_versions_404(collection): """ a TAXIICollectionSource.all_version() call that recieves an HTTP 404 response code from the taxii2client should be returned as an exception""" - ds = TAXIICollectionStore(collection) + ds = stix2.TAXIICollectionStore(collection) with pytest.raises(DataSourceError) as excinfo: ds.all_versions("indicator--1") @@ -381,7 +384,7 @@ def test_query_404(collection): """ a TAXIICollectionSource.query() call that recieves an HTTP 404 response code from the taxii2client should be returned as an exception""" - ds = TAXIICollectionStore(collection) + ds = stix2.TAXIICollectionStore(collection) query = [Filter("type", "=", "malware")] with pytest.raises(DataSourceError) as excinfo: diff --git a/stix2/test/v20/test_environment.py b/stix2/test/v20/test_environment.py index a5166b7..d80a70c 100644 --- a/stix2/test/v20/test_environment.py +++ b/stix2/test/v20/test_environment.py @@ -9,92 +9,99 @@ from .constants import (CAMPAIGN_ID, CAMPAIGN_KWARGS, FAKE_TIME, IDENTITY_ID, @pytest.fixture def ds(): - cam = stix2.Campaign(id=CAMPAIGN_ID, **CAMPAIGN_KWARGS) - idy = stix2.Identity(id=IDENTITY_ID, **IDENTITY_KWARGS) - ind = stix2.Indicator(id=INDICATOR_ID, **INDICATOR_KWARGS) - mal = stix2.Malware(id=MALWARE_ID, **MALWARE_KWARGS) - rel1 = stix2.Relationship(ind, 'indicates', mal, id=RELATIONSHIP_IDS[0]) - rel2 = stix2.Relationship(mal, 'targets', idy, id=RELATIONSHIP_IDS[1]) - rel3 = stix2.Relationship(cam, 'uses', mal, id=RELATIONSHIP_IDS[2]) + cam = stix2.v20.Campaign(id=CAMPAIGN_ID, **CAMPAIGN_KWARGS) + idy = stix2.v20.Identity(id=IDENTITY_ID, **IDENTITY_KWARGS) + ind = stix2.v20.Indicator(id=INDICATOR_ID, **INDICATOR_KWARGS) + mal = stix2.v20.Malware(id=MALWARE_ID, **MALWARE_KWARGS) + rel1 = stix2.v20.Relationship(ind, 'indicates', mal, id=RELATIONSHIP_IDS[0]) + rel2 = stix2.v20.Relationship(mal, 'targets', idy, id=RELATIONSHIP_IDS[1]) + rel3 = stix2.v20.Relationship(cam, 'uses', mal, id=RELATIONSHIP_IDS[2]) stix_objs = [cam, idy, ind, mal, rel1, rel2, rel3] yield stix2.MemoryStore(stix_objs) def test_object_factory_created_by_ref_str(): factory = stix2.ObjectFactory(created_by_ref=IDENTITY_ID) - ind = factory.create(stix2.Indicator, **INDICATOR_KWARGS) + ind = factory.create(stix2.v20.Indicator, **INDICATOR_KWARGS) assert ind.created_by_ref == IDENTITY_ID def test_object_factory_created_by_ref_obj(): - id_obj = stix2.Identity(id=IDENTITY_ID, **IDENTITY_KWARGS) + id_obj = stix2.v20.Identity(id=IDENTITY_ID, **IDENTITY_KWARGS) factory = stix2.ObjectFactory(created_by_ref=id_obj) - ind = factory.create(stix2.Indicator, **INDICATOR_KWARGS) + ind = factory.create(stix2.v20.Indicator, **INDICATOR_KWARGS) assert ind.created_by_ref == IDENTITY_ID def test_object_factory_override_default(): factory = stix2.ObjectFactory(created_by_ref=IDENTITY_ID) new_id = "identity--983b3172-44fe-4a80-8091-eb8098841fe8" - ind = factory.create(stix2.Indicator, created_by_ref=new_id, **INDICATOR_KWARGS) + ind = factory.create(stix2.v20.Indicator, created_by_ref=new_id, **INDICATOR_KWARGS) assert ind.created_by_ref == new_id def test_object_factory_created(): factory = stix2.ObjectFactory(created=FAKE_TIME) - ind = factory.create(stix2.Indicator, **INDICATOR_KWARGS) + ind = factory.create(stix2.v20.Indicator, **INDICATOR_KWARGS) assert ind.created == FAKE_TIME assert ind.modified == FAKE_TIME def test_object_factory_external_reference(): - ext_ref = stix2.ExternalReference(source_name="ACME Threat Intel", - description="Threat report") + ext_ref = stix2.v20.ExternalReference( + source_name="ACME Threat Intel", + description="Threat report") factory = stix2.ObjectFactory(external_references=ext_ref) - ind = factory.create(stix2.Indicator, **INDICATOR_KWARGS) + ind = factory.create(stix2.v20.Indicator, **INDICATOR_KWARGS) assert ind.external_references[0].source_name == "ACME Threat Intel" assert ind.external_references[0].description == "Threat report" - ind2 = factory.create(stix2.Indicator, external_references=None, **INDICATOR_KWARGS) + ind2 = factory.create(stix2.v20.Indicator, external_references=None, **INDICATOR_KWARGS) assert 'external_references' not in ind2 def test_object_factory_obj_markings(): - stmt_marking = stix2.StatementMarking("Copyright 2016, Example Corp") - mark_def = stix2.MarkingDefinition(definition_type="statement", - definition=stmt_marking) - factory = stix2.ObjectFactory(object_marking_refs=[mark_def, stix2.TLP_AMBER]) - ind = factory.create(stix2.Indicator, **INDICATOR_KWARGS) + stmt_marking = stix2.v20.StatementMarking("Copyright 2016, Example Corp") + mark_def = stix2.v20.MarkingDefinition( + definition_type="statement", + definition=stmt_marking) + factory = stix2.ObjectFactory(object_marking_refs=[mark_def, stix2.v20.TLP_AMBER]) + ind = factory.create(stix2.v20.Indicator, **INDICATOR_KWARGS) assert mark_def.id in ind.object_marking_refs - assert stix2.TLP_AMBER.id in ind.object_marking_refs + assert stix2.v20.TLP_AMBER.id in ind.object_marking_refs - factory = stix2.ObjectFactory(object_marking_refs=stix2.TLP_RED) - ind = factory.create(stix2.Indicator, **INDICATOR_KWARGS) - assert stix2.TLP_RED.id in ind.object_marking_refs + factory = stix2.ObjectFactory(object_marking_refs=stix2.v20.TLP_RED) + ind = factory.create(stix2.v20.Indicator, **INDICATOR_KWARGS) + assert stix2.v20.TLP_RED.id in ind.object_marking_refs def test_object_factory_list_append(): - ext_ref = stix2.ExternalReference(source_name="ACME Threat Intel", - description="Threat report from ACME") - ext_ref2 = stix2.ExternalReference(source_name="Yet Another Threat Report", - description="Threat report from YATR") - ext_ref3 = stix2.ExternalReference(source_name="Threat Report #3", - description="One more threat report") + ext_ref = stix2.v20.ExternalReference( + source_name="ACME Threat Intel", + description="Threat report from ACME") + ext_ref2 = stix2.v20.ExternalReference( + source_name="Yet Another Threat Report", + description="Threat report from YATR") + ext_ref3 = stix2.v20.ExternalReference( + source_name="Threat Report #3", + description="One more threat report") factory = stix2.ObjectFactory(external_references=ext_ref) - ind = factory.create(stix2.Indicator, external_references=ext_ref2, **INDICATOR_KWARGS) + ind = factory.create(stix2.v20.Indicator, external_references=ext_ref2, **INDICATOR_KWARGS) assert ind.external_references[1].source_name == "Yet Another Threat Report" - ind = factory.create(stix2.Indicator, external_references=[ext_ref2, ext_ref3], **INDICATOR_KWARGS) + ind = factory.create(stix2.v20.Indicator, external_references=[ext_ref2, ext_ref3], **INDICATOR_KWARGS) assert ind.external_references[2].source_name == "Threat Report #3" def test_object_factory_list_replace(): - ext_ref = stix2.ExternalReference(source_name="ACME Threat Intel", - description="Threat report from ACME") - ext_ref2 = stix2.ExternalReference(source_name="Yet Another Threat Report", - description="Threat report from YATR") + ext_ref = stix2.v20.ExternalReference( + source_name="ACME Threat Intel", + description="Threat report from ACME") + ext_ref2 = stix2.v20.ExternalReference( + source_name="Yet Another Threat Report", + description="Threat report from YATR") factory = stix2.ObjectFactory(external_references=ext_ref, list_append=False) - ind = factory.create(stix2.Indicator, external_references=ext_ref2, **INDICATOR_KWARGS) + ind = factory.create(stix2.v20.Indicator, external_references=ext_ref2, **INDICATOR_KWARGS) assert len(ind.external_references) == 1 assert ind.external_references[0].source_name == "Yet Another Threat Report" @@ -104,7 +111,7 @@ def test_environment_functions(): stix2.MemoryStore()) # Create a STIX object - ind = env.create(stix2.Indicator, id=INDICATOR_ID, **INDICATOR_KWARGS) + ind = env.create(stix2.v20.Indicator, id=INDICATOR_ID, **INDICATOR_KWARGS) assert ind.created_by_ref == IDENTITY_ID # Add objects to datastore @@ -133,7 +140,7 @@ def test_environment_functions(): def test_environment_source_and_sink(): - ind = stix2.Indicator(id=INDICATOR_ID, **INDICATOR_KWARGS) + ind = stix2.v20.Indicator(id=INDICATOR_ID, **INDICATOR_KWARGS) env = stix2.Environment(source=stix2.MemorySource([ind]), sink=stix2.MemorySink([ind])) assert env.get(INDICATOR_ID).labels[0] == 'malicious-activity' @@ -149,7 +156,7 @@ def test_environment_no_datastore(): env = stix2.Environment(factory=stix2.ObjectFactory()) with pytest.raises(AttributeError) as excinfo: - env.add(stix2.Indicator(**INDICATOR_KWARGS)) + env.add(stix2.v20.Indicator(**INDICATOR_KWARGS)) assert 'Environment has no data sink to put objects in' in str(excinfo.value) with pytest.raises(AttributeError) as excinfo: @@ -182,7 +189,7 @@ def test_environment_add_filters(): def test_environment_datastore_and_no_object_factory(): # Uses a default object factory env = stix2.Environment(store=stix2.MemoryStore()) - ind = env.create(stix2.Indicator, id=INDICATOR_ID, **INDICATOR_KWARGS) + ind = env.create(stix2.v20.Indicator, id=INDICATOR_ID, **INDICATOR_KWARGS) assert ind.id == INDICATOR_ID @@ -190,17 +197,15 @@ def test_parse_malware(): env = stix2.Environment() data = """{ "type": "malware", - "spec_version": "2.1", "id": "malware--fedcba98-7654-3210-fedc-ba9876543210", "created": "2017-01-01T12:34:56.000Z", "modified": "2017-01-01T12:34:56.000Z", "name": "Cryptolocker", "labels": [ "ransomware" - ], - "is_family": false + ] }""" - mal = env.parse(data) + mal = env.parse(data, version="2.0") assert mal.type == 'malware' assert mal.id == MALWARE_ID @@ -211,40 +216,40 @@ def test_parse_malware(): def test_creator_of(): - identity = stix2.Identity(**IDENTITY_KWARGS) + identity = stix2.v20.Identity(**IDENTITY_KWARGS) factory = stix2.ObjectFactory(created_by_ref=identity.id) env = stix2.Environment(store=stix2.MemoryStore(), factory=factory) env.add(identity) - ind = env.create(stix2.Indicator, **INDICATOR_KWARGS) + ind = env.create(stix2.v20.Indicator, **INDICATOR_KWARGS) creator = env.creator_of(ind) assert creator is identity def test_creator_of_no_datasource(): - identity = stix2.Identity(**IDENTITY_KWARGS) + identity = stix2.v20.Identity(**IDENTITY_KWARGS) factory = stix2.ObjectFactory(created_by_ref=identity.id) env = stix2.Environment(factory=factory) - ind = env.create(stix2.Indicator, **INDICATOR_KWARGS) + ind = env.create(stix2.v20.Indicator, **INDICATOR_KWARGS) with pytest.raises(AttributeError) as excinfo: env.creator_of(ind) assert 'Environment has no data source' in str(excinfo.value) def test_creator_of_not_found(): - identity = stix2.Identity(**IDENTITY_KWARGS) + identity = stix2.v20.Identity(**IDENTITY_KWARGS) factory = stix2.ObjectFactory(created_by_ref=identity.id) env = stix2.Environment(store=stix2.MemoryStore(), factory=factory) - ind = env.create(stix2.Indicator, **INDICATOR_KWARGS) + ind = env.create(stix2.v20.Indicator, **INDICATOR_KWARGS) creator = env.creator_of(ind) assert creator is None def test_creator_of_no_created_by_ref(): env = stix2.Environment(store=stix2.MemoryStore()) - ind = env.create(stix2.Indicator, **INDICATOR_KWARGS) + ind = env.create(stix2.v20.Indicator, **INDICATOR_KWARGS) creator = env.creator_of(ind) assert creator is None diff --git a/stix2/test/v20/test_external_reference.py b/stix2/test/v20/test_external_reference.py index 9b90998..e7226cb 100644 --- a/stix2/test/v20/test_external_reference.py +++ b/stix2/test/v20/test_external_reference.py @@ -17,7 +17,7 @@ VERIS = """{ def test_external_reference_veris(): - ref = stix2.ExternalReference( + ref = stix2.v20.ExternalReference( source_name="veris", external_id="0001AA7F-C601-424A-B2B8-BE6C9F5164E7", hashes={ @@ -36,7 +36,7 @@ CAPEC = """{ def test_external_reference_capec(): - ref = stix2.ExternalReference( + ref = stix2.v20.ExternalReference( source_name="capec", external_id="CAPEC-550", ) @@ -53,7 +53,7 @@ CAPEC_URL = """{ def test_external_reference_capec_url(): - ref = stix2.ExternalReference( + ref = stix2.v20.ExternalReference( source_name="capec", external_id="CAPEC-550", url="http://capec.mitre.org/data/definitions/550.html", @@ -70,7 +70,7 @@ THREAT_REPORT = """{ def test_external_reference_threat_report(): - ref = stix2.ExternalReference( + ref = stix2.v20.ExternalReference( source_name="ACME Threat Intel", description="Threat report", url="http://www.example.com/threat-report.pdf", @@ -87,7 +87,7 @@ BUGZILLA = """{ def test_external_reference_bugzilla(): - ref = stix2.ExternalReference( + ref = stix2.v20.ExternalReference( source_name="ACME Bugzilla", external_id="1370", url="https://www.example.com/bugs/1370", @@ -103,7 +103,7 @@ OFFLINE = """{ def test_external_reference_offline(): - ref = stix2.ExternalReference( + ref = stix2.v20.ExternalReference( source_name="ACME Threat Intel", description="Threat report", ) @@ -116,7 +116,7 @@ def test_external_reference_offline(): def test_external_reference_source_required(): with pytest.raises(stix2.exceptions.MissingPropertiesError) as excinfo: - stix2.ExternalReference() + stix2.v20.ExternalReference() - assert excinfo.value.cls == stix2.ExternalReference + assert excinfo.value.cls == stix2.v20.ExternalReference assert excinfo.value.properties == ["source_name"] diff --git a/stix2/test/v20/test_granular_markings.py b/stix2/test/v20/test_granular_markings.py index 9e024a1..b36bf65 100644 --- a/stix2/test/v20/test_granular_markings.py +++ b/stix2/test/v20/test_granular_markings.py @@ -1,7 +1,8 @@ import pytest -from stix2 import TLP_RED, Malware, markings +from stix2 import markings +from stix2.v20 import Malware, TLP_RED from stix2.exceptions import MarkingNotFoundError from .constants import MALWARE_MORE_KWARGS as MALWARE_KWARGS_CONST diff --git a/stix2/test/v20/test_identity.py b/stix2/test/v20/test_identity.py index ff3631f..e84138b 100644 --- a/stix2/test/v20/test_identity.py +++ b/stix2/test/v20/test_identity.py @@ -18,7 +18,7 @@ EXPECTED = """{ def test_identity_example(): - identity = stix2.Identity( + identity = stix2.v20.Identity( id="identity--311b2d2d-f010-5473-83ec-1edf84858f4c", created="2015-12-21T19:59:11.000Z", modified="2015-12-21T19:59:11.000Z", @@ -41,7 +41,7 @@ def test_identity_example(): }, ]) def test_parse_identity(data): - identity = stix2.parse(data) + identity = stix2.parse(data, version="2.0") assert identity.type == 'identity' assert identity.id == IDENTITY_ID @@ -59,11 +59,11 @@ def test_parse_no_type(): "modified": "2015-12-21T19:59:11.000Z", "name": "John Smith", "identity_class": "individual" - }""") + }""", version="2.0") def test_identity_with_custom(): - identity = stix2.Identity( + identity = stix2.v20.Identity( name="John Smith", identity_class="individual", custom_properties={'x_foo': 'bar'} diff --git a/stix2/test/v20/test_indicator.py b/stix2/test/v20/test_indicator.py index c9b6e56..5249d2c 100644 --- a/stix2/test/v20/test_indicator.py +++ b/stix2/test/v20/test_indicator.py @@ -35,7 +35,7 @@ def test_indicator_with_all_required_properties(): now = dt.datetime(2017, 1, 1, 0, 0, 1, tzinfo=pytz.utc) epoch = dt.datetime(1970, 1, 1, 0, 0, 1, tzinfo=pytz.utc) - ind = stix2.Indicator( + ind = stix2.v20.Indicator( type="indicator", id=INDICATOR_ID, created=now, @@ -71,9 +71,9 @@ def test_indicator_autogenerated_properties(indicator): def test_indicator_type_must_be_indicator(): with pytest.raises(stix2.exceptions.InvalidValueError) as excinfo: - stix2.Indicator(type='xxx', **INDICATOR_KWARGS) + stix2.v20.Indicator(type='xxx', **INDICATOR_KWARGS) - assert excinfo.value.cls == stix2.Indicator + assert excinfo.value.cls == stix2.v20.Indicator assert excinfo.value.prop_name == "type" assert excinfo.value.reason == "must equal 'indicator'." assert str(excinfo.value) == "Invalid value for Indicator 'type': must equal 'indicator'." @@ -81,9 +81,9 @@ def test_indicator_type_must_be_indicator(): def test_indicator_id_must_start_with_indicator(): with pytest.raises(stix2.exceptions.InvalidValueError) as excinfo: - stix2.Indicator(id='my-prefix--', **INDICATOR_KWARGS) + stix2.v20.Indicator(id='my-prefix--', **INDICATOR_KWARGS) - assert excinfo.value.cls == stix2.Indicator + assert excinfo.value.cls == stix2.v20.Indicator assert excinfo.value.prop_name == "id" assert excinfo.value.reason == "must start with 'indicator--'." assert str(excinfo.value) == "Invalid value for Indicator 'id': must start with 'indicator--'." @@ -91,26 +91,26 @@ def test_indicator_id_must_start_with_indicator(): def test_indicator_required_properties(): with pytest.raises(stix2.exceptions.MissingPropertiesError) as excinfo: - stix2.Indicator() + stix2.v20.Indicator() - assert excinfo.value.cls == stix2.Indicator + assert excinfo.value.cls == stix2.v20.Indicator assert excinfo.value.properties == ["labels", "pattern"] assert str(excinfo.value) == "No values for required properties for Indicator: (labels, pattern)." def test_indicator_required_property_pattern(): with pytest.raises(stix2.exceptions.MissingPropertiesError) as excinfo: - stix2.Indicator(labels=['malicious-activity']) + stix2.v20.Indicator(labels=['malicious-activity']) - assert excinfo.value.cls == stix2.Indicator + assert excinfo.value.cls == stix2.v20.Indicator assert excinfo.value.properties == ["pattern"] def test_indicator_created_ref_invalid_format(): with pytest.raises(stix2.exceptions.InvalidValueError) as excinfo: - stix2.Indicator(created_by_ref='myprefix--12345678', **INDICATOR_KWARGS) + stix2.v20.Indicator(created_by_ref='myprefix--12345678', **INDICATOR_KWARGS) - assert excinfo.value.cls == stix2.Indicator + assert excinfo.value.cls == stix2.v20.Indicator assert excinfo.value.prop_name == "created_by_ref" assert excinfo.value.reason == "must start with 'identity'." assert str(excinfo.value) == "Invalid value for Indicator 'created_by_ref': must start with 'identity'." @@ -118,9 +118,9 @@ def test_indicator_created_ref_invalid_format(): def test_indicator_revoked_invalid(): with pytest.raises(stix2.exceptions.InvalidValueError) as excinfo: - stix2.Indicator(revoked='no', **INDICATOR_KWARGS) + stix2.v20.Indicator(revoked='no', **INDICATOR_KWARGS) - assert excinfo.value.cls == stix2.Indicator + assert excinfo.value.cls == stix2.v20.Indicator assert excinfo.value.prop_name == "revoked" assert excinfo.value.reason == "must be a boolean value." @@ -134,16 +134,16 @@ def test_cannot_assign_to_indicator_attributes(indicator): def test_invalid_kwarg_to_indicator(): with pytest.raises(stix2.exceptions.ExtraPropertiesError) as excinfo: - stix2.Indicator(my_custom_property="foo", **INDICATOR_KWARGS) + stix2.v20.Indicator(my_custom_property="foo", **INDICATOR_KWARGS) - assert excinfo.value.cls == stix2.Indicator + assert excinfo.value.cls == stix2.v20.Indicator assert excinfo.value.properties == ['my_custom_property'] assert str(excinfo.value) == "Unexpected properties for Indicator: (my_custom_property)." def test_created_modified_time_are_identical_by_default(): """By default, the created and modified times should be the same.""" - ind = stix2.Indicator(**INDICATOR_KWARGS) + ind = stix2.v20.Indicator(**INDICATOR_KWARGS) assert ind.created == ind.modified @@ -163,7 +163,7 @@ def test_created_modified_time_are_identical_by_default(): }, ]) def test_parse_indicator(data): - idctr = stix2.parse(data) + idctr = stix2.parse(data, version="2.0") assert idctr.type == 'indicator' assert idctr.id == INDICATOR_ID @@ -176,19 +176,19 @@ def test_parse_indicator(data): def test_invalid_indicator_pattern(): with pytest.raises(stix2.exceptions.InvalidValueError) as excinfo: - stix2.Indicator( + stix2.v20.Indicator( labels=['malicious-activity'], pattern="file:hashes.MD5 = 'd41d8cd98f00b204e9800998ecf8427e'", ) - assert excinfo.value.cls == stix2.Indicator + assert excinfo.value.cls == stix2.v20.Indicator assert excinfo.value.prop_name == 'pattern' assert 'input is missing square brackets' in excinfo.value.reason with pytest.raises(stix2.exceptions.InvalidValueError) as excinfo: - stix2.Indicator( + stix2.v20.Indicator( labels=['malicious-activity'], pattern='[file:hashes.MD5 = "d41d8cd98f00b204e9800998ecf8427e"]', ) - assert excinfo.value.cls == stix2.Indicator + assert excinfo.value.cls == stix2.v20.Indicator assert excinfo.value.prop_name == 'pattern' assert 'mismatched input' in excinfo.value.reason diff --git a/stix2/test/v20/test_intrusion_set.py b/stix2/test/v20/test_intrusion_set.py index 53e18f5..1d58403 100644 --- a/stix2/test/v20/test_intrusion_set.py +++ b/stix2/test/v20/test_intrusion_set.py @@ -27,7 +27,7 @@ EXPECTED = """{ def test_intrusion_set_example(): - intrusion_set = stix2.IntrusionSet( + intrusion_set = stix2.v20.IntrusionSet( id="intrusion-set--4e78f46f-a023-4e5f-bc24-71b3ca22ec29", created_by_ref="identity--f431f809-377b-45e0-aa1c-6a4751cae5ff", created="2016-04-06T20:03:48.000Z", @@ -62,7 +62,7 @@ def test_intrusion_set_example(): }, ]) def test_parse_intrusion_set(data): - intset = stix2.parse(data) + intset = stix2.parse(data, version="2.0") assert intset.type == "intrusion-set" assert intset.id == INTRUSION_SET_ID diff --git a/stix2/test/v20/test_kill_chain_phases.py b/stix2/test/v20/test_kill_chain_phases.py index 220c714..d150757 100644 --- a/stix2/test/v20/test_kill_chain_phases.py +++ b/stix2/test/v20/test_kill_chain_phases.py @@ -11,7 +11,7 @@ LMCO_RECON = """{ def test_lockheed_martin_cyber_kill_chain(): - recon = stix2.KillChainPhase( + recon = stix2.v20.KillChainPhase( kill_chain_name="lockheed-martin-cyber-kill-chain", phase_name="reconnaissance", ) @@ -26,7 +26,7 @@ FOO_PRE_ATTACK = """{ def test_kill_chain_example(): - preattack = stix2.KillChainPhase( + preattack = stix2.v20.KillChainPhase( kill_chain_name="foo", phase_name="pre-attack", ) @@ -37,25 +37,25 @@ def test_kill_chain_example(): def test_kill_chain_required_properties(): with pytest.raises(stix2.exceptions.MissingPropertiesError) as excinfo: - stix2.KillChainPhase() + stix2.v20.KillChainPhase() - assert excinfo.value.cls == stix2.KillChainPhase + assert excinfo.value.cls == stix2.v20.KillChainPhase assert excinfo.value.properties == ["kill_chain_name", "phase_name"] def test_kill_chain_required_property_chain_name(): with pytest.raises(stix2.exceptions.MissingPropertiesError) as excinfo: - stix2.KillChainPhase(phase_name="weaponization") + stix2.v20.KillChainPhase(phase_name="weaponization") - assert excinfo.value.cls == stix2.KillChainPhase + assert excinfo.value.cls == stix2.v20.KillChainPhase assert excinfo.value.properties == ["kill_chain_name"] def test_kill_chain_required_property_phase_name(): with pytest.raises(stix2.exceptions.MissingPropertiesError) as excinfo: - stix2.KillChainPhase(kill_chain_name="lockheed-martin-cyber-kill-chain") + stix2.v20.KillChainPhase(kill_chain_name="lockheed-martin-cyber-kill-chain") - assert excinfo.value.cls == stix2.KillChainPhase + assert excinfo.value.cls == stix2.v20.KillChainPhase assert excinfo.value.properties == ["phase_name"] diff --git a/stix2/test/v20/test_malware.py b/stix2/test/v20/test_malware.py index cf14c19..de0f488 100644 --- a/stix2/test/v20/test_malware.py +++ b/stix2/test/v20/test_malware.py @@ -10,29 +10,26 @@ from .constants import FAKE_TIME, MALWARE_ID, MALWARE_KWARGS EXPECTED_MALWARE = """{ "type": "malware", - "spec_version": "2.1", "id": "malware--fedcba98-7654-3210-fedc-ba9876543210", "created": "2016-05-12T08:17:27.000Z", "modified": "2016-05-12T08:17:27.000Z", "name": "Cryptolocker", "labels": [ "ransomware" - ], - "is_family": false + ] }""" def test_malware_with_all_required_properties(): now = dt.datetime(2016, 5, 12, 8, 17, 27, tzinfo=pytz.utc) - mal = stix2.Malware( + mal = stix2.v20.Malware( type="malware", id=MALWARE_ID, created=now, modified=now, labels=["ransomware"], - name="Cryptolocker", - is_family=False + name="Cryptolocker" ) assert str(mal) == EXPECTED_MALWARE @@ -56,9 +53,9 @@ def test_malware_autogenerated_properties(malware): def test_malware_type_must_be_malware(): with pytest.raises(stix2.exceptions.InvalidValueError) as excinfo: - stix2.Malware(type='xxx', **MALWARE_KWARGS) + stix2.v20.Malware(type='xxx', **MALWARE_KWARGS) - assert excinfo.value.cls == stix2.Malware + assert excinfo.value.cls == stix2.v20.Malware assert excinfo.value.prop_name == "type" assert excinfo.value.reason == "must equal 'malware'." assert str(excinfo.value) == "Invalid value for Malware 'type': must equal 'malware'." @@ -66,9 +63,9 @@ def test_malware_type_must_be_malware(): def test_malware_id_must_start_with_malware(): with pytest.raises(stix2.exceptions.InvalidValueError) as excinfo: - stix2.Malware(id='my-prefix--', **MALWARE_KWARGS) + stix2.v20.Malware(id='my-prefix--', **MALWARE_KWARGS) - assert excinfo.value.cls == stix2.Malware + assert excinfo.value.cls == stix2.v20.Malware assert excinfo.value.prop_name == "id" assert excinfo.value.reason == "must start with 'malware--'." assert str(excinfo.value) == "Invalid value for Malware 'id': must start with 'malware--'." @@ -76,17 +73,17 @@ def test_malware_id_must_start_with_malware(): def test_malware_required_properties(): with pytest.raises(stix2.exceptions.MissingPropertiesError) as excinfo: - stix2.Malware() + stix2.v20.Malware() - assert excinfo.value.cls == stix2.Malware - assert excinfo.value.properties == ["is_family", "labels", "name"] + assert excinfo.value.cls == stix2.v20.Malware + assert excinfo.value.properties == ["labels", "name"] def test_malware_required_property_name(): with pytest.raises(stix2.exceptions.MissingPropertiesError) as excinfo: - stix2.Malware(labels=['ransomware'], is_family=False) + stix2.v20.Malware(labels=['ransomware']) - assert excinfo.value.cls == stix2.Malware + assert excinfo.value.cls == stix2.v20.Malware assert excinfo.value.properties == ["name"] @@ -99,9 +96,9 @@ def test_cannot_assign_to_malware_attributes(malware): def test_invalid_kwarg_to_malware(): with pytest.raises(stix2.exceptions.ExtraPropertiesError) as excinfo: - stix2.Malware(my_custom_property="foo", **MALWARE_KWARGS) + stix2.v20.Malware(my_custom_property="foo", **MALWARE_KWARGS) - assert excinfo.value.cls == stix2.Malware + assert excinfo.value.cls == stix2.v20.Malware assert excinfo.value.properties == ['my_custom_property'] assert str(excinfo.value) == "Unexpected properties for Malware: (my_custom_property)." @@ -110,17 +107,15 @@ def test_invalid_kwarg_to_malware(): EXPECTED_MALWARE, { "type": "malware", - "spec_version": "2.1", "id": "malware--fedcba98-7654-3210-fedc-ba9876543210", "created": "2016-05-12T08:17:27.000Z", "modified": "2016-05-12T08:17:27.000Z", "labels": ["ransomware"], - "name": "Cryptolocker", - "is_family": False + "name": "Cryptolocker" }, ]) def test_parse_malware(data): - mal = stix2.parse(data) + mal = stix2.parse(data, version="2.0") assert mal.type == 'malware' assert mal.id == MALWARE_ID @@ -133,7 +128,7 @@ def test_parse_malware(data): def test_parse_malware_invalid_labels(): data = re.compile('\\[.+\\]', re.DOTALL).sub('1', EXPECTED_MALWARE) with pytest.raises(ValueError) as excinfo: - stix2.parse(data) + stix2.parse(data, version="2.0") assert "Invalid value for Malware 'labels'" in str(excinfo.value) @@ -146,7 +141,7 @@ def test_parse_malware_kill_chain_phases(): } ]""" data = EXPECTED_MALWARE.replace('malware"', 'malware",%s' % kill_chain) - mal = stix2.parse(data) + mal = stix2.parse(data, version="2.0") assert mal.kill_chain_phases[0].kill_chain_name == "lockheed-martin-cyber-kill-chain" assert mal.kill_chain_phases[0].phase_name == "reconnaissance" assert mal['kill_chain_phases'][0]['kill_chain_name'] == "lockheed-martin-cyber-kill-chain" @@ -161,6 +156,6 @@ def test_parse_malware_clean_kill_chain_phases(): "phase_name": 1 } ]""" - data = EXPECTED_MALWARE.replace('2.1"', '2.1",%s' % kill_chain) - mal = stix2.parse(data) + data = EXPECTED_MALWARE.replace('malware"', 'malware",%s' % kill_chain) + mal = stix2.parse(data, version="2.0") assert mal['kill_chain_phases'][0]['phase_name'] == "1" diff --git a/stix2/test/v20/test_markings.py b/stix2/test/v20/test_markings.py index efd0476..7f22074 100644 --- a/stix2/test/v20/test_markings.py +++ b/stix2/test/v20/test_markings.py @@ -4,7 +4,7 @@ import pytest import pytz import stix2 -from stix2 import TLP_WHITE +from stix2.v20 import TLP_WHITE from .constants import MARKING_DEFINITION_ID @@ -75,11 +75,11 @@ def test_marking_def_example_with_tlp(): def test_marking_def_example_with_statement_positional_argument(): - marking_definition = stix2.MarkingDefinition( + marking_definition = stix2.v20.MarkingDefinition( id="marking-definition--613f2e26-407d-48c7-9eca-b8e91df99dc9", created="2017-01-20T00:00:00.000Z", definition_type="statement", - definition=stix2.StatementMarking(statement="Copyright 2016, Example Corp") + definition=stix2.v20.StatementMarking(statement="Copyright 2016, Example Corp") ) assert str(marking_definition) == EXPECTED_STATEMENT_MARKING_DEFINITION @@ -87,11 +87,11 @@ def test_marking_def_example_with_statement_positional_argument(): def test_marking_def_example_with_kwargs_statement(): kwargs = dict(statement="Copyright 2016, Example Corp") - marking_definition = stix2.MarkingDefinition( + marking_definition = stix2.v20.MarkingDefinition( id="marking-definition--613f2e26-407d-48c7-9eca-b8e91df99dc9", created="2017-01-20T00:00:00.000Z", definition_type="statement", - definition=stix2.StatementMarking(**kwargs) + definition=stix2.v20.StatementMarking(**kwargs) ) assert str(marking_definition) == EXPECTED_STATEMENT_MARKING_DEFINITION @@ -99,16 +99,16 @@ def test_marking_def_example_with_kwargs_statement(): def test_marking_def_invalid_type(): with pytest.raises(ValueError): - stix2.MarkingDefinition( + stix2.v20.MarkingDefinition( id="marking-definition--613f2e26-407d-48c7-9eca-b8e91df99dc9", created="2017-01-20T00:00:00.000Z", definition_type="my-definition-type", - definition=stix2.StatementMarking("Copyright 2016, Example Corp") + definition=stix2.v20.StatementMarking("Copyright 2016, Example Corp") ) def test_campaign_with_markings_example(): - campaign = stix2.Campaign( + campaign = stix2.v20.Campaign( id="campaign--8e2e2d2b-17d4-4cbf-938f-98ee46b3cd3f", created_by_ref="identity--f431f809-377b-45e0-aa1c-6a4751cae5ff", created="2016-04-06T20:03:00Z", @@ -121,7 +121,7 @@ def test_campaign_with_markings_example(): def test_granular_example(): - granular_marking = stix2.GranularMarking( + granular_marking = stix2.v20.GranularMarking( marking_ref="marking-definition--613f2e26-407d-48c7-9eca-b8e91df99dc9", selectors=["abc", "abc.[23]", "abc.def", "abc.[2].efg"] ) @@ -131,19 +131,19 @@ def test_granular_example(): def test_granular_example_with_bad_selector(): with pytest.raises(stix2.exceptions.InvalidValueError) as excinfo: - stix2.GranularMarking( + stix2.v20.GranularMarking( marking_ref="marking-definition--613f2e26-407d-48c7-9eca-b8e91df99dc9", selectors=["abc[0]"] # missing "." ) - assert excinfo.value.cls == stix2.GranularMarking + assert excinfo.value.cls == stix2.v20.GranularMarking assert excinfo.value.prop_name == "selectors" assert excinfo.value.reason == "must adhere to selector syntax." assert str(excinfo.value) == "Invalid value for GranularMarking 'selectors': must adhere to selector syntax." def test_campaign_with_granular_markings_example(): - campaign = stix2.Campaign( + campaign = stix2.v20.Campaign( id="campaign--8e2e2d2b-17d4-4cbf-938f-98ee46b3cd3f", created_by_ref="identity--f431f809-377b-45e0-aa1c-6a4751cae5ff", created="2016-04-06T20:03:00Z", @@ -151,7 +151,7 @@ def test_campaign_with_granular_markings_example(): name="Green Group Attacks Against Finance", description="Campaign by Green Group against a series of targets in the financial services sector.", granular_markings=[ - stix2.GranularMarking( + stix2.v20.GranularMarking( marking_ref="marking-definition--613f2e26-407d-48c7-9eca-b8e91df99dc9", selectors=["description"]) ]) @@ -171,7 +171,7 @@ def test_campaign_with_granular_markings_example(): }, ]) def test_parse_marking_definition(data): - gm = stix2.parse(data) + gm = stix2.parse(data, version="2.0") assert gm.type == 'marking-definition' assert gm.id == MARKING_DEFINITION_ID @@ -180,9 +180,9 @@ def test_parse_marking_definition(data): assert gm.definition_type == "tlp" -@stix2.common.CustomMarking('x-new-marking-type', [ - ('property1', stix2.properties.StringProperty(required=True)), - ('property2', stix2.properties.IntegerProperty()), +@stix2.v20.CustomMarking('x-new-marking-type', [ + ('property1', stix2.v20.properties.StringProperty(required=True)), + ('property2', stix2.v20.properties.IntegerProperty()), ]) class NewMarking(object): def __init__(self, property2=None, **kwargs): @@ -193,7 +193,7 @@ class NewMarking(object): def test_registered_custom_marking(): nm = NewMarking(property1='something', property2=55) - marking_def = stix2.MarkingDefinition( + marking_def = stix2.v20.MarkingDefinition( id="marking-definition--00000000-0000-0000-0000-000000000012", created="2017-01-22T00:00:00.000Z", definition_type="x-new-marking-type", @@ -218,9 +218,9 @@ def test_registered_custom_marking_raises_exception(): def test_not_registered_marking_raises_exception(): with pytest.raises(ValueError) as excinfo: # Used custom object on purpose to demonstrate a not-registered marking - @stix2.sdo.CustomObject('x-new-marking-type2', [ - ('property1', stix2.properties.StringProperty(required=True)), - ('property2', stix2.properties.IntegerProperty()), + @stix2.v20.CustomObject('x-new-marking-type2', [ + ('property1', stix2.v20.properties.StringProperty(required=True)), + ('property2', stix2.v20.properties.IntegerProperty()), ]) class NewObject2(object): def __init__(self, property2=None, **kwargs): @@ -228,7 +228,7 @@ def test_not_registered_marking_raises_exception(): no = NewObject2(property1='something', property2=55) - stix2.MarkingDefinition( + stix2.v20.MarkingDefinition( id="marking-definition--00000000-0000-0000-0000-000000000012", created="2017-01-22T00:00:00.000Z", definition_type="x-new-marking-type2", @@ -241,7 +241,7 @@ def test_not_registered_marking_raises_exception(): def test_marking_wrong_type_construction(): with pytest.raises(ValueError) as excinfo: # Test passing wrong type for properties. - @stix2.CustomMarking('x-new-marking-type2', ("a", "b")) + @stix2.v20.CustomMarking('x-new-marking-type2', ("a", "b")) class NewObject3(object): pass @@ -249,7 +249,7 @@ def test_marking_wrong_type_construction(): def test_campaign_add_markings(): - campaign = stix2.Campaign( + campaign = stix2.v20.Campaign( id="campaign--8e2e2d2b-17d4-4cbf-938f-98ee46b3cd3f", created_by_ref="identity--f431f809-377b-45e0-aa1c-6a4751cae5ff", created="2016-04-06T20:03:00Z", diff --git a/stix2/test/v20/test_memory.py b/stix2/test/v20/test_memory.py index 284c43e..c768eac 100644 --- a/stix2/test/v20/test_memory.py +++ b/stix2/test/v20/test_memory.py @@ -3,9 +3,9 @@ import shutil import pytest -from stix2 import (Bundle, Campaign, CustomObject, Filter, Identity, Indicator, - Malware, MemorySource, MemoryStore, Relationship, - properties) +from stix2 import (Filter, MemorySource, MemoryStore, properties) +from stix2.v20 import (Bundle, Campaign, CustomObject, Identity, Indicator, + Malware, Relationship) from stix2.datastore import make_id from .constants import (CAMPAIGN_ID, CAMPAIGN_KWARGS, IDENTITY_ID, diff --git a/stix2/test/v20/test_object_markings.py b/stix2/test/v20/test_object_markings.py index f216355..10741be 100644 --- a/stix2/test/v20/test_object_markings.py +++ b/stix2/test/v20/test_object_markings.py @@ -1,7 +1,8 @@ import pytest -from stix2 import TLP_AMBER, Malware, exceptions, markings +from stix2 import exceptions, markings +from stix2.v20 import TLP_AMBER, Malware from .constants import FAKE_TIME, MALWARE_ID from .constants import MALWARE_KWARGS as MALWARE_KWARGS_CONST diff --git a/stix2/test/v20/test_observed_data.py b/stix2/test/v20/test_observed_data.py index 11c74ca..389f27e 100644 --- a/stix2/test/v20/test_observed_data.py +++ b/stix2/test/v20/test_observed_data.py @@ -30,7 +30,7 @@ EXPECTED = """{ def test_observed_data_example(): - observed_data = stix2.ObservedData( + observed_data = stix2.v20.ObservedData( id="observed-data--b67d30ff-02ac-498a-92f9-32f845f448cf", created_by_ref="identity--f431f809-377b-45e0-aa1c-6a4751cae5ff", created="2016-04-06T19:58:16.000Z", @@ -75,7 +75,7 @@ EXPECTED_WITH_REF = """{ def test_observed_data_example_with_refs(): - observed_data = stix2.ObservedData( + observed_data = stix2.v20.ObservedData( id="observed-data--b67d30ff-02ac-498a-92f9-32f845f448cf", created_by_ref="identity--f431f809-377b-45e0-aa1c-6a4751cae5ff", created="2016-04-06T19:58:16.000Z", @@ -101,7 +101,7 @@ def test_observed_data_example_with_refs(): def test_observed_data_example_with_bad_refs(): with pytest.raises(stix2.exceptions.InvalidValueError) as excinfo: - stix2.ObservedData( + stix2.v20.ObservedData( id="observed-data--b67d30ff-02ac-498a-92f9-32f845f448cf", created_by_ref="identity--f431f809-377b-45e0-aa1c-6a4751cae5ff", created="2016-04-06T19:58:16.000Z", @@ -122,14 +122,14 @@ def test_observed_data_example_with_bad_refs(): }, ) - assert excinfo.value.cls == stix2.ObservedData + assert excinfo.value.cls == stix2.v20.ObservedData assert excinfo.value.prop_name == "objects" assert excinfo.value.reason == "Invalid object reference for 'Directory:contains_refs': '2' is not a valid object in local scope" def test_observed_data_example_with_non_dictionary(): with pytest.raises(stix2.exceptions.InvalidValueError) as excinfo: - stix2.ObservedData( + stix2.v20.ObservedData( id="observed-data--b67d30ff-02ac-498a-92f9-32f845f448cf", created_by_ref="identity--f431f809-377b-45e0-aa1c-6a4751cae5ff", created="2016-04-06T19:58:16.000Z", @@ -140,14 +140,14 @@ def test_observed_data_example_with_non_dictionary(): objects="file: foo.exe", ) - assert excinfo.value.cls == stix2.ObservedData + assert excinfo.value.cls == stix2.v20.ObservedData assert excinfo.value.prop_name == "objects" assert 'must contain a dictionary' in excinfo.value.reason def test_observed_data_example_with_empty_dictionary(): with pytest.raises(stix2.exceptions.InvalidValueError) as excinfo: - stix2.ObservedData( + stix2.v20.ObservedData( id="observed-data--b67d30ff-02ac-498a-92f9-32f845f448cf", created_by_ref="identity--f431f809-377b-45e0-aa1c-6a4751cae5ff", created="2016-04-06T19:58:16.000Z", @@ -158,7 +158,7 @@ def test_observed_data_example_with_empty_dictionary(): objects={}, ) - assert excinfo.value.cls == stix2.ObservedData + assert excinfo.value.cls == stix2.v20.ObservedData assert excinfo.value.prop_name == "objects" assert 'must contain a non-empty dictionary' in excinfo.value.reason @@ -183,7 +183,7 @@ def test_observed_data_example_with_empty_dictionary(): }, ]) def test_parse_observed_data(data): - odata = stix2.parse(data) + odata = stix2.parse(data, version="2.0") assert odata.type == 'observed-data' assert odata.id == OBSERVED_DATA_ID @@ -212,7 +212,7 @@ def test_parse_observed_data(data): ]) def test_parse_artifact_valid(data): odata_str = OBJECTS_REGEX.sub('"objects": { %s }' % data, EXPECTED) - odata = stix2.parse(odata_str) + odata = stix2.parse(odata_str, version="2.0") assert odata.objects["0"].type == "artifact" @@ -234,12 +234,12 @@ def test_parse_artifact_valid(data): def test_parse_artifact_invalid(data): odata_str = OBJECTS_REGEX.sub('"objects": { %s }' % data, EXPECTED) with pytest.raises(ValueError): - stix2.parse(odata_str) + stix2.parse(odata_str, version="2.0") def test_artifact_example_dependency_error(): with pytest.raises(stix2.exceptions.DependentPropertiesError) as excinfo: - stix2.Artifact(url="http://example.com/sirvizio.exe") + stix2.v20.Artifact(url="http://example.com/sirvizio.exe") assert excinfo.value.dependencies == [("hashes", "url")] assert str(excinfo.value) == "The property dependencies for Artifact: (hashes, url) are not met." @@ -255,7 +255,7 @@ def test_artifact_example_dependency_error(): ]) def test_parse_autonomous_system_valid(data): odata_str = OBJECTS_REGEX.sub('"objects": { %s }' % data, EXPECTED) - odata = stix2.parse(odata_str) + odata = stix2.parse(odata_str, version="2.0") assert odata.objects["0"].type == "autonomous-system" assert odata.objects["0"].number == 15139 assert odata.objects["0"].name == "Slime Industries" @@ -271,12 +271,12 @@ def test_parse_autonomous_system_valid(data): }""", ]) def test_parse_email_address(data): - odata = stix2.parse_observable(data, {"0": "user-account"}) + odata = stix2.parse_observable(data, {"0": "user-account"}, version='2.0') assert odata.type == "email-addr" odata_str = re.compile('"belongs_to_ref": "0"', re.DOTALL).sub('"belongs_to_ref": "3"', data) with pytest.raises(stix2.exceptions.InvalidObjRefError): - stix2.parse_observable(odata_str, {"0": "user-account"}) + stix2.parse_observable(odata_str, {"0": "user-account"}, version='2.0') @pytest.mark.parametrize("data", [ @@ -328,7 +328,7 @@ def test_parse_email_message(data): "4": "artifact", "5": "file", } - odata = stix2.parse_observable(data, valid_refs) + odata = stix2.parse_observable(data, valid_refs, version='2.0') assert odata.type == "email-message" assert odata.body_multipart[0].content_disposition == "inline" @@ -352,9 +352,9 @@ def test_parse_email_message_not_multipart(data): "1": "email-addr", } with pytest.raises(stix2.exceptions.DependentPropertiesError) as excinfo: - stix2.parse_observable(data, valid_refs) + stix2.parse_observable(data, valid_refs, version='2.0') - assert excinfo.value.cls == stix2.EmailMessage + assert excinfo.value.cls == stix2.v20.EmailMessage assert excinfo.value.dependencies == [("is_multipart", "body")] @@ -398,7 +398,7 @@ def test_parse_email_message_not_multipart(data): ]) def test_parse_file_archive(data): odata_str = OBJECTS_REGEX.sub('"objects": { %s }' % data, EXPECTED) - odata = stix2.parse(odata_str) + odata = stix2.parse(odata_str, version="2.0") assert odata.objects["3"].extensions['archive-ext'].version == "5.0" @@ -451,9 +451,9 @@ def test_parse_email_message_with_at_least_one_error(data): "5": "file", } with pytest.raises(stix2.exceptions.AtLeastOnePropertyError) as excinfo: - stix2.parse_observable(data, valid_refs) + stix2.parse_observable(data, valid_refs, version='2.0') - assert excinfo.value.cls == stix2.EmailMIMEComponent + assert excinfo.value.cls == stix2.v20.EmailMIMEComponent assert excinfo.value.properties == ["body", "body_raw_ref"] assert "At least one of the" in str(excinfo.value) assert "must be populated" in str(excinfo.value) @@ -472,7 +472,8 @@ def test_parse_email_message_with_at_least_one_error(data): """ ]) def test_parse_basic_tcp_traffic(data): - odata = stix2.parse_observable(data, {"0": "ipv4-addr", "1": "ipv4-addr"}) + odata = stix2.parse_observable(data, {"0": "ipv4-addr", "1": "ipv4-addr"}, + version='2.0') assert odata.type == "network-traffic" assert odata.src_ref == "0" @@ -500,9 +501,9 @@ def test_parse_basic_tcp_traffic(data): ]) def test_parse_basic_tcp_traffic_with_error(data): with pytest.raises(stix2.exceptions.AtLeastOnePropertyError) as excinfo: - stix2.parse_observable(data, {"4": "network-traffic"}) + stix2.parse_observable(data, {"4": "network-traffic"}, version='2.0') - assert excinfo.value.cls == stix2.NetworkTraffic + assert excinfo.value.cls == stix2.v20.NetworkTraffic assert excinfo.value.properties == ["dst_ref", "src_ref"] @@ -537,7 +538,7 @@ EXPECTED_PROCESS_OD = """{ def test_observed_data_with_process_example(): - observed_data = stix2.ObservedData( + observed_data = stix2.v20.ObservedData( id="observed-data--b67d30ff-02ac-498a-92f9-32f845f448cf", created_by_ref="identity--f431f809-377b-45e0-aa1c-6a4751cae5ff", created="2016-04-06T19:58:16.000Z", @@ -575,11 +576,12 @@ def test_observed_data_with_process_example(): # creating cyber observables directly def test_artifact_example(): - art = stix2.Artifact(mime_type="image/jpeg", - url="https://upload.wikimedia.org/wikipedia/commons/b/b4/JPEG_example_JPG_RIP_100.jpg", - hashes={ - "MD5": "6826f9a05da08134006557758bb3afbb" - }) + art = stix2.v20.Artifact( + mime_type="image/jpeg", + url="https://upload.wikimedia.org/wikipedia/commons/b/b4/JPEG_example_JPG_RIP_100.jpg", + hashes={ + "MD5": "6826f9a05da08134006557758bb3afbb" + }) assert art.mime_type == "image/jpeg" assert art.url == "https://upload.wikimedia.org/wikipedia/commons/b/b4/JPEG_example_JPG_RIP_100.jpg" assert art.hashes["MD5"] == "6826f9a05da08134006557758bb3afbb" @@ -587,25 +589,27 @@ def test_artifact_example(): def test_artifact_mutual_exclusion_error(): with pytest.raises(stix2.exceptions.MutuallyExclusivePropertiesError) as excinfo: - stix2.Artifact(mime_type="image/jpeg", - url="https://upload.wikimedia.org/wikipedia/commons/b/b4/JPEG_example_JPG_RIP_100.jpg", - hashes={ - "MD5": "6826f9a05da08134006557758bb3afbb" - }, - payload_bin="VBORw0KGgoAAAANSUhEUgAAADI==") + stix2.v20.Artifact( + mime_type="image/jpeg", + url="https://upload.wikimedia.org/wikipedia/commons/b/b4/JPEG_example_JPG_RIP_100.jpg", + hashes={ + "MD5": "6826f9a05da08134006557758bb3afbb" + }, + payload_bin="VBORw0KGgoAAAANSUhEUgAAADI==") - assert excinfo.value.cls == stix2.Artifact + assert excinfo.value.cls == stix2.v20.Artifact assert excinfo.value.properties == ["payload_bin", "url"] assert 'are mutually exclusive' in str(excinfo.value) def test_directory_example(): - dir = stix2.Directory(_valid_refs={"1": "file"}, - path='/usr/lib', - created="2015-12-21T19:00:00Z", - modified="2015-12-24T19:00:00Z", - accessed="2015-12-21T20:00:00Z", - contains_refs=["1"]) + dir = stix2.v20.Directory( + _valid_refs={"1": "file"}, + path='/usr/lib', + created="2015-12-21T19:00:00Z", + modified="2015-12-24T19:00:00Z", + accessed="2015-12-21T20:00:00Z", + contains_refs=["1"]) assert dir.path == '/usr/lib' assert dir.created == dt.datetime(2015, 12, 21, 19, 0, 0, tzinfo=pytz.utc) @@ -616,21 +620,23 @@ def test_directory_example(): def test_directory_example_ref_error(): with pytest.raises(stix2.exceptions.InvalidObjRefError) as excinfo: - stix2.Directory(_valid_refs=[], - path='/usr/lib', - created="2015-12-21T19:00:00Z", - modified="2015-12-24T19:00:00Z", - accessed="2015-12-21T20:00:00Z", - contains_refs=["1"]) + stix2.v20.Directory( + _valid_refs=[], + path='/usr/lib', + created="2015-12-21T19:00:00Z", + modified="2015-12-24T19:00:00Z", + accessed="2015-12-21T20:00:00Z", + contains_refs=["1"]) - assert excinfo.value.cls == stix2.Directory + assert excinfo.value.cls == stix2.v20.Directory assert excinfo.value.prop_name == "contains_refs" def test_domain_name_example(): - dn = stix2.DomainName(_valid_refs={"1": 'domain-name'}, - value="example.com", - resolves_to_refs=["1"]) + dn = stix2.v20.DomainName( + _valid_refs={"1": 'domain-name'}, + value="example.com", + resolves_to_refs=["1"]) assert dn.value == "example.com" assert dn.resolves_to_refs == ["1"] @@ -638,28 +644,29 @@ def test_domain_name_example(): def test_domain_name_example_invalid_ref_type(): with pytest.raises(stix2.exceptions.InvalidObjRefError) as excinfo: - stix2.DomainName(_valid_refs={"1": "file"}, - value="example.com", - resolves_to_refs=["1"]) + stix2.v20.DomainName( + _valid_refs={"1": "file"}, + value="example.com", + resolves_to_refs=["1"]) - assert excinfo.value.cls == stix2.DomainName + assert excinfo.value.cls == stix2.v20.DomainName assert excinfo.value.prop_name == "resolves_to_refs" def test_file_example(): - f = stix2.File(name="qwerty.dll", - hashes={ - "SHA-256": "ceafbfd424be2ca4a5f0402cae090dda2fb0526cf521b60b60077c0f622b285a"}, - size=100, - magic_number_hex="1C", - mime_type="application/msword", - created="2016-12-21T19:00:00Z", - modified="2016-12-24T19:00:00Z", - accessed="2016-12-21T20:00:00Z", - is_encrypted=True, - encryption_algorithm="AES128-CBC", - decryption_key="fred" - ) + f = stix2.v20.File( + name="qwerty.dll", + hashes={ + "SHA-256": "ceafbfd424be2ca4a5f0402cae090dda2fb0526cf521b60b60077c0f622b285a"}, + size=100, + magic_number_hex="1C", + mime_type="application/msword", + created="2016-12-21T19:00:00Z", + modified="2016-12-24T19:00:00Z", + accessed="2016-12-21T20:00:00Z", + is_encrypted=True, + encryption_algorithm="AES128-CBC", + decryption_key="fred") assert f.name == "qwerty.dll" assert f.size == 100 @@ -675,17 +682,18 @@ def test_file_example(): def test_file_example_with_NTFSExt(): - f = stix2.File(name="abc.txt", - extensions={ - "ntfs-ext": { - "alternate_data_streams": [ - { - "name": "second.stream", - "size": 25536 - } - ] - } - }) + f = stix2.v20.File( + name="abc.txt", + extensions={ + "ntfs-ext": { + "alternate_data_streams": [ + { + "name": "second.stream", + "size": 25536 + } + ] + } + }) assert f.name == "abc.txt" assert f.extensions["ntfs-ext"].alternate_data_streams[0].size == 25536 @@ -693,32 +701,33 @@ def test_file_example_with_NTFSExt(): def test_file_example_with_empty_NTFSExt(): with pytest.raises(stix2.exceptions.AtLeastOnePropertyError) as excinfo: - stix2.File(name="abc.txt", - extensions={ - "ntfs-ext": { - } - }) + stix2.v20.File( + name="abc.txt", + extensions={ + "ntfs-ext": {} + }) - assert excinfo.value.cls == stix2.NTFSExt + assert excinfo.value.cls == stix2.v20.NTFSExt assert excinfo.value.properties == sorted(list(stix2.NTFSExt._properties.keys())) def test_file_example_with_PDFExt(): - f = stix2.File(name="qwerty.dll", - extensions={ - "pdf-ext": { - "version": "1.7", - "document_info_dict": { - "Title": "Sample document", - "Author": "Adobe Systems Incorporated", - "Creator": "Adobe FrameMaker 5.5.3 for Power Macintosh", - "Producer": "Acrobat Distiller 3.01 for Power Macintosh", - "CreationDate": "20070412090123-02" - }, - "pdfid0": "DFCE52BD827ECF765649852119D", - "pdfid1": "57A1E0F9ED2AE523E313C" - } - }) + f = stix2.v20.File( + name="qwerty.dll", + extensions={ + "pdf-ext": { + "version": "1.7", + "document_info_dict": { + "Title": "Sample document", + "Author": "Adobe Systems Incorporated", + "Creator": "Adobe FrameMaker 5.5.3 for Power Macintosh", + "Producer": "Acrobat Distiller 3.01 for Power Macintosh", + "CreationDate": "20070412090123-02" + }, + "pdfid0": "DFCE52BD827ECF765649852119D", + "pdfid1": "57A1E0F9ED2AE523E313C" + } + }) assert f.name == "qwerty.dll" assert f.extensions["pdf-ext"].version == "1.7" @@ -726,21 +735,21 @@ def test_file_example_with_PDFExt(): def test_file_example_with_PDFExt_Object(): - f = stix2.File(name="qwerty.dll", - extensions={ - "pdf-ext": - stix2.PDFExt(version="1.7", - document_info_dict={ - "Title": "Sample document", - "Author": "Adobe Systems Incorporated", - "Creator": "Adobe FrameMaker 5.5.3 for Power Macintosh", - "Producer": "Acrobat Distiller 3.01 for Power Macintosh", - "CreationDate": "20070412090123-02" - }, - pdfid0="DFCE52BD827ECF765649852119D", - pdfid1="57A1E0F9ED2AE523E313C") - - }) + f = stix2.v20.File( + name="qwerty.dll", + extensions={ + "pdf-ext": stix2.v20.PDFExt( + version="1.7", + document_info_dict={ + "Title": "Sample document", + "Author": "Adobe Systems Incorporated", + "Creator": "Adobe FrameMaker 5.5.3 for Power Macintosh", + "Producer": "Acrobat Distiller 3.01 for Power Macintosh", + "CreationDate": "20070412090123-02" + }, + pdfid0="DFCE52BD827ECF765649852119D", + pdfid1="57A1E0F9ED2AE523E313C") + }) assert f.name == "qwerty.dll" assert f.extensions["pdf-ext"].version == "1.7" @@ -748,18 +757,19 @@ def test_file_example_with_PDFExt_Object(): def test_file_example_with_RasterImageExt_Object(): - f = stix2.File(name="qwerty.jpeg", - extensions={ - "raster-image-ext": { - "bits_per_pixel": 123, - "exif_tags": { - "Make": "Nikon", - "Model": "D7000", - "XResolution": 4928, - "YResolution": 3264 - } - } - }) + f = stix2.v20.File( + name="qwerty.jpeg", + extensions={ + "raster-image-ext": { + "bits_per_pixel": 123, + "exif_tags": { + "Make": "Nikon", + "Model": "D7000", + "XResolution": 4928, + "YResolution": 3264 + } + } + }) assert f.name == "qwerty.jpeg" assert f.extensions["raster-image-ext"].bits_per_pixel == 123 assert f.extensions["raster-image-ext"].exif_tags["XResolution"] == 4928 @@ -801,150 +811,156 @@ RASTER_IMAGE_EXT = """{ def test_raster_image_ext_parse(): - obj = stix2.parse(RASTER_IMAGE_EXT) + obj = stix2.parse(RASTER_IMAGE_EXT, version="2.0") assert obj.objects["0"].extensions['raster-image-ext'].image_width == 1024 def test_raster_images_ext_create(): - ext = stix2.RasterImageExt(image_width=1024) + ext = stix2.v20.RasterImageExt(image_width=1024) assert "image_width" in str(ext) def test_file_example_with_WindowsPEBinaryExt(): - f = stix2.File(name="qwerty.dll", - extensions={ - "windows-pebinary-ext": { - "pe_type": "exe", - "machine_hex": "014c", - "number_of_sections": 4, - "time_date_stamp": "2016-01-22T12:31:12Z", - "pointer_to_symbol_table_hex": "74726144", - "number_of_symbols": 4542568, - "size_of_optional_header": 224, - "characteristics_hex": "818f", - "optional_header": { - "magic_hex": "010b", - "major_linker_version": 2, - "minor_linker_version": 25, - "size_of_code": 512, - "size_of_initialized_data": 283648, - "size_of_uninitialized_data": 0, - "address_of_entry_point": 4096, - "base_of_code": 4096, - "base_of_data": 8192, - "image_base": 14548992, - "section_alignment": 4096, - "file_alignment": 4096, - "major_os_version": 1, - "minor_os_version": 0, - "major_image_version": 0, - "minor_image_version": 0, - "major_subsystem_version": 4, - "minor_subsystem_version": 0, - "win32_version_value_hex": "00", - "size_of_image": 299008, - "size_of_headers": 4096, - "checksum_hex": "00", - "subsystem_hex": "03", - "dll_characteristics_hex": "00", - "size_of_stack_reserve": 100000, - "size_of_stack_commit": 8192, - "size_of_heap_reserve": 100000, - "size_of_heap_commit": 4096, - "loader_flags_hex": "abdbffde", - "number_of_rva_and_sizes": 3758087646 - }, - "sections": [ - { - "name": "CODE", - "entropy": 0.061089 - }, - { - "name": "DATA", - "entropy": 7.980693 - }, - { - "name": "NicolasB", - "entropy": 0.607433 - }, - { - "name": ".idata", - "entropy": 0.607433 - } - ] - } - - }) + f = stix2.v20.File( + name="qwerty.dll", + extensions={ + "windows-pebinary-ext": { + "pe_type": "exe", + "machine_hex": "014c", + "number_of_sections": 4, + "time_date_stamp": "2016-01-22T12:31:12Z", + "pointer_to_symbol_table_hex": "74726144", + "number_of_symbols": 4542568, + "size_of_optional_header": 224, + "characteristics_hex": "818f", + "optional_header": { + "magic_hex": "010b", + "major_linker_version": 2, + "minor_linker_version": 25, + "size_of_code": 512, + "size_of_initialized_data": 283648, + "size_of_uninitialized_data": 0, + "address_of_entry_point": 4096, + "base_of_code": 4096, + "base_of_data": 8192, + "image_base": 14548992, + "section_alignment": 4096, + "file_alignment": 4096, + "major_os_version": 1, + "minor_os_version": 0, + "major_image_version": 0, + "minor_image_version": 0, + "major_subsystem_version": 4, + "minor_subsystem_version": 0, + "win32_version_value_hex": "00", + "size_of_image": 299008, + "size_of_headers": 4096, + "checksum_hex": "00", + "subsystem_hex": "03", + "dll_characteristics_hex": "00", + "size_of_stack_reserve": 100000, + "size_of_stack_commit": 8192, + "size_of_heap_reserve": 100000, + "size_of_heap_commit": 4096, + "loader_flags_hex": "abdbffde", + "number_of_rva_and_sizes": 3758087646 + }, + "sections": [ + { + "name": "CODE", + "entropy": 0.061089 + }, + { + "name": "DATA", + "entropy": 7.980693 + }, + { + "name": "NicolasB", + "entropy": 0.607433 + }, + { + "name": ".idata", + "entropy": 0.607433 + } + ] + } + }) assert f.name == "qwerty.dll" assert f.extensions["windows-pebinary-ext"].sections[2].entropy == 0.607433 def test_file_example_encryption_error(): with pytest.raises(stix2.exceptions.DependentPropertiesError) as excinfo: - stix2.File(name="qwerty.dll", - is_encrypted=False, - encryption_algorithm="AES128-CBC") + stix2.v20.File( + name="qwerty.dll", + is_encrypted=False, + encryption_algorithm="AES128-CBC") - assert excinfo.value.cls == stix2.File + assert excinfo.value.cls == stix2.v20.File assert excinfo.value.dependencies == [("is_encrypted", "encryption_algorithm")] assert "property dependencies" in str(excinfo.value) assert "are not met" in str(excinfo.value) with pytest.raises(stix2.exceptions.DependentPropertiesError) as excinfo: - stix2.File(name="qwerty.dll", - encryption_algorithm="AES128-CBC") + stix2.v20.File( + name="qwerty.dll", + encryption_algorithm="AES128-CBC") def test_ip4_address_example(): - ip4 = stix2.IPv4Address(_valid_refs={"4": "mac-addr", "5": "mac-addr"}, - value="198.51.100.3", - resolves_to_refs=["4", "5"]) + ip4 = stix2.v20.IPv4Address( + _valid_refs={"4": "mac-addr", "5": "mac-addr"}, + value="198.51.100.3", + resolves_to_refs=["4", "5"]) assert ip4.value == "198.51.100.3" assert ip4.resolves_to_refs == ["4", "5"] def test_ip4_address_example_cidr(): - ip4 = stix2.IPv4Address(value="198.51.100.0/24") + ip4 = stix2.v20.IPv4Address(value="198.51.100.0/24") assert ip4.value == "198.51.100.0/24" def test_ip6_address_example(): - ip6 = stix2.IPv6Address(value="2001:0db8:85a3:0000:0000:8a2e:0370:7334") + ip6 = stix2.v20.IPv6Address(value="2001:0db8:85a3:0000:0000:8a2e:0370:7334") assert ip6.value == "2001:0db8:85a3:0000:0000:8a2e:0370:7334" def test_mac_address_example(): - ip6 = stix2.MACAddress(value="d2:fb:49:24:37:18") + ip6 = stix2.v20.MACAddress(value="d2:fb:49:24:37:18") assert ip6.value == "d2:fb:49:24:37:18" def test_network_traffic_example(): - nt = stix2.NetworkTraffic(_valid_refs={"0": "ipv4-addr", "1": "ipv4-addr"}, - protocols="tcp", - src_ref="0", - dst_ref="1") + nt = stix2.v20.NetworkTraffic( + _valid_refs={"0": "ipv4-addr", "1": "ipv4-addr"}, + protocols="tcp", + src_ref="0", + dst_ref="1") assert nt.protocols == ["tcp"] assert nt.src_ref == "0" assert nt.dst_ref == "1" def test_network_traffic_http_request_example(): - h = stix2.HTTPRequestExt(request_method="get", - request_value="/download.html", - request_version="http/1.1", - request_header={ - "Accept-Encoding": "gzip,deflate", - "User-Agent": "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.6) Gecko/20040113", - "Host": "www.example.com" - }) - nt = stix2.NetworkTraffic(_valid_refs={"0": "ipv4-addr"}, - protocols="tcp", - src_ref="0", - extensions={'http-request-ext': h}) + h = stix2.v20.HTTPRequestExt( + request_method="get", + request_value="/download.html", + request_version="http/1.1", + request_header={ + "Accept-Encoding": "gzip,deflate", + "User-Agent": "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.6) Gecko/20040113", + "Host": "www.example.com" + }) + nt = stix2.v20.NetworkTraffic( + _valid_refs={"0": "ipv4-addr"}, + protocols="tcp", + src_ref="0", + extensions={'http-request-ext': h}) assert nt.extensions['http-request-ext'].request_method == "get" assert nt.extensions['http-request-ext'].request_value == "/download.html" assert nt.extensions['http-request-ext'].request_version == "http/1.1" @@ -954,25 +970,27 @@ def test_network_traffic_http_request_example(): def test_network_traffic_icmp_example(): - h = stix2.ICMPExt(icmp_type_hex="08", - icmp_code_hex="00") - nt = stix2.NetworkTraffic(_valid_refs={"0": "ipv4-addr"}, - protocols="tcp", - src_ref="0", - extensions={'icmp-ext': h}) + h = stix2.v20.ICMPExt(icmp_type_hex="08", icmp_code_hex="00") + nt = stix2.v20.NetworkTraffic( + _valid_refs={"0": "ipv4-addr"}, + protocols="tcp", + src_ref="0", + extensions={'icmp-ext': h}) assert nt.extensions['icmp-ext'].icmp_type_hex == "08" assert nt.extensions['icmp-ext'].icmp_code_hex == "00" def test_network_traffic_socket_example(): - h = stix2.SocketExt(is_listening=True, - address_family="AF_INET", - protocol_family="PF_INET", - socket_type="SOCK_STREAM") - nt = stix2.NetworkTraffic(_valid_refs={"0": "ipv4-addr"}, - protocols="tcp", - src_ref="0", - extensions={'socket-ext': h}) + h = stix2.v20.SocketExt( + is_listening=True, + address_family="AF_INET", + protocol_family="PF_INET", + socket_type="SOCK_STREAM") + nt = stix2.v20.NetworkTraffic( + _valid_refs={"0": "ipv4-addr"}, + protocols="tcp", + src_ref="0", + extensions={'socket-ext': h}) assert nt.extensions['socket-ext'].is_listening assert nt.extensions['socket-ext'].address_family == "AF_INET" assert nt.extensions['socket-ext'].protocol_family == "PF_INET" @@ -980,27 +998,29 @@ def test_network_traffic_socket_example(): def test_network_traffic_tcp_example(): - h = stix2.TCPExt(src_flags_hex="00000002") - nt = stix2.NetworkTraffic(_valid_refs={"0": "ipv4-addr"}, - protocols="tcp", - src_ref="0", - extensions={'tcp-ext': h}) + h = stix2.v20.TCPExt(src_flags_hex="00000002") + nt = stix2.v20.NetworkTraffic( + _valid_refs={"0": "ipv4-addr"}, + protocols="tcp", + src_ref="0", + extensions={'tcp-ext': h}) assert nt.extensions['tcp-ext'].src_flags_hex == "00000002" def test_mutex_example(): - m = stix2.Mutex(name="barney") + m = stix2.v20.Mutex(name="barney") assert m.name == "barney" def test_process_example(): - p = stix2.Process(_valid_refs={"0": "file"}, - pid=1221, - name="gedit-bin", - created="2016-01-20T14:11:25.55Z", - arguments=["--new-window"], - binary_ref="0") + p = stix2.v20.Process( + _valid_refs={"0": "file"}, + pid=1221, + name="gedit-bin", + created="2016-01-20T14:11:25.55Z", + arguments=["--new-window"], + binary_ref="0") assert p.name == "gedit-bin" assert p.arguments == ["--new-window"] @@ -1008,40 +1028,42 @@ def test_process_example(): def test_process_example_empty_error(): with pytest.raises(stix2.exceptions.AtLeastOnePropertyError) as excinfo: - stix2.Process() + stix2.v20.Process() - assert excinfo.value.cls == stix2.Process - properties_of_process = list(stix2.Process._properties.keys()) + assert excinfo.value.cls == stix2.v20.Process + properties_of_process = list(stix2.v20.Process._properties.keys()) properties_of_process.remove("type") assert excinfo.value.properties == sorted(properties_of_process) msg = "At least one of the ({1}) properties for {0} must be populated." - msg = msg.format(stix2.Process.__name__, + msg = msg.format(stix2.v20.Process.__name__, ", ".join(sorted(properties_of_process))) assert str(excinfo.value) == msg def test_process_example_empty_with_extensions(): with pytest.raises(stix2.exceptions.AtLeastOnePropertyError) as excinfo: - stix2.Process(extensions={ - "windows-process-ext": {} - }) + stix2.v20.Process( + extensions={ + "windows-process-ext": {} + }) - assert excinfo.value.cls == stix2.WindowsProcessExt - properties_of_extension = list(stix2.WindowsProcessExt._properties.keys()) + assert excinfo.value.cls == stix2.v20.WindowsProcessExt + properties_of_extension = list(stix2.v20.WindowsProcessExt._properties.keys()) assert excinfo.value.properties == sorted(properties_of_extension) def test_process_example_windows_process_ext(): - proc = stix2.Process(pid=314, - name="foobar.exe", - extensions={ - "windows-process-ext": { - "aslr_enabled": True, - "dep_enabled": True, - "priority": "HIGH_PRIORITY_CLASS", - "owner_sid": "S-1-5-21-186985262-1144665072-74031268-1309" - } - }) + proc = stix2.v20.Process( + pid=314, + name="foobar.exe", + extensions={ + "windows-process-ext": { + "aslr_enabled": True, + "dep_enabled": True, + "priority": "HIGH_PRIORITY_CLASS", + "owner_sid": "S-1-5-21-186985262-1144665072-74031268-1309" + } + }) assert proc.extensions["windows-process-ext"].aslr_enabled assert proc.extensions["windows-process-ext"].dep_enabled assert proc.extensions["windows-process-ext"].priority == "HIGH_PRIORITY_CLASS" @@ -1050,47 +1072,49 @@ def test_process_example_windows_process_ext(): def test_process_example_windows_process_ext_empty(): with pytest.raises(stix2.exceptions.AtLeastOnePropertyError) as excinfo: - stix2.Process(pid=1221, - name="gedit-bin", - extensions={ - "windows-process-ext": {} - }) + stix2.v20.Process( + pid=1221, + name="gedit-bin", + extensions={ + "windows-process-ext": {} + }) - assert excinfo.value.cls == stix2.WindowsProcessExt - properties_of_extension = list(stix2.WindowsProcessExt._properties.keys()) + assert excinfo.value.cls == stix2.v20.WindowsProcessExt + properties_of_extension = list(stix2.v20.WindowsProcessExt._properties.keys()) assert excinfo.value.properties == sorted(properties_of_extension) def test_process_example_extensions_empty(): with pytest.raises(stix2.exceptions.InvalidValueError) as excinfo: - stix2.Process(extensions={}) + stix2.v20.Process(extensions={}) - assert excinfo.value.cls == stix2.Process + assert excinfo.value.cls == stix2.v20.Process assert excinfo.value.prop_name == 'extensions' assert 'non-empty dictionary' in excinfo.value.reason def test_process_example_with_WindowsProcessExt_Object(): - p = stix2.Process(extensions={ - "windows-process-ext": stix2.WindowsProcessExt(aslr_enabled=True, - dep_enabled=True, - priority="HIGH_PRIORITY_CLASS", - owner_sid="S-1-5-21-186985262-1144665072-74031268-1309") # noqa - }) + p = stix2.v20.Process(extensions={ + "windows-process-ext": stix2.v20.WindowsProcessExt( + aslr_enabled=True, + dep_enabled=True, + priority="HIGH_PRIORITY_CLASS", + owner_sid="S-1-5-21-186985262-1144665072-74031268-1309") # noqa + }) assert p.extensions["windows-process-ext"].dep_enabled assert p.extensions["windows-process-ext"].owner_sid == "S-1-5-21-186985262-1144665072-74031268-1309" def test_process_example_with_WindowsServiceExt(): - p = stix2.Process(extensions={ - "windows-service-ext": { - "service_name": "sirvizio", - "display_name": "Sirvizio", - "start_type": "SERVICE_AUTO_START", - "service_type": "SERVICE_WIN32_OWN_PROCESS", - "service_status": "SERVICE_RUNNING" - } + p = stix2.v20.Process(extensions={ + "windows-service-ext": { + "service_name": "sirvizio", + "display_name": "Sirvizio", + "start_type": "SERVICE_AUTO_START", + "service_type": "SERVICE_WIN32_OWN_PROCESS", + "service_status": "SERVICE_RUNNING" + } }) assert p.extensions["windows-service-ext"].service_name == "sirvizio" @@ -1098,7 +1122,7 @@ def test_process_example_with_WindowsServiceExt(): def test_process_example_with_WindowsProcessServiceExt(): - p = stix2.Process(extensions={ + p = stix2.v20.Process(extensions={ "windows-service-ext": { "service_name": "sirvizio", "display_name": "Sirvizio", @@ -1121,10 +1145,11 @@ def test_process_example_with_WindowsProcessServiceExt(): def test_software_example(): - s = stix2.Software(name="Word", - cpe="cpe:2.3:a:microsoft:word:2000:*:*:*:*:*:*:*", - version="2002", - vendor="Microsoft") + s = stix2.v20.Software( + name="Word", + cpe="cpe:2.3:a:microsoft:word:2000:*:*:*:*:*:*:*", + version="2002", + vendor="Microsoft") assert s.name == "Word" assert s.cpe == "cpe:2.3:a:microsoft:word:2000:*:*:*:*:*:*:*" @@ -1133,24 +1158,25 @@ def test_software_example(): def test_url_example(): - s = stix2.URL(value="https://example.com/research/index.html") + s = stix2.v20.URL(value="https://example.com/research/index.html") assert s.type == "url" assert s.value == "https://example.com/research/index.html" def test_user_account_example(): - a = stix2.UserAccount(user_id="1001", - account_login="jdoe", - account_type="unix", - display_name="John Doe", - is_service_account=False, - is_privileged=False, - can_escalate_privs=True, - account_created="2016-01-20T12:31:12Z", - password_last_changed="2016-01-20T14:27:43Z", - account_first_login="2016-01-20T14:26:07Z", - account_last_login="2016-07-22T16:08:28Z") + a = stix2.v20.UserAccount( + user_id="1001", + account_login="jdoe", + account_type="unix", + display_name="John Doe", + is_service_account=False, + is_privileged=False, + can_escalate_privs=True, + account_created="2016-01-20T12:31:12Z", + password_last_changed="2016-01-20T14:27:43Z", + account_first_login="2016-01-20T14:26:07Z", + account_last_login="2016-07-22T16:08:28Z") assert a.user_id == "1001" assert a.account_login == "jdoe" @@ -1166,14 +1192,16 @@ def test_user_account_example(): def test_user_account_unix_account_ext_example(): - u = stix2.UNIXAccountExt(gid=1001, - groups=["wheel"], - home_dir="/home/jdoe", - shell="/bin/bash") - a = stix2.UserAccount(user_id="1001", - account_login="jdoe", - account_type="unix", - extensions={'unix-account-ext': u}) + u = stix2.v20.UNIXAccountExt( + gid=1001, + groups=["wheel"], + home_dir="/home/jdoe", + shell="/bin/bash") + a = stix2.v20.UserAccount( + user_id="1001", + account_login="jdoe", + account_type="unix", + extensions={'unix-account-ext': u}) assert a.extensions['unix-account-ext'].gid == 1001 assert a.extensions['unix-account-ext'].groups == ["wheel"] assert a.extensions['unix-account-ext'].home_dir == "/home/jdoe" @@ -1182,15 +1210,18 @@ def test_user_account_unix_account_ext_example(): def test_windows_registry_key_example(): with pytest.raises(ValueError): - v = stix2.WindowsRegistryValueType(name="Foo", - data="qwerty", - data_type="string") + stix2.v20.WindowsRegistryValueType( + name="Foo", + data="qwerty", + data_type="string") - v = stix2.WindowsRegistryValueType(name="Foo", - data="qwerty", - data_type="REG_SZ") - w = stix2.WindowsRegistryKey(key="hkey_local_machine\\system\\bar\\foo", - values=[v]) + v = stix2.v20.WindowsRegistryValueType( + name="Foo", + data="qwerty", + data_type="REG_SZ") + w = stix2.v20.WindowsRegistryKey( + key="hkey_local_machine\\system\\bar\\foo", + values=[v]) assert w.key == "hkey_local_machine\\system\\bar\\foo" assert w.values[0].name == "Foo" assert w.values[0].data == "qwerty" @@ -1198,7 +1229,7 @@ def test_windows_registry_key_example(): def test_x509_certificate_example(): - x509 = stix2.X509Certificate( + x509 = stix2.v20.X509Certificate( issuer="C=ZA, ST=Western Cape, L=Cape Town, O=Thawte Consulting cc, OU=Certification Services Division, CN=Thawte Server CA/emailAddress=server-certs@thawte.com", # noqa validity_not_before="2016-03-12T12:00:00Z", validity_not_after="2016-08-21T12:00:00Z", @@ -1210,7 +1241,7 @@ def test_x509_certificate_example(): def test_new_version_with_related_objects(): - data = stix2.ObservedData( + data = stix2.v20.ObservedData( first_observed="2016-03-12T12:00:00Z", last_observed="2016-03-12T12:00:00Z", number_observed=1, diff --git a/stix2/test/v20/test_pickle.py b/stix2/test/v20/test_pickle.py index 9e2cc9a..399fc7a 100644 --- a/stix2/test/v20/test_pickle.py +++ b/stix2/test/v20/test_pickle.py @@ -7,7 +7,7 @@ def test_pickling(): """ Ensure a pickle/unpickle cycle works okay. """ - identity = stix2.Identity( + identity = stix2.v20.Identity( id="identity--d66cb89d-5228-4983-958c-fa84ef75c88c", name="alice", description="this is a pickle test", diff --git a/stix2/test/v20/test_relationship.py b/stix2/test/v20/test_relationship.py index 9e92030..6de13e2 100644 --- a/stix2/test/v20/test_relationship.py +++ b/stix2/test/v20/test_relationship.py @@ -10,7 +10,6 @@ from .constants import (FAKE_TIME, INDICATOR_ID, MALWARE_ID, RELATIONSHIP_ID, EXPECTED_RELATIONSHIP = """{ "type": "relationship", - "spec_version": "2.1", "id": "relationship--00000000-1111-2222-3333-444444444444", "created": "2016-04-06T20:06:37.000Z", "modified": "2016-04-06T20:06:37.000Z", @@ -23,7 +22,7 @@ EXPECTED_RELATIONSHIP = """{ def test_relationship_all_required_properties(): now = dt.datetime(2016, 4, 6, 20, 6, 37, tzinfo=pytz.utc) - rel = stix2.Relationship( + rel = stix2.v20.Relationship( type='relationship', id=RELATIONSHIP_ID, created=now, @@ -55,9 +54,9 @@ def test_relationship_autogenerated_properties(relationship): def test_relationship_type_must_be_relationship(): with pytest.raises(stix2.exceptions.InvalidValueError) as excinfo: - stix2.Relationship(type='xxx', **RELATIONSHIP_KWARGS) + stix2.v20.Relationship(type='xxx', **RELATIONSHIP_KWARGS) - assert excinfo.value.cls == stix2.Relationship + assert excinfo.value.cls == stix2.v20.Relationship assert excinfo.value.prop_name == "type" assert excinfo.value.reason == "must equal 'relationship'." assert str(excinfo.value) == "Invalid value for Relationship 'type': must equal 'relationship'." @@ -65,9 +64,9 @@ def test_relationship_type_must_be_relationship(): def test_relationship_id_must_start_with_relationship(): with pytest.raises(stix2.exceptions.InvalidValueError) as excinfo: - stix2.Relationship(id='my-prefix--', **RELATIONSHIP_KWARGS) + stix2.v20.Relationship(id='my-prefix--', **RELATIONSHIP_KWARGS) - assert excinfo.value.cls == stix2.Relationship + assert excinfo.value.cls == stix2.v20.Relationship assert excinfo.value.prop_name == "id" assert excinfo.value.reason == "must start with 'relationship--'." assert str(excinfo.value) == "Invalid value for Relationship 'id': must start with 'relationship--'." @@ -75,27 +74,27 @@ def test_relationship_id_must_start_with_relationship(): def test_relationship_required_property_relationship_type(): with pytest.raises(stix2.exceptions.MissingPropertiesError) as excinfo: - stix2.Relationship() - assert excinfo.value.cls == stix2.Relationship + stix2.v20.Relationship() + assert excinfo.value.cls == stix2.v20.Relationship assert excinfo.value.properties == ["relationship_type", "source_ref", "target_ref"] def test_relationship_missing_some_required_properties(): with pytest.raises(stix2.exceptions.MissingPropertiesError) as excinfo: - stix2.Relationship(relationship_type='indicates') + stix2.v20.Relationship(relationship_type='indicates') - assert excinfo.value.cls == stix2.Relationship + assert excinfo.value.cls == stix2.v20.Relationship assert excinfo.value.properties == ["source_ref", "target_ref"] def test_relationship_required_properties_target_ref(): with pytest.raises(stix2.exceptions.MissingPropertiesError) as excinfo: - stix2.Relationship( + stix2.v20.Relationship( relationship_type='indicates', source_ref=INDICATOR_ID ) - assert excinfo.value.cls == stix2.Relationship + assert excinfo.value.cls == stix2.v20.Relationship assert excinfo.value.properties == ["target_ref"] @@ -108,15 +107,15 @@ def test_cannot_assign_to_relationship_attributes(relationship): def test_invalid_kwarg_to_relationship(): with pytest.raises(stix2.exceptions.ExtraPropertiesError) as excinfo: - stix2.Relationship(my_custom_property="foo", **RELATIONSHIP_KWARGS) + stix2.v20.Relationship(my_custom_property="foo", **RELATIONSHIP_KWARGS) - assert excinfo.value.cls == stix2.Relationship + assert excinfo.value.cls == stix2.v20.Relationship assert excinfo.value.properties == ['my_custom_property'] assert str(excinfo.value) == "Unexpected properties for Relationship: (my_custom_property)." def test_create_relationship_from_objects_rather_than_ids(indicator, malware): - rel = stix2.Relationship( + rel = stix2.v20.Relationship( relationship_type="indicates", source_ref=indicator, target_ref=malware, @@ -129,7 +128,7 @@ def test_create_relationship_from_objects_rather_than_ids(indicator, malware): def test_create_relationship_with_positional_args(indicator, malware): - rel = stix2.Relationship(indicator, 'indicates', malware) + rel = stix2.v20.Relationship(indicator, 'indicates', malware) assert rel.relationship_type == 'indicates' assert rel.source_ref == 'indicator--00000000-0000-0000-0000-000000000001' @@ -150,7 +149,7 @@ def test_create_relationship_with_positional_args(indicator, malware): }, ]) def test_parse_relationship(data): - rel = stix2.parse(data) + rel = stix2.parse(data, version="2.0") assert rel.type == 'relationship' assert rel.id == RELATIONSHIP_ID diff --git a/stix2/test/v20/test_report.py b/stix2/test/v20/test_report.py index b38ab40..456875e 100644 --- a/stix2/test/v20/test_report.py +++ b/stix2/test/v20/test_report.py @@ -28,7 +28,7 @@ EXPECTED = """{ def test_report_example(): - report = stix2.Report( + report = stix2.v20.Report( id="report--84e4d88f-44ea-4bcd-bbf3-b2c1c320bcb3", created_by_ref="identity--a463ffb3-1bd9-4d94-b02d-74e4f1658283", created="2015-12-21T19:59:11.000Z", @@ -48,7 +48,7 @@ def test_report_example(): def test_report_example_objects_in_object_refs(): - report = stix2.Report( + report = stix2.v20.Report( id="report--84e4d88f-44ea-4bcd-bbf3-b2c1c320bcb3", created_by_ref="identity--a463ffb3-1bd9-4d94-b02d-74e4f1658283", created="2015-12-21T19:59:11.000Z", @@ -69,7 +69,7 @@ def test_report_example_objects_in_object_refs(): def test_report_example_objects_in_object_refs_with_bad_id(): with pytest.raises(stix2.exceptions.InvalidValueError) as excinfo: - stix2.Report( + stix2.v20.Report( id="report--84e4d88f-44ea-4bcd-bbf3-b2c1c320bcb3", created_by_ref="identity--a463ffb3-1bd9-4d94-b02d-74e4f1658283", created="2015-12-21T19:59:11.000Z", @@ -85,7 +85,7 @@ def test_report_example_objects_in_object_refs_with_bad_id(): ], ) - assert excinfo.value.cls == stix2.Report + assert excinfo.value.cls == stix2.v20.Report assert excinfo.value.prop_name == "object_refs" assert excinfo.value.reason == "must match --." assert str(excinfo.value) == "Invalid value for Report 'object_refs': must match --." @@ -113,7 +113,7 @@ def test_report_example_objects_in_object_refs_with_bad_id(): }, ]) def test_parse_report(data): - rept = stix2.parse(data) + rept = stix2.parse(data, version="2.0") assert rept.type == 'report' assert rept.id == REPORT_ID diff --git a/stix2/test/v20/test_sighting.py b/stix2/test/v20/test_sighting.py index 06f96b8..620a05a 100644 --- a/stix2/test/v20/test_sighting.py +++ b/stix2/test/v20/test_sighting.py @@ -33,7 +33,7 @@ BAD_SIGHTING = """{ def test_sighting_all_required_properties(): now = dt.datetime(2016, 4, 6, 20, 6, 37, tzinfo=pytz.utc) - s = stix2.Sighting( + s = stix2.v20.Sighting( type='sighting', id=SIGHTING_ID, created=now, @@ -48,7 +48,7 @@ def test_sighting_bad_where_sighted_refs(): now = dt.datetime(2016, 4, 6, 20, 6, 37, tzinfo=pytz.utc) with pytest.raises(stix2.exceptions.InvalidValueError) as excinfo: - stix2.Sighting( + stix2.v20.Sighting( type='sighting', id=SIGHTING_ID, created=now, @@ -57,7 +57,7 @@ def test_sighting_bad_where_sighted_refs(): where_sighted_refs=["malware--8cc7afd6-5455-4d2b-a736-e614ee631d99"] ) - assert excinfo.value.cls == stix2.Sighting + assert excinfo.value.cls == stix2.v20.Sighting assert excinfo.value.prop_name == "where_sighted_refs" assert excinfo.value.reason == "must start with 'identity'." assert str(excinfo.value) == "Invalid value for Sighting 'where_sighted_refs': must start with 'identity'." @@ -65,9 +65,9 @@ def test_sighting_bad_where_sighted_refs(): def test_sighting_type_must_be_sightings(): with pytest.raises(stix2.exceptions.InvalidValueError) as excinfo: - stix2.Sighting(type='xxx', **SIGHTING_KWARGS) + stix2.v20.Sighting(type='xxx', **SIGHTING_KWARGS) - assert excinfo.value.cls == stix2.Sighting + assert excinfo.value.cls == stix2.v20.Sighting assert excinfo.value.prop_name == "type" assert excinfo.value.reason == "must equal 'sighting'." assert str(excinfo.value) == "Invalid value for Sighting 'type': must equal 'sighting'." @@ -75,15 +75,15 @@ def test_sighting_type_must_be_sightings(): def test_invalid_kwarg_to_sighting(): with pytest.raises(stix2.exceptions.ExtraPropertiesError) as excinfo: - stix2.Sighting(my_custom_property="foo", **SIGHTING_KWARGS) + stix2.v20.Sighting(my_custom_property="foo", **SIGHTING_KWARGS) - assert excinfo.value.cls == stix2.Sighting + assert excinfo.value.cls == stix2.v20.Sighting assert excinfo.value.properties == ['my_custom_property'] assert str(excinfo.value) == "Unexpected properties for Sighting: (my_custom_property)." def test_create_sighting_from_objects_rather_than_ids(malware): # noqa: F811 - rel = stix2.Sighting(sighting_of_ref=malware) + rel = stix2.v20.Sighting(sighting_of_ref=malware) assert rel.sighting_of_ref == 'malware--00000000-0000-0000-0000-000000000001' assert rel.id == 'sighting--00000000-0000-0000-0000-000000000003' @@ -103,7 +103,7 @@ def test_create_sighting_from_objects_rather_than_ids(malware): # noqa: F811 }, ]) def test_parse_sighting(data): - sighting = stix2.parse(data) + sighting = stix2.parse(data, version="2.0") assert sighting.type == 'sighting' assert sighting.id == SIGHTING_ID diff --git a/stix2/test/v20/test_threat_actor.py b/stix2/test/v20/test_threat_actor.py index 8079a21..85135d3 100644 --- a/stix2/test/v20/test_threat_actor.py +++ b/stix2/test/v20/test_threat_actor.py @@ -22,7 +22,7 @@ EXPECTED = """{ def test_threat_actor_example(): - threat_actor = stix2.ThreatActor( + threat_actor = stix2.v20.ThreatActor( id="threat-actor--8e2e2d2b-17d4-4cbf-938f-98ee46b3cd3f", created_by_ref="identity--f431f809-377b-45e0-aa1c-6a4751cae5ff", created="2016-04-06T20:03:48.000Z", @@ -51,7 +51,7 @@ def test_threat_actor_example(): }, ]) def test_parse_threat_actor(data): - actor = stix2.parse(data) + actor = stix2.parse(data, version="2.0") assert actor.type == 'threat-actor' assert actor.id == THREAT_ACTOR_ID diff --git a/stix2/test/v20/test_tool.py b/stix2/test/v20/test_tool.py index 9fc2c22..6444825 100644 --- a/stix2/test/v20/test_tool.py +++ b/stix2/test/v20/test_tool.py @@ -34,7 +34,7 @@ EXPECTED_WITH_REVOKED = """{ def test_tool_example(): - tool = stix2.Tool( + tool = stix2.v20.Tool( id="tool--8e2e2d2b-17d4-4cbf-938f-98ee46b3cd3f", created_by_ref="identity--f431f809-377b-45e0-aa1c-6a4751cae5ff", created="2016-04-06T20:03:48.000Z", @@ -61,7 +61,7 @@ def test_tool_example(): }, ]) def test_parse_tool(data): - tool = stix2.parse(data) + tool = stix2.parse(data, version="2.0") assert tool.type == 'tool' assert tool.id == TOOL_ID @@ -73,13 +73,13 @@ def test_parse_tool(data): def test_tool_no_workbench_wrappers(): - tool = stix2.Tool(name='VNC', labels=['remote-access']) + tool = stix2.v20.Tool(name='VNC', labels=['remote-access']) with pytest.raises(AttributeError): tool.created_by() def test_tool_serialize_with_defaults(): - tool = stix2.Tool( + tool = stix2.v20.Tool( id="tool--8e2e2d2b-17d4-4cbf-938f-98ee46b3cd3f", created_by_ref="identity--f431f809-377b-45e0-aa1c-6a4751cae5ff", created="2016-04-06T20:03:48.000Z", diff --git a/stix2/test/v20/test_utils.py b/stix2/test/v20/test_utils.py index 885c4d9..3917186 100644 --- a/stix2/test/v20/test_utils.py +++ b/stix2/test/v20/test_utils.py @@ -105,7 +105,7 @@ def test_deduplicate(stix_objs1): @pytest.mark.parametrize('object, tuple_to_find, expected_index', [ - (stix2.ObservedData( + (stix2.v20.ObservedData( id="observed-data--b67d30ff-02ac-498a-92f9-32f845f448cf", created_by_ref="identity--f431f809-377b-45e0-aa1c-6a4751cae5ff", created="2016-04-06T19:58:16.000Z", diff --git a/stix2/test/v20/test_versioning.py b/stix2/test/v20/test_versioning.py index 254090d..faa7009 100644 --- a/stix2/test/v20/test_versioning.py +++ b/stix2/test/v20/test_versioning.py @@ -6,7 +6,7 @@ from .constants import CAMPAIGN_MORE_KWARGS def test_making_new_version(): - campaign_v1 = stix2.Campaign(**CAMPAIGN_MORE_KWARGS) + campaign_v1 = stix2.v20.Campaign(**CAMPAIGN_MORE_KWARGS) campaign_v2 = campaign_v1.new_version(name="fred") @@ -20,7 +20,7 @@ def test_making_new_version(): def test_making_new_version_with_unset(): - campaign_v1 = stix2.Campaign(**CAMPAIGN_MORE_KWARGS) + campaign_v1 = stix2.v20.Campaign(**CAMPAIGN_MORE_KWARGS) campaign_v2 = campaign_v1.new_version(description=None) @@ -34,7 +34,7 @@ def test_making_new_version_with_unset(): def test_making_new_version_with_embedded_object(): - campaign_v1 = stix2.Campaign( + campaign_v1 = stix2.v20.Campaign( external_references=[{ "source_name": "capec", "external_id": "CAPEC-163" @@ -57,7 +57,7 @@ def test_making_new_version_with_embedded_object(): def test_revoke(): - campaign_v1 = stix2.Campaign(**CAMPAIGN_MORE_KWARGS) + campaign_v1 = stix2.v20.Campaign(**CAMPAIGN_MORE_KWARGS) campaign_v2 = campaign_v1.revoke() @@ -72,7 +72,7 @@ def test_revoke(): def test_versioning_error_invalid_property(): - campaign_v1 = stix2.Campaign(**CAMPAIGN_MORE_KWARGS) + campaign_v1 = stix2.v20.Campaign(**CAMPAIGN_MORE_KWARGS) with pytest.raises(stix2.exceptions.UnmodifiablePropertyError) as excinfo: campaign_v1.new_version(type="threat-actor") @@ -81,19 +81,19 @@ def test_versioning_error_invalid_property(): def test_versioning_error_bad_modified_value(): - campaign_v1 = stix2.Campaign(**CAMPAIGN_MORE_KWARGS) + campaign_v1 = stix2.v20.Campaign(**CAMPAIGN_MORE_KWARGS) with pytest.raises(stix2.exceptions.InvalidValueError) as excinfo: campaign_v1.new_version(modified="2015-04-06T20:03:00.000Z") - assert excinfo.value.cls == stix2.Campaign + assert excinfo.value.cls == stix2.v20.Campaign assert excinfo.value.prop_name == "modified" assert excinfo.value.reason == "The new modified datetime cannot be before than or equal to the current modified datetime." \ "It cannot be equal, as according to STIX 2 specification, objects that are different " \ "but have the same id and modified timestamp do not have defined consumer behavior." msg = "Invalid value for {0} '{1}': {2}" - msg = msg.format(stix2.Campaign.__name__, "modified", + msg = msg.format(stix2.v20.Campaign.__name__, "modified", "The new modified datetime cannot be before than or equal to the current modified datetime." "It cannot be equal, as according to STIX 2 specification, objects that are different " "but have the same id and modified timestamp do not have defined consumer behavior.") @@ -101,21 +101,21 @@ def test_versioning_error_bad_modified_value(): def test_versioning_error_usetting_required_property(): - campaign_v1 = stix2.Campaign(**CAMPAIGN_MORE_KWARGS) + campaign_v1 = stix2.v20.Campaign(**CAMPAIGN_MORE_KWARGS) with pytest.raises(stix2.exceptions.MissingPropertiesError) as excinfo: campaign_v1.new_version(name=None) - assert excinfo.value.cls == stix2.Campaign + assert excinfo.value.cls == stix2.v20.Campaign assert excinfo.value.properties == ["name"] msg = "No values for required properties for {0}: ({1})." - msg = msg.format(stix2.Campaign.__name__, "name") + msg = msg.format(stix2.v20.Campaign.__name__, "name") assert str(excinfo.value) == msg def test_versioning_error_new_version_of_revoked(): - campaign_v1 = stix2.Campaign(**CAMPAIGN_MORE_KWARGS) + campaign_v1 = stix2.v20.Campaign(**CAMPAIGN_MORE_KWARGS) campaign_v2 = campaign_v1.revoke() with pytest.raises(stix2.exceptions.RevokeError) as excinfo: @@ -127,7 +127,7 @@ def test_versioning_error_new_version_of_revoked(): def test_versioning_error_revoke_of_revoked(): - campaign_v1 = stix2.Campaign(**CAMPAIGN_MORE_KWARGS) + campaign_v1 = stix2.v20.Campaign(**CAMPAIGN_MORE_KWARGS) campaign_v2 = campaign_v1.revoke() with pytest.raises(stix2.exceptions.RevokeError) as excinfo: @@ -230,8 +230,8 @@ def test_remove_custom_stix_property(): def test_remove_custom_stix_object(): @stix2.CustomObject("x-animal", [ - ("species", stix2.properties.StringProperty(required=True)), - ("animal_class", stix2.properties.StringProperty()), + ("species", stix2.v20.properties.StringProperty(required=True)), + ("animal_class", stix2.v20.properties.StringProperty()), ]) class Animal(object): pass @@ -244,7 +244,7 @@ def test_remove_custom_stix_object(): def test_remove_custom_stix_no_custom(): - campaign_v1 = stix2.Campaign(**CAMPAIGN_MORE_KWARGS) + campaign_v1 = stix2.v20.Campaign(**CAMPAIGN_MORE_KWARGS) campaign_v2 = stix2.utils.remove_custom_stix(campaign_v1) assert len(campaign_v1.keys()) == len(campaign_v2.keys()) diff --git a/stix2/test/v20/test_vulnerability.py b/stix2/test/v20/test_vulnerability.py index e7358df..d2512f2 100644 --- a/stix2/test/v20/test_vulnerability.py +++ b/stix2/test/v20/test_vulnerability.py @@ -23,13 +23,13 @@ EXPECTED = """{ def test_vulnerability_example(): - vulnerability = stix2.Vulnerability( + vulnerability = stix2.v20.Vulnerability( id="vulnerability--0c7b5b88-8ff7-4a4d-aa9d-feb398cd0061", created="2016-05-12T08:17:27.000Z", modified="2016-05-12T08:17:27.000Z", name="CVE-2016-1234", external_references=[ - stix2.ExternalReference(source_name='cve', + stix2.v20.ExternalReference(source_name='cve', external_id="CVE-2016-1234"), ], ) @@ -54,7 +54,7 @@ def test_vulnerability_example(): }, ]) def test_parse_vulnerability(data): - vuln = stix2.parse(data) + vuln = stix2.parse(data, version="2.0") assert vuln.type == 'vulnerability' assert vuln.id == VULNERABILITY_ID