Exemplo n.º 1
0
def main():
    # Create a CyboX File Object
    f = File()

    # This automatically detects that it's an MD5 hash based on the length
    f.add_hash("4EC0027BEF4D7E1786A04D021FA8A67F")

    # Create an Indicator with the File Hash Object created above.
    indicator = Indicator()
    indicator.title = "File Hash Example"
    indicator.description = (
        "An indicator containing a File observable with an associated hash"
    )
    indicator.set_producer_identity("The MITRE Corporation")
    indicator.set_produced_time(utils.dates.now())

    # Add The File Object to the Indicator. This will promote the CybOX Object
    # to a CybOX Observable internally.
    indicator.add_object(f)

    # Create a STIX Package
    stix_package = STIXPackage()

    # Create the STIX Header and add a description.
    stix_header = STIXHeader()
    stix_header.description = "File Hash Indicator Example"
    stix_package.stix_header = stix_header

    # Add our Indicator object. The add() method will inspect the input and
    # append it to the `stix_package.indicators` collection.
    stix_package.add(indicator)

    # Print the XML!
    print(stix_package.to_xml())
def main():
    ioc = etree.parse('6d2a1b03-b216-4cd8-9a9e-8827af6ebf93.ioc')

    stix_package = STIXPackage()

    ttp = TTP()
    malware_instance = MalwareInstance()
    malware_instance.names = ['Zeus', 'twexts', 'sdra64', 'ntos']

    ttp = TTP(title="Zeus")
    ttp.behavior = Behavior()
    ttp.behavior.add_malware_instance(malware_instance)

    indicator = Indicator(title="Zeus", description="Finds Zeus variants, twexts, sdra64, ntos")

    tm = OpenIOCTestMechanism()
    tm.ioc = ioc
    tm.producer = InformationSource(identity=Identity(name="Mandiant"))
    time = Time()
    time.produced_time = "0001-01-01T00:00:00"
    tm.producer.time = time
    tm.producer.references = ["http://openioc.org/iocs/6d2a1b03-b216-4cd8-9a9e-8827af6ebf93.ioc"]
    indicator.test_mechanisms = TestMechanisms([tm])
    indicator.add_indicated_ttp(TTP(idref=ttp.id_))

    stix_package.add_indicator(indicator)
    stix_package.add_ttp(ttp)

    print(stix_package.to_xml(encoding=None))
def main():
    # Build Campaign instances
    camp1 = Campaign(title='Campaign 1')
    camp2 = Campaign(title='Campaign 2')

    # Build a CampaignRef object, setting the `idref` to the `id_` value of
    # our `camp2` Campaign object.
    campaign_ref = CampaignRef(idref=camp2.id_)

    # Build an Indicator object.
    i = Indicator()

    # Add CampaignRef object pointing to `camp2`.
    i.add_related_campaign(campaign_ref)

    # Add Campaign object, which gets promoted into an instance of
    # CampaignRef type internally. Only the `idref` is set.
    i.add_related_campaign(camp1)

    # Build our STIX Package and attach our Indicator and Campaign objects.
    package = STIXPackage()
    package.add_indicator(i)
    package.add_campaign(camp1)
    package.add_campaign(camp2)

    # Print!
    print package.to_xml()
Exemplo n.º 4
0
def SSHObj(SSH):
    networkconnection = NetworkConnection()
    networkconnection.layer3_protocol = "IPv4"
    networkconnection.layer4_protocol = "TCP"
    networkconnection.layer7_protocol = "SSH"
    if SSH[0] != VMIP and SSH[4] == 1 and SSH[5] == 0:  # incoming connection
        ssocketaddress = SocketAddress()
        ssocketaddress.ip_address = SSH[0]
        sport = Port()
        sport.port_value = SSH[1]
        sport.layer4_protocol = "TCP"
        ssocketaddress.port = sport
        networkconnection.source_socket_address = ssocketaddress
    elif SSH[2] != VMIP and SSH[4] == 1 and SSH[5] == 0:  # outgoing connection
        dsocketaddress = SocketAddress()
        dsocketaddress.ip_address = SSH[2]
        dport = Port()
        dport.port_value = SSH[3]
        dport.layer4_protocol = "TCP"
        dsocketaddress.port = dport
        networkconnection.destination_socket_address = dsocketaddress
    indicator = Indicator()
    if SSH[6] != '':
        indicator.title = "SSH Request with pulic key"
        indicator.description = ("SSH public key: " + SSH[6])
    else:
        indicator.title = "SSH Request"
        indicator.description = (
            "An indicator containing information about a SSH request")
    indicator.set_produced_time(utils.dates.now())
    indicator.add_object(networkconnection)
    return indicator
Exemplo n.º 5
0
    def test_markable_attributes(self):
        """Test that attribute selector used on resulting xpath.
            Does not check for accuracy of marked data."""
        container = stixmarx.new()
        package = container.package
        red_marking = generate_marking_spec(generate_red_marking_struct())

        indicator = Indicator(title="Test")
        observable = generate_observable()

        indicator.add_observable(observable)

        package.add_indicator(indicator)

        observable.object_.id_ = container.add_marking(observable.object_.id_,
                                                       red_marking)
        indicator.timestamp = container.add_marking(indicator.timestamp,
                                                    red_marking)

        self.assertTrue(package.stix_header is None)
        self.assertTrue(package.indicators[0].handling is None)

        container.flush()

        self.assertTrue(package.stix_header is None)

        self.assertTrue(package.indicators[0].handling is not None)

        for marking in package.indicators[0].handling.marking:
            selector = marking.controlled_structure.split("/")[-1]

            self.assertTrue(selector.startswith("@"))
Exemplo n.º 6
0
def convert_indicator(indicator20):
    indicator1x = Indicator(id_=convert_id20(indicator20["id"]),
                            timestamp=text_type(indicator20["modified"]))
    if "name" in indicator20:
        indicator1x.title = indicator20["name"]
    if "description" in indicator20:
        indicator1x.add_description(indicator20["description"])
    indicator1x.indicator_types = convert_open_vocabs_to_controlled_vocabs(
        indicator20["labels"], INDICATOR_LABEL_MAP)
    indicator1x.add_valid_time_position(
        convert_to_valid_time(
            text_type(indicator20["valid_from"]),
            text_type(indicator20["valid_until"])
            if "valid_until" in indicator20 else None))
    indicator1x.add_observable(
        create_pattern_object(
            indicator20["pattern"]).toSTIX1x(id20=indicator20["id"]))
    if "kill_chain_phases" in indicator20:
        process_kill_chain_phases(indicator20["kill_chain_phases"],
                                  indicator1x)
    if "object_marking_refs" in indicator20:
        for m_id in indicator20["object_marking_refs"]:
            ms = create_marking_specification(m_id)
            if ms:
                CONTAINER.add_marking(indicator1x, ms, descendants=True)
    if "granular_markings" in indicator20:
        error(
            "Granular Markings present in '%s' are not supported by stix2slider",
            604, indicator20["id"])
    record_id_object_mapping(indicator20["id"], indicator1x)
    return indicator1x
