Example #1
0
def capecbuild(capecid):
    """Build a STIX package based on a CAPEC ID."""
    data = _get_attack(capecid)
    if data:
        try:
            from stix.utils import set_id_namespace
            namespace = {NS: NS_PREFIX}
            set_id_namespace(namespace)
        except ImportError:
            from mixbox.idgen import set_id_namespace
            from mixbox.namespaces import Namespace
            namespace = Namespace(NS, NS_PREFIX, "")
            set_id_namespace(namespace)

        pkg = STIXPackage()
        pkg.stix_header = STIXHeader()
        pkg = STIXPackage()
        pkg.stix_header = STIXHeader()
        pkg.stix_header.handling = _marking()

        ttp = _buildttp(data)

        if data['related_attacks']:
            ttp.related_ttps.append(
                _buildttp(_get_attack(str(data['related_attacks'][0]))))
        pkg.add_ttp(ttp)
        xml = pkg.to_xml()
        title = pkg.id_.split(':', 1)[-1]
        if __name__ == '__main__':
            _postconstruct(xml, title)
    return xml
Example #2
0
def cvebuild(var):
    """Search for a CVE ID and return a STIX formatted response."""
    cve = CVESearch()
    data = json.loads(cve.id(var))
    if data:
        try:
            from stix.utils import set_id_namespace
            namespace = {NS: NS_PREFIX}
            set_id_namespace(namespace)
        except ImportError:
            from mixbox.idgen import set_id_namespace
            from mixbox.namespaces import Namespace
            namespace = Namespace(NS, NS_PREFIX, "")
            set_id_namespace(namespace)

        pkg = STIXPackage()
        pkg.stix_header = STIXHeader()
        pkg = STIXPackage()
        pkg.stix_header = STIXHeader()

        pkg.stix_header.handling = _marking()

        # Define the exploit target
        expt = ExploitTarget()
        expt.title = data['id']
        expt.description = data['summary']
        expt.information_source = InformationSource(identity=Identity(
            name="National Vulnerability Database"))

        # Add the vulnerability object to the package object
        expt.add_vulnerability(_vulnbuild(data))

        # Add the COA object to the ET object
        for coa in COAS:
            expt.potential_coas.append(
                CourseOfAction(idref=coa['id'], timestamp=expt.timestamp))

        # Do some TTP stuff with CAPEC objects
        if TTPON is True:
            try:
                for i in data['capec']:
                    pkg.add_ttp(_buildttp(i, expt))
            except KeyError:
                pass

        expt.add_weakness(_weakbuild(data))

        # Add the exploit target to the package object
        pkg.add_exploit_target(expt)

        xml = pkg.to_xml()
        title = pkg.id_.split(':', 1)[-1]
        # If the function is not imported then output the xml to a file.
        if __name__ == '__main__':
            _postconstruct(xml, title)
        return xml
    else:
        sys.exit("[-] Error retrieving details for " + var)
Example #3
0
def cvebuild(var):
    """Search for a CVE ID and return a STIX formatted response."""
    cve = CVESearch()
    data = json.loads(cve.id(var))
    if data:
        try:
            from stix.utils import set_id_namespace
            namespace = {NS: NS_PREFIX}
            set_id_namespace(namespace)
        except ImportError:
            from stix.utils import idgen
            from mixbox.namespaces import Namespace
            namespace = Namespace(NS, NS_PREFIX, "")
            idgen.set_id_namespace(namespace)

        pkg = STIXPackage()
        pkg.stix_header = STIXHeader()
        pkg = STIXPackage()
        pkg.stix_header = STIXHeader()

        pkg.stix_header.handling = marking()

        # Define the exploit target
        expt = ExploitTarget()
        expt.title = data['id']
        expt.description = data['summary']

        # Add the vulnerability object to the package object
        expt.add_vulnerability(vulnbuild(data))

        # Do some TTP stuff with CAPEC objects
        try:
            for i in data['capec']:
                ttp = TTP()
                ttp.title = "CAPEC-" + str(i['id'])
                ttp.description = i['summary']
                ttp.exploit_targets.append(ExploitTarget(idref=expt.id_))
                pkg.add_ttp(ttp)
        except KeyError:
            pass

        # Do some weakness stuff
        if data['cwe'] != 'Unknown':
            weak = Weakness()
            weak.cwe_id = data['cwe']
            expt.add_weakness(weak)

        # Add the exploit target to the package object
        pkg.add_exploit_target(expt)

        xml = pkg.to_xml()

        # If the function is not imported then output the xml to a file.
        if __name__ == '__main__':
            title = pkg.id_.split(':', 1)[-1]
            with open(title + ".xml", "w") as text_file:
                text_file.write(xml)
        return xml
