Esempio n. 1
0
class TestUrlHistoryEntry(EntityTestCase, unittest.TestCase):
    klass = URLHistoryEntry

    _full_dict = {
        'url': {
            'value': u('http://www.example.com/index.html'),
            'type': 'URL',
            'xsi:type': 'URIObjectType',
        },
        'hostname': {
            'hostname_value': u('www.example.com'),
            'xsi:type': 'HostnameObjectType',
        },
        'referrer_url': {
            'value': u('http://www.example2.com/index.html'),
            'type': 'URL',
            'xsi:type': 'URIObjectType',
        },
        'page_title': u('An example on URLHistoryEntry'),
        'user_profile_name': u('Default'),
        'visit_count': 5,
        'manually_entered_count': 1,
        'modification_datetime': '2001-01-01T06:56:50+04:00',
        'expiration_datetime': '2001-01-01T06:56:50+04:00',
        'first_visit_datetime': '2001-01-01T06:56:50+04:00',
        'last_visit_datetime': '2001-01-05T06:56:50+04:00',
    }
class TestWinCriticalSection(ObjectTestCase, unittest.TestCase):
    object_type = "WindowsComputerAccountObjectType"
    klass = WinComputerAccount

    _full_dict = {
        'security_id': u("An ID"),
        'type': u("A type"),
        'fully_qualified_name': {
            'netbeui_name': u("A NetBEUI name"),
            'full_name': u("A full name")
        },
        'kerberos': {
            'ticket': long(9000),
            'delegation': {
                'bitmask': "dead1234",
                'service': {
                    'computer': "Computer goes here",
                    'name': "name goes here",
                    'user': "******",
                    'port': {
                        'port_value': 80,
                        'layer4_protocol': 'TCP',
                        'xsi:type': "PortObjectType"
                    }
                }
            }
        },
        'xsi:type': object_type
    }
class TestUDP(EntityTestCase, unittest.TestCase):
    klass = UDP

    _full_dict = {
        'udp_header': {
            'srcport': {
                'port_value': 1664,
                'layer4_protocol': u('UDP'),
                'xsi:type': 'PortObjectType'
            },
            'destport': {
                'port_value': 53,
                'layer4_protocol': u('UDP'),
                'xsi:type': 'PortObjectType'
            },
            'length': 0x18,
            'checksum': u("1fc1"),
        },
        'data': {
            'data_format': "Hex",
            'data_size': {
                "value": u("16"),
                'units': "Bytes"
            },
            'data_segment': u("000102030405060708090a0b0c0d0e0f"),
        }
    }
Esempio n. 4
0
class TestFileSystemFlagList(EntityTestCase, unittest.TestCase):
    klass = FileSystemFlagList

    _full_dict = [
        u('FILE_UNICODE_ON_DISK'),
        u('FILE_CASE_SENSITIVE_SEARCH'),
    ]
Esempio n. 5
0
class TestAction(EntityTestCase, unittest.TestCase):
    klass = Action

    _full_dict = {
        'id':
        "example:Action-1",
        'idref':
        "example:Action-2",
        'ordinal_position':
        42,
        'action_status':
        "Success",
        'context':
        "Host",
        'timestamp':
        "2013-10-24T09:54:13",
        'type':
        u("Modify"),
        'name':
        u("Modify File"),
        'description': {
            'value': "An action!",
            'structuring_format': "Text"
        },
        'action_aliases': ['an alias', 'another_alias'],
        'action_arguments': [{
            'argument_name': u("infile"),
            'argument_value': "/tmp/somefile.txt",
        }, {
            'argument_name': u("outfile"),
            'argument_value': "/tmp/someotherfile.txt",
        }],
        'discovery_method': {
            'name': "A tool"
        },
        'associated_objects': [{
            'idref': "example:File-1",
        }],
        'relationships': [{
            'type':
            u("Followed_By"),
            'action_reference': [{
                'action_id': "example:Action-2"
            }]
        }],
        'frequency': {
            'rate': 1.0
        },
    }

    # Test that should be fixed by
    # https://github.com/CybOXProject/python-cybox/pull/236
    def test_tzinfo_copy(self):
        action = Action()
        action.timestamp = "2015-03-28T16:39:28.127296+03:00"
        action_xml = action.to_xml(encoding=None)

        action2 = Action.from_obj(parseString(action_xml))
        action2_copy = copy.deepcopy(action2)
        self.assertEqual(action_xml, action2_copy.to_xml(encoding=None))
