Ejemplo n.º 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
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())
def main():
    from stix.campaign import Campaign
    from stix.common.related import RelatedTTP
    from stix.core import STIXPackage
    from stix.ttp import TTP

    ttp = TTP()
    ttp.title = "Victim Targeting: Customer PII and Financial Data"
    ttp.victim_targeting.add_targeted_information("Information Assets - Customer PII")
    ttp.victim_targeting.add_targeted_information("Information Assets - Financial Data")

    ttp_ref = TTP()
    ttp_ref.idref = ttp.id_
    related_ttp = RelatedTTP(ttp_ref)
    related_ttp.relationship = "Targets"

    c = Campaign()
    c.title = "Operation Alpha"
    c.related_ttps.append(related_ttp)

    pkg = STIXPackage()
    pkg.add_campaign(c)
    pkg.add_ttp(ttp)

    print pkg.to_xml()
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))
Ejemplo n.º 5
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():
    stix_package = STIXPackage()
    ttp_phishing = TTP(title="Phishing")

    attack_pattern = AttackPattern()
    attack_pattern.capec_id = "CAPEC-98"
    attack_pattern.description = ("Phishing")

    ttp_phishing.behavior = Behavior()
    ttp_phishing.behavior.add_attack_pattern(attack_pattern)

    ttp_pivy = TTP(title="Poison Ivy Variant d1c6")
    malware_instance = MalwareInstance()
    malware_instance.add_name("Poison Ivy Variant d1c6")
    malware_instance.add_type("Remote Access Trojan")

    ttp_pivy.behavior = Behavior()
    ttp_pivy.behavior.add_malware_instance(malware_instance)

    ta_bravo = ThreatActor(title="Adversary Bravo")
    ta_bravo.identity = Identity(name="Adversary Bravo")

    related_ttp_phishing = RelatedTTP(TTP(idref=ttp_phishing.id_),
                                      relationship="Leverages Attack Pattern")
    ta_bravo.observed_ttps.append(related_ttp_phishing)

    related_ttp_pivy = RelatedTTP(TTP(idref=ttp_pivy.id_),
                                  relationship="Leverages Malware")
    ta_bravo.observed_ttps.append(related_ttp_pivy)

    stix_package.add_ttp(ttp_phishing)
    stix_package.add_ttp(ttp_pivy)
    stix_package.add_threat_actor(ta_bravo)

    print stix_package.to_xml()
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()
Ejemplo n.º 8
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)
Ejemplo n.º 9
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
def main():
    stix_package = STIXPackage()
    ttp_phishing = TTP(title="Phishing")

    attack_pattern = AttackPattern()
    attack_pattern.capec_id = "CAPEC-98"
    attack_pattern.description = ("Phishing")

    ttp_phishing.behavior = Behavior()
    ttp_phishing.behavior.add_attack_pattern(attack_pattern)

    ttp_pivy = TTP(title="Poison Ivy Variant d1c6")
    malware_instance = MalwareInstance()
    malware_instance.add_name("Poison Ivy Variant d1c6")
    malware_instance.add_type("Remote Access Trojan")

    ttp_pivy.behavior = Behavior()
    ttp_pivy.behavior.add_malware_instance(malware_instance)

    ta_bravo = ThreatActor(title="Adversary Bravo")
    ta_bravo.identity = Identity(name="Adversary Bravo")

    related_ttp_phishing = RelatedTTP(TTP(idref=ttp_phishing.id_), relationship="Leverages Attack Pattern")
    ta_bravo.observed_ttps.append(related_ttp_phishing)

    related_ttp_pivy = RelatedTTP(TTP(idref=ttp_pivy.id_), relationship="Leverages Malware")
    ta_bravo.observed_ttps.append(related_ttp_pivy)

    stix_package.add_ttp(ttp_phishing)
    stix_package.add_ttp(ttp_pivy)
    stix_package.add_threat_actor(ta_bravo)

    print(stix_package.to_xml(encoding=None))
def main():
    stix_package = STIXPackage()
    
    addr1 = Observable(Address(address_value="198.51.100.2", category=Address.CAT_IPV4))
    addr2 = Observable(Address(address_value="198.51.100.17", category=Address.CAT_IPV4))
    addr3 = Observable(Address(address_value="203.0.113.19", category=Address.CAT_IPV4))
    
    stix_package.add_observable(addr1)
    stix_package.add_observable(addr2)
    stix_package.add_observable(addr3)
    
    obs_addr1 = Observable()
    obs_addr2 = Observable()
    obs_addr3 = Observable()
    
    obs_addr1.id_ = None
    obs_addr2.id_ = None
    obs_addr3.id_ = None
    
    obs_addr1.idref = addr1.id_
    obs_addr2.idref = addr2.id_
    obs_addr3.idref = addr3.id_
    
    infrastructure = Infrastructure()
    infrastructure.observable_characterization = Observables([obs_addr1, obs_addr2, obs_addr3])
    
    resource = Resource()
    resource.infrastructure = infrastructure
    
    ttp = TTP(title="Malware C2 Channel")
    ttp.resources = resource
    
    stix_package.add_ttp(ttp)
    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))
Ejemplo n.º 13
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()
Ejemplo n.º 14
0
def main():
    from stix.campaign import Campaign
    from stix.common.related import RelatedTTP
    from stix.core import STIXPackage
    from stix.ttp import TTP, VictimTargeting

    ttp = TTP()
    ttp.title = "Victim Targeting: Customer PII and Financial Data"
    ttp.victim_targeting = VictimTargeting()
    ttp.victim_targeting.add_targeted_information(
        "Information Assets - Customer PII")
    ttp.victim_targeting.add_targeted_information(
        "Information Assets - Financial Data")

    ttp_ref = TTP()
    ttp_ref.idref = ttp.id_
    related_ttp = RelatedTTP(ttp_ref)
    related_ttp.relationship = "Targets"

    c = Campaign()
    c.title = "Operation Alpha"
    c.related_ttps.append(related_ttp)

    pkg = STIXPackage()
    pkg.add_campaign(c)
    pkg.add_ttp(ttp)

    print(pkg.to_xml(encoding=None))
def main():
    stix_package = STIXPackage()
    ttp = TTP(title="Phishing")
    stix_package.add_ttp(ttp)

    # Create the indicator for just the subject
    email_subject_object = EmailMessage()
    email_subject_object.header = EmailHeader()
    email_subject_object.header.subject = "[IMPORTANT] Please Review Before"
    email_subject_object.header.subject.condition = "StartsWith"
    
    email_subject_indicator = Indicator()
    email_subject_indicator.title = "Malicious E-mail Subject Line"
    email_subject_indicator.add_indicator_type("Malicious E-mail")
    email_subject_indicator.observable = email_subject_object
    email_subject_indicator.confidence = "Low"

    # Create the indicator for just the attachment

    file_attachment_object = EmailMessage()
    file_attachment_object.attachments = Attachments()

    attached_file_object = File()
    attached_file_object.file_name = "Final Report"
    attached_file_object.file_name.condition = "StartsWith"
    attached_file_object.file_extension = "doc.exe"
    attached_file_object.file_extension.condition = "Equals"

    file_attachment_object.add_related(attached_file_object, "Contains", inline=True)
    file_attachment_object.attachments.append(file_attachment_object.parent.id_)
    
    indicator_attachment = Indicator()
    indicator_attachment.title = "Malicious E-mail Attachment"
    indicator_attachment.add_indicator_type("Malicious E-mail")
    indicator_attachment.observable = file_attachment_object
    indicator_attachment.confidence = "Low"

    # Create the combined indicator w/ both subject an attachment
    full_email_object = EmailMessage()
    full_email_object.attachments = Attachments()

    # Add the previously referenced file as another reference rather than define it again:
    full_email_object.attachments.append(file_attachment_object.parent.id_)

    full_email_object.header = EmailHeader()
    full_email_object.header.subject = "[IMPORTANT] Please Review Before"
    full_email_object.header.subject.condition = "StartsWith"

    combined_indicator = Indicator(title="Malicious E-mail")
    combined_indicator.add_indicator_type("Malicious E-mail")
    combined_indicator.confidence = Confidence(value="High")
    combined_indicator.observable = full_email_object
    
    email_subject_indicator.add_indicated_ttp(TTP(idref=ttp.id_))
    indicator_attachment.add_indicated_ttp(TTP(idref=ttp.id_))
    combined_indicator.add_indicated_ttp(TTP(idref=ttp.id_))
    
    stix_package.indicators = [combined_indicator, email_subject_indicator, indicator_attachment]
    print stix_package.to_xml()
Ejemplo n.º 16
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
Ejemplo n.º 17
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)
Ejemplo n.º 18
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
def main():
    ciq_identity = CIQIdentity3_0Instance()
    identity_spec = STIXCIQIdentity3_0()
    identity_spec.organisation_info = OrganisationInfo(industry_type="Electricity, Industrial Control Systems")
    ciq_identity.specification = identity_spec

    ttp = TTP(title="Victim Targeting: Electricity Sector and Industrial Control System Sector")
    ttp.victim_targeting = VictimTargeting()
    ttp.victim_targeting.identity = ciq_identity

    stix_package = STIXPackage()
    stix_package.add_ttp(ttp)

    print(stix_package.to_xml(encoding=None))
def main():
    maec_malware_instance = MAECInstance()
    maec_malware_instance.add_name("Poison Ivy Variant v4392-acc")
    maec_malware_instance.add_type("Remote Access Trojan")
    maec_malware_instance.maec = etree.fromstring(MAEC_XML, parser=etree.ETCompatXMLParser())

    ttp = TTP(title="Poison Ivy Variant v4392-acc")
    ttp.behavior = Behavior()
    ttp.behavior.add_malware_instance(maec_malware_instance)

    stix_package = STIXPackage()
    stix_package.add_ttp(ttp)

    print(stix_package.to_xml(encoding=None))
Ejemplo n.º 21
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
Ejemplo n.º 22
0
def main():
    maec_malware_instance = MAECInstance()
    maec_malware_instance.add_name("Poison Ivy Variant v4392-acc")
    maec_malware_instance.add_type("Remote Access Trojan")
    maec_malware_instance.maec = etree.fromstring(
        MAEC_XML, parser=etree.ETCompatXMLParser())

    ttp = TTP(title="Poison Ivy Variant v4392-acc")
    ttp.behavior = Behavior()
    ttp.behavior.add_malware_instance(maec_malware_instance)

    stix_package = STIXPackage()
    stix_package.add_ttp(ttp)

    print stix_package.to_xml()