Example #4
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 #5
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 #6
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 #7
0
def generateMainPackage(events):
    stix_package = STIXPackage()
    stix_header = STIXHeader()
    stix_header.title="Export from " + namespace[1] + " MISP"
    stix_header.package_intents="Threat Report"
    stix_package.stix_header = stix_header
    return stix_package
Example #8
0
def main(args):
    if len(args) < 4:
        sys.exit("Invalid parameters")
    baseURL = args[1]
    if not baseURL:
        baseURL = 'https://www.misp-project.org'
    orgname = args[2]
    orgname = re.sub('[\W]+', '', orgname.replace(" ", "_"))
    NS_DICT[baseURL] = orgname
    try:
        idgen.set_id_namespace(Namespace(baseURL, orgname))
    except TypeError:
        idgen.set_id_namespace(Namespace(baseURL, orgname, "MISP"))
    stix_package = STIXPackage()
    stix_header = STIXHeader()
    stix_header.title = "Export from {} MISP".format(args[2])
    stix_header.package_intents = "Threat Report"
    stix_package.stix_header = stix_header
    stix_package.version = "1.1.1"
    stix_package.timestamp = datetime.datetime.now()
    if args[3] == 'json':
        stix_string = stix_package.to_json()[:-1]
        stix_string += ', "related_packages": ['
    else:
        stix_string = stix_package.to_xml(auto_namespace=False,
                                          ns_dict=NS_DICT,
                                          schemaloc_dict=SCHEMALOC_DICT)
        stix_string = stix_string.decode().replace("</stix:STIX_Package>\n",
                                                   "")
    print(stix_string)
Example #9
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))
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 #11
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 #12
0
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']:
        if info['bot'] not in ttps:
            ttps[info['bot']] = TTP(title=info['bot'])
            stix_package.add_ttp(ttps[info['bot']])

        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)

        stix_package.add_incident(incident)

    print(stix_package.to_xml(encoding=None))
def main():

    campaign = Campaign(title="Campaign against ICS")
    ttp = TTP(title="DrownedRat")

    alpha_report = Report()
    alpha_report.header = Header()
    alpha_report.header.title = "Report on Adversary Alpha's Campaign against the Industrial Control Sector"
    alpha_report.header.descriptions = "Adversary Alpha has a campaign against the ICS sector!"
    alpha_report.header.intents = "Campaign Characterization"
    alpha_report.add_campaign(Campaign(idref=campaign.id_))

    rat_report = Report()
    rat_report.header = Header()
    rat_report.header.title = "Indicators for Malware DrownedRat"
    rat_report.header.intents = "Indicators - Malware Artifacts"
    rat_report.add_ttp(TTP(idref=ttp.id_))

    wrapper = STIXPackage()
    info_src = InformationSource()
    info_src.identity = Identity(name="Government Sharing Program - GSP")
    wrapper.stix_header = STIXHeader(information_source=info_src)
    wrapper.add_report(alpha_report)
    wrapper.add_report(rat_report)
    wrapper.add_campaign(campaign)
    wrapper.add_ttp(ttp)

    print(wrapper.to_xml())
Example #14
0
 def test_to_xml_utf16_encoded(self):
     encoding = 'utf-16'
     s = STIXHeader()
     s.title = UNICODE_STR
     xml = s.to_xml(encoding=encoding)
     print(xml)
     self.assertTrue(UNICODE_STR in xml.decode(encoding))
Example #15
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 #16
0
def main():
    # Create a new STIXPackage
    stix_package = STIXPackage()

    # Create a new STIXHeader
    stix_header = STIXHeader()

    # Add Information Source. This is where we will add the tool information.
    stix_header.information_source = InformationSource()

    # Create a ToolInformation object. Use the initialization parameters
    # to set the tool and vendor names.
    #
    # Note: This is an instance of cybox.common.ToolInformation and NOT
    # stix.common.ToolInformation.
    tool = ToolInformation(tool_name="python-stix",
                           tool_vendor="The MITRE Corporation")

    # Set the Information Source "tools" section to a
    # cybox.common.ToolInformationList which contains our tool that we
    # created above.
    stix_header.information_source.tools = ToolInformationList(tool)

    # Set the header description
    stix_header.description = "Example"

    # Set the STIXPackage header
    stix_package.stix_header = stix_header

    # Print the XML!
    print(stix_package.to_xml())

    # Print the dictionary!
    pprint(stix_package.to_dict())
