Example #1
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
Example #2
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
Example #3
0
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()
Example #4
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()
Example #5
0
    def create_indicator(self, ce1sus_indicator, event_permissions, user):
        indicator = Indicator()
        indicator.id_ = 'ce1sus:Indicator-{0}'.format(ce1sus_indicator.uuid)
        indicator.title = ce1sus_indicator.title
        indicator.description = ce1sus_indicator.description
        indicator.short_description = ce1sus_indicator.short_description
        if ce1sus_indicator.confidence:
            indicator.confidence = ce1sus_indicator.confidence.title()
        else:
            indicator.confidence = 'Low'
        # TODO: handling
        # TODO: markings
        for type_ in ce1sus_indicator.types:
            indicator.add_indicator_type(type_.name)

        if ce1sus_indicator.operator:
            indicator.observable_composition_operator = ce1sus_indicator.operator
        # Todo Add confidence
        # indicator_attachment.confidence = "Low"
        creator = self.create_stix_identity(ce1sus_indicator)
        time = self.cybox_mapper.get_time(
            produced_time=ce1sus_indicator.created_at)
        info_source = InformationSource(identity=creator, time=time)
        indicator.producer = info_source
        observables = ce1sus_indicator.get_observables_for_permissions(
            event_permissions, user)
        for obs in observables:
            cybox_obs = self.create_observable(obs, event_permissions, user)
            indicator.add_observable(cybox_obs)
        valid_time = ValidTime(start_time=ce1sus_indicator.created_at,
                               end_time=ce1sus_indicator.created_at)
        indicator.add_valid_time_position(valid_time)
        return indicator
Example #6
0
    def generate_indicators(self, count):
        '''Generate a list of STIX Indicators'''
        indicators = []
        for i in range(0, count):
            indicator = Indicator(title='Multiple indicator types')
            indicator.set_producer_identity(Identity(name='Secret Source'))
            indicator.set_produced_time(datetime.today())
            indicator.add_indicator_type(choice(['Malware Artifacts', 'C2', 'Exfiltration']))
            indicator.add_short_description('Short description...')
            indicator.add_description('Long description...')
            indicator.confidence = Confidence(choice(['High', 'Medium', 'Low', 'None', 'Unknown']))
            kill_chain_phase = choice(LMCO_KILL_CHAIN_PHASES)
            indicator.kill_chain_phases = KillChainPhasesReference(
                [KillChainPhaseReference(name=kill_chain_phase.name)])
            ips = self.gen_ips(randint(0, 5))
            for ip in ips:
                indicator.add_observable(ip)

            # user_agents = self.gen_user_agents(randint(0, 5))
            # for ua in user_agents:
            #     indicator.add_observable(ua)

            # fqnds = self.gen_fqdns(randint(0, 5))
            # for f in fqnds:
            #     indicator.add_observable(f)

            # urls = self.gen_urls(randint(0, 5))
            # for u in urls:
            #     indicator.add_observable(u)

            indicators.append(indicator)

        return indicators
Example #7
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)
Example #8
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
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))
Example #10
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("@"))
Example #11
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
Example #12
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()
Example #13
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()
Example #14
0
File: actor.py Project: 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())
Example #15
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)
Example #16
0
def ICMPObj(icmp):
    # block types 0 (ping response), 8 (ping request)
    nc = NetworkConnection()
    indicator = Indicator()
    nc.layer3_protocol = "ICMP"
    if icmp[0] == 0:  # echo-reply
        if icmp[1] != VMIP:  # incoming reply from a server VM pinged
            ssocketaddress = SocketAddress()
            ssocketaddress.ip_address = icmp[1]
            nc.source_socket_address = ssocketaddress
            indicator.title = "ICMP echo-reply"
            indicator.description = ("0")
        else:  # outgoing reply to a server that pinged you
            dsocketaddress = SocketAddress()
            dsocketaddress.ip_address = icmp[2]
            nc.destination_socket_address = dsocketaddress
            indicator.title = "ICMP echo-reply"
            indicator.description = ("0")
    elif icmp[0] == 8:  # echo-request
        if icmp[1] != VMIP:  # incoming ping request from a server
            ssocketaddress = SocketAddress()
            ssocketaddress.ip_address = icmp[1]
            nc.source_socket_address = ssocketaddress
            indicator.title = "ICMP echo-request"
            indicator.description = ("8")
        else:  # VM is sending a ping request
            dsocketaddress = SocketAddress()
            dsocketaddress.ip_address = icmp[2]
            nc.destination_socket_address = dsocketaddress
            indicator.title = "ICMP echo-request"
            indicator.description = ("8")
    indicator.set_produced_time(utils.dates.now())
    indicator.add_object(nc)
    return indicator
Example #17
0
def main(hash_value, title, description, confidence_value):
    # Create a CyboX File Object
    f = File()

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

    # Create an Indicator with the File Hash Object created above.
    indicator = Indicator()

    indicator.title = title
    indicator.description = (description)
    indicator.confidence = confidence_value
    indicator.set_producer_identity("Information Security")
    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 = description
    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!
    with open('FileHash_indicator.xml', 'w') as the_file:
        the_file.write(stix_package.to_xml().decode('utf-8'))