Esempio n. 6
0
class TestPESection(EntityTestCase, unittest.TestCase):
    klass = PESection

    _full_dict = {
        'section_header':
        TestPESectionHeaderStruct._full_dict,
        'data_hashes': [
            {
                'type': u("MD5"),
                'simple_hash_value': EMPTY_MD5
            },
        ],
        'entropy':
        TestEntropy._full_dict,
        'header_hashes': [
            {
                'type': u("MD5"),
                'simple_hash_value': EMPTY_MD5
            },
            {
                'type': u("MD5"),
                'simple_hash_value': EMPTY_MD5
            },
        ],
    }
Esempio n. 7
0
class TestExtractedFeatures(EntityTestCase, unittest.TestCase):
    klass = ExtractedFeatures

    _full_dict = {
        'strings': [
            {
                'encoding': u("ASCII"),
                'string_value': u("A String"),
                'length': 8
            },
            {
                'encoding': u("UTF-8"),
                'string_value': u("Another String")
            },
        ],
        'imports': [u("CreateFileA"), u("LoadLibrary")],
        'functions': [u("DoSomething"), u("DoSomethingElse")],
        #TODO: Use CodeObject instead of AddressObject
        'code_snippets': [
            {
                'address_value': u("8.8.8.8"),
                'category': Address.CAT_IPV4,
                'xsi:type': "AddressObjectType"
            },
            {
                'address_value': u("1.2.3.4"),
                'category': Address.CAT_IPV4,
                'xsi:type': "AddressObjectType"
            },
        ],
    }
Esempio n. 8
0
class TestWinMemoryPageRegion(ObjectTestCase, unittest.TestCase):
    object_type = "WindowsMemoryPageRegionObjectType"
    klass = WinMemoryPageRegion

    _full_dict = {
        'is_injected': True,
        'is_mapped': False,
        'is_protected': True,
        'is_volatile': False,
        'name': u("A page region"),
        'memory_source': u("A source"),
        'region_size': long(10000),
        'block_type': u("A block type"),
        'region_start_address': u("1234abcde"),
        'region_end_address': u("1234abdde"),
        'allocation_base_address': u("1234abbbe"),
        'type': u("A type"),
        'allocation_protect': u("allocate protection"),
        'state': u("A state"),
        'protect': u("protection"),
        # TODO: add:
        # - 'extracted_features'
        # - 'hashes'
        'xsi:type': object_type,
    }
Esempio n. 9
0
class TestWinEvent(ObjectTestCase, unittest.TestCase):
    object_type = "WindowsEventObjectType"
    klass = WinEvent

    _full_dict = {
        'name': u("Object Open"),
        'handle': {
            'name': u("Event Handle"),
            'type': u("Event"),
            'xsi:type': "WindowsHandleObjectType",
        },
        'type': u("Success"),
        'xsi:type': "WindowsEventObjectType",
    }

    # https://github.com/CybOXProject/python-cybox/issues/213
    def test_object_construction(self):
        event = WinEvent()
        event.name = "Object Open"
        event.type_ = "Success"

        # Before #213 was solved, these would raise exceptions because the
        # `type_` was called `type`
        d = event.to_dict()  # Should not raise.
        self.assertEqual("Success", d['type'])
        o = event.to_xml()  # Should not raise.
        self.assertTrue(b"Success" in o)
Esempio n. 10
0
class ObjectTest(EntityTestCase, unittest.TestCase):
    klass = Object

    _full_dict = {
        'id':
        "example:Object-1",
        'properties': {
            'file_name': u("example.txt"),
            'xsi:type': "FileObjectType"
        },
        'related_objects': [
            {
                'idref': "example:Object-2",
                'relationship': u("Same As"),
            },
        ],
    }

    def test_id_autoset(self):
        o = Object()
        self.assertNotEqual(o.id_, None)

    def test_id_prefix(self):
        a = Address()
        o = Object(a)
        self.assertTrue("Address" in o.id_)

    def test_round_trip(self):
        o = Object()
        o.idref = "example:a1"
        o.properties = Address("1.2.3.4", Address.CAT_IPV4)
        o2 = round_trip(o)

        self.assertEqual(o.to_dict(), o2.to_dict())