Exemplo n.º 7
0
def url(ip, provider, reporttime):
    vuln = Vulnerability()
    vuln.cve_id = "IPV4-" + str(ip)
    vuln.description = "maliciousURL"
    et = ExploitTarget(title=provider + " observable")
    et.add_vulnerability(vuln)

    addr = Address(address_value=str(ip), category=Address.CAT_IPV4)
    addr.condition = "Equals"

    # Create an Indicator with the File Hash Object created above.
    indicator = Indicator()
    indicator.title = "URL-" + str(ip)
    indicator.description = ("Malicious URL " + str(ip) + " reported from " +
                             provider)
    indicator.set_producer_identity(provider)
    indicator.set_produced_time(reporttime)
    indicator.add_observable(addr)
    # Create a STIX Package
    stix_package = STIXPackage()

    stix_package.add(et)
    stix_package.add(indicator)

    # Print the XML!
    #print(stix_package.to_xml())
    f = open('/opt/TARDIS/Observables/URL/' + str(ip) + '.xml', 'w')
    f.write(stix_package.to_xml())
    f.close()
Exemplo n.º 8
0
 def test_indicator(self):
     i = Indicator()
     i.title = UNICODE_STR
     i.description = UNICODE_STR
     i.short_description = UNICODE_STR
     i2 = round_trip(i)
     self._test_equal(i, i2)
def main():

    rule = """
rule silent_banker : banker
{
    meta:
        description = "This is just an example"
        thread_level = 3
        in_the_wild = true

    strings:
        $a = {6A 40 68 00 30 00 00 6A 14 8D 91}
        $b = {8D 4D B0 2B C1 83 C0 27 99 6A 4E 59 F7 F9}
        $c = "UVODFRYSIHLNWPEJXQZAKCBGMT"

    condition:
        $a or $b or $c
}
"""

    stix_package = STIXPackage()

    indicator = Indicator(title="silent_banker",
                          description="This is just an example")

    tm = YaraTestMechanism()
    tm.rule = rule
    tm.producer = InformationSource(identity=Identity(name="Yara"))
    tm.producer.references = ["http://plusvic.github.io/yara/"]
    indicator.test_mechanisms = TestMechanisms([tm])

    stix_package.add_indicator(indicator)

    print(stix_package.to_xml(encoding=None))
Exemplo n.º 10
0
def md5(hash, provider, reporttime):
    vuln = Vulnerability()
    vuln.cve_id = "MD5-" + hash
    vuln.description = "maliciousMD5"
    et = ExploitTarget(title=provider + " observable")
    et.add_vulnerability(vuln)
    # Create a CyboX File Object
    f = File()
    # This automatically detects that it's an MD5 hash based on the length
    f.add_hash(hash)

    # Create an Indicator with the File Hash Object created above.
    indicator = Indicator()
    indicator.title = "MD5-" + hash
    indicator.description = ("Malicious hash " + hash + " reported from " +
                             provider)
    indicator.set_producer_identity(provider)
    indicator.set_produced_time(reporttime)

    # Add The File Object to the Indicator. This will promote the CybOX Object
    # to a CybOX Observable internally.

    indicator.add_observable(f)

    # Create a STIX Package
    stix_package = STIXPackage()

    stix_package.add(et)
    stix_package.add(indicator)

    # Print the XML!
    #print(stix_package.to_xml())
    f = open('/opt/TARDIS/Observables/MD5/' + hash + '.xml', 'w')
    f.write(stix_package.to_xml())
    f.close()
Exemplo n.º 11
0
 def test_indicator(self):
     i = Indicator()
     i.title = UNICODE_STR
     i.description = UNICODE_STR
     i.short_description = UNICODE_STR
     i2 = round_trip(i)
     self._test_equal(i, i2)
Exemplo n.º 12
0
def main():
    ioc = etree.parse('6d2a1b03-b216-4cd8-9a9e-8827af6ebf93.ioc')

    stix_package = STIXPackage()

    ttp = TTP()
    malware_instance = MalwareInstance()
    malware_instance.names = ['Zeus', 'twexts', 'sdra64', 'ntos']
    
    ttp = TTP(title="Zeus")
    ttp.behavior = Behavior()
    ttp.behavior.add_malware_instance(malware_instance)

    indicator = Indicator(title="Zeus", description="Finds Zeus variants, twexts, sdra64, ntos")

    tm = OpenIOCTestMechanism()
    tm.ioc = ioc
    tm.producer = InformationSource(identity=Identity(name="Yara"))
    time = Time()
    time.produced_time = "0001-01-01T00:00:00"
    tm.producer.time = time
    tm.producer.references = ["http://openioc.org/iocs/6d2a1b03-b216-4cd8-9a9e-8827af6ebf93.ioc"]
    indicator.test_mechanisms = [tm]

    indicator.add_indicated_ttp(TTP(idref=ttp.id_))

    stix_package.add_indicator(indicator)
    stix_package.add_ttp(ttp)
    
    print stix_package.to_xml()
def main():

    rule = """
rule silent_banker : banker
{
    meta:
        description = "This is just an example"
        thread_level = 3
        in_the_wild = true

    strings:
        $a = {6A 40 68 00 30 00 00 6A 14 8D 91}
        $b = {8D 4D B0 2B C1 83 C0 27 99 6A 4E 59 F7 F9}
        $c = "UVODFRYSIHLNWPEJXQZAKCBGMT"

    condition:
        $a or $b or $c
}
"""

    stix_package = STIXPackage()

    indicator = Indicator(title="silent_banker", description="This is just an example")

    tm = YaraTestMechanism()
    tm.rule = rule
    tm.producer = InformationSource(identity=Identity(name="Yara"))
    tm.producer.references = ["http://plusvic.github.io/yara/"]
    indicator.test_mechanisms = [tm]

    stix_package.add_indicator(indicator)
    
    print stix_package.to_xml()
Exemplo n.º 14
0
    def test_datetime_format(self):
        indicator = Indicator(title="title")
        valid_time = ValidTime(
            start_time=datetime.strptime("2010-03-05", "%Y-%m-%d"))
        indicator.add_valid_time_position(valid_time)

        ixml = indicator.to_xml()
        self.assertTrue("2010-03-05T" in text_type(ixml))
Exemplo n.º 15
0
    def test_datetime_format(self):
        indicator = Indicator(title="title")
        valid_time = ValidTime(start_time=datetime.strptime("2010-03-05",
                                                            "%Y-%m-%d"))
        indicator.add_valid_time_position(valid_time)

        ixml = indicator.to_xml()
        self.assertTrue("2010-03-05T" in text_type(ixml))
Exemplo n.º 16
0
    def test_set_indicator_observables_to_list_of_two_observables(self):
        # https://github.com/STIXProject/python-stix/issues/325
        i = Indicator()
        o1 = Observable()
        o2 = Observable()

        i.observables = [o1, o2]
        self.assertEqual(mixbox.typedlist.TypedList, type(i.observables))
        self.assertEqual(2, len(i.observables))
Exemplo n.º 17
0
    def test_set_indicator_observables_to_list_of_one_observable(self):
        # https://github.com/STIXProject/python-stix/issues/325
        i = Indicator()
        o1 = Observable()
        o2 = Observable()

        i.observables = [o1]
        self.assertEqual(type([]), type(i.observables))
        self.assertEqual(1, len(i.observables))
