Ejemplo n.º 1
0
    def test_encryption(self):
        a = Artifact(self.binary_data)
        a.packaging = Packaging()
        a.packaging.encryption.append(XOREncryption(0x4a))
        a.packaging.encoding.append(Base64Encoding())
        a2 = round_trip(a, Artifact)

        self.assertEqual(self.binary_data, a2.data)
Ejemplo n.º 2
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)
Ejemplo n.º 3
0
    def test_base64_encoding(self):
        a = Artifact(self.binary_data)
        a.packaging = Packaging()
        a.packaging.encoding.append(Base64Encoding())
        a2 = round_trip(a, Artifact)
        self.assertEqual(self.binary_data, a2.data)

        expected = b64encode(self.binary_data).decode('ascii')
        self.assertEqual(expected, a2.packed_data)
Ejemplo n.º 4
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)
Ejemplo n.º 5
0
    def test_zlib_base64_encoding(self):
        a = Artifact(self.binary_data)
        a.packaging = Packaging()
        a.packaging.compression.append(ZlibCompression())
        a.packaging.encoding.append(Base64Encoding())
        a2 = round_trip(a, Artifact)
        self.assertEqual(self.binary_data, a2.data)

        expected = base64.b64encode(compress(self.binary_data)).decode('ascii')
        self.assertEqual(expected, a2.packed_data)
Ejemplo n.º 6
0
 def create_artifact_object(self, attribute, artifact=None):
     try:
         artifact = Artifact(data=bytes(attribute.data, encoding='utf-8'))
     except TypeError:
         artifact = Artifact(data=bytes(attribute.data))
     artifact.parent.id_ = "{}:ArtifactObject-{}".format(self.namespace_prefix, attribute.uuid)
     observable = Observable(artifact)
     id_type = "observable"
     if artifact is not None:
         id_type += "-artifact"
     observable.id_ = "{}:{}-{}".format(self.namespace_prefix, id_type, attribute.uuid)
     return observable
Ejemplo n.º 7
0
    def test_set_data_and_packed_data(self):
        a = Artifact()
        self.assertEqual(a.data, None)
        self.assertEqual(a.packed_data, None)

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

        a.packed_data = "Blob"
        self.assertRaises(ValueError, _set_data, a, "blob")
        a.packed_data = None
Ejemplo n.º 8
0
    def test_cannot_set_nonascii_data_with_no_packaging(self):
        a = Artifact()
        # You can set this data, but if you don't add any packaging, you should
        # get an error when trying to get the packed data, since it can't be
        # encoded as ASCII.
        a.data = b"\x00abc123\xff"
        self.assertEqual(six.binary_type, type(a.data))
        self.assertRaises(ValueError, _get_packed_data, a)

        # With Base64 encoding, we can retrieve this.
        a.packaging.append(Base64Encoding())
        self.assertEqual("AGFiYzEyM/8=", a.packed_data)
Ejemplo n.º 9
0
    def test_cannot_set_nonascii_data_with_no_packaging(self):
        a = Artifact()
        # You can set this data, but if you don't add any packaging, you should
        # get an error when trying to get the packed data, since it can't be
        # encoded as ASCII.
        a.data = b"\x00abc123\xff"
        self.assertEqual(six.binary_type, type(a.data))
        self.assertRaises(ValueError, _get_packed_data, a)

        # With Base64 encoding, we can retrieve this.
        a.packaging.append(Base64Encoding())
        self.assertEqual("AGFiYzEyM/8=", a.packed_data)
Ejemplo n.º 10
0
def returnAttachmentComposition(attribute):
    file_object = File()
    file_object.file_name = attribute["value"]
    file_object.parent.id_ = cybox.utils.idgen.__generator.namespace.prefix + ":FileObject-" + attribute[
        "uuid"]
    observable = Observable()
    if "data" in attribute:
        artifact = Artifact(data=attribute["data"])
        artifact.parent.id_ = cybox.utils.idgen.__generator.namespace.prefix + ":ArtifactObject-" + attribute[
            "uuid"]
        observable_artifact = Observable(artifact)
        observable_artifact.id_ = cybox.utils.idgen.__generator.namespace.prefix + ":observable-artifact-" + attribute[
            "uuid"]
        observable_file = Observable(file_object)
        observable_file.id_ = cybox.utils.idgen.__generator.namespace.prefix + ":observable-file-" + attribute[
            "uuid"]
        composition = ObservableComposition(
            observables=[observable_artifact, observable_file])
        observable.observable_composition = composition
    else:
        observable = Observable(file_object)
    observable.id_ = cybox.utils.idgen.__generator.namespace.prefix + ":observable-" + attribute[
        "uuid"]
    if attribute["comment"] != "":
        observable.description = attribute["comment"]
    return observable