Ejemplo n.º 23
0
def generateEventPackage(event):
    package_name = namespace[1] + ':STIXPackage-' + event["Event"]["uuid"]
    timestamp = getDateFromTimestamp(int(event["Event"]["timestamp"]))
    stix_package = STIXPackage(id_=package_name, timestamp=timestamp)
    stix_header = STIXHeader()
    stix_header.title=event["Event"]["info"] + " (MISP Event #" + event["Event"]["id"] + ")"
    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
Ejemplo n.º 24
0
def generateEventPackage(event):
    package_name = namespace[1] + ":STIXPackage-" + event["Event"]["uuid"]
    timestamp = getDateFromTimestamp(int(event["Event"]["timestamp"]))
    stix_package = STIXPackage(id_=package_name, timestamp=timestamp)
    stix_header = STIXHeader()
    stix_header.title = event["Event"]["info"] + " (MISP Event #" + event["Event"]["id"] + ")"
    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
Ejemplo n.º 25
0
 def generateEventPackage(self):
     package_name = "{}:STIXPackage-{}".format(namespace[1], self.misp_event.uuid)
     # timestamp = self.get_date_from_timestamp(int(str(self.misp_event.timestamp)))
     timestamp = self.misp_event.timestamp
     stix_package = STIXPackage(id_=package_name, timestamp=timestamp)
     stix_package.version = "1.1.1"
     stix_header = STIXHeader()
     stix_header.title = "Export from {} MISP".format(self.namespace_prefix)
     stix_header.package_intents = "Threat Report"
     stix_package.stix_header = stix_header
     incident = self.generate_stix_objects()
     stix_package.add_incident(incident)
     for ttp in self.ttps:
         stix_package.add_ttp(ttp)
     self.stix_package = stix_package
def main():
    stix_package = STIXPackage()
    ttp = TTP(title="C2 Behavior")

    indicator = Indicator(title="IP Address for known C2 Channel")
    indicator.add_indicator_type("IP Watchlist")

    addr = Address(address_value="10.0.0.0", category=Address.CAT_IPV4)
    addr.condition = "Equals"
    indicator.add_observable(addr)
    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():
    stix_package = STIXPackage()
    ttp = TTP(title="C2 Behavior")

    indicator = Indicator(title="IP Address for known C2 Channel")
    indicator.add_indicator_type("IP Watchlist")

    addr = Address(address_value="10.0.0.0", category=Address.CAT_IPV4)
    addr.condition = "Equals"
    indicator.add_observable(addr)
    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():
    malware = MalwareInstance()
    malware.add_name("Poison Ivy")
    malware.add_type("Remote Access Trojan")
    
    ttp = TTP(title="Poison Ivy")
    ttp.behavior = Behavior()
    ttp.behavior.add_malware_instance(malware)
    
    incident = Incident(title="Detected Poison Ivy beaconing through perimeter firewalls")
    related_ttp = RelatedTTP(TTP(idref=ttp.id_), relationship="Uses Malware")
    incident.leveraged_ttps.append(related_ttp)
    
    stix_package = STIXPackage()
    stix_package.add_ttp(ttp)
    stix_package.add_incident(incident)
    
    print stix_package.to_xml() 
Ejemplo n.º 29
0
def main():
    ciq_identity = CIQIdentity3_0Instance()
    identity_spec = STIXCIQIdentity3_0()
    identity_spec.organisation_info = OrganisationInfo(
        industry_type="Electricity, Industrial Control Systems")
    ciq_identity.specification = identity_spec

    ttp = TTP(
        title=
        "Victim Targeting: Electricity Sector and Industrial Control System Sector"
    )
    ttp.victim_targeting = VictimTargeting()
    ttp.victim_targeting.identity = ciq_identity

    stix_package = STIXPackage()
    stix_package.add_ttp(ttp)

    print stix_package.to_xml()
Ejemplo n.º 30
0
def wrap_maec(maec_package, file_name=None):
    """Wrap a MAEC Package in a STIX TTP/Package. Return the newly created STIX Package.

    Args:
        maec_package: the ``maec.package.package.Package`` instance to wrap in STIX.
        file_name: the name of the input file from which the MAEC Package originated,
            to be used in the Title of the STIX TTP that wraps the MAEC Package. Optional.

    Returns:
        A ``stix.STIXPackage`` instance with a single TTP that wraps the input MAEC Package.
    """

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

    # Create the STIX MAEC Instance
    maec_malware_instance = MAECInstance()
    maec_malware_instance.maec = maec_package

    # Create the STIX TTP that includes the MAEC Instance
    ttp = TTP()
    ttp.behavior = Behavior()
    ttp.behavior.add_malware_instance(maec_malware_instance)

    # Create the STIX Package and add the TTP to it
    stix_package = STIXPackage()
    stix_package.add_ttp(ttp)

    # Create the STIX Header and add it to the Package
    stix_header = STIXHeader()
    if file_name:
        stix_header.title = "STIX TTP wrapper around MAEC file: " + str(
            file_name)
    stix_header.add_package_intent("Malware Characterization")
    # Add the Information Source to the STIX Header
    tool_info = ToolInformation()
    stix_header.information_source = InformationSource()
    tool_info.name = "MAEC to STIX"
    tool_info.version = str(maec_to_stix.__version__)
    stix_header.information_source.tools = ToolInformationList(tool_info)
    stix_package.stix_header = stix_header

    return stix_package
def main():
    malware = MalwareInstance()
    malware.add_name("Poison Ivy")
    malware.add_type("Remote Access Trojan")

    ttp = TTP(title="Poison Ivy")
    ttp.behavior = Behavior()
    ttp.behavior.add_malware_instance(malware)

    incident = Incident(
        title="Detected Poison Ivy beaconing through perimeter firewalls")
    related_ttp = RelatedTTP(TTP(idref=ttp.id_), relationship="Uses Malware")
    incident.leveraged_ttps.append(related_ttp)

    stix_package = STIXPackage()
    stix_package.add_ttp(ttp)
    stix_package.add_incident(incident)

    print(stix_package.to_xml(encoding=None))
Ejemplo n.º 32
0
def wrap_maec(maec_package, file_name=None):
    """Wrap a MAEC Package in a STIX TTP/Package. Return the newly created STIX Package.

    Args:
        maec_package: the ``maec.package.package.Package`` instance to wrap in STIX.
        file_name: the name of the input file from which the MAEC Package originated,
            to be used in the Title of the STIX TTP that wraps the MAEC Package. Optional.

    Returns:
        A ``stix.STIXPackage`` instance with a single TTP that wraps the input MAEC Package.
    """

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

    # Create the STIX MAEC Instance
    maec_malware_instance = MAECInstance()
    maec_malware_instance.maec = maec_package
    
    # Create the STIX TTP that includes the MAEC Instance
    ttp = TTP()
    ttp.behavior = Behavior()
    ttp.behavior.add_malware_instance(maec_malware_instance)
    
    # Create the STIX Package and add the TTP to it
    stix_package = STIXPackage()
    stix_package.add_ttp(ttp)

    # Create the STIX Header and add it to the Package
    stix_header = STIXHeader()
    if file_name:
        stix_header.title = "STIX TTP wrapper around MAEC file: " + str(file_name)
    stix_header.add_package_intent("Malware Characterization")
    # Add the Information Source to the STIX Header
    tool_info = ToolInformation()
    stix_header.information_source = InformationSource()
    tool_info.name = "MAEC to STIX"
    tool_info.version = str(maec_to_stix.__version__)
    stix_header.information_source.tools = ToolInformationList(tool_info)
    stix_package.stix_header = stix_header
    
    return stix_package
def main():
    stix_package = STIXPackage()

    addr1 = Observable(
        Address(address_value="198.51.100.2", category=Address.CAT_IPV4))
    addr2 = Observable(
        Address(address_value="198.51.100.17", category=Address.CAT_IPV4))
    addr3 = Observable(
        Address(address_value="203.0.113.19", category=Address.CAT_IPV4))

    stix_package.add_observable(addr1)
    stix_package.add_observable(addr2)
    stix_package.add_observable(addr3)

    obs_addr1 = Observable()
    obs_addr2 = Observable()
    obs_addr3 = Observable()

    obs_addr1.id_ = None
    obs_addr2.id_ = None
    obs_addr3.id_ = None

    obs_addr1.idref = addr1.id_
    obs_addr2.idref = addr2.id_
    obs_addr3.idref = addr3.id_

    vocab_string = VocabString(value='Malware C2')

    infrastructure = Infrastructure()
    infrastructure.observable_characterization = Observables(
        [obs_addr1, obs_addr2, obs_addr3])
    infrastructure.add_type(vocab_string)

    resource = Resource()
    resource.infrastructure = infrastructure

    ttp = TTP(title="Malware C2 Channel")
    ttp.resources = resource

    stix_package.add_ttp(ttp)
    print(stix_package.to_xml())
Ejemplo n.º 34
0
def main():

    fileIn = open('tor_exit_node_list.txt', 'r')
    fileOut = open('tor_stix.xml', 'w')

    #print("List of Tor Exit nodes as of 5/4/2018")
    ip_addr_list = []

    for line in fileIn:

        ip_addr = re.search(
            '(([2][5][0-5]\.)|([2][0-4][0-9]\.)|([0-1]?[0-9]?[0-9]\.)){3}(([2][5][0-5])|([2][0-4][0-9])|([0-1]?[0-9]?[0-9]))',
            line)
        if ip_addr:
            ip_addr_list.append(ip_addr)
            #print("    ", ip_addr.group(0))

    stix_package = STIXPackage()
    ttp = TTP(title="Tor Exit Nodes")

    i = 0
    for ip_addr in ip_addr_list:

        indicator = Indicator(title="IP Address for known Tor exit Node")
        indicator.add_indicator_type("IP Watchlist")
        addr = Address(address_value=ip_addr.group(0),
                       category=Address.CAT_IPV4)
        addr.condition = "Equals"
        indicator.add_observable(addr)
        indicator.add_indicated_ttp(TTP(idref=ttp.id_))

        stix_package.add_indicator(indicator)
        print(i)
        i = i + 1

    stix_package.add_ttp(ttp)

    #print(stix_package.to_xml(encoding=None))
    fileOut.write(stix_package.to_xml(encoding=None))
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))
def main():
    stix_package = STIXPackage()
        
    malware_instance = MalwareInstance()
    malware_instance.add_name("Poison Ivy")
    malware_instance.add_type("Remote Access Trojan")
    
    ttp = TTP(title="Poison Ivy")
    ttp.behavior = Behavior()
    ttp.behavior.add_malware_instance(malware_instance)
    
    file_object = File()
    file_object.add_hash(Hash("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"))
    
    indicator = Indicator(title="File hash for Poison Ivy variant")
    indicator.add_indicator_type("File Hash Watchlist")
    indicator.add_observable(file_object)
    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():
    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))