Exemplo n.º 18
0
    def test_set_indicator_observables_to_list_of_two_observables(self):
        # https://github.com/STIXProject/python-stix/issues/325
        i = Indicator()
        o1 = Observable()
        o2 = Observable()

        i.observables = [o1, o2]
        self.assertEqual(mixbox.typedlist.TypedList, type(i.observables))
        self.assertEqual(2, len(i.observables))
Exemplo n.º 19
0
    def test_set_indicator_observables_to_list_of_one_observable(self):
        # https://github.com/STIXProject/python-stix/issues/325
        i = Indicator()
        o1 = Observable()
        o2 = Observable()

        i.observables = [o1]
        self.assertEqual(type([]), type(i.observables))
        self.assertEqual(1, len(i.observables))
Exemplo n.º 20
0
def md5(hash,provider,reporttime):
    vuln = Vulnerability()
    vuln.cve_id = "MD5-" + hash
    vuln.description = "maliciousMD5"
    et = ExploitTarget(title=provider + " observable")
    et.add_vulnerability(vuln) 
    # Create a CyboX File Object
    f = File()
    # This automatically detects that it's an MD5 hash based on the length
    f.add_hash(hash)
    
    # Create an Indicator with the File Hash Object created above.
    indicator = Indicator()
    indicator.title = "MD5-" + hash
    indicator.description = ("Malicious hash " + hash + " reported from " + provider)
    indicator.set_producer_identity(provider)
    indicator.set_produced_time(reporttime)

    
    # Add The File Object to the Indicator. This will promote the CybOX Object
    # to a CybOX Observable internally.
    
    indicator.add_observable(f)

    # Create a STIX Package
    stix_package = STIXPackage()
    
    stix_package.add(et)
    stix_package.add(indicator)
    
    # Print the XML!
    #print(stix_package.to_xml())
    f = open('/opt/TARDIS/Observables/MD5/' + hash + '.xml','w')
    f.write(stix_package.to_xml())
    f.close()
Exemplo n.º 21
0
def url(ip,provider,reporttime):
    vuln = Vulnerability()
    vuln.cve_id = "IPV4-" + str(ip)
    vuln.description = "maliciousURL"
    et = ExploitTarget(title=provider + " observable")
    et.add_vulnerability(vuln)
    
    addr = Address(address_value=str(ip), category=Address.CAT_IPV4) 
    addr.condition = "Equals"
    
     # Create an Indicator with the File Hash Object created above.
    indicator = Indicator()
    indicator.title = "URL-" + str(ip)
    indicator.description = ("Malicious URL " + str(ip) + " reported from " + provider)
    indicator.set_producer_identity(provider)
    indicator.set_produced_time(reporttime)
    indicator.add_observable(addr)
    # Create a STIX Package
    stix_package = STIXPackage()
    
    stix_package.add(et)
    stix_package.add(indicator)
    
    # Print the XML!
    #print(stix_package.to_xml())
    f = open('/opt/TARDIS/Observables/URL/' + str(ip) + '.xml','w')
    f.write(stix_package.to_xml())
    f.close()
Exemplo n.º 22
0
def main():
    file_hash = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'

    stix_header = STIXHeader(
        title="File Hash Reputation Service Results",
        package_intents=["Indicators - Malware Artifacts"])
    stix_package = STIXPackage(stix_header=stix_header)

    indicator = Indicator(
        title=
        "File Reputation for SHA256=e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
    )
    indicator.add_indicator_type("File Hash Watchlist")

    file_object = File()
    file_object.add_hash(Hash(file_hash))
    file_object.hashes[0].simple_hash_value.condition = "Equals"
    file_object.hashes[0].type_.condition = "Equals"
    indicator.add_observable(file_object)

    indicator.add_indicated_ttp(TTP(title="Malicious file"))

    indicator.confidence = Confidence(value=VocabString('75'))
    indicator.confidence.value.vocab_name = "Percentage"
    indicator.confidence.value.vocab_reference = "https://en.wikipedia.org/wiki/Percentage"

    stix_package.add_indicator(indicator)

    print(stix_package.to_xml(encoding=None))
Exemplo n.º 23
0
    def test_observables_property_standard(self):
        f = File()
        f.file_name = "README.txt"
        obs = Observable(f)
        ind = Indicator()
        ind.observable = obs

        ind2 = Indicator.from_dict(ind.to_dict())

        self.assertEqual([obs.to_dict()],
                         [x.to_dict() for x in ind2.observables])
Exemplo n.º 24
0
    def test_observables_property_standard(self):
        f = File()
        f.file_name = "README.txt"
        obs = Observable(f)
        ind = Indicator()
        ind.observable = obs

        ind2 = Indicator.from_dict(ind.to_dict())

        self.assertEqual([obs.to_dict()],
                         [x.to_dict() for x in ind2.observables])
Exemplo n.º 25
0
def generateIndicator(attribute):
    indicator = Indicator()
    indicator.id_="example:indicator-" + attribute["uuid"]
    setTLP(indicator, attribute["distribution"])
    indicator.title = "MISP Attribute #" + attribute["id"] + " uuid: " + attribute["uuid"]
    confidence_description = "Derived from MISP's IDS flag. If an attribute is marked for IDS exports, the confidence will be high, otherwise none"
    confidence_value = confidence_mapping.get(attribute["to_ids"], None)
    if confidence_value is None:
        return indicator
    indicator.confidence = Confidence(value=confidence_value, description=confidence_description)
    return indicator
Exemplo n.º 26
0
    def _add_stix_indicators(self, final_indicator_objects, ttp_id):
        """Create and add STIX Indicators for a list of Object History entries. 
        Link each Indicator to their Indicated TTP.

        Note:
            Each STIX Indicator is added to the STIX Package stored in the ``stix_package`` class
            member.

        Args:
            final_indicator_objects: a list of ``maec.bundle.object_history.ObjectHistoryEntry`` objects representing
                the final, pruned list of Objects to be used in the STIX Indicators.
            ttp_id: the id of the STIX TTP that each STIX Indicator should reference as its Indicated TTP.
        """
        object_values_list = []
        actions_list = []
        final_object_list = []

        # Deduplicate the Objects and combine their Actions
        for entry in final_indicator_objects:
            object = entry.object
            # Test if we've already created an Indicator for this Object
            obj_values = BundleDeduplicator.get_object_values(object)
            if obj_values not in object_values_list:
                object_values_list.append(obj_values)
                final_object_list.append(object)
                actions_list.append(entry.get_action_names())
            else:
                object_index = object_values_list.index(obj_values)
                existing_actions = actions_list[object_index]
                existing_actions += entry.get_action_names()

        # Create the STIX Indicators
        for object in final_object_list:
            object_index = final_object_list.index(object)
            indicator = Indicator()
            indicator.title = "Malware Artifact Extracted from MAEC Document"
            indicator.add_indicator_type("Malware Artifacts")
            indicator.add_observable(object.properties)
            # Add the Action-derived description to the Indicator
            description = "Corresponding Action(s): "
            for action_name in actions_list[object_index]:
                description += (action_name + ", ")
            indicator.description = description[:-2]
            # Set the proper Confidence on the Indicator
            confidence = Confidence()
            confidence.value = "Low"
            confidence.description = "Tool-generated Indicator. It is HIGHLY recommended that it be vetted by a human analyst before usage."
            indicator.confidence = confidence
            # Link the Indicator to its Indicated TTP
            ttp = TTP(idref=ttp_id)
            indicator.add_indicated_ttp(ttp)
            # Add the Indicator to the STIX Package
            self.stix_package.add_indicator(indicator)