Ejemplo n.º 11
0
    def to_cybox(self, exclude=None):
        if exclude == None:
            exclude = []

        observables = []
        f = File()
        for attr in ['md5', 'sha1', 'sha256']:
            if attr not in exclude:
                val = getattr(self, attr, None)
                if val:
                    setattr(f, attr, val)
        if self.ssdeep and 'ssdeep' not in exclude:
            f.add_hash(Hash(self.ssdeep, Hash.TYPE_SSDEEP))
        if 'size' not in exclude and 'size_in_bytes' not in exclude:
            f.size_in_bytes = UnsignedLong(self.size)
        if 'filename' not in exclude and 'file_name' not in exclude:
            f.file_name = self.filename
        # create an Artifact object for the binary if it exists
        if 'filedata' not in exclude:
            data = self.filedata.read()
            if data:
                data = base64.b64encode(data)
                a = Artifact(data=data, type_=Artifact.TYPE_FILE)
                observables.append(Observable(a))
        #if 'filetype' not in exclude and 'file_format' not in exclude:
        #NOTE: this doesn't work because the CybOX File object does not
        #   have any support built in for setting the filetype to a
        #   CybOX-binding friendly object (e.g., calling .to_dict() on
        #   the resulting CybOX object fails on this field.
        #f.file_format = self.filetype
        observables.append(Observable(f))
        return (observables, self.releasability)
Ejemplo n.º 12
0
    def to_cybox_observable(self):
        """
            Convert a Certificate to a CybOX Observables.
            Returns a tuple of (CybOX object, releasability list).

            To get the cybox object as xml or json, call to_xml() or
            to_json(), respectively, on the resulting CybOX object.
        """
        custom_prop = Property(
        )  # make a custom property so CRITs import can identify Certificate exports
        custom_prop.name = "crits_type"
        custom_prop.description = "Indicates the CRITs type of the object this CybOX object represents"
        custom_prop._value = "Certificate"
        obj = File()  # represent cert information as file
        obj.md5 = self.md5
        obj.file_name = self.filename
        obj.file_format = self.filetype
        obj.size_in_bytes = self.size
        obj.custom_properties = CustomProperties()
        obj.custom_properties.append(custom_prop)
        obs = Observable(obj)
        obs.description = self.description
        data = self.filedata.read()
        if data:  # if cert data available
            a = Artifact(data, Artifact.TYPE_FILE)  # create artifact w/data
            a.packaging.append(Base64Encoding())
            obj.add_related(a, "Child_Of")  # relate artifact to file
        return ([obs], self.releasability)
Ejemplo n.º 13
0
def createArtifactObject(indicator, attribute):
    artifact = Artifact(data=attribute["data"])
    artifact.parent.id_ = cybox.utils.idgen.__generator.namespace.prefix + ":ArtifactObject-" + attribute[
        "uuid"]
    observable = Observable(artifact)
    observable.id_ = cybox.utils.idgen.__generator.namespace.prefix + ":observable-artifact-" + attribute[
        "uuid"]
    indicator.add_observable(observable)
Ejemplo n.º 14
0
def returnAttachmentComposition(attribute):
    file_object = File()
    file_object.file_name = attribute["value"]
    observable = Observable()
    if "data" in attribute:
        artifact = Artifact(data=attribute["data"])
        composition = ObservableComposition(
            observables=[artifact, file_object])
        observable.observable_composition = composition
    else:
        observable = Observable(file_object)
    return observable
Ejemplo n.º 15
0
    def to_cybox_observable(self):
        """
            Convert a RawData to a CybOX Observables.
            Returns a tuple of (CybOX object, releasability list).

            To get the cybox object as xml or json, call to_xml() or
            to_json(), respectively, on the resulting CybOX object.
        """
        obj = Artifact(self.data, Artifact.TYPE_FILE)
        obj.packaging.append(Base64Encoding())
        obs = Observable(obj)
        obs.description = self.description
        return ([obs], self.releasability)