def main():

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

    stix_package = STIXPackage()

    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']])

        indicator = Indicator(title=info['ip'])
        indicator.add_indicator_type("IP Watchlist")

        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)

    print stix_package.to_xml()
def main():
    stix_package = STIXPackage()
        
    malware_instance = MalwareInstance()
    malware_instance.add_name("Poison Ivy")
    malware_instance.add_type("Remote Access Trojan")
    
    ttp = TTP(title="Poison Ivy")
    ttp.behavior = Behavior()
    ttp.behavior.add_malware_instance(malware_instance)
    
    file_object = File()
    file_object.add_hash(Hash("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"))
    file_object.hashes[0].simple_hash_value.condition = "Equals"
    
    indicator = Indicator(title="File hash for Poison Ivy variant")
    indicator.add_indicator_type("File Hash Watchlist")
    indicator.add_observable(file_object)
    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():

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

  stix_package = STIXPackage()

  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']])

    indicator = Indicator(title=info['ip'])
    indicator.add_indicator_type("IP Watchlist")

    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)

  print stix_package.to_xml()
def main():
    # NOTE: ID values will differ due to being regenerated on each script execution
    pkg1 = STIXPackage()
    pkg1.title = "Example of Indicator Composition for an aggregate indicator composition"

    # USE CASE: Indicator with aggregate pattern

    # Add TTP for malware usage
    malware_ttp = TTP()
    malware_ttp.behavior = Behavior()

    malware = MalwareInstance()
    malware.title = "foobar malware"
    malware.add_type("Remote Access Trojan")
    malware_ttp.behavior.add_malware_instance(malware)

    c2_ttp = TTP()
    c2_ttp.resources = Resource()
    c2_ttp.resources.infrastructure = Infrastructure()
    c2_ttp.resources.infrastructure.add_type(VocabString("Malware C2"))

    pkg1.add_ttp(c2_ttp)
    pkg1.add_ttp(malware_ttp)

    nw_ind = Indicator()
    nw_ind.description = "Indicator for a particular C2 infstructure IP address."
    # add network network connection to this indicator
    obs = NetworkConnection()
    sock = SocketAddress()
    sock.ip_address = "46.123.99.25"
    sock.ip_address.category = "ipv4-addr"
    sock.ip_address.condition = "Equals"
    obs.destination_socket_address = sock
    nw_ind.add_observable(obs)

    nw_ind.add_indicated_ttp(TTP(idref=c2_ttp.id_))

    # create File Hash indicator w/ embedded Observable
    file_ind = Indicator()

    file_ind.description = "Indicator for the hash of the foobar malware."
    file_ind.add_indicator_type("File Hash Watchlist")

    file_obs = File()
    file_obs.add_hash("01234567890abcdef01234567890abcdef")
    file_obs.hashes[0].type_ = "MD5"
    file_obs.hashes[0].type_.condition = "Equals"
    file_ind.add_observable(file_obs)

    # create references
    file_ind.add_indicated_ttp(TTP(idref=malware_ttp.id_))

    # create container indicator
    ind = Indicator()
    ind.add_indicator_type(VocabString("Campaign Characteristics"))
    ind.description = "Indicator for a composite of characteristics for the use of specific malware and C2 infrastructure within a Campaign."

    # Add campaign with related
    camp = Campaign()
    camp.title = "holy grail"
    pkg1.add_campaign(camp)
    camp.related_ttps.append(TTP(idref=c2_ttp.id_))
    camp.related_ttps.append(TTP(idref=malware_ttp.id_))

    # Add threat actor
    ta = ThreatActor()
    ta.identity = Identity()
    ta.identity.name = "boobear"
    ta.observed_ttps.append(TTP(idref=malware_ttp.id_))
    pkg1.add_threat_actor(ta)

    # Create composite expression

    ind.composite_indicator_expression = CompositeIndicatorExpression()
    ind.composite_indicator_expression.operator = "AND"

    ind.composite_indicator_expression.append(file_ind)
    ind.composite_indicator_expression.append(nw_ind)

    pkg1.add_indicator(ind)

    print pkg1.to_xml()

    #  USE CASE: Indicator with partial matching

    pkg2 = STIXPackage()
    pkg2.title = "Example of Indicator Composition for a one of many indicator composition"

    # create container indicator
    watchlistind = Indicator()
    watchlistind.add_indicator_type("IP Watchlist")
    watchlistind.description = "This Indicator specifies a pattern where any one or more of a set of three IP addresses are observed."

    watchlistind.add_indicated_ttp(TTP(idref=c2_ttp.id_))

    # Create composite expression
    watchlistind.composite_indicator_expression = CompositeIndicatorExpression(
    )
    watchlistind.composite_indicator_expression.operator = "OR"

    ips = ['23.5.111.68', '23.5.111.99', '46.123.99.25']
    for ip in ips:
        new_ind = Indicator()
        new_ind.description = "This Indicator specifies a pattern where one specific IP address is observed"
        # add network network connection to this indicator
        obs = Address()
        obs.address_value = ip
        obs.address_value.condition = "Equals"
        new_ind.add_observable(obs)

        new_ind.add_indicated_ttp(TTP(idref=c2_ttp.id_))

        watchlistind.composite_indicator_expression.append(new_ind)

    pkg2.add_indicator(watchlistind)

    print pkg2.to_xml()

    #  USE CASE: Indicator with compound detection

    pkg3 = STIXPackage()
    pkg3.title = "Example of Indicator Composition for compound detection"

    # create container indicator
    watchlistind2 = Indicator()
    watchlistind2.add_indicator_type("IP Watchlist")
    watchlistind2.description = "This Indicator specifies a composite condition of two preexisting Indicators (each identifying a particular TTP with low confidence) that in aggregate identify the particular TTP with high confidence."
    # Create composite expression
    watchlistind2.composite_indicator_expression = CompositeIndicatorExpression(
    )
    watchlistind2.composite_indicator_expression.operator = "OR"

    watchlistind2.add_indicated_ttp(TTP(idref=c2_ttp.id_))
    watchlistind2.confidence = "High"

    nw_ind.description = "Indicator for a particular C2 IP address used by a malware variant."
    nw_ind.confidence = "Low"
    nw_ind.indicator_types = ["C2"]
    file_ind.description = "Indicator that contains malicious file hashes for a particular malware variant."
    file_ind.confidence = "Low"
    watchlistind2.composite_indicator_expression.append(nw_ind)
    watchlistind2.composite_indicator_expression.append(file_ind)

    pkg3.add_indicator(watchlistind2)

    print pkg3.to_xml()
Ejemplo n.º 42
0
    def toStixXml(self, confidence, efficacy):
        """
        This method converts a list of FASGuard generated Snort rules  into a STIX
        compliant XML string ready for output. It first converts the object
        into a hash of the right format and then converts it into XML using
        STIXPackage.from_dict and to_xml on the resulting object.

        Arguments:

        confidence - High, Medium or Low. High means low false alarm rate.
        efficacy - High, Medium or Low. High means a low missed detection rate.

        Returns:

        Reference to string containing STIX/CybOX XML file.
        """
        logger = logging.getLogger('simple_example')
        self.logger = logger
        self.logger.debug('In asg.fasguardStixRule')
        stix_package = STIXPackage()

        # Build the Exploit Target
        vuln = Vulnerability()
        vuln.cve_id = "Unknown"

        et = ExploitTarget(title="From FASGuard")
        et.add_vulnerability(vuln)

        stix_package.add_exploit_target(et)

        # Build the TTP
        ttp = TTP(title="FASGuard Produced Signatures")
        ttp.exploit_targets.append(ExploitTarget(idref=et.id_))

        stix_package.add_ttp(ttp)

        # Build the indicator
        indicator = Indicator(title="Snort Signature from FASGuard")
        indicator.confidence = Confidence(confidence)

        tm = SnortTestMechanism()
        tm.rules = self.ruleList
        tm.efficacy = efficacy
        tm.producer = InformationSource(identity=Identity(name="FASGuard"))
        tm.producer.references = ["http://fasguard.github.io/"]
        indicator.test_mechanisms = [tm]
        indicator.add_indicated_ttp(TTP(idref=ttp.id_))

        stix_package.add_indicator(indicator)

        return stix_package.to_xml()

        # stixDict = {'campaigns': [{}],
        #             'courses_of_action': [{}],
        #             'exploit_targets': [{}],
        #             'id': 'INSERT_PACKAGE_ID_HERE'}
        # stixDict['indicators'] = [{'indicator':
        #                            {'title':
        #                             'Automatically Generated FASGuard Signatures',
        #                             'test_mechanisms':
        #                             {'test_mechanism':
        #                              {'efficacy':'Low',
        #                               'producer':
        #                               {'Identity':'FASGuard'},
        #                               'rule':'xyz'}}}}
        # ]
        stix_package = STIXPackage.from_dict(stixDict)
        stix_xml = stix_package.to_xml()
        return stix_xml