Exemplo n.º 27
0
 def convert(self):
     if self.deleted == 0:
         observable = self.get_observable()
         if observable is not None:
             indicator = Indicator(title=str(self.id_),
                                   timestamp=self.dt,
                                   description=self.comment)
             indicator.observable = self.get_observable()
         else:
             indicator = None
     else:
         indicator = None
     return indicator
Exemplo n.º 28
0
def generateIndicator(attribute):
    indicator = Indicator(timestamp=getDateFromTimestamp(int(attribute["timestamp"])))
    indicator.id_= namespace[1] + ":indicator-" + attribute["uuid"]
    if attribute["comment"] != "":
        indicator.description = attribute["comment"]
    setTLP(indicator, attribute["distribution"])
    indicator.title = attribute["category"] + ": " + attribute["value"] + " (MISP Attribute #" + attribute["id"] + ")"
    confidence_description = "Derived from MISP's IDS flag. If an attribute is marked for IDS exports, the confidence will be high, otherwise none"
    confidence_value = confidence_mapping.get(attribute["to_ids"], None)
    if confidence_value is None:
        return indicator
    indicator.confidence = Confidence(value=confidence_value, description=confidence_description, timestamp=getDateFromTimestamp(int(attribute["timestamp"])))
    return indicator
Exemplo n.º 29
0
def generateIndicator(attribute):
    indicator = Indicator()
    indicator.id_ = "example:indicator-" + attribute["uuid"]
    setTLP(indicator, attribute["distribution"])
    indicator.title = "MISP Attribute #" + attribute[
        "id"] + " uuid: " + attribute["uuid"]
    confidence_description = "Derived from MISP's IDS flag. If an attribute is marked for IDS exports, the confidence will be high, otherwise none"
    confidence_value = confidence_mapping.get(attribute["to_ids"], None)
    if confidence_value is None:
        return indicator
    indicator.confidence = Confidence(value=confidence_value,
                                      description=confidence_description)
    return indicator
Exemplo n.º 30
0
def DNSRequestObj(dnsinfo):
    networkconnection = NetworkConnection()
    networkconnection.layer3_protocol = "IPv4"
    networkconnection.layer4_protocol = "UDP"
    networkconnection.layer7_protocol = "DNS"
    ssocketaddress = SocketAddress()
    sport = Port()
    sport.port_value = dnsinfo[1]
    sport.layer4_protocol = "UDP"
    ssocketaddress.port = sport
    networkconnection.source_socket_address = ssocketaddress
    dsocketaddress = SocketAddress()
    dsocketaddress.ip_address = dnsinfo[2]
    dport = Port()
    dport.port_value = dnsinfo[3]
    dport.layer4_protocol = "UDP"
    dsocketaddress.port = dport
    networkconnection.destination_socket_address = dsocketaddress
    layer7connections = Layer7Connections()
    dqr = DNSQuery()
    indicator = Indicator()
    dnsques = DNSQuestion()
    dnsques.qname = dnsinfo[4]
    dnsques.qtype = translateType(dnsinfo[5])
    dqr.question = dnsques
    indicator.title = "DNS Request"
    indicator.description = (
        "An indicator containing information about a DNS Request")
    layer7connections.dns_query = dqr
    networkconnection.layer7_connections = layer7connections
    indicator.set_produced_time(utils.dates.now())
    indicator.add_object(networkconnection)
    return indicator
Exemplo n.º 31
0
def TCPConnectionEstablishedObj(tcpinfo):
    networkconnection = NetworkConnection()
    networkconnection.layer3_protocol = "IPv4"
    networkconnection.layer4_protocol = "TCP"
    if tcpinfo[0] != VMIP:  # incoming connection
        networkconnection.destination_tcp_state = "ESTABLISHED"
        ssocketaddress = SocketAddress()
        ssocketaddress.ip_address = tcpinfo[0]
        sport = Port()
        sport.port_value = tcpinfo[2]
        sport.layer4_protocol = "TCP"
        ssocketaddress.port = sport
        networkconnection.source_socket_address = ssocketaddress
    elif tcpinfo[1] != VMIP:  # outgoing connection
        networkconnection.source_tcp_state = "ESTABLISHED"
        dsocketaddress = SocketAddress()
        dsocketaddress.ip_address = tcpinfo[1]
        dport = Port()
        dport.port_value = tcpinfo[3]
        dport.layer4_protocol = "TCP"
        dsocketaddress.port = dport
        networkconnection.destination_socket_address = dsocketaddress
    indicator = Indicator()
    indicator.title = "TCP Connection Established"
    indicator.description = (
        "An indicator containing information about a successful TCP hand shake"
    )
    indicator.set_produced_time(utils.dates.now())
    indicator.add_object(networkconnection)
    return indicator
Exemplo n.º 32
0
def UDPRequestObj(udpinfo):
    u = NetworkConnection()
    u.layer3_protocol = "IPv4"
    u.layer4_protocol = "UDP"
    ssocketaddress = SocketAddress()
    if udpinfo[3] != VMIP:
        ssocketaddress.ip_address = udpinfo[3]
        sport = Port()
        sport.port_value = udpinfo[0]
        sport.layer4_protocol = "UDP"
        ssocketaddress.port = sport
        u.source_socket_address = ssocketaddress
    dsocketaddress = SocketAddress()
    if udpinfo[2] != VMIP:
        dsocketaddress.ip_address = udpinfo[2]
        dport = Port()
        dport.port_value = udpinfo[1]
        dport.layer4_protocol = "UDP"
        dsocketaddress.port = dport
        u.destination_socket_address = dsocketaddress
    indicator = Indicator()
    indicator.title = "UDP connection"
    indicator.description = (
        "An indicator containing information about a UDP connection")
    indicator.set_produced_time(utils.dates.now())
    indicator.add_object(u)
    return indicator
Exemplo n.º 33
0
    def test_observables_property_composition(self):
        f1 = File()
        f1.file_name = "README.txt"
        f2 = File()
        f2.file_name = "README2.txt"
        obs1 = Observable(f1)
        obs2 = Observable(f2)

        comp = Observable(ObservableComposition('AND', [obs1, obs2]))

        ind = Indicator()
        ind.observable = comp
        ind2 = Indicator.from_dict(ind.to_dict())
        self.assertEqual([obs1.to_dict(), obs2.to_dict()],
                         [x.to_dict() for x in ind2.observables])
Exemplo n.º 34
0
    def test_observables_property_composition(self):
        f1 = File()
        f1.file_name = "README.txt"
        f2 = File()
        f2.file_name = "README2.txt"
        obs1 = Observable(f1)
        obs2 = Observable(f2)

        comp = Observable(ObservableComposition('AND', [obs1, obs2]))

        ind = Indicator()
        ind.observable = comp
        ind2 = Indicator.from_dict(ind.to_dict())
        self.assertEqual([obs1.to_dict(), obs2.to_dict()],
                         [x.to_dict() for x in ind2.observables])