Ejemplo n.º 16
0
    def test_custom_encoding(self):
        @EncodingFactory.register_extension
        class Base32Encoding(Encoding):
            _ENCODING_TYPE = "Base32"

            def __init__(self):
                super(Base32Encoding, self).__init__(algorithm="Base32")

            def pack(self, data):
                return base64.b32encode(data)

            def unpack(self, packed_data):
                return base64.b32decode(packed_data)

        a = Artifact(self.binary_data)
        a.packaging = Packaging()
        a.packaging.compression.append(Bz2Compression())
        a.packaging.encryption.append(XOREncryption(0x4a))
        a.packaging.encoding.append(Base32Encoding())
        a2 = round_trip(a, Artifact)

        self.assertEqual(self.binary_data, a2.data)
Ejemplo n.º 17
0
def main():
    test_file = os.path.join(os.path.dirname(__file__), "test.pcap")

    with open(test_file) as f:
        data = f.read()

    a = Artifact(data, Artifact.TYPE_NETWORK)
    a.packaging.append(Base64Encoding())

    o = Observable(a)

    o.description = ("This Observable specifies an instance of an Artifact "
                     "object, specifically some network traffic that was "
                     "captured in a PCAP file and then base64 encoded for "
                     "transport.")

    print(Observables(o).to_xml())
Ejemplo n.º 18
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
Ejemplo n.º 19
0
Archivo: pcap.py Proyecto: he0x/crits
    def to_cybox_observable(self):
        """
            Convert a PCAP to a CybOX Observables.
            Returns a tuple of (CybOX object, releasability list).

            To get the cybox object as xml or json, call to_xml() or
            to_json(), respectively, on the resulting CybOX object.
        """
        obj = File()
        obj.md5 = self.md5
        obj.file_name = self.filename
        obj.file_format = self.contentType
        obj.size_in_bytes = self.length
        obs = Observable(obj)
        obs.description = self.description
        art = Artifact(self.filedata.read(), Artifact.TYPE_NETWORK)
        art.packaging.append(Base64Encoding())
        obj.add_related(art, "Child_Of")  # relate artifact to file
        return ([obs], self.releasability)
Ejemplo n.º 20
0
    def to_cybox_observable(self, exclude=None, bin_fmt="raw"):
        if exclude == None:
            exclude = []

        observables = []
        f = File()
        for attr in ['md5', 'sha1', 'sha256']:
            if attr not in exclude:
                val = getattr(self, attr, None)
                if val:
                    setattr(f, attr, val)
        if self.ssdeep and 'ssdeep' not in exclude:
            f.add_hash(Hash(self.ssdeep, Hash.TYPE_SSDEEP))
        if 'size' not in exclude and 'size_in_bytes' not in exclude:
            f.size_in_bytes = UnsignedLong(self.size)
        if 'filename' not in exclude and 'file_name' not in exclude:
            f.file_name = self.filename
        # create an Artifact object for the binary if it exists
        if 'filedata' not in exclude and bin_fmt:
            data = self.filedata.read()
            if data:  # if sample data available
                a = Artifact(data,
                             Artifact.TYPE_FILE)  # create artifact w/data
                if bin_fmt == "zlib":
                    a.packaging.append(ZlibCompression())
                    a.packaging.append(Base64Encoding())
                elif bin_fmt == "base64":
                    a.packaging.append(Base64Encoding())
                f.add_related(a, "Child_Of")  # relate artifact to file
        if 'filetype' not in exclude and 'file_format' not in exclude:
            #NOTE: this doesn't work because the CybOX File object does not
            #   have any support built in for setting the filetype to a
            #   CybOX-binding friendly object (e.g., calling .to_dict() on
            #   the resulting CybOX object fails on this field.
            f.file_format = self.filetype
        observables.append(Observable(f))
        return (observables, self.releasability)
Ejemplo n.º 21
0
 def test_round_trip(self):
     a = Artifact(self.test_text_data, Artifact.TYPE_GENERIC)
     a2 = round_trip(a, Artifact)
     self.assertEqual(a.to_dict(), a2.to_dict())
Ejemplo n.º 22
0
 def test_round_trip(self):
     # Without any packaging, the only data an Artifact can encode
     # successfully is ASCII data.
     a = Artifact(self.ascii_data, Artifact.TYPE_GENERIC)
     a2 = round_trip(a, Artifact)
     self.assertEqual(a.to_dict(), a2.to_dict())