Esempio n. 11
0
class TestWinNetworkShare(ObjectTestCase, unittest.TestCase):
    object_type = "WindowsNetworkShareObjectType"
    klass = WinNetworkShare

    _full_dict = {
        'access_read': True,
        'access_write': False,
        'access_create': True,
        'access_exec': False,
        'access_delete': True,
        'access_atrib': False,
        'access_perm': True,
        'access_all': False,
        'current_uses': 1,
        'local_path': u("Z:/"),
        'max_uses': 10,
        'netname': u("shared drive"),
        'type': u("Folder"),
        'xsi:type': object_type,
    }

    # https://github.com/CybOXProject/python-cybox/issues/267
    def test_type(self):
        share = WinNetworkShare()
        share.type_ = "STREE_DISKTREE"
        self.assertTrue(b"STREE_DISKTREE" in share.to_xml())
Esempio n. 12
0
class TestSiLKRecord(EntityTestCase, unittest.TestCase):
    klass = SiLKRecord

    _full_dict = {
        'packet_count': 55,
        'byte_count': 12800,
        'tcp_flags': u('B9'),
        'start_time': 1582060823,
        'duration': 100,
        'end_time': 1582060923,
        'sensor_info': TestSiLKSensorInfo._full_dict,
        'icmp_type': 6,
        'icmp_code': 2,
        'router_next_hop_ip': TestAddress._full_dict,
        'initial_tcp_flags': TestTCPFlags._full_dict,
        'session_tcp_flags': u('3'),
        'flow_attributes': u(SiLKFlowAttributes.TERM_F),
        'flow_application': u('My Flow Application'),
        'src_ip_type': u(SiLKAddress.TERM_INTERNAL),
        'dest_ip_type': u(SiLKAddress.TERM_EXTERNAL),
        'src_country_code': u('US'),
        'dest_country_code': u('US'),
        'src_mapname': u('some value1'),
        'dest_mapname': u('some value2'),
    }
Esempio n. 13
0
class TestLayer7Connections(EntityTestCase, unittest.TestCase):
    klass = Layer7Connections

    _full_dict = {
        'http_session': {
            'object_reference': "example:ABC-1",
            'xsi:type': "HTTPSessionObjectType",
        },
        'dns_query': [
            {
                'question': {
                    'qname': {
                        'value': u("www.example.com"),
                        'xsi:type': "URIObjectType",
                    },
                    'qtype': u("A"),
                    'qclass': u("IN"),
                },
                'successful': True,
                'xsi:type': "DNSQueryObjectType",
            },
            {
                'question': {
                    'qname': {
                        'value': u("www.example2.com"),
                        'xsi:type': "URIObjectType",
                    },
                    'qtype': u("CNAME"),
                },
                'successful': False,
                'xsi:type': "DNSQueryObjectType",
            },
        ]
    }
Esempio n. 14
0
class TestSocketOptions(EntityTestCase, unittest.TestCase):
    klass = SocketOptions

    _full_dict = {
        'ip_multicast_if': u("eth1"),  # Should probably be a boolean
        'ip_multicast_if2': u("wlan0"),  # Should probably be a boolean
        'ip_multicast_loop': False,
        'ip_tos': u("true"),  # Should probably be a boolean
        'so_broadcast': False,
        'so_conditional_accept': True,
        'so_keepalive': False,
        'so_dontroute': True,
        'so_linger': 17,  # Should probably be a boolean
        'so_dontlinger': True,
        'so_oobinline': False,
        'so_rcvbuf': 44,  # Should probably be a boolean
        'so_group_priority': 19,
        'so_reuseaddr': True,
        'so_debug': False,
        'so_rcvtimeo': 42,  # Should this allow both seconds and microseconds?
        'so_sndbuf': 1000,
        'so_sndtimeo': 22,  # Should this allow both seconds and microseconds?
        'so_update_accept_context': 3,  # Should probably be a boolean
        'so_timeout': 99,
        'tcp_nodelay': False,
    }
Esempio n. 15
0
class TestProcess(ObjectTestCase, unittest.TestCase):
    object_type = "ProcessObjectType"
    klass = Process

    _full_dict = {
        'pid': 512,
        'name': u('testproc'),
        'creation_time': '2001-01-01T06:56:50+04:00',
        'parent_pid': 1024,
        'child_pid_list': TestChildPIDList._full_dict,
        'image_info': TestImageInfo._full_dict,
        'argument_list': TestArgumentList._full_dict,
        'environment_variable_list': [
            {
                'name': 'TEMP',
                'value': 'C:/TEMP'
            },
        ],
        'kernel_time': u('293457969'),
        'port_list': TestPortList._full_dict,
        'network_connection_list': TestNetworkConnectionList._full_dict,
        'start_time': '2001-01-01T06:56:50+04:00',
        'username': u('jondoe'),
        'user_time': u('120'),
        # 'extracted_features': '',
        'is_hidden': True,
        'xsi:type': object_type,
    }