Exemplo n.º 35
0
    def test_duplicate_marking(self):
        """Test that duplicate markings get added once."""
        container = stixmarx.new()
        package = container.package
        red_marking = generate_marking_spec(generate_red_marking_struct())

        indicator = Indicator(title="Test")

        package.add_indicator(indicator)

        container.add_marking(indicator, red_marking)
        self.assertRaises(errors.DuplicateMarkingError, container.add_marking,
                          indicator, red_marking, False)

        container.add_global(red_marking)
        self.assertRaises(errors.DuplicateMarkingError, container.add_global,
                          red_marking)

        self.assertTrue(indicator.handling is None)
        self.assertTrue(package.stix_header is None)

        container.flush()

        self.assertTrue(len(indicator.handling.marking) == 1)
        self.assertTrue(len(package.stix_header.handling.marking) == 1)
Exemplo n.º 36
0
    def test_markable_self_node(self):
        """Test that a marking to an element with descendants=False will result
        in ``self::node()`` selector."""
        container = stixmarx.new()
        package = container.package
        red_marking = generate_marking_spec(generate_red_marking_struct())

        indicator = Indicator(title="Test")

        package.add_indicator(indicator)

        container.add_marking(indicator, red_marking)

        self.assertTrue(package.indicators[0].handling is None)

        container.flush()

        indicator_path = package.indicators[0].handling.marking[0] \
            .controlled_structure.split("/")[-1]

        self.assertTrue(indicator_path == xml.XPATH_AXIS_SELF_NODE)

        counter = 0
        for elem in navigator.iterwalk(package):
            if api.is_marked(elem):
                counter += 1

        # There should be only one object with markings in the whole package.
        self.assertTrue(counter == 1)
Exemplo n.º 37
0
    def from_obj(cls, obj, return_obj=None):
        if not return_obj:
            return_obj = cls()

        return_obj.id_ = obj.id
        return_obj.idref = obj.idref
        return_obj.timestamp = obj.timestamp
        return_obj.stix_header = STIXHeader.from_obj(obj.STIX_Header)
        return_obj.related_packages = RelatedPackages.from_obj(obj.Related_Packages)

        if obj.version:
            return_obj.version = obj.version
        if obj.Campaigns:
            return_obj.campaigns = [Campaign.from_obj(x) for x in obj.Campaigns.Campaign]
        if obj.Courses_Of_Action:
            return_obj.courses_of_action = [CourseOfAction.from_obj(x) for x in obj.Courses_Of_Action.Course_Of_Action]
        if obj.Exploit_Targets:
            return_obj.exploit_targets = [ExploitTarget.from_obj(x) for x in obj.Exploit_Targets.Exploit_Target]
        if obj.Indicators:
            return_obj.indicators = [Indicator.from_obj(x) for x in obj.Indicators.Indicator]
        if obj.Observables:
            return_obj.observables = Observables.from_obj(obj.Observables)
        if obj.Incidents:
            return_obj.incidents = [Incident.from_obj(x) for x in obj.Incidents.Incident]
        if obj.Threat_Actors:
            return_obj.threat_actors = [ThreatActor.from_obj(x) for x in obj.Threat_Actors.Threat_Actor]
        if obj.TTPs:
            return_obj.ttps = TTPs.from_obj(obj.TTPs)
            
        return return_obj
Exemplo n.º 38
0
def MISPtoSTIX(mispJSON):
    """
        Function to convert from a MISP JSON to a STIX stix

        :param mispJSON: A dict (json) containing a misp Event.
        :returns stix: A STIX stix with as much of the original
                          data as we could convert.
    """
    if isinstance(mispJSON, mispevent.MISPEvent):
        misp_event = mispJSON
    else:
        misp_event = mispevent.MISPEvent()
        misp_event.load(mispJSON)

    # We should now have a proper MISP JSON loaded.

    # Create a base stix
    stix = STIXPackage()

    # Create a header for the new stix
    stix.stix_header = STIXHeader()

    # Try to use the event title as the stix title
    stix.stix_header.title = misp_event.info

    # We're going to store our observables inside an indicator
    indicator = Indicator()

    # Go through each attribute and transfer what we can.
    for one_attrib in misp_event.attributes:
        # Build an attribute from the JSON. Is all nice.
        buildSTIXAttribute.buildAttribute(one_attrib, stix, indicator)
    stix.add_indicator(indicator)
    return stix
Exemplo n.º 39
0
    def from_obj(cls, obj, return_obj=None):
        if not return_obj:
            return_obj = cls()

        return_obj.id_ = obj.get_id()
        return_obj.idref = obj.get_idref()
        return_obj.timestamp = obj.get_timestamp()
        return_obj.stix_header = STIXHeader.from_obj(obj.get_STIX_Header())
        return_obj.related_packages = RelatedPackages.from_obj(obj.get_Related_Packages())

        if obj.get_version():
            return_obj.version = obj.get_version()
        if obj.get_Campaigns():
            return_obj.campaigns = [Campaign.from_obj(x) for x in obj.get_Campaigns().get_Campaign()]
        if obj.get_Courses_Of_Action():
            return_obj.courses_of_action = [CourseOfAction.from_obj(x) for x in obj.get_Courses_Of_Action().get_Course_Of_Action()]
        if obj.get_Exploit_Targets():
            return_obj.exploit_targets = [ExploitTarget.from_obj(x) for x in obj.get_Exploit_Targets().get_Exploit_Target()]
        if obj.get_Indicators():
            return_obj.indicators = [Indicator.from_obj(x) for x in obj.get_Indicators().get_Indicator()]
        if obj.get_Observables():
            return_obj.observables = Observables.from_obj(obj.get_Observables())
        if obj.get_Incidents():
            return_obj.incidents = [Incident.from_obj(x) for x in obj.get_Incidents().get_Incident()]
        if obj.get_Threat_Actors():
            return_obj.threat_actors = [ThreatActor.from_obj(x) for x in obj.get_Threat_Actors().get_Threat_Actor()]
        if obj.get_TTPs():
            return_obj.ttps = TTPs.from_obj(obj.get_TTPs())
            
        return return_obj
Exemplo n.º 40
0
def main():
    infilename = ''
    outfilename = ''

    #Get the command-line arguments
    args = sys.argv[1:]
    
    if len(args) < 4:
        usage()
        sys.exit(1)
        
    for i in range(0,len(args)):
        if args[i] == '-i':
            infilename = args[i+1]
        elif args[i] == '-o':
            outfilename = args[i+1]
    if os.path.isfile(infilename): 
        try:
            # Perform the translation using the methods from the OpenIOC to CybOX Script
            openioc_indicators = openioc.parse(infilename)
            observables_obj = openioc_to_cybox.generate_cybox(openioc_indicators, infilename, True)
            observables_cls = Observables.from_obj(observables_obj)

            # Set the namespace to be used in the STIX Package
            stix.utils.set_id_namespace({"https://github.com/STIXProject/openioc-to-stix":"openiocToSTIX"})

            # Wrap the created Observables in a STIX Package/Indicator
            stix_package = STIXPackage()
            # Add the OpenIOC namespace
            input_namespaces = {"http://openioc.org/":"openioc"}
            stix_package.__input_namespaces__ = input_namespaces

            for observable in observables_cls.observables:
                indicator_dict = {}
                producer_dict = {}
                producer_dict['tools'] = [{'name':'OpenIOC to STIX Utility', 'version':str(__VERSION__)}]
                indicator_dict['producer'] = producer_dict
                indicator_dict['title'] = "CybOX-represented Indicator Created from OpenIOC File"
                indicator = Indicator.from_dict(indicator_dict)
                indicator.add_observable(observables_cls.observables[0])
                stix_package.add_indicator(indicator)

            # Create and write the STIX Header
            stix_header = STIXHeader()
            stix_header.package_intent = "Indicators - Malware Artifacts"
            stix_header.description = "CybOX-represented Indicators Translated from OpenIOC File"
            stix_package.stix_header = stix_header

            # Write the generated STIX Package as XML to the output file
            outfile = open(outfilename, 'w')
            # Ignore any warnings - temporary fix for no schemaLocation w/ namespace
            with warnings.catch_warnings():
                warnings.simplefilter("ignore")
                outfile.write(stix_package.to_xml())
                warnings.resetwarnings()
            outfile.flush()
            outfile.close()
        except Exception, err:
            print('\nError: %s\n' % str(err))
            traceback.print_exc()