Ejemplo n.º 43
0
def main():
    stix_package = STIXPackage()
    ttp = TTP(title="Phishing")
    stix_package.add_ttp(ttp)

    # Create the indicator for just the subject
    email_subject_object = EmailMessage()
    email_subject_object.header = EmailHeader()
    email_subject_object.header.subject = "[IMPORTANT] Please Review Before"
    email_subject_object.header.subject.condition = "StartsWith"

    email_subject_indicator = Indicator()
    email_subject_indicator.title = "Malicious E-mail Subject Line"
    email_subject_indicator.add_indicator_type("Malicious E-mail")
    email_subject_indicator.observable = email_subject_object
    email_subject_indicator.confidence = "Low"

    # Create the indicator for just the attachment

    file_attachment_object = EmailMessage()
    file_attachment_object.attachments = Attachments()

    attached_file_object = File()
    attached_file_object.file_name = "Final Report"
    attached_file_object.file_name.condition = "StartsWith"
    attached_file_object.file_extension = "doc.exe"
    attached_file_object.file_extension.condition = "Equals"

    file_attachment_object.add_related(attached_file_object,
                                       "Contains",
                                       inline=True)
    file_attachment_object.attachments.append(attached_file_object.parent.id_)

    indicator_attachment = Indicator()
    indicator_attachment.title = "Malicious E-mail Attachment"
    indicator_attachment.add_indicator_type("Malicious E-mail")
    indicator_attachment.observable = file_attachment_object
    indicator_attachment.confidence = "Low"

    # Create the combined indicator w/ both subject an attachment
    full_email_object = EmailMessage()
    full_email_object.attachments = Attachments()

    # Add the previously referenced file as another reference rather than define it again:
    full_email_object.attachments.append(attached_file_object.parent.id_)

    full_email_object.header = EmailHeader()
    full_email_object.header.subject = "[IMPORTANT] Please Review Before"
    full_email_object.header.subject.condition = "StartsWith"

    combined_indicator = Indicator(title="Malicious E-mail")
    combined_indicator.add_indicator_type("Malicious E-mail")
    combined_indicator.confidence = Confidence(value="High")
    combined_indicator.observable = full_email_object

    email_subject_indicator.add_indicated_ttp(TTP(idref=ttp.id_))
    indicator_attachment.add_indicated_ttp(TTP(idref=ttp.id_))
    combined_indicator.add_indicated_ttp(TTP(idref=ttp.id_))

    stix_package.add_indicator(combined_indicator)
    stix_package.add_indicator(email_subject_indicator)
    stix_package.add_indicator(indicator_attachment)
    print(stix_package.to_xml(encoding=None))
Ejemplo n.º 44
0
def genStixDoc(
        outputDir_,
        targetFileSha1_,
        targetFileSha256_,
        targetFileSha512_,
        targetFileSsdeep_,
        targetFileMd5_,
        targetFileSize_,
        targetFileName_,
        ipv4Addresses_,
        hostNames_):
    """
    Generate Stix document from the input values. The doc structure is the file
    object along with the related network items: addresses, domain names. Output
    is written to files, which are then wrapped with taxii and uploaded using a 
    separate script.
    """
    parsedTargetFileName = reFileName(targetFileName_)[1]
    parsedTargetFilePrefix = reFileName(targetFileName_)[0]
    stix.utils.set_id_namespace({"http://www.equifax.com/cuckoo2Stix" : "cuckoo2Stix"})
    NS = cybox.utils.Namespace("http://www.equifax.com/cuckoo2Stix", "cuckoo2Stix")
    cybox.utils.set_id_namespace(NS)
    stix_package = STIXPackage()

    stix_header = STIXHeader()
    stix_header.title = 'File: ' + parsedTargetFileName + ' with the associated hashes, network indicators'
    stix_header.description = 'File: ' + parsedTargetFileName + ' with the associated hashes, network indicators'
    stix_package.stix_header = stix_header

    # Create the ttp
    malware_instance = MalwareInstance()
    malware_instance.add_name(parsedTargetFileName)
    malware_instance.description = targetFileSha1_
    ttp = TTP(title='TTP: ' + parsedTargetFileName)
    ttp.behavior = Behavior()
    ttp.behavior.add_malware_instance(malware_instance)
    stix_package.add_ttp(ttp)
    
    # Create the indicator for the ipv4 addresses
    ipv4Object = Address(ipv4Addresses_, Address.CAT_IPV4)
    ipv4Object.condition = 'Equals'
    ipv4Indicator = Indicator()
    ipv4Indicator.title = parsedTargetFileName + ': ipv4 addresses'
    ipv4Indicator.add_indicator_type('IP Watchlist')
    ipv4Indicator.add_indicated_ttp(RelatedTTP(TTP(idref=ttp.id_), relationship='Indicates Malware'))
    ipv4Indicator.observable = ipv4Object
    ipv4Indicator.confidence = 'Low'
    
    # Create the indicator for the domain names
    domainNameObject = DomainName()
    domainNameObject.value = hostNames_
    domainNameObject.condition = 'Equals'
    domainNameIndicator = Indicator()
    domainNameIndicator.title = parsedTargetFileName + ': domain names'
    domainNameIndicator.add_indicator_type('Domain Watchlist')
    domainNameIndicator.add_indicated_ttp(RelatedTTP(TTP(idref=ttp.id_), relationship='Indicates Malware'))
    domainNameIndicator.observable = domainNameObject
    domainNameIndicator.confidence = 'Low'

    # Create the indicator for the file
    fileObject = File()
    fileObject.file_name = parsedTargetFileName
    fileObject.file_name.condition = 'Equals'
    fileObject.size_in_bytes = targetFileSize_
    fileObject.size_in_bytes.condition = 'Equals'
    fileObject.add_hash(Hash(targetFileSha1_, type_='SHA1', exact=True))
    fileObject.add_hash(Hash(targetFileSha256_, type_='SHA256', exact=True))
    fileObject.add_hash(Hash(targetFileSha512_, type_='SHA512', exact=True))
    fileObject.add_hash(Hash(targetFileSsdeep_, type_='SSDEEP', exact=True))
    fileObject.add_hash(Hash(targetFileMd5_, type_='MD5', exact=True))
    fileIndicator = Indicator()
    fileIndicator.title = parsedTargetFileName + ': hashes'
    fileIndicator.description = parsedTargetFilePrefix
    fileIndicator.add_indicator_type('File Hash Watchlist')
    fileIndicator.add_indicated_ttp(RelatedTTP(TTP(idref=ttp.id_), relationship="Indicates Malware"))
    fileIndicator.observable = fileObject
    fileIndicator.confidence = 'Low'
    
    stix_package.indicators = [fileIndicator, ipv4Indicator, domainNameIndicator]

    stagedStixDoc = stix_package.to_xml()
    stagedStixDoc = fixAddressObject(stagedStixDoc)
    stagedStixDoc = fixDomainObject(stagedStixDoc)
    today = datetime.datetime.now()
    now = today.strftime('%Y-%m-%d_%H%M%S')
    if not os.path.exists(outputDir_):
        os.makedirs(outputDir_)
    with open (outputDir_ + '/' + now + '-' + targetFileSha1_ + '.stix.xml', 'a') as myfile:
        myfile.write(stagedStixDoc)
    _l.debug('Wrote file: ' + now + '-' + targetFileSha1_ + '.stix.xml')
    return