Ejemplo n.º 23
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))
Ejemplo n.º 24
0
def make_cybox_object(type_, name=None, value=None):
    """
    Converts type_, name, and value to a CybOX object instance.

    :param type_: The object type.
    :type type_: str
    :param name: The object name.
    :type name: str
    :param value: The object value.
    :type value: str
    :returns: CybOX object
    """

    if type_ == "Account":
        acct = Account()
        acct.description = value
        return acct
    elif type_ == "Address":
        return Address(category=name, address_value=value)
    elif type_ == "Email Message":
        e = EmailMessage()
        e.raw_body = value
        return e
    elif type_ == "API":
        api = API()
        api.description = value
        return api
    elif type_ == "Artifact":
        if name == "Data Region":
            atype = Artifact.TYPE_GENERIC
        elif name == 'FileSystem Fragment':
            atype = Artifact.TYPE_FILE_SYSTEM
        elif name == 'Memory Region':
            atype = Artifact.TYPE_MEMORY
        else:
            raise UnsupportedCybOXObjectTypeError(type_, name)
        return Artifact(value, atype)
    elif type_ == "Code":
        obj = Code()
        obj.code_segment = value
        obj.type = name
        return obj
    elif type_ == "Disk":
        disk = Disk()
        disk.disk_name = type_
        disk.type = name
        return disk
    elif type_ == "Disk Partition":
        disk = DiskPartition()
        disk.device_name = type_
        disk.type = name
        return disk
    elif type_ == "DNS Query":
        r = URI()
        r.value = value
        dq = DNSQuestion()
        dq.qname = r
        d = DNSQuery()
        d.question = dq
        return d
    elif type_ == "DNS Record":
        # DNS Record indicators in CRITs are just a free form text box, there
        # is no good way to map them into the attributes of a DNSRecord cybox
        # object. So just stuff it in the description until someone tells me
        # otherwise.
        d = StructuredText(value=value)
        dr = DNSRecord()
        dr.description = d
        return dr
    elif type_ == "GUI Dialogbox":
        obj = GUIDialogbox()
        obj.box_text = value
        return obj
    elif type_ == "GUI Window":
        obj = GUIWindow()
        obj.window_display_name = value
        return obj
    elif type_ == "HTTP Request Header Fields" and name and name == "User-Agent":
        # TODO/NOTE: HTTPRequestHeaderFields has a ton of fields for info.
        #    we should revisit this as UI is reworked or CybOX is improved.
        obj = HTTPRequestHeaderFields()
        obj.user_agent = value
        return obj
    elif type_ == "Library":
        obj = Library()
        obj.name = value
        obj.type = name
        return obj
    elif type_ == "Memory":
        obj = Memory()
        obj.memory_source = value
        return obj
    elif type_ == "Mutex":
        m = Mutex()
        m.named = True
        m.name = String(value)
        return m
    elif type_ == "Network Connection":
        obj = NetworkConnection()
        obj.layer7_protocol = value
        return obj
    elif type_ == "Pipe":
        p = Pipe()
        p.named = True
        p.name = String(value)
        return p
    elif type_ == "Port":
        p = Port()
        try:
            p.port_value = PositiveInteger(value)
        except ValueError:  # XXX: Raise a better exception...
            raise UnsupportedCybOXObjectTypeError(type_, name)
        return p
    elif type_ == "Process":
        p = Process()
        p.name = String(value)
        return p
    elif type_ == "String":
        c = Custom()
        c.custom_name = "crits:String"
        c.description = ("This is a generic string used as the value of an "
                         "Indicator or Object within CRITs.")
        c.custom_properties = CustomProperties()

        p1 = Property()
        p1.name = "value"
        p1.description = "Generic String"
        p1.value = value
        c.custom_properties.append(p1)
        return c
    elif type_ == "System":
        s = System()
        s.hostname = String(value)
        return s
    elif type_ == "URI":
        r = URI()
        r.type_ = name
        r.value = value
        return r
    elif type_ == "User Account":
        obj = UserAccount()
        obj.username = value
        return obj
    elif type_ == "Volume":
        obj = Volume()
        obj.name = value
        return obj
    elif type_ == "Win Driver":
        w = WinDriver()
        w.driver_name = String(value)
        return w
    elif type_ == "Win Event Log":
        obj = WinEventLog()
        obj.log = value
        return obj
    elif type_ == "Win Event":
        w = WinEvent()
        w.name = String(value)
        return w
    elif type_ == "Win Handle":
        obj = WinHandle()
        obj.type_ = name
        obj.object_address = value
        return obj
    elif type_ == "Win Kernel Hook":
        obj = WinKernelHook()
        obj.description = value
        return obj
    elif type_ == "Win Mailslot":
        obj = WinMailslot()
        obj.name = value
        return obj
    elif type_ == "Win Network Share":
        obj = WinNetworkShare()
        obj.local_path = value
        return obj
    elif type_ == "Win Process":
        obj = WinProcess()
        obj.window_title = value
        return obj
    elif type_ == "Win Registry Key":
        obj = WinRegistryKey()
        obj.key = value
        return obj
    elif type_ == "Win Service":
        obj = WinService()
        obj.service_name = value
        return obj
    elif type_ == "Win System":
        obj = WinSystem()
        obj.product_name = value
        return obj
    elif type_ == "Win Task":
        obj = WinTask()
        obj.name = value
        return obj
    elif type_ == "Win User Account":
        obj = WinUser()
        obj.security_id = value
        return obj
    elif type_ == "Win Volume":
        obj = WinVolume()
        obj.drive_letter = value
        return obj
    elif type_ == "X509 Certificate":
        obj = X509Certificate()
        obj.raw_certificate = value
        return obj
    """
    The following are types that are listed in the 'Indicator Type' box of
    the 'New Indicator' dialog in CRITs. These types, unlike those handled
    above, cannot be written to or read from CybOX at this point.

    The reason for the type being omitted is written as a comment inline.
    This can (and should) be revisited as new versions of CybOX are released.
    NOTE: You will have to update the corresponding make_crits_object function
    with handling for the reverse direction.

    In the mean time, these types will raise unsupported errors.
    """
    #elif type_ == "Device": # No CybOX API
    #elif type_ == "DNS Cache": # No CybOX API
    #elif type_ == "GUI": # revisit when CRITs supports width & height specification
    #elif type_ == "HTTP Session": # No good mapping between CybOX/CRITs
    #elif type_ == "Linux Package": # No CybOX API
    #elif type_ == "Network Packet": # No good mapping between CybOX/CRITs
    #elif type_ == "Network Route Entry": # No CybOX API
    #elif type_ == "Network Route": # No CybOX API
    #elif type_ == "Network Subnet": # No CybOX API
    #elif type_ == "Semaphore": # No CybOX API
    #elif type_ == "Socket": # No good mapping between CybOX/CRITs
    #elif type_ == "UNIX File": # No CybOX API
    #elif type_ == "UNIX Network Route Entry": # No CybOX API
    #elif type_ == "UNIX Pipe": # No CybOX API
    #elif type_ == "UNIX Process": # No CybOX API
    #elif type_ == "UNIX User Account": # No CybOX API
    #elif type_ == "UNIX Volume": # No CybOX API
    #elif type_ == "User Session": # No CybOX API
    #elif type_ == "Whois": # No good mapping between CybOX/CRITs
    #elif type_ == "Win Computer Account": # No CybOX API
    #elif type_ == "Win Critical Section": # No CybOX API
    #elif type_ == "Win Executable File": # No good mapping between CybOX/CRITs
    #elif type_ == "Win File": # No good mapping between CybOX/CRITs
    #elif type_ == "Win Kernel": # No CybOX API
    #elif type_ == "Win Mutex": # No good mapping between CybOX/CRITs
    #elif type_ == "Win Network Route Entry": # No CybOX API
    #elif type_ == "Win Pipe": # No good mapping between CybOX/CRITs
    #elif type_ == "Win Prefetch": # No CybOX API
    #elif type_ == "Win Semaphore": # No CybOX API
    #elif type_ == "Win System Restore": # No CybOX API
    #elif type_ == "Win Thread": # No good mapping between CybOX/CRITs
    #elif type_ == "Win Waitable Timer": # No CybOX API
    raise UnsupportedCybOXObjectTypeError(type_, name)