Exemplo n.º 41
0
    def test_add_related_indicator(self):
        from stix.indicator import Indicator
        from stix.common.related import RelatedIndicator

        i = self.klass()

        self.assertEqual(0, len(i.related_indicators))
        i.add_related_indicator(Indicator())
        self.assertEqual(1, len(i.related_indicators))

        related = RelatedIndicator(Indicator())
        i.add_related_indicator(related)
        self.assertEqual(2, len(i.related_indicators))

        # Test that this fails
        self.assertRaises(TypeError, i.add_related_indicator,
                          "THIS SHOULD FAIL")
Exemplo n.º 42
0
    def test_embedded_observable_marking_removal(self):
        """Test that markings on embedded Observables can be removed"""
        container = stixmarx.new()
        package = container.package
        red_marking = generate_marking_spec(generate_red_marking_struct())

        indicator = Indicator(title="Test")
        package.add_indicator(indicator)

        observable = generate_observable()
        indicator.add_observable(observable)

        container.add_marking(observable, red_marking)
        self.assertTrue(container.is_marked(observable, red_marking))

        container.remove_marking(observable, red_marking)
        self.assertFalse(container.is_marked(observable, red_marking))
Exemplo n.º 43
0
    def test_embedded_observable_direct_marking(self):
        """Test that embedded Observables can be directly marked"""
        container = stixmarx.new()
        package = container.package
        red_marking = generate_marking_spec(generate_red_marking_struct())
        amber_marking = generate_marking_spec(generate_amber_marking_struct())

        indicator = Indicator(title="Test")
        package.add_indicator(indicator)

        observable = generate_observable()
        indicator.add_observable(observable)

        container.add_marking(indicator, amber_marking)
        container.add_marking(observable, red_marking)

        self.assertTrue(container.is_marked(observable, red_marking))
Exemplo n.º 44
0
    def test_append_bad_type(self):
        l = RelatedCampaignRefs()

        self.assertRaises(
            TypeError,
            l.append,
            Indicator()
        )
Exemplo n.º 45
0
def stix_xml(bldata):
    # Create the STIX Package and Header objects
    stix_package = STIXPackage()
    stix_header = STIXHeader()
    # Set the description
    stix_header.description = "RiskIQ Blacklist Data - STIX Format"
    # Set the namespace
    NAMESPACE = {"http://www.riskiq.com": "RiskIQ"}
    set_id_namespace(NAMESPACE)
    # Set the produced time to now
    stix_header.information_source = InformationSource()
    stix_header.information_source.time = Time()
    stix_header.information_source.time.produced_time = datetime.now()
    # Create the STIX Package
    stix_package = STIXPackage()
    # Build document
    stix_package.stix_header = stix_header
    # Build the Package Intent
    stix_header.package_intents.append(PackageIntent.TERM_INDICATORS)

    # Build the indicator
    indicator = Indicator()
    indicator.title = "List of Malicious URLs detected by RiskIQ - Malware, Phishing, and Spam"
    indicator.add_indicator_type("URL Watchlist")
    for datum in bldata:
        url = URI()
        url.value = ""
        url.value = datum['url']
        url.type_ = URI.TYPE_URL
        url.condition = "Equals"
        indicator.add_observable(url)

    stix_package.add_indicator(indicator)
    return stix_package.to_xml()
Exemplo n.º 46
0
Arquivo: actor.py Projeto: Lartsen/TFG
def main():

    # Creamos el indicador con la información de la que disponemos
    threatActor = ThreatActor()
    threatActor.title = "Ip/Domain/Hostname"
    threatActor.description = ("A threatActor commited with malicious tasks")
    threatActor.information_source = ("Malshare")
    threatActor.timestamp = ("01/05/2019")
    threatActor.identity = ("106.113.123.197")
    threatActor.types = ("eCrime Actor - Spam Service")

    # Creamos el indicador con la información de la que disponemos
    indicator = Indicator()
    indicator.title = "Risk Score"
    indicator.description = (
        "An indicator containing the appropriate Risk Score")
    indicator.set_produced_time("01/05/2019")
    indicator.likely_impact = ("Risk Score: 2(Medium)")
    # Creamos el reporte en STIX, con una brve descripción
    stix_package = STIXPackage()
    stix_header = STIXHeader()
    stix_header.description = "Feeds in STIX format with their Risk Scores"
    stix_package.stix_header = stix_header

    # Añadimos al reporte el indicador que hemos construido antes
    stix_package.add(threatActor)
    stix_package.add(indicator)
    # Imprimimos el xml en pantalla
    print(stix_package.to_xml())
Exemplo n.º 47
0
def buildIndicator(input_dict):
    indicator = Indicator()
    indicator.description = input_dict["description"]
    if input_dict["confidence"]:
        indicator.confidence = input_dict["confidence"]

    if input_dict["impact"]:
        indicator.likely_impact = input_dict["impact"]

    if input_dict["producer"]:
        indicator.producer = InformationSource()
        indicator.producer.identity = Identity(input_dict["producer"])
    indicator.title = input_dict["title"]
    indicator.add_valid_time_position(valid_time.ValidTime(input_dict["starttime"], input_dict["endtime"]))
    if input_dict["type"]:
        indicator.add_indicator_type(input_dict["type"])

    return indicator
def main():

  data = json.load(open("data.json"))

  stix_package = STIXPackage(stix_header=STIXHeader(title=data['title'], package_intents='Incident'))

  ttps = {}

  for info in data['ips']:
    # Add TTP, unless it's already been added
    if info['bot'] not in ttps:
      ttps[info['bot']] = TTP(title=info['bot'])
      stix_package.add_ttp(ttps[info['bot']])

    # Add indicator
    indicator = Indicator(title=info['ip'])
    addr = Address(address_value=info['ip'], category=Address.CAT_IPV4)
    addr.condition = "Equals"
    indicator.add_observable(addr)
    indicator.add_indicated_ttp(TTP(idref=ttps[info['bot']].id_))

    stix_package.add_indicator(indicator)

    # Add incident
    incident = Incident(title=info['ip'])
    incident.time = Time()
    incident.time.first_malicious_action = info['first_seen']

    addr = Address(address_value=info['ip'], category=Address.CAT_IPV4)
    observable = Observable(item=addr)
    stix_package.add_observable(observable)

    related_ttp = RelatedTTP(TTP(idref=ttps[info['bot']].id_), relationship="Used Malware")
    incident.leveraged_ttps.append(related_ttp)

    related_observable = RelatedObservable(Observable(idref=observable.id_))
    incident.related_observables.append(related_observable)

    related_indicator = RelatedIndicator(Indicator(idref=indicator.id_))
    incident.related_indicators.append(related_indicator)

    stix_package.add_incident(incident)

  print stix_package.to_xml()