Example #18
0
def main():
    # Crea un objeto vía CybOX
    f = File()

    # Asocia el hash a dicho objeto, la tipología del hash la detecta automáticamente en función de su amplitud
    f.add_hash("8994a4713713e4683117e35d8689ea24")

    # Creamos el indicador con la información de la que disponemos
    indicator = Indicator()
    indicator.title = "Feeds and Risk Score"
    indicator.description = (
        "An indicator containing the feed and the appropriate Risk Score"
    )
    indicator.set_producer_identity("Malshare")
    indicator.set_produced_time("01/05/2019")
    indicator.likely_impact = ("Risk Score: 4(Critical)")

    # Asociamos el hash anterior a nuestro indicador
    indicator.add_object(f)

    # 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(indicator)

    # Imprimimos el xml en pantalla
    print(stix_package.to_xml())
Example #19
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
def _dostix(hashes):
    '''This function creates a STIX packages containing hashes.'''
    print("[+] Creating STIX Package")
    title = SETTINGS['stix']['ind_title'] + " " + str(datetime.datetime.now())
    _custom_namespace(SETTINGS['stix']['ns'], SETTINGS['stix']['ns_prefix'])
    stix_package = STIXPackage()
    stix_package.stix_header = STIXHeader()
    stix_package.stix_header.title = title
    stix_package.stix_header.handling = _marking()
    try:
        indicator = Indicator()
        indicator.set_producer_identity(SETTINGS['stix']['producer'])
        indicator.set_produced_time(indicator.timestamp)
        indicator.set_received_time(indicator.timestamp)
        indicator.add_kill_chain_phase(PHASE_DELIVERY)
        indicator.confidence = "Low"

        indicator.title = title
        indicator.add_indicator_type("File Hash Watchlist")
        indicator.description = SETTINGS['stix']['ind_desc']

        try:
            indicator.add_indicated_ttp(
                TTP(idref=SETTINGS['indicated_ttp'],
                    timestamp=indicator.timestamp))
            indicator.suggested_coas.append(
                CourseOfAction(idref=SETTINGS['suggested_coa'],
                               timestamp=indicator.timestamp))
        except KeyError:
            pass

        for info in hashes:
            try:
                file_name = info['filename']
                file_object = File()
                file_object.file_name = file_name
                file_object.file_name.condition = "Equals"
                file_object.file_extension = "." + file_name.split('.')[-1]
                file_object.file_extension.condition = "Equals"
                file_object.size_in_bytes = info['filesize']
                file_object.size_in_bytes.condition = "Equals"
                file_object.file_format = info['fileformat']
                file_object.file_format.condition = "Equals"
                file_object.add_hash(Hash(info['md5']))
                file_object.add_hash(Hash(info['sha1']))
                file_object.add_hash(Hash(info['sha256']))
                file_object.add_hash(Hash(info['sha512']))
                file_object.add_hash(Hash(info['ssdeep'], Hash.TYPE_SSDEEP))
                for hashobj in file_object.hashes:
                    hashobj.simple_hash_value.condition = "Equals"
                    hashobj.type_.condition = "Equals"
                file_obs = Observable(file_object)
                file_obs.title = "File: " + file_name
                indicator.add_observable(file_obs)
            except TypeError:
                pass
        stix_package.add_indicator(indicator)
        return stix_package
    except KeyError:
        pass
Example #21
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()
Example #22
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)
Example #23
0
def resolveObjects(incident, ttps, objects, eventTags, org):
    for obj in objects:
        tmp_incident = Incident()
        resolveAttributes(tmp_incident, ttps, obj["Attribute"], eventTags, org)
        indicator = Indicator(
            timestamp=getDateFromTimestamp(int(obj["timestamp"])))
        indicator.id_ = namespace[1] + ":MispObject-" + obj["uuid"]
        setProd(indicator, org)
        if obj["comment"] != "":
            indicator.description = obj["comment"]
        tlpTags = eventTags
        for attr in obj["Attribute"]:
            tlpTags = mergeTags(tlpTags, attr)
        setTLP(indicator, obj["distribution"], tlpTags, True)
        indicator.title = obj["name"] + " (MISP Object #" + obj["id"] + ")"
        indicator.description = indicator.title
        indicator.add_indicator_type("Malware Artifacts")
        indicator.add_valid_time_position(ValidTime())
        indicator.observable_composition_operator = "AND"
        for rindicator in tmp_incident.related_indicators:
            if rindicator.item.observable:
                indicator.add_observable(rindicator.item.observable)
        relatedIndicator = RelatedIndicator(indicator,
                                            relationship=obj["meta-category"])
        incident.related_indicators.append(relatedIndicator)
Example #24
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())
Example #25
0
def main():
    f = File()
    f.add_hash("4EC0027BEF4D7E1786A04D021FA8A67F")

    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(datetime.now(tzutc()))
    indicator.add_object(f)

    party_name = PartyName(name_lines=["Foo", "Bar"],
                           person_names=["John Smith", "Jill Smith"],
                           organisation_names=["Foo Inc.", "Bar Corp."])
    ident_spec = STIXCIQIdentity3_0(party_name=party_name)
    ident_spec.add_electronic_address_identifier("*****@*****.**")
    ident_spec.add_free_text_line("Demonstrating Free Text!")
    ident_spec.add_contact_number("555-555-5555")
    ident_spec.add_contact_number("555-555-5556")
    identity = CIQIdentity3_0Instance(specification=ident_spec)
    indicator.set_producer_identity(identity)

    stix_package = STIXPackage()
    stix_header = STIXHeader()
    stix_header.description = "Example 05"
    stix_package.stix_header = stix_header
    stix_package.add_indicator(indicator)

    xml = stix_package.to_xml()
    print(xml)
Example #26
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))
Example #27
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
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(encoding=None))
Example #29
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))
Example #30
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")