Esempio n. 16
0
class TestToolInformation(EntityTestCase, unittest.TestCase):
    klass = ToolInformation

    _full_dict = {
        'id':
        "example:Tool-A1",
        # 'idref': "example:Tool-A1-ref",  # CAnnot set both an id and idref
        'name':
        "AwesomeTool(tm)",
        'type': [{
            'value': u('NIDS'),
            'xsi:type': 'cyboxVocabs:ToolTypeVocab-1.1'
        }, {
            'value': u('HIPS'),
            'xsi:type': 'cyboxVocabs:ToolTypeVocab-1.1'
        }],
        'description': {
            'structuring_format': 'HTML',
            'value': '<p>An awesome tool!</p>'
        },
        'vendor':
        "Awesome Co.",
        'version':
        "1.0.0",
        'service_pack':
        'N/A',
        'tool_hashes': [{
            'simple_hash_value': EMPTY_MD5,
            'type': Hash.TYPE_MD5
        }],
    }
Esempio n. 17
0
class TestDisk(ObjectTestCase, unittest.TestCase):
    object_type = "DiskObjectType"
    klass = Disk

    _full_dict = {
        'disk_name':
        u("A disk"),
        'disk_size':
        12345678,
        'free_space':
        1234567,
        'partition_list': [
            {
                'device_name': u("A partition"),
                'xsi:type': "DiskPartitionObjectType",
            },
            {
                'device_name': u("B partition"),
                'xsi:type': "DiskPartitionObjectType",
            },
        ],
        'type':
        u("Fixed"),
        'xsi:type':
        object_type,
    }

    # https://github.com/CybOXProject/python-cybox/issues/267
    def test_type(self):
        disk = Disk()
        disk.type_ = "Fixed"
        self.assertTrue(b"Fixed" in disk.to_xml())
Esempio n. 18
0
class WhoisEntry(ObjectProperties):
    _binding = whois_binding
    _binding_class = whois_binding.WhoisObjectType
    _namespace = "http://cybox.mitre.org/objects#WhoisObject-2"
    _XSI_NS = 'WhoisObj'
    _XSI_TYPE = 'WhoisObjectType'

    lookup_date = fields.TypedField("Lookup_Date", DateTime)
    remarks = fields.TypedField("Remarks", String)
    contact_info = fields.TypedField("Contact_Info", WhoisContact)
    domain_name = fields.TypedField("Domain_Name", URI)
    domain_id = fields.TypedField("Domain_ID", String)
    server_name = fields.TypedField("Server_Name", URI)
    ip_address = fields.TypedField("IP_Address", Address)
    dnssec = fields.TypedField("DNSSEC")
    nameservers = fields.TypedField("Nameservers", WhoisNameservers)
    status = fields.TypedField("Status", WhoisStatuses)
    updated_date = fields.TypedField("Updated_Date", Date)
    creation_date = fields.TypedField("Creation_Date", Date)
    expiration_date = fields.TypedField("Expiration_Date", Date)
    regional_internet_registry = fields.TypedField(
        "Regional_Internet_Registry", String)
    sponsoring_registrar = fields.TypedField("Sponsoring_Registrar", String)
    registrar_info = fields.TypedField("Registrar_Info", WhoisRegistrar)
    registrants = fields.TypedField("Registrants", WhoisRegistrants)

    DNSSEC_SIGNED = u("Signed")
    DNSSEC_UNSIGNED = u("Unsigned")
Esempio n. 19
0
class TestNetworkRoute(ObjectTestCase, unittest.TestCase):
    object_type = "NetRouteObjectType"
    klass = NetRoute

    _full_dict = {
        'is_ipv6':
        False,
        'is_autoconfigure_address':
        True,
        'is_immortal':
        False,
        'is_loopback':
        False,
        'is_publish':
        True,
        'description':
        "A description",
        'preferred_lifetime':
        u("P10D"),
        'valid_lifetime':
        u("P5D"),
        'route_age':
        u("P1D"),
        'network_route_entries': [
            TestNetworkRouteEntry._full_dict,
            TestNetworkRouteEntry._full_dict,
        ],
        'xsi:type':
        object_type,
    }