Exemplo n.º 49
0
def main():
    # get args
    parser = argparse.ArgumentParser(
        description="Parse an input JSON file and output STIX XML ",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)

    parser.add_argument("infile",help="input file")
    parser.add_argument("--outfile","-o", help="output file")

    args = parser.parse_args()
    
    # We assume the input file is a flat JSON file
    # format 'bot_name':[list,of,ips]
    content = json.load(open(args.infile))
        
    # Set up STIX document
    stix_package = STIXPackage()
    stix_header = STIXHeader()
    stix_header.title = "C2 Server IP Addresses"
    stix_header.add_package_intent (PackageIntent.TERM_INDICATORS_WATCHLIST)
    stix_package.stix_header = stix_header

    # Create Indicator and TTP for each item in JSON document
    for item in content:

        # Create TTP for C2 server
        ttp = TTP()
        ttp.title = item
        stix_package.add_ttp(ttp)

        # Create Indicator for C2 IP addresses
        indicator = Indicator()
        indicator.title = "IP addresses for known C2 channel"
        indicator.description = "Bot connecting to control server"

        # Add IPs for C2 node
        addr = Address(address_value=content[item], category=Address.CAT_IPV4)
        addr.address_value.condition= "Equals"
        indicator.add_object(addr)

        # Relate Indicator and TTP
        indicator.add_indicated_ttp(TTP(idref=ttp.id_))

        # Add Indicator to STIX PAckage
        stix_package.add_indicator(indicator)

    # Output to given file
    # The context manager is just to make the output look nicer by ignoring
    # warnings from to_xml()
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        stix_out = stix_package.to_xml()

        if args.outfile:
            fd = open(args.outfile,'w')
            fd.write(stix_out)
        else:
            print stix_out
Exemplo n.º 50
0
    def to_stix_indicator(self):
        """
        Creates a STIX Indicator object from a CybOX object.

        Returns the STIX Indicator and the original CRITs object's
        releasability list.
        """
        from stix.indicator import Indicator as S_Ind
        from stix.common.identity import Identity
        ind = S_Ind()
        obs, releas = self.to_cybox()
        for ob in obs:
            ind.add_observable(ob)
        #TODO: determine if a source wants its name shared. This will
        #   probably have to happen on a per-source basis rather than a per-
        #   object basis.
        identity = Identity(name=settings.COMPANY_NAME)
        ind.set_producer_identity(identity)

        return (ind, releas)
def main():
  package = STIXPackage()

  # Create the indicator
  indicator = Indicator(title="IP Address for known C2 Channel")
  indicator.add_indicator_type("IP Watchlist")
  address = Address(category="ipv4-addr")
  address.address_value = "10.0.0.0"
  address.address_value.condition = "Equals"
  indicator.observable = address
  package.add_indicator(indicator)

  # Create the campaign
  campaign = Campaign(title="Operation Omega")
  package.add_campaign(campaign)

  # Link the campaign to the indicator
  campaign.related_indicators.append(RelatedIndicator(item=Indicator(idref=indicator.id_)))

  print package.to_xml()
Exemplo n.º 52
0
def fqdn(fqdn,provider,reporttime):
    currentTime = time.time()
    parsed_uri = urlparse( str(fqdn) )
    domain = '{uri.scheme}://{uri.netloc}/'.format(uri=parsed_uri)
    if domain.startswith('https'):
        domain = domain[8:]
    else:
        domain = domain[7:]
    if domain.endswith('/'):
        domain = domain[:-1]


    vuln = Vulnerability()
    vuln.cve_id = "FQDN-" + str(domain) + '_' + str(currentTime)
    vuln.description = "maliciousIPV4"
    et = ExploitTarget(title=provider + " observable")
    et.add_vulnerability(vuln)
    
    url = URI()
    url.value = fqdn
    url.type_ =  URI.TYPE_URL
    url.condition = "Equals"
    
     # Create an Indicator with the File Hash Object created above.
    indicator = Indicator()
    indicator.title = "FQDN-" + str(fqdn)
    indicator.description = ("Malicious FQDN " + str(fqdn) + " reported from " + provider)
    indicator.set_producer_identity(provider)
    indicator.set_produced_time(reporttime)
    indicator.add_observable(url)
    # Create a STIX Package
    stix_package = STIXPackage()
    
    stix_package.add(et)
    stix_package.add(indicator)
    
    # Print the XML!
    #print(stix_package.to_xml())
    
    
    f = open('/opt/TARDIS/Observables/FQDN/' + str(domain) + '_' + str(currentTime) + '.xml','w')
    f.write(stix_package.to_xml())
    f.close()

    
Exemplo n.º 53
0
def stix_xml(bldata):
    # Create the STIX Package and Header objects
    stix_package = STIXPackage()
    stix_header = STIXHeader()
    # Set the description
    stix_header.description = "RiskIQ Blacklist Data - STIX Format"
    # Set the namespace
    NAMESPACE = {"http://www.riskiq.com" : "RiskIQ"}
    set_id_namespace(NAMESPACE) 
    # Set the produced time to now
    stix_header.information_source = InformationSource()
    stix_header.information_source.time = Time()
    stix_header.information_source.time.produced_time = datetime.now()
    # Create the STIX Package
    stix_package = STIXPackage()
    # Build document
    stix_package.stix_header = stix_header
    # Build the Package Intent
    stix_header.package_intents.append(PackageIntent.TERM_INDICATORS)

    # Build the indicator
    indicator = Indicator()
    indicator.title = "List of Malicious URLs detected by RiskIQ - Malware, Phishing, and Spam"
    indicator.add_indicator_type("URL Watchlist")
    for datum in bldata:
        url = URI()
        url.value = ""
        url.value = datum['url']
        url.type_ =  URI.TYPE_URL
        url.condition = "Equals"
        indicator.add_observable(url)

    stix_package.add_indicator(indicator)
    return stix_package.to_xml()