Ejemplo n.º 25
0
def createArtifactObject(indicator, attribute):
    artifact = Artifact(data=attribute["data"])
    indicator.add_observable(artifact)
Ejemplo n.º 26
0
 def test_non_ascii_round_trip_raises_error(self):
     a = Artifact(self.binary_data, Artifact.TYPE_GENERIC)
     # Since the data is non-ASCII, this should raise an error.
     self.assertRaises(ValueError, round_trip, a, Artifact)
Ejemplo n.º 27
0
 def test_round_trip(self):
     # Without any packaging, the only data an Artifact can encode
     # successfully is ASCII data.
     a = Artifact(self.ascii_data, Artifact.TYPE_GENERIC)
     a2 = round_trip(a, Artifact)
     self.assertEqual(a.to_dict(), a2.to_dict())
Ejemplo n.º 28
0
 def test_round_trip(self):
     a = Artifact(self.test_text_data, Artifact.TYPE_GENERIC)
     a2 = round_trip(a, Artifact)
     self.assertEqual(a.to_dict(), a2.to_dict())
Ejemplo n.º 29
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))
Ejemplo n.º 30
0
    def transform(self, event):
        self._set_namespace(self.config['contact_domain'], self.config['contact_name'])
        stix_package = STIXPackage()
        self._add_header(stix_package, "Unauthorized traffic to honeypot", "Describes one or more honeypot incidents")

        incident = Incident(id_="%s:%s-%s" % (self.config['contact_name'], 'incident', event['session_id']))
        initial_time = StixTime()
        initial_time.initial_compromise = event['timestamp'].isoformat()
        incident.time = initial_time
        incident.title = "Conpot Event"
        incident.short_description = "Traffic to Conpot ICS honeypot"
        incident.add_category(VocabString(value='Scans/Probes/Attempted Access'))

        tool_list = ToolInformationList()
        tool_list.append(ToolInformation.from_dict({
            'name': "Conpot",
            'vendor': "Conpot Team",
            'version': conpot.__version__,
            'description': textwrap.dedent('Conpot is a low interactive server side Industrial Control Systems '
                                           'honeypot designed to be easy to deploy, modify and extend.')
        }))
        incident.reporter = InformationSource(tools=tool_list)

        incident.add_discovery_method("Monitoring Service")
        incident.confidence = "High"

        # Victim Targeting by Sector
        ciq_identity = CIQIdentity3_0Instance()
        #identity_spec = STIXCIQIdentity3_0()
        #identity_spec.organisation_info = OrganisationInfo(industry_type="Electricity, Industrial Control Systems")
        #ciq_identity.specification = identity_spec
        ttp = TTP(title="Victim Targeting: Electricity Sector and Industrial Control System Sector")
        ttp.victim_targeting = VictimTargeting()
        ttp.victim_targeting.identity = ciq_identity

        incident.leveraged_ttps.append(ttp)

        indicator = Indicator(title="Conpot Event")
        indicator.description = "Conpot network event"
        indicator.confidence = "High"
        source_port = Port.from_dict({'port_value': event['remote'][1], 'layer4_protocol': 'tcp'})
        dest_port = Port.from_dict({'port_value': self.protocol_to_port_mapping[event['data_type']],
                                    'layer4_protocol': 'tcp'})
        source_ip = Address.from_dict({'address_value': event['remote'][0], 'category': Address.CAT_IPV4})
        dest_ip = Address.from_dict({'address_value': event['public_ip'], 'category': Address.CAT_IPV4})
        source_address = SocketAddress.from_dict({'ip_address': source_ip.to_dict(), 'port': source_port.to_dict()})
        dest_address = SocketAddress.from_dict({'ip_address': dest_ip.to_dict(), 'port': dest_port.to_dict()})
        network_connection = NetworkConnection.from_dict(
            {'source_socket_address': source_address.to_dict(),
             'destination_socket_address': dest_address.to_dict(),
             'layer3_protocol': u"IPv4",
             'layer4_protocol': u"TCP",
             'layer7_protocol': event['data_type'],
             'source_tcp_state': u"ESTABLISHED",
             'destination_tcp_state': u"ESTABLISHED",
             }
        )
        indicator.add_observable(Observable(network_connection))

        artifact = Artifact()
        artifact.data = json.dumps(event['data'])
        artifact.packaging.append(ZlibCompression())
        artifact.packaging.append(Base64Encoding())
        indicator.add_observable(Observable(artifact))

        incident.related_indicators.append(indicator)
        stix_package.add_incident(incident)

        stix_package_xml = stix_package.to_xml()
        return stix_package_xml