Esempio n. 20
0
class TestPacker(EntityTestCase, unittest.TestCase):
    klass = Packer

    _full_dict = {
        'name':
        u("CrazyPack"),
        'version':
        u("2.0.1"),
        'entry_point':
        u("EB0FA192"),
        'signature':
        u("xxCrAzYpAcKxx"),
        'type':
        u("Protector"),
        'ep_jump_codes': {
            'depth': 2,
            'opcodes': u("A B C")
        },
        'detected_entrypoint_signatures': [{
            'name': u("test 1"),
            'type': u('type 1')
        }, {
            'name': u("test 2"),
            'type': u('type 2')
        }],
    }
class TestX509CertificateSignature(EntityTestCase, unittest.TestCase):
    klass = X509CertificateSignature

    _full_dict = {
        'signature_algorithm': u('sha1WithRSAEncryption'),
        'signature': u('79:11:c0:4b:b3:91:b6:fc:f0:e9:67:d4:0d:6e:45:be:55:e8:93:d2:ce:03:3f:ed:da:25:b0:1d:57:cb:1e:3a:76:a0:4c:ec:50:76:e8:64:72:0c:a4:a9:f1:b8:8b:d6:d6:87:84:bb:32:e5:41:11:c0:77:d9:b3:60:9d:eb:1b:d5:d1:6e:44:44:a9:a6:01:ec:55:62:1d:77:b8:5c:8e:48:49:7c:9c:3b:57:11:ac:ad:73:37:8e:2f:78:5c:90:68:47:d9:60:60:e6:fc:07:3d:22:20:17:c4:f7:16:e9:c4:d8:72:f9:c8:73:7c:df:16:2f:15:a9:3e:fd:6a:27:b6:a1:eb:5a:ba:98:1f:d5:e3:4d:64:0a:9d:13:c8:61:ba:f5:39:1c:87:ba:b8:bd:7b:22:7f:f6:fe:ac:40:79:e5:ac:10:6f:3d:8f:1b:79:76:8b:c4:37:b3:21:18:84:e5:36:00:eb:63:20:99:b9:e9:fe:33:04:bb:41:c8:c1:02:f9:44:63:20:9e:81:ce:42:d3:d6:3f:2c:76:d3:63:9c:59:dd:8f:a6:e1:0e:a0:2e:41:f7:2e:95:47:cf:bc:fd:33:f3:f6:0b:61:7e:7e:91:2b:81:47:c2:27:30:ee:a7:10:5d:37:8f:5c:39:2b:e4:04:f0:7b:8d:56:8c:68'),
    }
Esempio n. 22
0
class TestSiLKSensorInfo(EntityTestCase, unittest.TestCase):
    klass = SiLKSensorInfo

    _full_dict = {
        'sensor_id': u('2349'),
        'class': u(SiLKSensorClass.TERM_ALL),
        'type': u(SiLKSensorDirection.TERM_IN),
    }
Esempio n. 23
0
class TestPEExportedFunction(EntityTestCase, unittest.TestCase):
    klass = PEExportedFunction

    _full_dict = {
        'function_name': u('important_calculation'),
        'entry_point': u('0x000ECB99'),
        'ordinal': 1,
    }
class TestX509V3Extensions(EntityTestCase, unittest.TestCase):
    klass = X509V3Extensions

    _full_dict = {
        'basic_constraints': u('CA:TRUE'),
        'key_usage':  u('Certificate Sign, CRL Sign'),
        'subject_key_identifier': u('7B:5B:45:CF:AF:CE:CB:7A:FD:31:92:1A:6A:B6:F3:46:EB:57:48:50')
    }
Esempio n. 25
0
class TestServiceDescriptionList(EntityTestCase, unittest.TestCase):
    klass = ServiceDescriptionList

    _full_dict = [
        u('Provides infrastructure support for deploying Store applications. This service is started on demand and if disabled Store applications will not be deployed to the system, and may not function properly.'
          ),
        u('Description 2'),
    ]
Esempio n. 26
0
class TestPEBuildInformation(EntityTestCase, unittest.TestCase):
    klass = PEBuildInformation

    _full_dict = {
        'linker_name': u('lld'),
        'linker_version': u('11'),
        'compiler_name': u('GNU GCC'),
        'compiler_version': u('7.8.4'),
    }
class TestX509NonStandardExtensions(EntityTestCase, unittest.TestCase):
    klass = X509NonStandardExtensions

    _full_dict = {
        'netscape_comment': u('some netscape comment'),
        'netscape_certificate_type': u('cert type'),
        'old_authority_key_identifier': u('CE:CB'),
        'old_primary_key_attributes': u('CA:TRUE'),
    }