Example #17
0
def main():
    # Create our CybOX Simple Hash Value
    shv = Hash()
    shv.simple_hash_value = "4EC0027BEF4D7E1786A04D021FA8A67F"

    # Create a CybOX File Object and add the Hash we created above.
    f = File()
    h = Hash(shv, Hash.TYPE_MD5)
    f.add_hash(h)

    # Create the STIX Package
    stix_package = STIXPackage()

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

    # Add the File Hash Observable to the STIX Package. The add() method will
    # inspect the input and add it to the top-level stix_package.observables
    # collection.
    stix_package.add(f)

    # Print the XML!
    print(stix_package.to_xml())
Example #18
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 #19
0
def to_stix(infile):
    """Converts the `infile` OpenIOC xml document into a STIX Package.

    Args:
        infile: OpenIOC xml filename to translate

    Returns:
       stix.core.STIXPackage object
    """
    observables = to_cybox(infile)

    # Build Indicators from the Observable objects
    indicators = [_observable_to_indicator_stix(o) for o in observables]

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

    # Set the Indicators collection
    stix_package.indicators = Indicators(indicators)

    # Create and write the STIX Header. Warning: these fields have been
    # deprecated in STIX v1.2!
    stix_header = STIXHeader()
    stix_header.package_intent = PackageIntent.TERM_INDICATORS_MALWARE_ARTIFACTS
    stix_header.description = "CybOX-represented Indicators Translated from OpenIOC File"
    stix_package.stix_header = stix_header

    return stix_package
Example #20
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 #21
0
 def test_stix_header(self):
     header = STIXHeader()
     header.title = UNICODE_STR
     header.description = UNICODE_STR
     header.short_description = UNICODE_STR
     header2 = round_trip(header)
     self._test_equal(header, header2)
Example #22
0
 def init_stix(self):
     stix_package = STIXPackage()
     stix_header = STIXHeader()
     info_source = InformationSource()
     info_source.description = 'HAR file analysis of visit to malicious URL'
     stix_header.information_source = info_source
     stix_package.stix_header = stix_header
     return stix_package
Example #23
0
 def _add_header(self, stix_package, title, desc):
     stix_header = STIXHeader()
     stix_header.title = title
     stix_header.description = desc
     stix_header.information_source = InformationSource()
     stix_header.information_source.time = CyboxTime()
     stix_header.information_source.time.produced_time = datetime.now().isoformat()
     stix_package.stix_header = stix_header
Example #24
0
def main():
    mydata = loaddata()
    '''
    Your Namespace
    '''
    #    NAMESPACE = {sanitizer(mydata["NSXURL"]) : (mydata["NS"])}
    #    set_id_namespace(NAMESPACE)
    NAMESPACE = Namespace(sanitizer(mydata['NSXURL']), sanitizer(mydata['NS']))
    set_id_namespace(NAMESPACE)  # new ids will be prefixed by "myNS"

    wrapper = STIXPackage()
    info_src = InformationSource()
    info_src.identity = Identity(name=sanitizer(mydata["Identity"]))

    marking_specification = MarkingSpecification()
    marking_specification.controlled_structure = "//node() | //@*"
    tlp = TLPMarkingStructure()
    tlp.color = sanitizer(mydata["TLP_COLOR"])
    marking_specification.marking_structures.append(tlp)

    handling = Marking()
    handling.add_marking(marking_specification)

    timestamp = datetime.datetime.fromtimestamp(
        time.time()).strftime('%Y-%m-%d %H:%M:%S')
    MyTITLE = sanitizer(mydata["Title"])
    SHORT = timestamp

    DESCRIPTION = sanitizer(mydata["Description"])

    wrapper.stix_header = STIXHeader(information_source=info_src,
                                     title=MyTITLE,
                                     description=DESCRIPTION,
                                     short_description=SHORT)
    wrapper.stix_header.handling = handling

    indiDom = Indicator()
    indiDom.title = MyTITLE
    indiDom.add_indicator_type("IP Watchlist")

    for key in mydata["IOC"].keys():
        myip = Address(address_value=sanitizer(key), category=Address.CAT_IPV4)
        myip.condition = "Equals"

        obsu = Observable(myip)

        #if mydata[key].size:
        for idx, mydata["IOC"][key] in enumerate(mydata["IOC"][key]):
            ioc = File()
            ioc.add_hash(sanitizer(mydata["IOC"][key]))

            myip.add_related(ioc, "Downloaded")

        indiDom.add_observable(obsu)

    wrapper.add_indicator(indiDom)

    print(wrapper.to_xml())