def main():
    stix_pkg = STIXPackage()

    # create LM-style kill chain
    # REF: http://stix.mitre.org/language/version{{site.current_version}}/stix_v{{site.current_version}}_lmco_killchain.xml

    recon = KillChainPhase(phase_id="stix:TTP-af1016d6-a744-4ed7-ac91-00fe2272185a", name="Reconnaissance", ordinality="1")
    weapon = KillChainPhase(phase_id="stix:TTP-445b4827-3cca-42bd-8421-f2e947133c16", name="Weaponization", ordinality="2")
    deliver = KillChainPhase(phase_id="stix:TTP-79a0e041-9d5f-49bb-ada4-8322622b162d", name="Delivery", ordinality="3")
    exploit = KillChainPhase(phase_id="stix:TTP-f706e4e7-53d8-44ef-967f-81535c9db7d0", name="Exploitation", ordinality="4")
    install = KillChainPhase(phase_id="stix:TTP-e1e4e3f7-be3b-4b39-b80a-a593cfd99a4f", name="Installation", ordinality="5")
    control = KillChainPhase(phase_id="stix:TTP-d6dc32b9-2538-4951-8733-3cb9ef1daae2", name="Command and Control", ordinality="6")
    action = KillChainPhase(phase_id="stix:TTP-786ca8f9-2d9a-4213-b38e-399af4a2e5d6", name="Actions on Objectives", ordinality="7")

    lmchain = KillChain(id_="stix:TTP-af3e707f-2fb9-49e5-8c37-14026ca0a5ff", name="LM Cyber Kill Chain")
    lmchain.definer = "LMCO"

    lmchain.kill_chain_phases = [recon, weapon, deliver, exploit, install, control, action]
    stix_pkg.ttps.kill_chains.append(lmchain)

    infect = KillChainPhase(name="Infect Machine")
    exfil = KillChainPhase(name="Exfiltrate Data")

    mychain = KillChain(name="Organization-specific Kill Chain")
    mychain.definer = "Myself"

    mychain.kill_chain_phases = [infect, exfil]
    stix_pkg.ttps.add_ttp(TTP())
    stix_pkg.ttps.kill_chains.append(mychain)

    indicator = Indicator()
    indicator.kill_chain_phases = KillChainPhasesReference([
        KillChainPhaseReference(phase_id=exfil.phase_id, kill_chain_id=mychain.id_),
        KillChainPhaseReference(phase_id=action.phase_id, kill_chain_id=lmchain.id_)
    ])
    stix_pkg.add_indicator(indicator)

    print(stix_pkg.to_xml(encoding=None))
Exemplo n.º 55
0
def _observable_to_indicator_stix(observable):
    """Translate a CybOX Observable into a STIX Indicator.

    Args:
        observable: Observable object that will be translated

    Returns:
        Indicator object with STIX utility and CybOX tags
    """
    # Build STIX tool content
    tool = ToolInformation(tool_name='OpenIOC to STIX Utility')
    tool.version = version.__version__

    # Build Indicator.producer contents
    producer = InformationSource()
    producer.tools = ToolInformationList(tool)

    # Build Indicator
    indicator = Indicator(title="CybOX-represented Indicator Created from OpenIOC File")
    indicator.producer = producer
    indicator.add_observable(observable)

    return indicator
def main():
    stix_pkg = STIXPackage()


    # make indicator 
    ind = Indicator()
    ind.title = "Malicious executable"
    ind.description = "Resident binary which implements infostealing and credit card grabber"
    
    # link to "Installation" phase and kill chain by ID values
    infect = KillChainPhase(name="Infect Machine")
    exfil = KillChainPhase(name="Exfiltrate Data")
    mychain = KillChain(name="Organization-specific Kill Chain")
    
    mychain.kill_chain_phases = [infect, exfil]
    stix_pkg.ttps.kill_chains.append(mychain)    
    stix_pkg.add_indicator(ind)
    
    
    # add referenced phase to indicator
    ind.kill_chain_phases.append(KillChainPhaseReference(phase_id=infect.phase_id,kill_chain_id = mychain.id_))
    
    print stix_pkg.to_xml() 
Exemplo n.º 57
0
def main():
    infilename = ''
    outfilename = ''

    #Get the command-line arguments
    args = sys.argv[1:]
    
    if len(args) < 4:
        usage()
        sys.exit(1)
        
    for i in range(0,len(args)):
        if args[i] == '-i':
            infilename = args[i+1]
        elif args[i] == '-o':
            outfilename = args[i+1]
    if os.path.isfile(infilename): 
        try:
            # Perform the translation using the methods from the OpenIOC to CybOX Script
            openioc_indicators = openioc.parse(infilename)
            observables_obj = openioc_to_cybox.generate_cybox(openioc_indicators, infilename, True)
            observables_cls = Observables.from_obj(observables_obj)

            # Wrap the created Observables in a STIX Package/Indicator
            stix_package = STIXPackage()

            for observable in observables_cls.observables:
                indicator_dict = {}
                producer_dict = {}
                producer_dict['tools'] = [{'name':'OpenIOC to STIX Utility', 'version':str(__VERSION__)}]
                indicator_dict['producer'] = producer_dict
                indicator_dict['title'] = "CybOX-represented Indicator Created from OpenIOC File"
                indicator = Indicator.from_dict(indicator_dict)
                indicator.add_observable(observables_cls.observables[0])
                stix_package.add_indicator(indicator)

            # Create and write the STIX Header
            stix_header = STIXHeader()
            stix_header.package_intent = "Indicators - Malware Artifacts"
            stix_header.description = "CybOX-represented Indicators Translated from OpenIOC File"
            stix_package.stix_header = stix_header

            # Write the generated STIX Package as XML to the output file
            outfile = open(outfilename, 'w')
            outfile.write(stix_package.to_xml())
            outfile.flush()
            outfile.close()
        except Exception, err:
            print('\nError: %s\n' % str(err))
            traceback.print_exc()
def main():
    stix_package = STIXPackage()

    # Build the Exploit Target
    vuln = Vulnerability()
    vuln.cve_id = "CVE-2014-0160"
    vuln.add_reference("http://heartbleed.com/")

    et = ExploitTarget(title="Heartbleed")
    et.add_vulnerability(vuln)

    stix_package.add_exploit_target(et)

    # Build the TTP
    ttp = TTP(title="Generic Heartbleed Exploits")
    ttp.exploit_targets.append(ExploitTarget(idref=et.id_))

    stix_package.add_ttp(ttp)

    # Build the indicator
    indicator = Indicator(title="Snort Signature for Heartbleed")
    indicator.confidence = Confidence("High")

    tm = SnortTestMechanism()
    tm.rules = [
        """alert tcp any any -> any any (msg:"FOX-SRT - Flowbit - TLS-SSL Client Hello"; flow:established; dsize:< 500; content:"|16 03|"; depth:2; byte_test:1, <=, 2, 3; byte_test:1, !=, 2, 1; content:"|01|"; offset:5; depth:1; content:"|03|"; offset:9; byte_test:1, <=, 3, 10; byte_test:1, !=, 2, 9; content:"|00 0f 00|"; flowbits:set,foxsslsession; flowbits:noalert; threshold:type limit, track by_src, count 1, seconds 60; reference:cve,2014-0160; classtype:bad-unknown; sid: 21001130; rev:9;)""",
        """alert tcp any any -> any any (msg:"FOX-SRT - Suspicious - TLS-SSL Large Heartbeat Response"; flow:established; flowbits:isset,foxsslsession; content:"|18 03|"; depth: 2; byte_test:1, <=, 3, 2; byte_test:1, !=, 2, 1; byte_test:2, >, 200, 3; threshold:type limit, track by_src, count 1, seconds 600; reference:cve,2014-0160; classtype:bad-unknown; sid: 21001131; rev:5;)"""
    ]
    tm.efficacy = "Low"
    tm.producer = InformationSource(identity=Identity(name="FOX IT"))
    tm.producer.references = ["http://blog.fox-it.com/2014/04/08/openssl-heartbleed-bug-live-blog/"]
    indicator.test_mechanisms = TestMechanisms([tm])
    indicator.add_indicated_ttp(TTP(idref=ttp.id_))

    stix_package.add_indicator(indicator)

    print(stix_package.to_xml(encoding=None))