Ejemplo n.º 45
0
def csv2stix(outFormat,inFile):

	#=============
	# Build package metadata
	#=============

	stix_package = STIXPackage()
	stix_package.stix_header = STIXHeader()
	stix_package.stix_header.title = "TG3390"
	stix_package.stix_header.description = "Dell SecureWorks Counter Threat Unit(TM) (CTU) researchers investigated activities associated with Threat Group-3390[1] (TG-3390) - http://www.secureworks.com/cyber-threat-intelligence/threats/threat-group-3390-targets-organizations-for-cyberespionage/"

	marking_specification = MarkingSpecification()
	marking_specification.controlled_structure = "../../../../descendant-or-self::node()"

	tlp = TLPMarkingStructure()
	tlp.color = "WHITE"
	marking_specification.marking_structures.append(tlp)

	handling = Marking()
	handling.add_marking(marking_specification)

	stix_package.stix_header.handling = handling

        #=============
        # Build package structure
        #=============

	ta_tg3390 = ThreatActor(title="TG3390")
	ta_tg3390.identity = Identity(name="TG3390")

	attack_pattern = AttackPattern()
	attack_pattern.description = ("Infrastructure Building")
	ttp_infrastructure = TTP(title="Infrastructure Building")
	ttp_infrastructure.behavior = Behavior()
	ttp_infrastructure.behavior.add_attack_pattern(attack_pattern)
	ttp_infrastructure.add_intended_effect("Unauthorized Access")
	infra_domainInd = Indicator(title="Domains associated with TG3390 Infrastructure")
	infra_domainInd.add_indicator_type("Domain Watchlist")
	infra_domainInd.confidence = "High"
	infra_domainInd.add_indicated_ttp(TTP(idref=ttp_infrastructure.id_))

	infra_IPInd = Indicator(title="[H] IP Addresses associated with TG3390 Infrastructure")
	infra_IPInd.add_indicator_type("IP Watchlist")
	infra_IPInd.confidence = "High"
	infra_IPInd.add_indicated_ttp(TTP(idref=ttp_infrastructure.id_))

	infra_IPInd_M = Indicator(title="[M] IP Addresses associated with TG3390 Infrastructure")
        infra_IPInd_M.add_indicator_type("IP Watchlist")
	infra_IPInd_M.confidence = "Medium"
        infra_IPInd_M.add_indicated_ttp(TTP(idref=ttp_infrastructure.id_))


	httpBrowserObj = MalwareInstance()
	httpBrowserObj.add_name("HTTP Browser")
	ttp_httpB = TTP(title="HTTP Browser")
	ttp_httpB.behavior = Behavior()
	ttp_httpB.behavior.add_malware_instance(httpBrowserObj)
	ttp_httpB.add_intended_effect("Theft - Intellectual Property")
	httpB_hashInd = Indicator(title="File hashes for HTTP Browser")
	httpB_hashInd.add_indicator_type("File Hash Watchlist")
	httpB_hashInd.confidence = "High"
	httpB_hashInd.add_indicated_ttp(TTP(idref=ttp_httpB.id_))

	httpBrowserDropperObj = MalwareInstance()
	httpBrowserDropperObj.add_name("HTTP Browser Dropper")
	ttp_httpBDpr = TTP(title="HTTP Browser Dropper")
	ttp_httpBDpr.behavior = Behavior()
	ttp_httpBDpr.behavior.add_malware_instance(httpBrowserDropperObj)
	ttp_httpBDpr.add_intended_effect("Theft - Intellectual Property")
	httpBDpr_hashInd = Indicator(title="File hashes for HTTP Browser Dropper")
	httpBDpr_hashInd.add_indicator_type("File Hash Watchlist")
	httpBDpr_hashInd.confidence = "High"
	httpBDpr_hashInd.add_indicated_ttp(TTP(idref=ttp_httpBDpr.id_))


	plugXObj = MalwareInstance()
	plugXObj.add_name("PlugX Dropper")
	ttp_plugX = TTP(title="PlugX Dropper")
	ttp_plugX.behavior = Behavior()
	ttp_plugX.behavior.add_malware_instance(plugXObj)
	ttp_plugX.add_intended_effect("Theft - Intellectual Property")
	plugX_hashInd = Indicator(title="File hashes for PlugX Dropper")
	plugX_hashInd.add_indicator_type("File Hash Watchlist")
	plugX_hashInd.confidence = "High"
	plugX_hashInd.add_indicated_ttp(TTP(idref=ttp_plugX.id_))

        #=============
        # Process content in to structure
        #=============
	ip_rules = []
	ip_rules_M = []
	domain_rules = []
	with open(inFile, 'rb') as f:
                reader = csv.reader(f)
		for row in reader:
                        obs = row[0]
                        obsType = row[1]
                        description = row[2]
                        confidence = row[3]
			#print obs,obsType,description,confidence
			if description == 'TG-3390 infrastructure':
				if obsType == 'Domain name':
					domain_obj = DomainName()
        	                        domain_obj.value = obs
					#domain_obj.title = description
	                                infra_domainInd.add_object(domain_obj)
					domain_rule = generate_snort([obs], 'DomainName', str(infra_domainInd.id_).split(':',1)[1].split('-',1)[1])
					domain_rules.append(domain_rule)
				elif obsType == 'IP address':
					ipv4_obj = Address()
                	                ipv4_obj.category = "ipv4-addr"
        	                        ipv4_obj.address_value = obs
					ipv4_obj.title = description
					ind_ref = str(infra_IPInd.id_).split(':',1)[1].split('-',1)[1]
					if confidence == "High":
	                                	infra_IPInd.add_object(ipv4_obj)
						ip_rules.append(obs)
					else:
						infra_IPInd_M.add_object(ipv4_obj)
						ip_rules_M.append(obs)
				else:
					print "TTP Infra: obsType is wrong"
			elif description == 'HttpBrowser RAT dropper':
				file_obj = File()
				file_obj.add_hash(Hash(obs))
				file_obj.title = description
				httpBDpr_hashInd.add_observable(file_obj)
			elif description == 'HttpBrowser RAT':
				file_obj = File()
                                file_obj.add_hash(Hash(obs))
				file_obj.title = description
                                httpB_hashInd.add_observable(file_obj)
			elif description == 'PlugX RAT dropper':
				file_obj = File()
                                file_obj.add_hash(Hash(obs))
				file_obj.title = description
                                plugX_hashInd.add_observable(file_obj)
			else:
				print "TTP not found"
	#print ip_rules
	ip_rule = generate_snort(ip_rules, 'Address', str(infra_IPInd.id_).split(':',1)[1].split('-',1)[1])
	ip_rule_M = generate_snort(ip_rules_M, 'Address', str(infra_IPInd_M.id_).split(':',1)[1].split('-',1)[1])

	ip_tm = SnortTestMechanism()
	ip_tm.rules = [ip_rule]
	ip_tm.efficacy = "High"
	ip_tm.producer = InformationSource(identity=Identity(name="Auto"))
	infra_IPInd.test_mechanisms = [ip_tm]

	ip_M_tm = SnortTestMechanism()
        ip_M_tm.rules = [ip_rule_M]
        ip_M_tm.efficacy = "Medium"
        ip_M_tm.producer = InformationSource(identity=Identity(name="Auto"))
	infra_IPInd_M.test_mechanisms = [ip_M_tm]

	domain_tm = SnortTestMechanism()
        domain_tm.rules = domain_rules
        domain_tm.efficacy = "High"
        domain_tm.producer = InformationSource(identity=Identity(name="Auto"))
        infra_domainInd.test_mechanisms = [domain_tm]
	
        #=============
        # Add the composed content to the structure
        #=============

	stix_package.add_indicator(infra_domainInd)
	stix_package.add_indicator(infra_IPInd)
	stix_package.add_indicator(infra_IPInd_M)
	stix_package.add_indicator(httpBDpr_hashInd)
	stix_package.add_indicator(httpB_hashInd)
	stix_package.add_indicator(plugX_hashInd)

	stix_package.add_ttp(ttp_infrastructure)
	stix_package.add_ttp(ttp_httpB)
	stix_package.add_ttp(ttp_httpBDpr)
	stix_package.add_ttp(ttp_plugX)
					
				
	"""
	if outFormat =='dict':
		print stix_package.to_dict()
	if outFormat =='json':
		parsed = stix_package.to_json()
		jsonpkg = json.loads(parsed)
		pprint.pprint(jsonpkg)
	if outFormat =='stix':
		print stix_package.to_xml()
	"""
	#if verbose:
		#print stix_package.to_xml()
	#pprint(stix_package.to_json())
	return stix_package
Ejemplo n.º 46
0
ttp2.victim_targeting = victim_targeting

ttp2.related_ttps.append(related_ttp)

# Related TTP (Exploit; by id)
ttp3 = TTP(title='Remote Exploit of Server Software')
exploit = Exploit(title='Exploit Apache')
exploit.description = 'Exploit Description'
exploit.short_description = 'Short Description'
ttp3.behavior = Behavior()
ttp3.behavior.add_exploit(exploit)
vt3 = VictimTargeting()
vt3.identity = Identity(name='Steve Franchak')
ttp3.victim_targeting = vt3

# TTP 3 - Related Exploit Target
et = ExploitTarget(title='Apache HTTP Vulnerability - CVE-2018-1312')
ttp3.exploit_targets.append(ExploitTarget(idref=et.id_))

# Generate STIX Package
stix_package = STIXPackage()
stix_package.add_ttp(ttp)
stix_package.add_ttp(ttp2)
stix_package.add_ttp(ttp3)
stix_package.add_threat_actor(ta)
stix_package.add_observable(observable)
stix_package.add_observable(observable2)
stix_package.add_exploit_target(et)

print(stix_package.to_xml().decode())
Ejemplo n.º 47
0
    def toStixXml(self, confidence, efficacy):
        """
        This method converts a list of FASGuard generated Snort rules  into a STIX
        compliant XML string ready for output. It first converts the object
        into a hash of the right format and then converts it into XML using
        STIXPackage.from_dict and to_xml on the resulting object.

        Arguments:

        confidence - High, Medium or Low. High means low false alarm rate.
        efficacy - High, Medium or Low. High means a low missed detection rate.

        Returns:

        Reference to string containing STIX/CybOX XML file.
        """
        logger = logging.getLogger('simple_example')
        self.logger = logger
        self.logger.debug('In asg.fasguardStixRule')
        stix_package = STIXPackage()

        # Build the Exploit Target
        vuln = Vulnerability()
        vuln.cve_id = "Unknown"

        et = ExploitTarget(title="From FASGuard")
        et.add_vulnerability(vuln)

        stix_package.add_exploit_target(et)

        # Build the TTP
        ttp = TTP(title="FASGuard Produced Signatures")
        ttp.exploit_targets.append(ExploitTarget(idref=et.id_))

        stix_package.add_ttp(ttp)

        # Build the indicator
        indicator = Indicator(title = "Snort Signature from FASGuard")
        indicator.confidence = Confidence(confidence)

        tm = SnortTestMechanism()
        tm.rules = self.ruleList
        tm.efficacy = efficacy
        tm.producer = InformationSource(identity=Identity(name="FASGuard"))
        tm.producer.references = ["http://fasguard.github.io/"]
        indicator.test_mechanisms = [tm]
        indicator.add_indicated_ttp(TTP(idref=ttp.id_))

        stix_package.add_indicator(indicator)

        return stix_package.to_xml()

        # stixDict = {'campaigns': [{}],
        #             'courses_of_action': [{}],
        #             'exploit_targets': [{}],
        #             'id': 'INSERT_PACKAGE_ID_HERE'}
        # stixDict['indicators'] = [{'indicator':
        #                            {'title':
        #                             'Automatically Generated FASGuard Signatures',
        #                             'test_mechanisms':
        #                             {'test_mechanism':
        #                              {'efficacy':'Low',
        #                               'producer':
        #                               {'Identity':'FASGuard'},
        #                               'rule':'xyz'}}}}
        # ]
        stix_package = STIXPackage.from_dict(stixDict)
        stix_xml = stix_package.to_xml()
        return stix_xml
def main():
    # NOTE: ID values will differ due to being regenerated on each script execution
    pkg1 = STIXPackage()
    pkg1.title = "Example of Indicator Composition for an aggregate indicator composition"

    # USE CASE: Indicator with aggregate pattern

    # Add TTP for malware usage
    malware_ttp = TTP()
    malware_ttp.behavior = Behavior()

    malware = MalwareInstance()
    malware.title = "foobar malware"
    malware.add_type("Remote Access Trojan")
    malware_ttp.behavior.add_malware_instance(malware)

    c2_ttp = TTP()
    c2_ttp.resources = Resource()
    c2_ttp.resources.infrastructure = Infrastructure()
    c2_ttp.resources.infrastructure.add_type(VocabString("Malware C2"))

    pkg1.add_ttp(c2_ttp)
    pkg1.add_ttp(malware_ttp)

    nw_ind = Indicator()
    nw_ind.description = "Indicator for a particular C2 infstructure IP address."
    # add network network connection to this indicator
    obs = NetworkConnection()
    sock = SocketAddress()
    sock.ip_address = "46.123.99.25"
    sock.ip_address.category = "ipv4-addr"
    sock.ip_address.condition = "Equals"
    obs.destination_socket_address = sock
    nw_ind.add_observable(obs)

    nw_ind.add_indicated_ttp(TTP(idref=c2_ttp.id_))

    # create File Hash indicator w/ embedded Observable
    file_ind = Indicator()

    file_ind.description = "Indicator for the hash of the foobar malware."
    file_ind.add_indicator_type("File Hash Watchlist")

    file_obs = File()
    file_obs.add_hash("01234567890abcdef01234567890abcdef")
    file_obs.hashes[0].type_ = "MD5"
    file_obs.hashes[0].type_.condition = "Equals"
    file_ind.add_observable(file_obs)

    # create references
    file_ind.add_indicated_ttp(TTP(idref=malware_ttp.id_))

    # create container indicator
    ind = Indicator()
    ind.add_indicator_type(VocabString("Campaign Characteristics"))
    ind.description = "Indicator for a composite of characteristics for the use of specific malware and C2 infrastructure within a Campaign."

    # Add campaign with related
    camp = Campaign()
    camp.title = "holy grail"
    pkg1.add_campaign(camp)
    camp.related_ttps.append(TTP(idref=c2_ttp.id_))
    camp.related_ttps.append(TTP(idref=malware_ttp.id_))

    # Add threat actor
    ta = ThreatActor()
    ta.identity = Identity()
    ta.identity.name = "boobear"
    ta.observed_ttps.append(TTP(idref=malware_ttp.id_))
    pkg1.add_threat_actor(ta)

    # Create composite expression

    ind.composite_indicator_expression = CompositeIndicatorExpression()
    ind.composite_indicator_expression.operator = "AND"

    ind.composite_indicator_expression.append(file_ind)
    ind.composite_indicator_expression.append(nw_ind)

    pkg1.add_indicator(ind)

    print pkg1.to_xml()