Example #25
0
def main():
    # Create a CybOX File Object with a contained hash
    f = File()
    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)

    # Build our STIX CIQ Identity object
    party_name = stix_ciq.PartyName(name_lines=("Foo", "Bar"),
                                    person_names=("John Smith", "Jill Smith"),
                                    organisation_names=("Foo Inc.",
                                                        "Bar Corp."))
    ident_spec = stix_ciq.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")

    # Build and add a CIQ Address
    addr = stix_ciq.Address(free_text_address='1234 Example Lane.',
                            country='USA',
                            administrative_area='An Admin Area')
    ident_spec.add_address(addr)
    identity = stix_ciq.CIQIdentity3_0Instance(specification=ident_spec)

    # Set the Indicator producer identity to our CIQ Identity
    indicator.set_producer_identity(identity)

    # Build our STIX Package
    stix_package = STIXPackage()

    # Build a STIX Header and add a description
    stix_header = STIXHeader()
    stix_header.description = "STIX CIQ Identity Extension Example"

    # Set the STIX Header on our STIX Package
    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())

    # Print a dictionary!
    pprint(stix_package.to_dict())
Example #26
0
    def __init__(self, description='unknown', *args, **kwargs):
        self._description = description

        stix_package = STIXPackage()
        stix_header = STIXHeader()
        stix_header.description = self._description
        stix_package.stix_header = stix_header

        self._handle = stix_package
Example #27
0
    def __repr__(self):
        stix_package = STIXPackage()
        stix_header = STIXHeader()
        stix_package.stix_header = stix_header

        for d in self.data:
            i = self._create_indicator(d)
            stix_package.add_indicator(i)
        return str(stix_package.to_xml())
Example #28
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()
Example #29
0
def buildSTIX(ident,confid,restconfid, effect, resteffect,typeIncident,resttype,asset,restasset,hashPkg):
    # IMPLEMENTATION WORKAROUND - 
    # restConfid --> header.description
    # resteffect --> breach.description
    # resttype --> reporter.description
    # restasset --> reporter.identity.name 
    # setup stix document
    stix_package = STIXPackage()
    stix_header = STIXHeader()
    stix_header.description = restconfid # "Example description"
    stix_package.stix_header = stix_header
    # add incident and confidence
    breach = Incident(id_=ident)
    breach.description = resteffect # "Intrusion into enterprise network"
    breach.confidence = Confidence()
    breach.confidence.value=confid
    print("confidence set to %s"%(str(breach.confidence.value)))
    breach._binding_class.xml_type = typeIncident
    print("incident set to %s"%(str(breach._binding_class.xml_type)))
    # stamp with reporter
    breach.reporter = InformationSource()
    breach.reporter.description = resttype #"The person who reported it"

    breach.reporter.time = Time()
    breach.reporter.time.produced_time = datetime.strptime("2014-03-11","%Y-%m-%d") # when they submitted it

    breach.reporter.identity = Identity()
    breach.reporter.identity.name = restasset 

    # set incident-specific timestamps
    breach.time = incidentTime()
    breach.title = "Breach of Company Dynamics"
    breach.time.initial_compromise = datetime.strptime("2012-01-30", "%Y-%m-%d") 
    breach.time.incident_discovery = datetime.strptime("2012-05-10", "%Y-%m-%d") 
    breach.time.restoration_achieved = datetime.strptime("2012-08-10", "%Y-%m-%d") 
    breach.time.incident_reported = datetime.strptime("2012-12-10", "%Y-%m-%d") 

    affected_asset = AffectedAsset()
    affected_asset.description = "Database server at hr-data1.example.com" 
    affected_asset.type_ = asset
    
    breach.affected_assets = affected_asset
    # add the victim
    breach.add_victim (hashPkg)

    # add the impact
    impact = ImpactAssessment()
    impact.add_effect(effect)
    breach.impact_assessment = impact


    stix_package.add_incident(breach)
 
    return stix_package
Example #30
0
def generateEventPackage(event):
    package_name = namespace[1] + ':STIXPackage-' + event["Event"]["uuid"]
    stix_package = STIXPackage(id_=package_name)
    stix_header = STIXHeader()
    stix_header.title="MISP event #" + event["Event"]["id"] + " uuid: " + event["Event"]["uuid"]
    stix_header.package_intents="Threat Report"
    stix_package.stix_header = stix_header
    objects = generateSTIXObjects(event)
    incident = objects[0]
    ttps = objects[1]
    stix_package.add_incident(incident)
    for ttp in ttps:
        stix_package.add_ttp(ttp)
    return stix_package