Esempio n. 28
0
class TestGUIDialogbox(ObjectTestCase, unittest.TestCase):
    object_type = "GUIDialogboxObjectType"
    klass = GUIDialogbox

    _full_dict = {
        'box_caption': u('Sample caption'),
        'box_text': u('Sample text'),
        'xsi:type': object_type,
    }
Esempio n. 29
0
class TestIPFIXDataRecord(EntityTestCase, unittest.TestCase):
    klass = IPFIXDataRecord

    _full_dict = {
        'field_value': [
            u('value1'),
            u('value2'),
        ]
    }
Esempio n. 30
0
class TestNetflowV9TemplateRecord(EntityTestCase, unittest.TestCase):
    klass = NetflowV9TemplateRecord

    _full_dict = {
        'template_id': 2345,
        'field_count': 110,
        'field_type': u(NetflowV9Field.TERM_IN_BYTES),
        'field_length': u('FF'),
    }
Esempio n. 31
0
    def test_set_data_and_packed_data(self):
        a = Artifact()
        self.assertEqual(a.data, None)
        self.assertEqual(a.packed_data, None)

        a.data = b"Blob"
        self.assertRaises(ValueError, _set_packed_data, a, u("blob"))
        a.data = None

        a.packed_data = u("Blob")
        self.assertRaises(ValueError, _set_data, a, b"blob")
        a.packed_data = None
Esempio n. 32
0
    def test_xsi_type_unicode(self):
        string = u("test\u2010value")
        vocab_dict = {
                        'value': string,
                        'condition': u("Equals"),
                        'xsi:type': u("some_xsi_type"),
                     }

        vocab_dict2 = cybox.test.round_trip_dict(VocabString, vocab_dict)
        self.assertEqual(vocab_dict, vocab_dict2)
        xml = VocabString.from_dict(vocab_dict).to_xml()
        string_utf8 = string.encode("utf-8")
        self.assertTrue(string_utf8 in xml)
Esempio n. 33
0
    def test_correct_namespace_output(self):
        link = Link()
        link.value = u("https://www.example.com")

        xml = Observables(link).to_xml()
        self.assertTrue(b"cybox:Properties" in xml)
        self.assertTrue(b"LinkObj:Properties" not in xml)
Esempio n. 34
0
 def test_nonstandard_type_vocab(self):
     ar = ActionRelationship()
     ar.type = VocabString(u("AddedMultipleTimes"))
     ar.type.vocab_reference = "http://example.com/action-types/"
     ar.type.xsi_type = None
     ar2 = round_trip(ar)
     self.assertEqual(ar.to_dict(), ar2.to_dict())
Esempio n. 35
0
 def test_string_type(self):
     # We are technically testing different things here in Python 2 and
     # Python 3, but in both cases a string (byte string or unicode string)
     # should not be a "sequence" by our definition.
     self.assertFalse(is_sequence(""))
     self.assertFalse(is_sequence(six.u("")))
     self.assertFalse(is_sequence(six.b("")))
Esempio n. 36
0
    def test_xml_output(self):
        # A RawArtifact stores a Unicode string, even though it typically
        # consists only of valid Base64 characters.
        data = u("0123456789abcdef")
        ra = RawArtifact(data)

        expected_data = data.encode('utf-8')
        self.assertTrue(expected_data in ra.to_xml())
Esempio n. 37
0
    def test_unicode_string(self):
        s = u("A Unicode \ufffd string")
        string = String(s)

        unicode_string = six.text_type(string)
        self.assertEqual(s, unicode_string)
        self.assertEqual(s.encode("utf-8"), unicode_string.encode("utf-8"))
        self.assertTrue(s.encode("utf-8") in string.to_xml())
Esempio n. 38
0
 def test_relationship_nonstandard_xsitype(self):
     d = {
         'id': "example:Object-1",
         'relationship': {
             'value': u("Created"),
             'xsi:type': "Foo",
         }
     }
     self._test_round_trip_dict(d)
Esempio n. 39
0
    def test_cannot_set_nonascii_artifact_packed_data(self):
        a = Artifact()
        a.packed_data = u("\x00abc123\xff")
        self.assertEqual(six.text_type, type(a.packed_data))

        #TODO: Should this raise an error sooner, since there's nothing we can
        # do at this point? There's no reason that the packed_data should
        # contain non-ascii characters.
        self.assertRaises(UnicodeEncodeError, _get_data, a)