Ejemplo n.º 31
0
    def transform(self, event):
        stix_package = STIXPackage()
        self._add_header(stix_package, "Unauthorized traffic to honeypot",
                         "Describes one or more honeypot incidents")

        incident = Incident(
            id_="%s:%s-%s" %
            (CONPOT_NAMESPACE, 'incident', event['session_id']))
        initial_time = StixTime()
        initial_time.initial_compromise = event['timestamp'].isoformat()
        incident.time = initial_time
        incident.title = "Conpot Event"
        incident.short_description = "Traffic to Conpot ICS honeypot"
        incident.add_category(
            VocabString(value='Scans/Probes/Attempted Access'))

        tool_list = ToolInformationList()
        tool_list.append(
            ToolInformation.from_dict({
                'name':
                "Conpot",
                'vendor':
                "Conpot Team",
                'version':
                conpot.__version__,
                'description':
                textwrap.dedent(
                    'Conpot is a low interactive server side Industrial Control Systems '
                    'honeypot designed to be easy to deploy, modify and extend.'
                )
            }))
        incident.reporter = InformationSource(tools=tool_list)

        incident.add_discovery_method("Monitoring Service")
        incident.confidence = "High"

        # Victim Targeting by Sector
        ciq_identity = CIQIdentity3_0Instance()
        #identity_spec = STIXCIQIdentity3_0()
        #identity_spec.organisation_info = OrganisationInfo(industry_type="Electricity, Industrial Control Systems")
        #ciq_identity.specification = identity_spec
        ttp = TTP(
            title=
            "Victim Targeting: Electricity Sector and Industrial Control System Sector"
        )
        ttp.victim_targeting = VictimTargeting()
        ttp.victim_targeting.identity = ciq_identity

        incident.leveraged_ttps.append(ttp)

        indicator = Indicator(title="Conpot Event")
        indicator.description = "Conpot network event"
        indicator.confidence = "High"
        source_port = Port.from_dict({
            'port_value': event['remote'][1],
            'layer4_protocol': 'tcp'
        })
        dest_port = Port.from_dict({
            'port_value':
            self.protocol_to_port_mapping[event['data_type']],
            'layer4_protocol':
            'tcp'
        })
        source_ip = Address.from_dict({
            'address_value': event['remote'][0],
            'category': Address.CAT_IPV4
        })
        dest_ip = Address.from_dict({
            'address_value': event['public_ip'],
            'category': Address.CAT_IPV4
        })
        source_address = SocketAddress.from_dict({
            'ip_address':
            source_ip.to_dict(),
            'port':
            source_port.to_dict()
        })
        dest_address = SocketAddress.from_dict({
            'ip_address': dest_ip.to_dict(),
            'port': dest_port.to_dict()
        })
        network_connection = NetworkConnection.from_dict({
            'source_socket_address':
            source_address.to_dict(),
            'destination_socket_address':
            dest_address.to_dict(),
            'layer3_protocol':
            "IPv4",
            'layer4_protocol':
            "TCP",
            'layer7_protocol':
            event['data_type'],
            'source_tcp_state':
            "ESTABLISHED",
            'destination_tcp_state':
            "ESTABLISHED",
        })
        indicator.add_observable(Observable(network_connection))

        artifact = Artifact()
        artifact.data = json.dumps(event['data'])
        artifact.packaging.append(ZlibCompression())
        artifact.packaging.append(Base64Encoding())
        indicator.add_observable(Observable(artifact))

        incident.related_indicators.append(indicator)
        stix_package.add_incident(incident)

        stix_package_xml = stix_package.to_xml()
        return stix_package_xml