#  USE CASE: Indicator with partial matching

    pkg2 = STIXPackage()
    pkg2.title = "Example of Indicator Composition for a one of many indicator composition"

    # create container indicator
    watchlistind = Indicator()
    watchlistind.add_indicator_type("IP Watchlist")
    watchlistind.description = "This Indicator specifies a pattern where any one or more of a set of three IP addresses are observed."

    watchlistind.add_indicated_ttp(TTP(idref=c2_ttp.id_))

    # Create composite expression
    watchlistind.composite_indicator_expression = CompositeIndicatorExpression()
    watchlistind.composite_indicator_expression.operator = "OR"

    ips = ['23.5.111.68', '23.5.111.99', '46.123.99.25']
    for ip in ips:
        new_ind = Indicator()
        new_ind.description = "This Indicator specifies a pattern where one specific IP address is observed"
        # add network network connection to this indicator
        obs = Address()
        obs.address_value = ip
        obs.address_value.condition = "Equals"
        new_ind.add_observable(obs)

        new_ind.add_indicated_ttp(TTP(idref=c2_ttp.id_))

        watchlistind.composite_indicator_expression.append(new_ind)

    pkg2.add_indicator(watchlistind)

    print pkg2.to_xml()

    #  USE CASE: Indicator with compound detection

    pkg3 = STIXPackage()
    pkg3.title = "Example of Indicator Composition for compound detection"

    # create container indicator
    watchlistind2 = Indicator()
    watchlistind2.add_indicator_type("IP Watchlist")
    watchlistind2.description = "This Indicator specifies a composite condition of two preexisting Indicators (each identifying a particular TTP with low confidence) that in aggregate identify the particular TTP with high confidence."
    # Create composite expression
    watchlistind2.composite_indicator_expression = CompositeIndicatorExpression()
    watchlistind2.composite_indicator_expression.operator = "OR"

    watchlistind2.add_indicated_ttp(TTP(idref=c2_ttp.id_))
    watchlistind2.confidence = "High"

    nw_ind.description = "Indicator for a particular C2 IP address used by a malware variant."
    nw_ind.confidence = "Low"
    nw_ind.indicator_types = ["C2"]
    file_ind.description = "Indicator that contains malicious file hashes for a particular malware variant."
    file_ind.confidence = "Low"
    watchlistind2.composite_indicator_expression.append(nw_ind)
    watchlistind2.composite_indicator_expression.append(file_ind)

    pkg3.add_indicator(watchlistind2)

    print pkg3.to_xml()
Ejemplo n.º 49
0
def main():
    stix_package = STIXPackage()

    malware_instance = MalwareInstance()
    malware_instance.add_name("plugin1.exe")
    #not really remote access but am not sure what else to put
    malware_instance.add_type("Remote Access Trojan")

    ttp = TTP(title="Install+plugin1.exe")
    ttp.behavior = Behavior()
    ttp.behavior.add_malware_instance(malware_instance)

    #observable 1 Install+plugin1.exe
    file_object = File()
    file_object.file_name = "Install+plugin1.exe"
    file_object.add_hash(
        Hash("164ecfc36893ee368a3c4cb2fd500b58262f1b87de1e68df74390db0b5445915"
             ))
    file_object.hashes[0].simple_hash_value.condition = "Equals"

    #observable 2 plugin1.exe
    #http://cybox.readthedocs.io/en/stable/examples.html#creating-observables
    file_plugin1 = File()
    file_plugin1.file_name = "plugin1.exe"
    file_plugin1.file_path = "C:\\Users\\Default\\AppData\\Local\\temp\plugin1"
    file_plugin1.add_hash(
        Hash("ae768b62f5fef4dd604e1b736bdbc3ed30417ef4f67bff74bb57f779d794d6df"
             ))
    file_plugin1.hashes[0].simple_hash_value.condition = "Equals"

    #observable 3 registry key
    #http://cybox.readthedocs.io/en/stable/api/coverage.html
    registry_object = WinRegistryKey()
    registry_object.name = "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run\\Google Ultron Updater"

    #observable 4 network traffic
    #http://stixproject.github.io/documentation/idioms/malware-hash/
    #I couldn't figure out how to correctly indicate the source, dest or protocol
    addr = Address(address_value="192.168.52.219", category=Address.CAT_IPV4)

    #indicator 1 Install+plugin1.exe
    indicator = Indicator(title="File hash for Install+plugin.exe")
    indicator.add_indicator_type("File Hash Watchlist")
    indicator.add_observable(file_object)
    indicator.add_indicated_ttp(TTP(idref=ttp.id_))

    #indicator 2 plugin1.exe
    indicator2 = Indicator(title="File hash for plugin1.exe")
    indicator2.add_indicator_type("File Hash Watchlist")
    indicator2.add_observable(file_plugin1)
    indicator2.add_indicated_ttp(TTP(idref=ttp.id_))

    #indicator3 registry key
    indicator3 = Indicator(title="Registry entry for Install+plugin.exe")
    indicator3.add_indicator_type("Malware Artifacts")
    indicator3.add_observable(registry_object)
    indicator3.add_indicated_ttp(TTP(idref=ttp.id_))

    #indicator4 network traffic
    indicator4 = Indicator(title="Network Traffic for plugine1.exe")
    indicator.add_indicator_type("IP Watchlist")
    indicator4.add_observable(Observable(addr))
    indicator4.add_indicated_ttp(TTP(idref=ttp.id_))

    stix_package.add_indicator(indicator)
    stix_package.add_indicator(indicator2)
    stix_package.add_indicator(indicator3)
    stix_package.add_indicator(indicator4)
    stix_package.add_ttp(ttp)

    print(stix_package.to_xml(encoding=None))
Ejemplo n.º 50
0
def adptrTransform_Dict2Obj(srcData, data=None):
    sNAMEFUNC = 'adptrTransform_Dict2Obj'
    sndMSG('Called...', 'INFO', sNAMEFUNC)
    if not srcData: return (None)  #srcData can not be empty

    from stix.core import STIXPackage
    from stix.common import InformationSource, Identity
    from stix.data_marking import Marking
    from stix.ttp import TTP

    ### Build Package
    objMarkingSpecification = genObject_MarkingSpecification(data)
    objMarkingSpecification.controlled_structure = "//node()"

    objHdr = genData_STIXHeader(data)
    objHdr.handling = Marking(objMarkingSpecification)
    objHdr.information_source = InformationSource(identity=Identity(
        name=srcData.pkgLink))

    objTTP = genObject_TTP(data)
    objTTP.information_source = InformationSource(identity=Identity(
        name=srcData.pkgLink))

    objPkg = STIXPackage()
    objPkg.stix_header = objHdr
    objPkg.add_ttp(objTTP)

    for sKey in data['data']:
        obsList = []
        ### Build Observables
        obsURI = genObject_URI(data['data'][sKey]['src'])
        try:
            obsURI.id_ = data['data'][sKey]['meta']['uri']
        except:
            data['data'][sKey]['meta'].update({'uri': obsURI.id_})

        ### Srt: Stupid test to make sure URL be output via STIX.to_xml()
        try:
            testPkg = STIXPackage()
            testPkg.add_observable(obsURI)
            testPkg.to_xml()
        except:
            sNAMEFUNC = 'adptrTransform_Dict2Obj'
            sndMSG('Error Parsing URL for this key: [' + sKey + ']', 'INFO',
                   sNAMEFUNC)
            testPkg = None
            continue
        ### End: Stupid test

        objPkg.add_observable(obsURI)
        obsList.append(genRefObs(obsURI))

        ### Build Indicators
        objInd = genObject_Indicator(data['data'][sKey]['src'])
        try:
            obsURI.id_ = data['data'][sKey]['meta']['ind']
        except:
            data['data'][sKey]['meta'].update({'ind': objInd.id_})

        objInd.producer = InformationSource(identity=Identity(
            name=srcData.pkgLink))
        objInd.observables = obsList
        objInd.indicator_types = ["URL Watchlist"]
        objInd.observable_composition_operator = "OR"
        objInd.set_received_time(data['data'][sKey]['meta']['dateDL'])
        try:
            objInd.set_produced_time(
                data['data'][sKey]['src']['verification_time'])
        except:
            pass

        if not data['data'][sKey]['src']['target'] == 'Other':
            from stix.ttp import TTP
            objVictimTargeting = genData_VictimTargeting(
                data['data'][sKey]['src'])
            if obsURI:
                objVictimTargeting.targeted_technical_details = genRefObs(
                    obsURI)
            objTTP_vic = TTP()
            objTTP_vic.title = "Targeting: " + data['data'][sKey]['src'][
                'target']
            objTTP_vic.victim_targeting = objVictimTargeting
            objInd.add_indicated_ttp(objTTP_vic)

        objInd.add_indicated_ttp(TTP(idref=objTTP.id_))
        objPkg.add_indicator(objInd)

    #updateDB_local(data,srcData)
    return (objPkg)