Esempio n. 40
0
 def test_relationship_vocabnameref(self):
     d = {
         'id': "example:Object-1",
         'relationship': {
             'value': u("Created"),
             'vocab_name': "Foo",
             'vocab_reference': "http://example.com/FooVocab",
         }
     }
     self._test_round_trip_dict(d)
 def test_object_reference(self, ref_dict=None):
     # We have to put at least some content in here, since at least one
     # HTTPRequestResponse is required by the bindings for the round trip.
     sess_dict = {
         'http_request_response': [{
                 'http_client_request': {
                     'http_request_line': {'http_method': u("GET")}
                 }
         }]
     }
     ObjectTestCase.test_object_reference(self, sess_dict)
Esempio n. 42
0
    def test_issue_227_binding_init(self):
        # Fax_Number and Organization were added to the __init__ method of
        # WhoisContactType, but not to its subclass (WhoisRegistrantType). Once
        # the objects are constructed, they should have equivalent dictionary
        # represesntations (as long as the extra fields in the subclass are not
        # present).
        contact_obj = WhoisContactType(
            contact_type="ADMIN",
            Contact_ID=StringObjectPropertyType(valueOf_="abc123"),
            Fax_Number=StringObjectPropertyType(valueOf_=u("(800) 555-1200")),
            Organization=StringObjectPropertyType(valueOf_=u("XYZ Hosting")),
        )
        contact = WhoisContact.from_obj(contact_obj)

        reg_obj = WhoisRegistrantInfoType(
            contact_type="ADMIN",
            Contact_ID=StringObjectPropertyType(valueOf_="abc123"),
            Fax_Number=StringObjectPropertyType(valueOf_=u("(800) 555-1200")),
            Organization=StringObjectPropertyType(valueOf_=u("XYZ Hosting")),
        )
        registrant = WhoisRegistrant.from_obj(reg_obj)

        self.assertEqual(contact.to_dict(), registrant.to_dict())
 def test_unicode(self):
     unicode_uri = u("www.\u0395\u03a7\u0391\u039c\u03a1LE.com")
     uri = URI(unicode_uri, URI.TYPE_DOMAIN)
     uri2 = cybox.test.round_trip(uri)
     self.assertEqual(uri.to_dict(), uri2.to_dict())
Esempio n. 44
0
 def test_quote_attrib_none(self):
     i = None
     s = quote_attrib(i)
     self.assertEqual(u('""'), s)
Esempio n. 45
0
 def test_setting_ascii_artifact_packed_data_no_packaging(self):
     a = Artifact()
     a.packed_data = u("abc123")
     self.assertEqual(six.binary_type, type(a.data))
     self.assertEqual(six.text_type, type(a.packed_data))
Esempio n. 46
0
 def test_relationship_standard_xsitype(self):
     d = {
         'id': "example:Object-1",
         'relationship': u("Created"),
     }
     self._test_round_trip_dict(d)
Esempio n. 47
0
# -*- coding: utf-8 -*-
# Copyright (c) 2015, The MITRE Corporation. All rights reserved.
# See LICENSE.txt for complete terms.

"""Tests for binding_utils"""

import unittest

from mixbox.vendor import six
from mixbox.vendor.six import u

from mixbox.binding_utils import quote_attrib, quote_xml

UNICODE_STR = u("❤ ♎ ☀ ★ ☂ ♞ ☯ ☭ ☢ €☎⚑ ❄♫✂")


class EncodingTests(unittest.TestCase):

    def test_quote_xml(self):
        s = quote_xml(UNICODE_STR)
        self.assertEqual(s, UNICODE_STR)

    def test_quote_attrib(self):
        """Tests that the quote_attrib method works properly on Unicode inputs.

        Note:
            The quote_attrib method (more specifically, saxutils.quoteattr())
            adds quotation marks around the input data, so we need to strip
            the leading and trailing chars to test effectively
        """
        s = quote_attrib(UNICODE_STR)
Esempio n. 48
0
 def test_cannot_create_artifact_from_unicode_data(self):
     self.assertRaises(ValueError, Artifact, u("abc123"))
Esempio n. 49
0
 def test_quote_attrib_int(self):
     i = 65536
     s = quote_attrib(i)
     self.assertEqual(u('"65536"'), s)
Esempio n. 50
0
# Copyright (c) 2015, The MITRE Corporation. All rights reserved.
# See LICENSE.txt for complete terms.

import logging
import unittest

from mixbox.vendor.six import u