Ejemplo n.º 32
0
def to_cybox_observable(obj, exclude=None, bin_fmt="raw"):
    """
    Convert a CRITs TLO to a CybOX Observable.

    :param obj: The TLO to convert.
    :type obj: :class:`crits.core.crits_mongoengine.CRITsBaseAttributes`
    :param exclude: Attributes to exclude.
    :type exclude: list
    :param bin_fmt: The format for the binary (if applicable).
    :type bin_fmt: str
    """

    type_ = obj._meta['crits_type']
    if type_ == 'Certificate':
        custom_prop = Property(
        )  # make a custom property so CRITs import can identify Certificate exports
        custom_prop.name = "crits_type"
        custom_prop.description = "Indicates the CRITs type of the object this CybOX object represents"
        custom_prop._value = "Certificate"
        obje = File()  # represent cert information as file
        obje.md5 = obj.md5
        obje.file_name = obj.filename
        obje.file_format = obj.filetype
        obje.size_in_bytes = obj.size
        obje.custom_properties = CustomProperties()
        obje.custom_properties.append(custom_prop)
        obs = Observable(obje)
        obs.description = obj.description
        data = obj.filedata.read()
        if data:  # if cert data available
            a = Artifact(data, Artifact.TYPE_FILE)  # create artifact w/data
            a.packaging.append(Base64Encoding())
            obje.add_related(a, "Child_Of")  # relate artifact to file
        return ([obs], obj.releasability)
    elif type_ == 'Domain':
        obje = DomainName()
        obje.value = obj.domain
        obje.type_ = obj.record_type
        return ([Observable(obje)], obj.releasability)
    elif type_ == 'Email':
        if exclude == None:
            exclude = []

        observables = []

        obje = EmailMessage()
        # Assume there is going to be at least one header
        obje.header = EmailHeader()

        if 'message_id' not in exclude:
            obje.header.message_id = String(obj.message_id)

        if 'subject' not in exclude:
            obje.header.subject = String(obj.subject)

        if 'sender' not in exclude:
            obje.header.sender = Address(obj.sender, Address.CAT_EMAIL)

        if 'reply_to' not in exclude:
            obje.header.reply_to = Address(obj.reply_to, Address.CAT_EMAIL)

        if 'x_originating_ip' not in exclude:
            obje.header.x_originating_ip = Address(obj.x_originating_ip,
                                                   Address.CAT_IPV4)

        if 'x_mailer' not in exclude:
            obje.header.x_mailer = String(obj.x_mailer)

        if 'boundary' not in exclude:
            obje.header.boundary = String(obj.boundary)

        if 'raw_body' not in exclude:
            obje.raw_body = obj.raw_body

        if 'raw_header' not in exclude:
            obje.raw_header = obj.raw_header

        #copy fields where the names differ between objects
        if 'helo' not in exclude and 'email_server' not in exclude:
            obje.email_server = String(obj.helo)
        if ('from_' not in exclude and 'from' not in exclude
                and 'from_address' not in exclude):
            obje.header.from_ = EmailAddress(obj.from_address)
        if 'date' not in exclude and 'isodate' not in exclude:
            obje.header.date = DateTime(obj.isodate)

        obje.attachments = Attachments()

        observables.append(Observable(obje))
        return (observables, obj.releasability)
    elif type_ == 'Indicator':
        observables = []
        obje = make_cybox_object(obj.ind_type, obj.value)
        observables.append(Observable(obje))
        return (observables, obj.releasability)
    elif type_ == 'IP':
        obje = Address()
        obje.address_value = obj.ip
        if obj.ip_type == IPTypes.IPv4_ADDRESS:
            obje.category = "ipv4-addr"
        elif obj.ip_type == IPTypes.IPv6_ADDRESS:
            obje.category = "ipv6-addr"
        elif obj.ip_type == IPTypes.IPv4_SUBNET:
            obje.category = "ipv4-net"
        elif obj.ip_type == IPTypes.IPv6_SUBNET:
            obje.category = "ipv6-subnet"
        return ([Observable(obje)], obj.releasability)
    elif type_ == 'PCAP':
        obje = File()
        obje.md5 = obj.md5
        obje.file_name = obj.filename
        obje.file_format = obj.contentType
        obje.size_in_bytes = obj.length
        obs = Observable(obje)
        obs.description = obj.description
        art = Artifact(obj.filedata.read(), Artifact.TYPE_NETWORK)
        art.packaging.append(Base64Encoding())
        obje.add_related(art, "Child_Of")  # relate artifact to file
        return ([obs], obj.releasability)
    elif type_ == 'RawData':
        obje = Artifact(obj.data.encode('utf-8'), Artifact.TYPE_FILE)
        obje.packaging.append(Base64Encoding())
        obs = Observable(obje)
        obs.description = obj.description
        return ([obs], obj.releasability)
    elif type_ == 'Sample':
        if exclude == None:
            exclude = []

        observables = []
        f = File()
        for attr in ['md5', 'sha1', 'sha256']:
            if attr not in exclude:
                val = getattr(obj, attr, None)
                if val:
                    setattr(f, attr, val)
        if obj.ssdeep and 'ssdeep' not in exclude:
            f.add_hash(Hash(obj.ssdeep, Hash.TYPE_SSDEEP))
        if 'size' not in exclude and 'size_in_bytes' not in exclude:
            f.size_in_bytes = UnsignedLong(obj.size)
        if 'filename' not in exclude and 'file_name' not in exclude:
            f.file_name = obj.filename
        # create an Artifact object for the binary if it exists
        if 'filedata' not in exclude and bin_fmt:
            data = obj.filedata.read()
            if data:  # if sample data available
                a = Artifact(data,
                             Artifact.TYPE_FILE)  # create artifact w/data
                if bin_fmt == "zlib":
                    a.packaging.append(ZlibCompression())
                    a.packaging.append(Base64Encoding())
                elif bin_fmt == "base64":
                    a.packaging.append(Base64Encoding())
                f.add_related(a, "Child_Of")  # relate artifact to file
        if 'filetype' not in exclude and 'file_format' not in exclude:
            #NOTE: this doesn't work because the CybOX File object does not
            #   have any support built in for setting the filetype to a
            #   CybOX-binding friendly object (e.g., calling .to_dict() on
            #   the resulting CybOX object fails on this field.
            f.file_format = obj.filetype
        observables.append(Observable(f))
        return (observables, obj.releasability)
    else:
        return (None, None)