def main():

    # "hardcoded" values
    ns = "urn:example.com:marks_malware_metadata_mart"
    ns_alias = "m4"

    # Set the STIX ID Namespace
    stix_namespace = {ns: ns_alias}
    stix_sin(stix_namespace)

    # Set the CybOX ID Namespace
    cybox_namespace = Namespace(ns, ns_alias)
    cybox_sin(cybox_namespace)

    ttp_id = 'ttp-d539bb85-9363-4814-83c8-fa9975045686'
    ttp_timestamp = '2014-09-30T15:56:27.000000+00:00'

    # Fake database values
    md5_hash = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
    object_id = 'File-927731f2-cc2c-421c-a40e-dc6f4a6c75a4'
    observable_id = 'Observable-45e3e64c-8438-441e-bc49-51e417466e29'
    confidence = 'High'
    confidence_timestamp = '2014-09-29T14:32:00.000000'
    indicator_id = 'Indicator-54baefc1-4742-4b40-ba83-afd51115015b'
    indicator_timestamp = '2014-09-29T14:32:00.000000'

    # Code to create the STIX Package
    sp = STIXPackage()
    sp.stix_header = STIXHeader()
    sp.stix_header.title = "File Hash Reputation for %s" % md5_hash
    sp.stix_header.add_package_intent("Indicators - Malware Artifacts")
    sp.stix_header.information_source = InformationSource()
    sp.stix_header.information_source.identity = Identity()
    sp.stix_header.information_source.identity.name = "Mark's Malware Metadata Mart"

    file_hash = Hash(hash_value=md5_hash, type_='MD5', exact=True)
    file_hash.type_.condition = "Equals"

    file_obj = File()
    file_obj.id_ = (ns_alias + ':' + object_id)
    file_obj.add_hash(file_hash)

    indicator = Indicator(title="File Hash Reputation",
                          id_=(ns_alias + ':' + indicator_id),
                          timestamp=indicator_timestamp)
    indicator.indicator_type = "File Hash Reputation"
    indicator.add_observable(file_obj)
    indicator.observables[0].id_ = ns_alias + ':' + observable_id

    ttp = TTP()
    ttp.id_ = ns_alias + ':' + ttp_id
    ttp.timestamp = ttp_timestamp
    ttp.title = "Malicious File"

    indicator.add_indicated_ttp(TTP(idref=ttp.id_, timestamp=ttp.timestamp))
    indicator.indicated_ttps[0].confidence = confidence
    indicator.indicated_ttps[0].confidence.timestamp = confidence_timestamp

    sp.add_indicator(indicator)
    sp.add_ttp(ttp)

    stix_xml = sp.to_xml()

    poll_response = tm11.PollResponse(message_id=generate_message_id(),
                                      in_response_to="1234",
                                      collection_name='file_hash_reputation')
    cb = tm11.ContentBlock(content_binding=CB_STIX_XML_111, content=stix_xml)
    poll_response.content_blocks.append(cb)
    print poll_response.to_xml(pretty_print=True)
Ejemplo n.º 52
0
def main():
    # define constants
    TI_REQUEST_URL = "https://api.intelgraph.idefense.com/rest/threatindicator/v0"
    # iDefense API Key
    # To avoid hard-coding creds, I'm using environment variables

    if os.environ.get('IDEF_TOKEN') is None:
        print(
            "error: please store your iDefense IntelGraph API key in the IDEF_TOKEN environment"
        )
        sys.exit(1)

    API_KEY = os.environ.get('IDEF_TOKEN')
    API_SECRET = ''

    # TODO: use command-line parameter
    timestr = datetime.datetime.utcnow() - datetime.timedelta(days=1)
    LAST_IMPORT = timestr.strftime("%Y-%m-%dT%H:%M:%S") + ".000Z"

    HEADERS = {
        "Content-Type": "application/json",
        "auth-token": API_KEY,
        "X-Api-Key-Proof": API_SECRET
    }

    print(HEADERS)

    page = 1
    more_data = True
    count = 0

    # Set namespace
    NAMESPACE = Namespace("https://intelgraph.idefense.com", "idefense")
    set_id_namespace(NAMESPACE)

    # Create STIX Package
    stix_package = STIXPackage()
    stix_header = STIXHeader()
    stix_header.description = "iDefense Threat Indicators Feed"
    stix_package.stix_header = stix_header

    ttps = {}
    malware = {}

    try:

        while more_data:
            request_payload = {
                "start_date": LAST_IMPORT,
                "page_size": 200,
                "page": page
            }
            r = requests.post(TI_REQUEST_URL,
                              headers=HEADERS,
                              data=json.dumps(request_payload))
            print(r)
            response = []
            if r.status_code == requests.codes.ok:
                try:
                    # Read in response as json
                    response = r.json()

                except (ValueError, KeyError):
                    print("Response couldn't be decoded :(")
                    more_data = False
                    continue

                more_data = response.get('more', 'False')
                print("Page %d ==> %s (%s)" %
                      (page, response['more'], response['total_size']))
                page += 1

                # Iterate the response
                for indicatorD in response['results']:
                    count += 1
                    # Indicator value such as the value of the IP/Domain/URL
                    indicator = indicatorD.get('key')
                    print(indicator, indicatorD.get('type'))
                    if indicatorD.get('last_seen_as') is None:
                        last_seen_as = 'UNKNOWN'
                    else:
                        last_seen_as = ''.join(indicatorD.get('last_seen_as'))

                    # Identify TTP
                    if last_seen_as not in ttps:
                        ttps[last_seen_as] = TTP(title=last_seen_as)
                        stix_package.add_ttp(ttps[last_seen_as])

                    # Identify malware source
                    if 'files' in indicatorD:
                        for hashD in indicatorD['files']:
                            md5 = hashD.get('key')
                            # Malware Family classification of the hash if available
                            if hashD.get('malware_family') is None:
                                malware_family = "Unknown"
                            else:
                                malware_family = ''.join(
                                    hashD.get('malware_family'))
                            if md5 not in malware:
                                malware[md5] = add_malware(
                                    md5, malware_family, hashD.get('uuid'))

                    if indicatorD.get('type') == "url":
                        # Create indicator
                        indicator = Indicator(
                            id_="indicator-{0}".format(indicatorD.get('uuid')),
                            title=''.join(indicatorD.get('malware_family')),
                            timestamp=indicatorD.get('last_seen'))
                        indicator.add_indicator_type("URL Watchlist")

                        # Populate URL
                        url = URI()
                        url.value = indicatorD.get('key')
                        url.type_ = URI.TYPE_URL
                        url.value.condition = "Equals"

                        indicator.add_observable(url)

                    elif indicatorD.get('type') == "domain":
                        # Populate domain name
                        indicator = Indicator(
                            id_="indicator-{0}".format(indicatorD.get('uuid')),
                            title=''.join(indicatorD.get('malware_family')),
                            timestamp=indicatorD.get('last_seen'))
                        indicator.add_indicator_type("Domain Watchlist")
                        domain = DomainName()
                        domain.value = indicatorD.get('key')
                        domain.value.condition = "Equals"
                        indicator.add_observable(domain)

                    elif indicatorD.get('type') == "ip":
                        # Create indicator
                        indicator = Indicator(
                            id_="indicator-{0}".format(indicatorD.get('uuid')),
                            title=indicatorD.get('malware_family'),
                            timestamp=indicatorD.get('last_seen'))
                        indicator.add_indicator_type("IP Watchlist")
                        # Populate IP address
                        addr = Address(address_value=indicatorD.get('key'),
                                       category=Address.CAT_IPV4)
                        addr.condition = "Equals"
                        indicator.add_observable(addr)

                    # Link TTP
                    indicator.add_indicated_ttp(
                        TTP(idref=ttps[last_seen_as].id_))
                    # Indicate confidence score
                    indicator.confidence = Confidence(
                        value=VocabString(indicatorD.get('confidence')))
                    # Add related indicator to malware
                    indicator.add_related_indicator(malware[md5])
                    # Add to package
                    stix_package.add_indicator(indicator)

            else:
                print("API request couldn't be fulfilled due status code: %d" %
                      r.status_code)
                more_data = False

    except requests.exceptions.ConnectionError as e:
        print("Check your network connection\n %s" % str(e))

    except requests.exceptions.HTTPError as e:
        print("Bad HTTP response\n %s" % str(e))

    except Exception as e:
        print("Uncaught exception\n %s" % str(e))

    # Output to XML
    with open('stix-1.2.1.xml', 'wb') as f:
        f.write(stix_package.to_xml())