from cybox.common import Hash, HashList, HashName, HexBinary
import cybox.test

logger = logging.getLogger(__name__)

EMPTY_MD5 = u("d41d8cd98f00b204e9800998ecf8427e")
EMPTY_SHA1 = u("da39a3ee5e6b4b0d3255bfef95601890afd80709")
EMPTY_SHA224 = u("d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f")
EMPTY_SHA256 = \
        u("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")
EMPTY_SHA384 = u(
        "38b060a751ac96384cd9327eb1b1e36a21fdb71114be0743"
        "4c0cc7bf63f6e1da274edebfe76f65fbd51ad2f14898b95b")
EMPTY_SHA512 = u(
        "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce"
        "47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e")

TEST_HASH_LIST = [
    {'simple_hash_value': EMPTY_MD5,
        'type': Hash.TYPE_MD5},
    {'simple_hash_value': EMPTY_SHA1,
        'type': Hash.TYPE_SHA1},
    {'simple_hash_value': EMPTY_SHA224,
Esempio n. 51
0
 def test_quote_attrib_bool(self):
     b = True
     s = quote_attrib(b)
     self.assertEqual(u('"True"'), s)
Esempio n. 52
0
 def test_list_of_strings_with_comma(self):
     s = String([u("string,1"), u("string,1"), u("string,3")])
     s2 = cybox.test.round_trip(s)
     self.assertEqual(s, s2)
Esempio n. 53
0
 def test_quote_attrib_zero(self):
     i = 0
     s = quote_attrib(i)
     self.assertEqual(u('"0"'), s)
Esempio n. 54
0
 def test_quote_xml_none(self):
     i = None
     s = quote_xml(i)
     self.assertEqual(u(''), s)
Esempio n. 55
0
 def test_quote_xml_empty(self):
     i = ''
     s = quote_xml(i)
     self.assertEqual(u(''), s)
Esempio n. 56
0
 def test_unicode(self):
     a = u("\u00fc\u00f1\u00ed\[email protected]")
     addr = Address(a, Address.CAT_EMAIL)
     addr2 = cybox.test.round_trip(addr)
     self.assertEqual(addr.to_dict(), addr2.to_dict())
Esempio n. 57
0
"""Tests for various encoding issues throughout the library"""

import unittest

from mixbox.vendor import six
from mixbox.vendor.six import u

from cybox.common import Contributor, String, MeasureSource
from cybox.core import Observable
from cybox.objects.code_object import Code, CodeSegmentXOR
from cybox.objects.whois_object import WhoisEntry
from cybox.test import round_trip

#UNICODE_STR = six.u("❤ ♎ ☀ ★ ☂ ♞ ☯ ☭ ☢ €☎⚑ ❄♫✂")
if six.PY2:
    UNICODE_STR = u(r'\u2764 \u264e \u2600 \u2605 \u2602 \u265e \u262f \
        \u262d \u2622 \u20ac\u260e\u2691 \u2744\u266b\u2702')
else:
    UNICODE_STR = '\u2764 \u264e \u2600 \u2605 \u2602 \u265e \u262f \
        \u262d \u2622 \u20ac\u260e\u2691 \u2744\u266b\u2702'

class EncodingTests(unittest.TestCase):

    def test_double_encode(self):
        s = String(UNICODE_STR)
        s2 = round_trip(s)

    def test_contributor(self):
        c = Contributor()
        c.name = UNICODE_STR
        c.role = UNICODE_STR
        c.email = UNICODE_STR
# Copyright (c) 2017, The MITRE Corporation. All rights reserved.
# See LICENSE.txt for complete terms.

import binascii
import unittest

from mixbox.vendor import six
from mixbox.vendor.six import u

from cybox.common import ExtractedString, Hash
from cybox.test import EntityTestCase

STRING = u("This is a string")
HEX_STRING = six.text_type(binascii.hexlify(STRING.encode("ascii")))

class TestExtractedString(EntityTestCase, unittest.TestCase):
    klass = ExtractedString

    _full_dict = {
        'encoding': u("UTF-8"),
        'string_value': STRING,
        'byte_string_value': HEX_STRING,
        'hashes': [{'type': Hash.TYPE_MD5}],
        'address': u("1a2b"),
        'length': len(STRING),
        'language': u("English"),
        'english_translation': STRING,
    }


if __name__ == "__main__":
Esempio n. 59
0
 def test_quote_attrib_empty(self):
     i = ''
     s = quote_attrib(i)
     self.assertEqual(u('""'), s)