Ejemplo n.º 53
0
def genStixDoc(
        outputDir_,
        targetFileSha1_,
        targetFileSha256_,
        targetFileSha512_,
        targetFileSsdeep_,
        targetFileMd5_,
        targetFileSize_,
        targetFileName_,
        ipv4Addresses_,
        hostNames_):
    """
    Generate Stix document from the input values. The doc structure is the file
    object along with the related network items: addresses, domain names. Output
    is written to files, which are then wrapped with taxii and uploaded using a 
    separate script.
    """
    parsedTargetFileName = reFileName(targetFileName_)[1]
    parsedTargetFilePrefix = reFileName(targetFileName_)[0]
    stix.utils.set_id_namespace({"http://www.equifax.com/cuckoo2Stix" : "cuckoo2Stix"})
    NS = cybox.utils.Namespace("http://www.equifax.com/cuckoo2Stix", "cuckoo2Stix")
    cybox.utils.set_id_namespace(NS)
    stix_package = STIXPackage()

    stix_header = STIXHeader()
    stix_header.title = 'File: ' + parsedTargetFileName + ' with the associated hashes, network indicators'
    stix_header.description = 'File: ' + parsedTargetFileName + ' with the associated hashes, network indicators'
    stix_package.stix_header = stix_header

    # Create the ttp
    malware_instance = MalwareInstance()
    malware_instance.add_name(parsedTargetFileName)
    malware_instance.description = targetFileSha1_
    ttp = TTP(title='TTP: ' + parsedTargetFileName)
    ttp.behavior = Behavior()
    ttp.behavior.add_malware_instance(malware_instance)
    stix_package.add_ttp(ttp)
    
    # Create the indicator for the ipv4 addresses
    ipv4Object = Address(ipv4Addresses_, Address.CAT_IPV4)
    ipv4Object.condition = 'Equals'
    ipv4Indicator = Indicator()
    ipv4Indicator.title = parsedTargetFileName + ': ipv4 addresses'
    ipv4Indicator.add_indicator_type('IP Watchlist')
    ipv4Indicator.add_indicated_ttp(RelatedTTP(TTP(idref=ttp.id_), relationship='Indicates Malware'))
    ipv4Indicator.observable = ipv4Object
    ipv4Indicator.confidence = 'Low'
    
    # Create the indicator for the domain names
    domainNameObject = DomainName()
    domainNameObject.value = hostNames_
    domainNameObject.condition = 'Equals'
    domainNameIndicator = Indicator()
    domainNameIndicator.title = parsedTargetFileName + ': domain names'
    domainNameIndicator.add_indicator_type('Domain Watchlist')
    domainNameIndicator.add_indicated_ttp(RelatedTTP(TTP(idref=ttp.id_), relationship='Indicates Malware'))
    domainNameIndicator.observable = domainNameObject
    domainNameIndicator.confidence = 'Low'

    # Create the indicator for the file
    fileObject = File()
    fileObject.file_name = parsedTargetFileName
    fileObject.file_name.condition = 'Equals'
    fileObject.size_in_bytes = targetFileSize_
    fileObject.size_in_bytes.condition = 'Equals'
    fileObject.add_hash(Hash(targetFileSha1_, type_='SHA1', exact=True))
    fileObject.add_hash(Hash(targetFileSha256_, type_='SHA256', exact=True))
    fileObject.add_hash(Hash(targetFileSha512_, type_='SHA512', exact=True))
    fileObject.add_hash(Hash(targetFileSsdeep_, type_='SSDEEP', exact=True))
    fileObject.add_hash(Hash(targetFileMd5_, type_='MD5', exact=True))
    fileIndicator = Indicator()
    fileIndicator.title = parsedTargetFileName + ': hashes'
    fileIndicator.description = parsedTargetFilePrefix
    fileIndicator.add_indicator_type('File Hash Watchlist')
    fileIndicator.add_indicated_ttp(RelatedTTP(TTP(idref=ttp.id_), relationship="Indicates Malware"))
    fileIndicator.observable = fileObject
    fileIndicator.confidence = 'Low'
    
    stix_package.indicators = [fileIndicator, ipv4Indicator, domainNameIndicator]

    stagedStixDoc = stix_package.to_xml()
    stagedStixDoc = fixAddressObject(stagedStixDoc)
    stagedStixDoc = fixDomainObject(stagedStixDoc)
    today = datetime.datetime.now()
    now = today.strftime('%Y-%m-%d_%H%M%S')
    if not os.path.exists(outputDir_):
        os.makedirs(outputDir_)
    with open (outputDir_ + '/' + now + '-' + targetFileSha1_ + '.stix.xml', 'a') as myfile:
        myfile.write(stagedStixDoc)
    _l.debug('Wrote file: ' + now + '-' + targetFileSha1_ + '.stix.xml')
    return
Ejemplo n.º 54
0
def main():

    # get args
    parser = argparse.ArgumentParser ( description = "Parse a given CSV from Shadowserver and output STIX XML to stdout"
    , formatter_class=argparse.ArgumentDefaultsHelpFormatter )

    parser.add_argument("--infile","-f", help="input CSV with bot data", default = "bots.csv")

    args = parser.parse_args()


    # setup stix document
    stix_package = STIXPackage()
    stix_header = STIXHeader()
    stix_header.title = "Bot Server IP addresses"
    stix_header.description = "IP addresses connecting to bot control servers at a given port"
    stix_header.add_package_intent ("Indicators - Watchlist")

    # add marking
    mark = Marking()
    markspec = MarkingSpecification()
    markstruct = SimpleMarkingStructure()
    markstruct.statement = "Usage of this information, including integration into security mechanisms implies agreement with the Shadowserver Terms of Service  available at  https://www.shadowserver.org/wiki/pmwiki.php/Shadowserver/TermsOfService"
    markspec.marking_structures.append(markstruct)
    mark.add_marking(markspec)

    stix_header.handling = mark

    # include author info
    stix_header.information_source = InformationSource()
    stix_header.information_source.time = Time()
    stix_header.information_source.time.produced_time  =datetime.now(tzutc())
    stix_header.information_source.tools = ToolInformationList()
    stix_header.information_source.tools.append("ShadowBotnetIP-STIXParser")
    stix_header.information_source.identity = Identity()
    stix_header.information_source.identity.name = "MITRE STIX Team"
    stix_header.information_source.add_role(VocabString("Format Transformer"))

    src = InformationSource()
    src.description = "https://www.shadowserver.org/wiki/pmwiki.php/Services/Botnet-CCIP"
    srcident = Identity()
    srcident.name = "shadowserver.org"
    src.identity = srcident
    src.add_role(VocabString("Originating Publisher"))
    stix_header.information_source.add_contributing_source(src)

    stix_package.stix_header = stix_header

    # add TTP for overall indicators
    bot_ttp = TTP()
    bot_ttp.title = 'Botnet C2'
    bot_ttp.resources = Resource()
    bot_ttp.resources.infrastructure = Infrastructure()
    bot_ttp.resources.infrastructure.title = 'Botnet C2'

    stix_package.add_ttp(bot_ttp)

    # read input data
    fd = open (args.infile, "rb") 
    infile = csv.DictReader(fd)

    for row in infile:
    # split indicators out, may be 1..n with positional storage, same port and channel, inconsistent delims
        domain = row['Domain'].split()
        country = row['Country'].split()
        region = row['Region'].split('|')
        state = row['State'].split('|')
        asn = row['ASN'].split()
        asname = row['AS Name'].split()
        asdesc = row['AS Description'].split('|')

        index = 0
        for ip in row['IP Address'].split():
            indicator = Indicator()
            indicator.title = "IP indicator for " + row['Channel'] 
            indicator.description = "Bot connecting to control server"


            # point to overall TTP
            indicator.add_indicated_ttp(TTP(idref=bot_ttp.id_))

            # add our IP and port
            sock = SocketAddress()
            sock.ip_address = ip

            # add sighting
            sight = Sighting()
            sight.timestamp = ""
            obs = Observable(item=sock.ip_address)
            obsref = Observable(idref=obs.id_)
            sight.related_observables.append(obsref)
            indicator.sightings.append(sight)

            stix_package.add_observable(obs)

            # add pattern for indicator
            sock_pattern = SocketAddress()
            sock_pattern.ip_address = ip
            port = Port()
            port.port_value = row['Port']
            sock_pattern.port = port

            sock_pattern.ip_address.condition= "Equals"
            sock_pattern.port.port_value.condition= "Equals"

            indicator.add_object(sock_pattern)
            stix_package.add_indicator(indicator)
            
            # add domain
            domain_obj = DomainName()
            domain_obj.value = domain[index]
            domain_obj.add_related(sock.ip_address,"Resolved_To", inline=False)

            stix_package.add_observable(domain_obj)

            # add whois obs
            whois_obj = WhoisEntry()
            registrar = WhoisRegistrar()
            registrar.name = asname[index] 
            registrar.address = state[index] + region[index] + country[index]

            whois_obj.registrar_info = registrar 
            whois_obj.add_related(sock.ip_address,"Characterizes", inline=False)

            stix_package.add_observable(whois_obj)
            
            # add ASN obj
            asn_obj = AutonomousSystem()
            asn_obj.name = asname[index] 
            asn_obj.number = asn[index]
            asn_obj.handle = "AS" + str(asn[index])
            asn_obj.add_related(sock.ip_address,"Contains", inline=False)

            stix_package.add_observable(asn_obj)

            # iterate 
            index = index + 1

    print stix_package.to_xml() 
def main():

    # "hardcoded" values
    ns = "urn:example.com:marks_malware_metadata_mart"
    ns_alias = "m4"

    # Set the STIX ID Namespace
    stix_namespace = {ns: ns_alias}
    stix_sin(stix_namespace)

    # Set the CybOX ID Namespace
    cybox_namespace = Namespace(ns, ns_alias)
    cybox_sin(cybox_namespace)

    ttp_id = 'ttp-d539bb85-9363-4814-83c8-fa9975045686'
    ttp_timestamp = '2014-09-30T15:56:27.000000+00:00'

    # Fake database values
    md5_hash = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
    object_id = 'File-927731f2-cc2c-421c-a40e-dc6f4a6c75a4'
    observable_id = 'Observable-45e3e64c-8438-441e-bc49-51e417466e29'
    confidence = 'High'
    confidence_timestamp = '2014-09-29T14:32:00.000000'
    indicator_id = 'Indicator-54baefc1-4742-4b40-ba83-afd51115015b'
    indicator_timestamp = '2014-09-29T14:32:00.000000'

    # Code to create the STIX Package
    sp = STIXPackage()
    sp.stix_header = STIXHeader()
    sp.stix_header.title = "File Hash Reputation for %s" % md5_hash
    sp.stix_header.add_package_intent("Indicators - Malware Artifacts")
    sp.stix_header.information_source = InformationSource()
    sp.stix_header.information_source.identity = Identity()
    sp.stix_header.information_source.identity.name = "Mark's Malware Metadata Mart"

    file_hash = Hash(hash_value=md5_hash, type_='MD5', exact=True)
    file_hash.type_.condition = "Equals"

    file_obj = File()
    file_obj.id_ = (ns_alias + ':' + object_id)
    file_obj.add_hash(file_hash)

    indicator = Indicator(title="File Hash Reputation",
                          id_=(ns_alias + ':' + indicator_id),
                          timestamp=indicator_timestamp)
    indicator.indicator_type = "File Hash Reputation"
    indicator.add_observable(file_obj)
    indicator.observables[0].id_ = ns_alias + ':' + observable_id

    ttp = TTP()
    ttp.id_ = ns_alias + ':' + ttp_id
    ttp.timestamp = ttp_timestamp
    ttp.title = "Malicious File"

    indicator.add_indicated_ttp(TTP(idref=ttp.id_, timestamp=ttp.timestamp))
    indicator.indicated_ttps[0].confidence = confidence
    indicator.indicated_ttps[0].confidence.timestamp = confidence_timestamp

    sp.add_indicator(indicator)
    sp.add_ttp(ttp)

    stix_xml = sp.to_xml()

    poll_response = tm11.PollResponse(message_id=generate_message_id(),
                                      in_response_to="1234",
                                      collection_name='file_hash_reputation')
    cb = tm11.ContentBlock(content_binding=CB_STIX_XML_111,
                           content=stix_xml)
    poll_response.content_blocks.append(cb)
    print poll_response.to_xml(pretty_print=True)