def main(): ioc = etree.parse('6d2a1b03-b216-4cd8-9a9e-8827af6ebf93.ioc') stix_package = STIXPackage() ttp = TTP() malware_instance = MalwareInstance() malware_instance.names = ['Zeus', 'twexts', 'sdra64', 'ntos'] ttp = TTP(title="Zeus") ttp.behavior = Behavior() ttp.behavior.add_malware_instance(malware_instance) indicator = Indicator(title="Zeus", description="Finds Zeus variants, twexts, sdra64, ntos") tm = OpenIOCTestMechanism() tm.ioc = ioc tm.producer = InformationSource(identity=Identity(name="Yara")) time = Time() time.produced_time = "0001-01-01T00:00:00" tm.producer.time = time tm.producer.references = ["http://openioc.org/iocs/6d2a1b03-b216-4cd8-9a9e-8827af6ebf93.ioc"] indicator.test_mechanisms = [tm] indicator.add_indicated_ttp(TTP(idref=ttp.id_)) stix_package.add_indicator(indicator) stix_package.add_ttp(ttp) print stix_package.to_xml()
def stix_xml(bldata): # Create the STIX Package and Header objects stix_package = STIXPackage() stix_header = STIXHeader() # Set the description stix_header.description = "RiskIQ Blacklist Data - STIX Format" # Set the namespace NAMESPACE = {"http://www.riskiq.com" : "RiskIQ"} set_id_namespace(NAMESPACE) # Set the produced time to now stix_header.information_source = InformationSource() stix_header.information_source.time = Time() stix_header.information_source.time.produced_time = datetime.now() # Create the STIX Package stix_package = STIXPackage() # Build document stix_package.stix_header = stix_header # Build the Package Intent stix_header.package_intents.append(PackageIntent.TERM_INDICATORS) # Build the indicator indicator = Indicator() indicator.title = "List of Malicious URLs detected by RiskIQ - Malware, Phishing, and Spam" indicator.add_indicator_type("URL Watchlist") for datum in bldata: url = URI() url.value = "" url.value = datum['url'] url.type_ = URI.TYPE_URL url.condition = "Equals" indicator.add_observable(url) stix_package.add_indicator(indicator) return stix_package.to_xml()
def _dostix(hashes): '''This function creates a STIX packages containing hashes.''' print("[+] Creating STIX Package") title = SETTINGS['stix']['ind_title'] + " " + str(datetime.datetime.now()) _custom_namespace(SETTINGS['stix']['ns'], SETTINGS['stix']['ns_prefix']) stix_package = STIXPackage() stix_package.stix_header = STIXHeader() stix_package.stix_header.title = title stix_package.stix_header.handling = _marking() try: indicator = Indicator() indicator.set_producer_identity(SETTINGS['stix']['producer']) indicator.set_produced_time(indicator.timestamp) indicator.set_received_time(indicator.timestamp) indicator.add_kill_chain_phase(PHASE_DELIVERY) indicator.confidence = "Low" indicator.title = title indicator.add_indicator_type("File Hash Watchlist") indicator.description = SETTINGS['stix']['ind_desc'] try: indicator.add_indicated_ttp( TTP(idref=SETTINGS['indicated_ttp'], timestamp=indicator.timestamp)) indicator.suggested_coas.append( CourseOfAction(idref=SETTINGS['suggested_coa'], timestamp=indicator.timestamp)) except KeyError: pass for info in hashes: try: file_name = info['filename'] file_object = File() file_object.file_name = file_name file_object.file_name.condition = "Equals" file_object.file_extension = "." + file_name.split('.')[-1] file_object.file_extension.condition = "Equals" file_object.size_in_bytes = info['filesize'] file_object.size_in_bytes.condition = "Equals" file_object.file_format = info['fileformat'] file_object.file_format.condition = "Equals" file_object.add_hash(Hash(info['md5'])) file_object.add_hash(Hash(info['sha1'])) file_object.add_hash(Hash(info['sha256'])) file_object.add_hash(Hash(info['sha512'])) file_object.add_hash(Hash(info['ssdeep'], Hash.TYPE_SSDEEP)) for hashobj in file_object.hashes: hashobj.simple_hash_value.condition = "Equals" hashobj.type_.condition = "Equals" file_obs = Observable(file_object) file_obs.title = "File: " + file_name indicator.add_observable(file_obs) except TypeError: pass stix_package.add_indicator(indicator) return stix_package except KeyError: pass
def main(): infilename = '' outfilename = '' #Get the command-line arguments args = sys.argv[1:] if len(args) < 4: usage() sys.exit(1) for i in range(0,len(args)): if args[i] == '-i': infilename = args[i+1] elif args[i] == '-o': outfilename = args[i+1] if os.path.isfile(infilename): try: # Perform the translation using the methods from the OpenIOC to CybOX Script openioc_indicators = openioc.parse(infilename) observables_obj = openioc_to_cybox.generate_cybox(openioc_indicators, infilename, True) observables_cls = Observables.from_obj(observables_obj) # Set the namespace to be used in the STIX Package stix.utils.set_id_namespace({"https://github.com/STIXProject/openioc-to-stix":"openiocToSTIX"}) # Wrap the created Observables in a STIX Package/Indicator stix_package = STIXPackage() # Add the OpenIOC namespace input_namespaces = {"http://openioc.org/":"openioc"} stix_package.__input_namespaces__ = input_namespaces for observable in observables_cls.observables: indicator_dict = {} producer_dict = {} producer_dict['tools'] = [{'name':'OpenIOC to STIX Utility', 'version':str(__VERSION__)}] indicator_dict['producer'] = producer_dict indicator_dict['title'] = "CybOX-represented Indicator Created from OpenIOC File" indicator = Indicator.from_dict(indicator_dict) indicator.add_observable(observables_cls.observables[0]) stix_package.add_indicator(indicator) # Create and write the STIX Header stix_header = STIXHeader() stix_header.package_intent = "Indicators - Malware Artifacts" stix_header.description = "CybOX-represented Indicators Translated from OpenIOC File" stix_package.stix_header = stix_header # Write the generated STIX Package as XML to the output file outfile = open(outfilename, 'w') # Ignore any warnings - temporary fix for no schemaLocation w/ namespace with warnings.catch_warnings(): warnings.simplefilter("ignore") outfile.write(stix_package.to_xml()) warnings.resetwarnings() outfile.flush() outfile.close() except Exception, err: print('\nError: %s\n' % str(err)) traceback.print_exc()
def create_stix(self, event, user): stix_package = STIXPackage() stix_package.id_ = 'ce1sus:Event-{0}'.format(event.uuid) stix_header = self.__map_stix_header(event) stix_package.stix_header = stix_header event_permissions = self.event_controller.get_event_user_permissions( event, user) # observables if event.observables: for observable in event.get_observables_for_permissions( event_permissions, user): cybox_obs = self.create_observable(observable, event_permissions, user) stix_package.add_observable(cybox_obs) # indicators if event.indicators: indicators = event.get_indicators_for_permissions( event_permissions, user) else: # generate indicators indicators = self.indicator_controller.get_generic_indicators( event, user) for indicator in indicators: stix_indicator = self.create_indicator(indicator, event_permissions, user) stix_package.add_indicator(stix_indicator) return stix_package
def main(): # Build Campaign instances camp1 = Campaign(title='Campaign 1') camp2 = Campaign(title='Campaign 2') # Build a CampaignRef object, setting the `idref` to the `id_` value of # our `camp2` Campaign object. campaign_ref = CampaignRef(idref=camp2.id_) # Build an Indicator object. i = Indicator() # Add CampaignRef object pointing to `camp2`. i.add_related_campaign(campaign_ref) # Add Campaign object, which gets promoted into an instance of # CampaignRef type internally. Only the `idref` is set. i.add_related_campaign(camp1) # Build our STIX Package and attach our Indicator and Campaign objects. package = STIXPackage() package.add_indicator(i) package.add_campaign(camp1) package.add_campaign(camp2) # Print! print package.to_xml()
def main(): rule = """ rule silent_banker : banker { meta: description = "This is just an example" thread_level = 3 in_the_wild = true strings: $a = {6A 40 68 00 30 00 00 6A 14 8D 91} $b = {8D 4D B0 2B C1 83 C0 27 99 6A 4E 59 F7 F9} $c = "UVODFRYSIHLNWPEJXQZAKCBGMT" condition: $a or $b or $c } """ stix_package = STIXPackage() indicator = Indicator(title="silent_banker", description="This is just an example") tm = YaraTestMechanism() tm.rule = rule tm.producer = InformationSource(identity=Identity(name="Yara")) tm.producer.references = ["http://plusvic.github.io/yara/"] indicator.test_mechanisms = TestMechanisms([tm]) stix_package.add_indicator(indicator) print(stix_package.to_xml(encoding=None))
def main(): f = File() f.add_hash("4EC0027BEF4D7E1786A04D021FA8A67F") indicator = Indicator() indicator.title = "File Hash Example" indicator.description = "An indicator containing a File observable with an associated hash" indicator.set_producer_identity("The MITRE Corporation") indicator.set_produced_time(datetime.now(tzutc())) indicator.add_object(f) party_name = PartyName(name_lines=["Foo", "Bar"], person_names=["John Smith", "Jill Smith"], organisation_names=["Foo Inc.", "Bar Corp."]) ident_spec = STIXCIQIdentity3_0(party_name=party_name) ident_spec.add_electronic_address_identifier("*****@*****.**") ident_spec.add_free_text_line("Demonstrating Free Text!") ident_spec.add_contact_number("555-555-5555") ident_spec.add_contact_number("555-555-5556") identity = CIQIdentity3_0Instance(specification=ident_spec) indicator.set_producer_identity(identity) stix_package = STIXPackage() stix_header = STIXHeader() stix_header.description = "Example 05" stix_package.stix_header = stix_header stix_package.add_indicator(indicator) xml = stix_package.to_xml() print(xml)
def main(): f = File() f.add_hash("4EC0027BEF4D7E1786A04D021FA8A67F") indicator = Indicator() indicator.title = "File Hash Example" indicator.description = "An indicator containing a File observable with an associated hash" indicator.set_producer_identity("The MITRE Corporation") indicator.set_produced_time(datetime.now(tzutc())) indicator.add_object(f) party_name = PartyName(name_lines=["Foo", "Bar"], person_names=["John Smith", "Jill Smith"], organisation_names=["Foo Inc.", "Bar Corp."]) ident_spec = STIXCIQIdentity3_0(party_name=party_name) ident_spec.add_electronic_address_identifier("*****@*****.**") ident_spec.add_free_text_line("Demonstrating Free Text!") ident_spec.add_contact_number("555-555-5555") ident_spec.add_contact_number("555-555-5556") identity = CIQIdentity3_0Instance(specification=ident_spec) indicator.set_producer_identity(identity) stix_package = STIXPackage() stix_header = STIXHeader() stix_header.description = "Example" stix_package.stix_header = stix_header stix_package.add_indicator(indicator) xml = stix_package.to_xml() print(xml)
def main(): NAMESPACE = {"https://www.ncsc.gov.uk/": "ncscuk"} idgen.set_id_namespace(NAMESPACE) pkg = STIXPackage() coa = CourseOfAction() obj = file_to_obj('out.json') if obj.type == 'bundle': for _dict in obj.objects: object = dict_to_obj(_dict) if object.type == 'indicator': ind = Indicator() id_str = object.id.replace('--', '-') print id_str #ind.id_ = object.id pattern_type = object.pattern.split(':')[0] _value = re.sub("'", '', object.pattern.split(' = ')[1]) if pattern_type == 'ipv4-addr': obs = Observable( Address(address_value=_value, category=Address.CAT_IPV4)) elif pattern_type == 'url': obs = Observable(URI(value=_value, type_=URI.TYPE_URL)) pkg.add_observable(obs) obs_ref = Observable() obs_ref.id_ = None obs_ref.idref = obs.id_ ind.add_observable(obs_ref) pkg.add_indicator(ind) print pkg.to_xml()
def stix_pkg(config, src, endpoint, payload, title='random test data', description='random test data', package_intents='Indicators - Watchlist', tlp_color='WHITE', dest=None): '''package observables''' # setup the xmlns... xmlns_url = config['edge']['sites'][dest]['stix']['xmlns_url'] xmlns_name = config['edge']['sites'][dest]['stix']['xmlns_name'] set_stix_id_namespace({xmlns_url: xmlns_name}) set_cybox_id_namespace(Namespace(xmlns_url, xmlns_name)) # construct a stix package... stix_package = STIXPackage() stix_header = STIXHeader() stix_header.title = title stix_header.description = description stix_header.package_intents = package_intents marking = MarkingSpecification() marking.controlled_structure = '../../../../descendant-or-self::node()' tlp_marking = TLPMarkingStructure() tlp_marking.color = tlp_color marking.marking_structures.append(tlp_marking) stix_package.stix_header = stix_header stix_package.stix_header.handling = Marking() stix_package.stix_header.handling.add_marking(marking) if isinstance(payload, Observable): stix_package.add_observable(payload) elif isinstance(payload, Indicator): stix_package.add_indicator(payload) elif isinstance(payload, Incident): stix_package.add_incident(payload) return(stix_package)
def stix_xml(bldata): # Create the STIX Package and Header objects stix_package = STIXPackage() stix_header = STIXHeader() # Set the description stix_header.description = "RiskIQ Blacklist Data - STIX Format" # Set the namespace NAMESPACE = {"http://www.riskiq.com": "RiskIQ"} set_id_namespace(NAMESPACE) # Set the produced time to now stix_header.information_source = InformationSource() stix_header.information_source.time = Time() stix_header.information_source.time.produced_time = datetime.now() # Create the STIX Package stix_package = STIXPackage() # Build document stix_package.stix_header = stix_header # Build the Package Intent stix_header.package_intents.append(PackageIntent.TERM_INDICATORS) # Build the indicator indicator = Indicator() indicator.title = "List of Malicious URLs detected by RiskIQ - Malware, Phishing, and Spam" indicator.add_indicator_type("URL Watchlist") for datum in bldata: url = URI() url.value = "" url.value = datum['url'] url.type_ = URI.TYPE_URL url.condition = "Equals" indicator.add_observable(url) stix_package.add_indicator(indicator) return stix_package.to_xml()
def main(): ioc = etree.parse('6d2a1b03-b216-4cd8-9a9e-8827af6ebf93.ioc') stix_package = STIXPackage() ttp = TTP() malware_instance = MalwareInstance() malware_instance.names = ['Zeus', 'twexts', 'sdra64', 'ntos'] ttp = TTP(title="Zeus") ttp.behavior = Behavior() ttp.behavior.add_malware_instance(malware_instance) indicator = Indicator(title="Zeus", description="Finds Zeus variants, twexts, sdra64, ntos") tm = OpenIOCTestMechanism() tm.ioc = ioc tm.producer = InformationSource(identity=Identity(name="Mandiant")) time = Time() time.produced_time = "0001-01-01T00:00:00" tm.producer.time = time tm.producer.references = ["http://openioc.org/iocs/6d2a1b03-b216-4cd8-9a9e-8827af6ebf93.ioc"] indicator.test_mechanisms = TestMechanisms([tm]) indicator.add_indicated_ttp(TTP(idref=ttp.id_)) stix_package.add_indicator(indicator) stix_package.add_ttp(ttp) print(stix_package.to_xml(encoding=None))
def main(): rule = """ rule silent_banker : banker { meta: description = "This is just an example" thread_level = 3 in_the_wild = true strings: $a = {6A 40 68 00 30 00 00 6A 14 8D 91} $b = {8D 4D B0 2B C1 83 C0 27 99 6A 4E 59 F7 F9} $c = "UVODFRYSIHLNWPEJXQZAKCBGMT" condition: $a or $b or $c } """ stix_package = STIXPackage() indicator = Indicator(title="silent_banker", description="This is just an example") tm = YaraTestMechanism() tm.rule = rule tm.producer = InformationSource(identity=Identity(name="Yara")) tm.producer.references = ["http://plusvic.github.io/yara/"] indicator.test_mechanisms = [tm] stix_package.add_indicator(indicator) print stix_package.to_xml()
def MISPtoSTIX(mispJSON): """ Function to convert from a MISP JSON to a STIX stix :param mispJSON: A dict (json) containing a misp Event. :returns stix: A STIX stix with as much of the original data as we could convert. """ if isinstance(mispJSON, mispevent.MISPEvent): misp_event = mispJSON else: misp_event = mispevent.MISPEvent() misp_event.load(mispJSON) # We should now have a proper MISP JSON loaded. # Create a base stix stix = STIXPackage() # Create a header for the new stix stix.stix_header = STIXHeader() # Try to use the event title as the stix title stix.stix_header.title = misp_event.info # We're going to store our observables inside an indicator indicator = Indicator() # Go through each attribute and transfer what we can. for one_attrib in misp_event.attributes: # Build an attribute from the JSON. Is all nice. buildSTIXAttribute.buildAttribute(one_attrib, stix, indicator) stix.add_indicator(indicator) return stix
def main(): file_hash = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855' stix_header = STIXHeader( title="File Hash Reputation Service Results", package_intents=["Indicators - Malware Artifacts"]) stix_package = STIXPackage(stix_header=stix_header) indicator = Indicator( title= "File Reputation for SHA256=e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" ) indicator.add_indicator_type("File Hash Watchlist") file_object = File() file_object.add_hash(Hash(file_hash)) file_object.hashes[0].simple_hash_value.condition = "Equals" file_object.hashes[0].type_.condition = "Equals" indicator.add_observable(file_object) indicator.add_indicated_ttp(TTP(title="Malicious file")) indicator.confidence = Confidence(value=VocabString('75')) indicator.confidence.value.vocab_name = "Percentage" indicator.confidence.value.vocab_reference = "https://en.wikipedia.org/wiki/Percentage" stix_package.add_indicator(indicator) print(stix_package.to_xml(encoding=None))
def generate_package(self): '''Generate a STIX Package''' stix_package = STIXPackage() inds = self.generate_indicators(randint(1, 1)) for i in inds: stix_package.add_indicator(i) return stix_package
def main(): mydata = loaddata() ''' Your Namespace ''' # NAMESPACE = {sanitizer(mydata["NSXURL"]) : (mydata["NS"])} # set_id_namespace(NAMESPACE) NAMESPACE = Namespace(sanitizer(mydata['NSXURL']), sanitizer(mydata['NS'])) set_id_namespace(NAMESPACE) # new ids will be prefixed by "myNS" wrapper = STIXPackage() info_src = InformationSource() info_src.identity = Identity(name=sanitizer(mydata["Identity"])) marking_specification = MarkingSpecification() marking_specification.controlled_structure = "//node() | //@*" tlp = TLPMarkingStructure() tlp.color = sanitizer(mydata["TLP_COLOR"]) marking_specification.marking_structures.append(tlp) handling = Marking() handling.add_marking(marking_specification) timestamp = datetime.datetime.fromtimestamp( time.time()).strftime('%Y-%m-%d %H:%M:%S') MyTITLE = sanitizer(mydata["Title"]) SHORT = timestamp DESCRIPTION = sanitizer(mydata["Description"]) wrapper.stix_header = STIXHeader(information_source=info_src, title=MyTITLE, description=DESCRIPTION, short_description=SHORT) wrapper.stix_header.handling = handling indiDom = Indicator() indiDom.title = MyTITLE indiDom.add_indicator_type("IP Watchlist") for key in mydata["IOC"].keys(): myip = Address(address_value=sanitizer(key), category=Address.CAT_IPV4) myip.condition = "Equals" obsu = Observable(myip) #if mydata[key].size: for idx, mydata["IOC"][key] in enumerate(mydata["IOC"][key]): ioc = File() ioc.add_hash(sanitizer(mydata["IOC"][key])) myip.add_related(ioc, "Downloaded") indiDom.add_observable(obsu) wrapper.add_indicator(indiDom) print(wrapper.to_xml())
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 __repr__(self): stix_package = STIXPackage() stix_header = STIXHeader() stix_package.stix_header = stix_header for d in self.data: i = self._create_indicator(d) stix_package.add_indicator(i) return str(stix_package.to_xml())
def __repr__(self): stix_package = STIXPackage() stix_header = STIXHeader() stix_package.stix_header = stix_header for d in self.data: i = self._create_indicator(d) stix_package.add_indicator(i) return stix_package.to_xml()
def main(): infilename = '' outfilename = '' #Get the command-line arguments args = sys.argv[1:] if len(args) < 4: usage() sys.exit(1) for i in range(0, len(args)): if args[i] == '-i': infilename = args[i + 1] elif args[i] == '-o': outfilename = args[i + 1] if os.path.isfile(infilename): try: # Perform the translation using the methods from the OpenIOC to CybOX Script openioc_indicators = openioc.parse(infilename) observables_obj = openioc_to_cybox.generate_cybox( openioc_indicators, infilename, True) observables_cls = Observables.from_obj(observables_obj) # Wrap the created Observables in a STIX Package/Indicator stix_package = STIXPackage() for observable in observables_cls.observables: indicator_dict = {} producer_dict = {} producer_dict['tools'] = [{ 'name': 'OpenIOC to STIX Utility', 'version': str(__VERSION__) }] indicator_dict['producer'] = producer_dict indicator_dict[ 'title'] = "CybOX-represented Indicator Created from OpenIOC File" indicator = Indicator.from_dict(indicator_dict) indicator.add_observable(observables_cls.observables[0]) stix_package.add_indicator(indicator) # Create and write the STIX Header stix_header = STIXHeader() stix_header.package_intent = "Indicators - Malware Artifacts" stix_header.description = "CybOX-represented Indicators Translated from OpenIOC File" stix_package.stix_header = stix_header # Write the generated STIX Package as XML to the output file outfile = open(outfilename, 'w') outfile.write(stix_package.to_xml()) outfile.flush() outfile.close() except Exception, err: print('\nError: %s\n' % str(err)) traceback.print_exc()
def main(): infilename = '' outfilename = '' #Get the command-line arguments args = sys.argv[1:] if len(args) < 4: usage() sys.exit(1) for i in range(0,len(args)): if args[i] == '-i': infilename = args[i+1] elif args[i] == '-o': outfilename = args[i+1] if os.path.isfile(infilename): try: # Perform the translation using the methods from the OpenIOC to CybOX Script openioc_indicators = openioc.parse(infilename) observables_obj = openioc_to_cybox.generate_cybox(openioc_indicators, infilename, True) observables_cls = Observables.from_obj(observables_obj) # Wrap the created Observables in a STIX Package/Indicator stix_package = STIXPackage() for observable in observables_cls.observables: indicator_dict = {} producer_dict = {} producer_dict['tools'] = [{'name':'OpenIOC to STIX Utility', 'version':str(__VERSION__)}] indicator_dict['producer'] = producer_dict indicator_dict['title'] = "CybOX-represented Indicator Created from OpenIOC File" indicator = Indicator.from_dict(indicator_dict) indicator.add_observable(observables_cls.observables[0]) stix_package.add_indicator(indicator) # Create and write the STIX Header stix_header = STIXHeader() stix_header.package_intent = "Indicators - Malware Artifacts" stix_header.description = "CybOX-represented Indicators Translated from OpenIOC File" stix_package.stix_header = stix_header # Write the generated STIX Package as XML to the output file outfile = open(outfilename, 'w') outfile.write(stix_package.to_xml()) outfile.flush() outfile.close() except Exception, err: print('\nError: %s\n' % str(err)) traceback.print_exc()
def _export_multi_json(): from stix.core import STIXPackage, STIXHeader if jsonPattern is None: if streamFlag: #stream fullFileName = "cifStream" else: fullFileName = myJsonFile xmlFileName = outputFile else: fullFileName = jsonPath + myJsonFile + '.json' fileName = "stix_" + str(myJsonFile) xmlFileName = stixPath + fileName + '.xml' if testMode: print "-----------------File Name: -------- " + fullFileName print "xmlFileName: " + xmlFileName global log_string log_string = log_string + "\n\n" + str(datetime.datetime.now().time()) + ": fullFileName: " + fullFileName + "\n" log_string = log_string + str(datetime.datetime.now().time()) + ": xmlFileName: " + xmlFileName + "\n" wholeJson = _prepare_json(fullFileName) stix_package = STIXPackage() stix_header = STIXHeader() stix_header.description = "Search result from CIF with search parameter " + str(mySearchParam) stix_header.title = "Indicators from search by " + str(mySearchParam) stix_package.stix_header = stix_header stix_header.package_intent = "Purpose: mitigation" for x in wholeJson: indicatorIns = _export_from_json_to_xml(json.loads(x)) stix_package.add_indicator(indicatorIns) if streamFlag is False: f = open(xmlFileName, 'w') try: f.write(stix_package.to_xml()) finally: f.close() #if testMode: # print stix_package.to_xml() log_string = log_string + str(datetime.datetime.now().time()) + ": -------------- STIX----------- \n\n" + stix_package.to_xml() return stix_package.to_xml()
def stix(self): """Output data as STIX. STIX is highly subjective and difficult to format without getting more data from the user. Passive DNS results are formtted into a STIX watchlist with descriptions and other details about the record. :return: STIX formatted watchlist """ if python3: raise RuntimeError("STIX is not supported when using Python 3 due to dependency libraries.") stix_package = STIXPackage() stix_header = STIXHeader() stix_header.description = "Passive DNS resolutions associated" \ " with %s during the time periods of " \ " %s - %s" % (self.queryValue, self.firstSeen, self.lastSeen) stix_package.stix_header = stix_header for record in self._records: indicator = Indicator( title="Observed from %s - %s" % ( record.firstSeen, record.lastSeen ), short_description="Resolution observed by %s." % ( ','.join(record.source) ), description="Passive DNS data collected and aggregated from" \ " PassiveTotal services." ) if is_ip(record.resolve): indicator.add_indicator_type('IP Watchlist') ioc = Address( address_value=record.resolve, category=Address.CAT_IPV4 ) else: indicator.add_indicator_type('Domain Watchlist') ioc = DomainName(value=record.resolve) ioc.condition = "Equals" indicator.add_observable(ioc) stix_package.add_indicator(indicator) output = stix_package.to_xml() return output
def MISPtoSTIX(mispJSON): """ Function to convert from a MISP JSON to a STIX stix :param mispJSON: A dict (json) containing a misp Event. :returns stix: A STIX stix with as much of the original data as we could convert. """ if isinstance(mispJSON, mispevent.MISPEvent): misp_event = mispJSON else: misp_event = mispevent.MISPEvent() misp_event.load(mispJSON) # We should now have a proper MISP JSON loaded. # Create a base stix stix = STIXPackage() try: stix.MISPID = mispJSON["Event"]["id"] except Exception: # We don't have an ID? # Generate a random number and use that stix.MISPID = random.randint(1, 9000) # it's being silly # backup the ID backupID = stix.MISPID # Create a header for the new stix stix.stix_header = STIXHeader() # Try to use the event title as the stix title stix.stix_header.title = misp_event.info # Go through each attribute and transfer what we can. for one_attrib in misp_event.attributes: # We're going to store our observables inside an indicator # One for each attribute because @iglocska said so # I swear STIX is gonna be the death of me. indicator = Indicator() # Build an attribute from the JSON. Is all nice. buildSTIXAttribute.buildAttribute(one_attrib, stix, indicator) stix.add_indicator(indicator) stix.MISPID = backupID return stix
def main(): pkg = STIXPackage() indicator = Indicator() indicator.id_ = "example:package-382ded87-52c9-4644-bab0-ad3168cbad50" indicator.title = "Malicious site hosting downloader" indicator.add_indicator_type("URL Watchlist") url = URI() url.value = "http://x4z9arb.cn/4712" url.type_ = URI.TYPE_URL indicator.add_observable(url) pkg.add_indicator(indicator) print pkg.to_xml()
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 MISPtoSTIX(mispJSON): """ Function to convert from a MISP JSON to a STIX stix :param mispJSON: A dict (json) containing a misp Event. :returns stix: A STIX stix with as much of the original data as we could convert. """ if not isinstance(mispJSON, dict): # It's likely not a loaded JSON. Attempt to load it. try: mispJSON = json.loads(mispJSON) except json.decoder.JSONDecodeError: # We couldn't make head nor tail of it try: mispJSON = json.load(mispJSON) except: raise MISPLoadError("COULD NOT LOAD MISP JSON!") # We should now have a proper MISP JSON loaded. # Create a base stix stix = STIXPackage() # Create a header for the new stix stix.stix_header = STIXHeader() # Try to use the event title as the stix title if "info" in mispJSON: stix.stix_header.title = mispJSON["Event"]["info"] else: # We don't have an easy name for it stix.stix_header.title = "MISP Export" # Best we can do really # Get the event Attributes attributes = mispJSON["Event"]["Attribute"] # We're going to store our observables inside an indicator indicator = Indicator() # Go through each attribute and transfer what we can. for one_attrib in attributes: # Build an attribute from the JSON. Is all nice. buildSTIXAttribute.buildAttribute(one_attrib, stix, indicator) stix.add_indicator(indicator) return stix
def main(): data = json.load(open("data.json")) stix_package = STIXPackage(stix_header=STIXHeader( title=data['title'], package_intents='Incident')) ttps = {} for info in data['ips']: # Add TTP, unless it's already been added if info['bot'] not in ttps: ttps[info['bot']] = TTP(title=info['bot']) stix_package.add_ttp(ttps[info['bot']]) # Add indicator indicator = Indicator(title=info['ip']) addr = Address(address_value=info['ip'], category=Address.CAT_IPV4) addr.condition = "Equals" indicator.add_observable(addr) indicator.add_indicated_ttp(TTP(idref=ttps[info['bot']].id_)) stix_package.add_indicator(indicator) # Add incident incident = Incident(title=info['ip']) incident.time = Time() incident.time.first_malicious_action = info['first_seen'] addr = Address(address_value=info['ip'], category=Address.CAT_IPV4) observable = Observable(item=addr) stix_package.add_observable(observable) related_ttp = RelatedTTP(TTP(idref=ttps[info['bot']].id_), relationship="Used Malware") incident.leveraged_ttps.append(related_ttp) related_observable = RelatedObservable( Observable(idref=observable.id_)) incident.related_observables.append(related_observable) related_indicator = RelatedIndicator(Indicator(idref=indicator.id_)) incident.related_indicators.append(related_indicator) stix_package.add_incident(incident) print(stix_package.to_xml(encoding=None))
def main(): pkg = STIXPackage() indicator = Indicator() indicator.id_ = "example:package-382ded87-52c9-4644-bab0-ad3168cbad50" indicator.title = "Malicious site hosting downloader" indicator.add_indicator_type("URL Watchlist") url = URI() url.value = "http://x4z9arb.cn/4712" url.type_ = URI.TYPE_URL url.value.condition = "Equals" indicator.add_observable(url) pkg.add_indicator(indicator) print pkg.to_xml()
def convert(self, stix_id_prefix='', published_only=True, **kw_arg): self.parse(**kw_arg) stix_packages = [] for event in self.events: if published_only: if not event.published: continue # id generator package_id = self.get_misp_pacakge_id(stix_id_prefix, event) stix_package = STIXPackage(timestamp=event.dt, id_=package_id) stix_header = STIXHeader() # set identity information identity = Identity(name=self.identity_name) information_source = InformationSource(identity=identity) stix_header.information_source = information_source tlp = None for tag in event.tags: if tag.tlp is not None: tlp = tag.tlp break if tlp is not None: # TLP for Generic format tlp_marking_structure = TLPMarkingStructure() tlp_marking_structure.color = tlp marking_specification = MarkingSpecification() marking_specification.marking_structures = tlp_marking_structure marking_specification.controlled_structure = '../../../../descendant-or-self::node() | ../../../../descendant-or-self::node()/@*' marking = Marking() marking.add_marking(marking_specification) stix_header.handling = marking stix_header.title = event.info stix_header.description = event.info stix_header.short_description = event.info for attribute in event.attributes: stix_package.add_indicator(attribute.convert()) stix_package.stix_header = stix_header stix_packages.append(stix_package) return stix_packages
def gen_stix_indicator_sample( config, target=None, datatype=None, title="random test data", description="random test data", package_intents="Indicators - Watchlist", tlp_color="WHITE", observables_list=None, ): """generate sample stix data comprised of indicator_count indicators of type datatype""" # setup the xmlns... xmlns_url = config["edge"]["sites"][target]["stix"]["xmlns_url"] xmlns_name = config["edge"]["sites"][target]["stix"]["xmlns_name"] set_stix_id_namespace({xmlns_url: xmlns_name}) set_cybox_id_namespace(Namespace(xmlns_url, xmlns_name)) # construct a stix package... stix_package = STIXPackage() stix_header = STIXHeader() stix_header.title = title stix_header.description = description stix_header.package_intents = package_intents marking = MarkingSpecification() marking.controlled_structure = "../../../../descendant-or-self::node()" tlp_marking = TLPMarkingStructure() tlp_marking.color = tlp_color marking.marking_structures.append(tlp_marking) stix_package.stix_header = stix_header stix_package.stix_header.handling = Marking() stix_package.stix_header.handling.add_marking(marking) indicator_ = Indicator() indicator_.title = str(uuid.uuid4()) + "_sample_indicator" indicator_.confidence = "Unknown" indicator_.add_indicator_type("Malware Artifacts") observable_composition_ = ObservableComposition() observable_composition_.operator = indicator_.observable_composition_operator for observable_id in observables_list: observable_ = Observable() observable_.idref = observable_id observable_composition_.add(observable_) indicator_.observable = Observable() indicator_.observable.observable_composition = observable_composition_ stix_package.add_indicator(indicator_) return stix_package
def main(): data = json.load(open("data.json")) stix_package = STIXPackage(stix_header=STIXHeader(title=data['title'], package_intents='Incident')) ttps = {} for info in data['ips']: # Add TTP, unless it's already been added if info['bot'] not in ttps: ttps[info['bot']] = TTP(title=info['bot']) stix_package.add_ttp(ttps[info['bot']]) # Add indicator indicator = Indicator(title=info['ip']) addr = Address(address_value=info['ip'], category=Address.CAT_IPV4) addr.condition = "Equals" indicator.add_observable(addr) indicator.add_indicated_ttp(TTP(idref=ttps[info['bot']].id_)) stix_package.add_indicator(indicator) # Add incident incident = Incident(title=info['ip']) incident.time = Time() incident.time.first_malicious_action = info['first_seen'] addr = Address(address_value=info['ip'], category=Address.CAT_IPV4) observable = Observable(item=addr) stix_package.add_observable(observable) related_ttp = RelatedTTP(TTP(idref=ttps[info['bot']].id_), relationship="Used Malware") incident.leveraged_ttps.append(related_ttp) related_observable = RelatedObservable(Observable(idref=observable.id_)) incident.related_observables.append(related_observable) related_indicator = RelatedIndicator(Indicator(idref=indicator.id_)) incident.related_indicators.append(related_indicator) stix_package.add_incident(incident) print stix_package.to_xml()
def gen_stix_indicator_sample(config, target=None, datatype=None, title='random test data', description='random test data', package_intents='Indicators - Watchlist', tlp_color='WHITE', observables_list=None): '''generate sample stix data comprised of indicator_count indicators of type datatype''' # setup the xmlns... xmlns_url = config['edge']['sites'][target]['stix']['xmlns_url'] xmlns_name = config['edge']['sites'][target]['stix']['xmlns_name'] set_stix_id_namespace({xmlns_url: xmlns_name}) set_cybox_id_namespace(Namespace(xmlns_url, xmlns_name)) # construct a stix package... stix_package = STIXPackage() stix_header = STIXHeader() stix_header.title = title stix_header.description = description stix_header.package_intents = package_intents marking = MarkingSpecification() marking.controlled_structure = '../../../../descendant-or-self::node()' tlp_marking = TLPMarkingStructure() tlp_marking.color = tlp_color marking.marking_structures.append(tlp_marking) stix_package.stix_header = stix_header stix_package.stix_header.handling = Marking() stix_package.stix_header.handling.add_marking(marking) indicator_ = Indicator() indicator_.title = str(uuid.uuid4()) + '_sample_indicator' indicator_.confidence = 'Unknown' indicator_.add_indicator_type('Malware Artifacts') observable_composition_ = ObservableComposition() observable_composition_.operator = \ indicator_.observable_composition_operator for observable_id in observables_list: observable_ = Observable() observable_.idref = observable_id observable_composition_.add(observable_) indicator_.observable = Observable() indicator_.observable.observable_composition = observable_composition_ stix_package.add_indicator(indicator_) return (stix_package)
def main(): package = STIXPackage() # Create the indicator indicator = Indicator(title="IP Address for known C2 Channel") indicator.add_indicator_type("IP Watchlist") address = Address(category="ipv4-addr") address.address_value = "10.0.0.0" address.address_value.condition = "Equals" indicator.observable = address package.add_indicator(indicator) # Create the campaign campaign = Campaign(title="Operation Omega") package.add_campaign(campaign) # Link the campaign to the indicator campaign.related_indicators.append(RelatedIndicator(item=Indicator(idref=indicator.id_))) print package.to_xml()
def main(): f = File() # This automatically detects that it's an MD5 hash based on the length f.add_hash("4EC0027BEF4D7E1786A04D021FA8A67F") indicator = Indicator() indicator.title = "File Hash Example" indicator.description = "An indicator containing a File observable with an associated hash" indicator.set_producer_identity("The MITRE Corporation") indicator.set_produced_time(datetime.now(tzutc())) indicator.add_object(f) stix_package = STIXPackage() stix_header = STIXHeader() stix_header.description = "Example " stix_package.stix_header = stix_header stix_package.add_indicator(indicator) print(stix_package.to_xml())
def gen_stix_indicator_sample(config, target=None, datatype=None, title='random test data', description='random test data', package_intents='Indicators - Watchlist', tlp_color='WHITE', observables_list=None): '''generate sample stix data comprised of indicator_count indicators of type datatype''' # setup the xmlns... xmlns_url = config['edge']['sites'][target]['stix']['xmlns_url'] xmlns_name = config['edge']['sites'][target]['stix']['xmlns_name'] set_stix_id_namespace({xmlns_url: xmlns_name}) set_cybox_id_namespace(Namespace(xmlns_url, xmlns_name)) # construct a stix package... stix_package = STIXPackage() stix_header = STIXHeader() stix_header.title = title stix_header.description = description stix_header.package_intents = package_intents marking = MarkingSpecification() marking.controlled_structure = '../../../../descendant-or-self::node()' tlp_marking = TLPMarkingStructure() tlp_marking.color = tlp_color marking.marking_structures.append(tlp_marking) stix_package.stix_header = stix_header stix_package.stix_header.handling = Marking() stix_package.stix_header.handling.add_marking(marking) indicator_ = Indicator() indicator_.title = str(uuid.uuid4()) + '_sample_indicator' indicator_.confidence = 'Unknown' indicator_.add_indicator_type('Malware Artifacts') observable_composition_ = ObservableComposition() observable_composition_.operator = \ indicator_.observable_composition_operator for observable_id in observables_list: observable_ = Observable() observable_.idref = observable_id observable_composition_.add(observable_) indicator_.observable = Observable() indicator_.observable.observable_composition = observable_composition_ stix_package.add_indicator(indicator_) return(stix_package)
def export_stix(iocs): '''Export to STIX. Adapted from: github.com/STIXProject/openioc-to-stix/blob/master/openioc_to_stix.py ''' cybox_observables = export_cybox(iocs) stix_package = STIXPackage() for obs in cybox_observables: indicator_dict = {} producer_dict = {} producer_dict['tools'] = [{'name': 'export_iocs'}] indicator_dict['producer'] = producer_dict indicator_dict['title'] = "export_iocs STIX export" indicator = Indicator.from_dict(indicator_dict) indicator.add_observable(obs) stix_package.add_indicator(indicator) # Create and write the STIX Header stix_header = STIXHeader() stix_header.package_intent = "Indicators - Malware Artifacts" stix_header.description = "CybOX-represented Indicators extracted with export_iocs" stix_package.stix_header = stix_header return stix_package.to_xml()
def export_stix(iocs): '''Export to STIX. Adapted from: github.com/STIXProject/openioc-to-stix/blob/master/openioc_to_stix.py ''' cybox_observables = export_cybox(iocs) stix_package = STIXPackage() for obs in cybox_observables: indicator_dict = {} producer_dict = {} producer_dict['tools'] = [{'name':'extract_iocs'}] indicator_dict['producer'] = producer_dict indicator_dict['title'] = "extract_iocs STIX export" indicator = Indicator.from_dict(indicator_dict) indicator.add_observable(obs) stix_package.add_indicator(indicator) # Create and write the STIX Header stix_header = STIXHeader() stix_header.package_intent = "Indicators - Malware Artifacts" stix_header.description = "CybOX-represented Indicators extracted with extract_iocs" stix_package.stix_header = stix_header return stix_package.to_xml()
def main(): package = STIXPackage() # Create the indicator indicator = Indicator(title="IP Address for known C2 Channel") indicator.add_indicator_type("IP Watchlist") address = Address(category="ipv4-addr") address.address_value = "10.0.0.0" address.address_value.condition = "Equals" indicator.observable = address package.add_indicator(indicator) # Create the campaign campaign = Campaign(title="Operation Omega") package.add_campaign(campaign) # Link the campaign to the indicator campaign.related_indicators.append( RelatedIndicator(item=Indicator(idref=indicator.id_))) print package.to_xml()
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(): shv = Hash() shv.simple_hash_value = "4EC0027BEF4D7E1786A04D021FA8A67F" f = File() h = Hash(shv, Hash.TYPE_MD5) f.add_hash(h) indicator = Indicator() indicator.title = "File Hash Example" indicator.description = "An indicator containing a File observable with an associated hash" indicator.set_producer_identity("The MITRE Corporation") indicator.set_produced_time(datetime.now()) indicator.add_object(f) stix_package = STIXPackage() stix_header = STIXHeader() stix_header.description = "Example 02" stix_package.stix_header = stix_header stix_package.add_indicator(indicator) 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(): file_hash = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' badness = 0 # Value between 0-100, or None if the badness is unknown sp = STIXPackage() sp.stix_header = STIXHeader() sp.stix_header.title = "File Hash Reputation for %s" % file_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 = "TAXII Service Profile: File Hash Reputation" file_obj = File() file_obj.add_hash(file_hash) file_obj.hashes[0].simple_hash_value.condition = "Equals" indicator = Indicator(title="File Hash Reputation") indicator.indicator_type = "File Hash Reputation" indicator.add_observable(file_obj) if badness is None: indicator.likely_impact = "Unknown" else: vs = VocabString(str(badness)) vs.vocab_name = 'percentage' vs.vocab_reference = "http://en.wikipedia.org/wiki/Percentage" indicator.likely_impact = vs sp.add_indicator(indicator) 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)
def main(): stix_pkg = STIXPackage() # make indicator ind = Indicator() ind.title = "Malicious executable" ind.description = "Resident binary which implements infostealing and credit card grabber" # link to "Installation" phase and kill chain by ID values infect = KillChainPhase(name="Infect Machine") exfil = KillChainPhase(name="Exfiltrate Data") mychain = KillChain(name="Organization-specific Kill Chain") mychain.kill_chain_phases = [infect, exfil] stix_pkg.ttps.add_ttp(TTP()) stix_pkg.ttps.kill_chains.append(mychain) stix_pkg.add_indicator(ind) # add referenced phase to indicator ind.kill_chain_phases.append(KillChainPhaseReference(phase_id=infect.phase_id, kill_chain_id=mychain.id_)) print(stix_pkg.to_xml(encoding=None))
def _generate_stix_package(packages): compiled_package = STIXPackage() for package in packages: sio = IOhandler(package.content) sp = STIXPackage.from_xml(sio) if sp.indicators: [compiled_package.add_indicator(ind) for ind in sp.indicators] if sp.observables: [ compiled_package.add_observable(obs) for obs in sp.observables ] return compiled_package
def main(): stix_pkg = STIXPackage() # create LM-style kill chain # REF: http://stix.mitre.org/language/version{{site.current_version}}/stix_v{{site.current_version}}_lmco_killchain.xml recon = KillChainPhase(phase_id="stix:TTP-af1016d6-a744-4ed7-ac91-00fe2272185a", name="Reconnaissance", ordinality="1") weapon = KillChainPhase(phase_id="stix:TTP-445b4827-3cca-42bd-8421-f2e947133c16", name="Weaponization", ordinality="2") deliver = KillChainPhase(phase_id="stix:TTP-79a0e041-9d5f-49bb-ada4-8322622b162d", name="Delivery", ordinality="3") exploit = KillChainPhase(phase_id="stix:TTP-f706e4e7-53d8-44ef-967f-81535c9db7d0", name="Exploitation", ordinality="4") install = KillChainPhase(phase_id="stix:TTP-e1e4e3f7-be3b-4b39-b80a-a593cfd99a4f", name="Installation", ordinality="5") control = KillChainPhase(phase_id="stix:TTP-d6dc32b9-2538-4951-8733-3cb9ef1daae2", name="Command and Control", ordinality="6") action = KillChainPhase(phase_id="stix:TTP-786ca8f9-2d9a-4213-b38e-399af4a2e5d6", name="Actions on Objectives", ordinality="7") lmchain = KillChain(id_="stix:TTP-af3e707f-2fb9-49e5-8c37-14026ca0a5ff", name="LM Cyber Kill Chain") lmchain.definer = "LMCO" lmchain.kill_chain_phases = [recon, weapon, deliver, exploit, install, control, action] stix_pkg.ttps.kill_chains.append(lmchain) infect = KillChainPhase(name="Infect Machine") exfil = KillChainPhase(name="Exfiltrate Data") mychain = KillChain(name="Organization-specific Kill Chain") mychain.definer = "Myself" mychain.kill_chain_phases = [infect, exfil] stix_pkg.ttps.add_ttp(TTP()) stix_pkg.ttps.kill_chains.append(mychain) indicator = Indicator() indicator.kill_chain_phases = KillChainPhasesReference([ KillChainPhaseReference(phase_id=exfil.phase_id, kill_chain_id=mychain.id_), KillChainPhaseReference(phase_id=action.phase_id, kill_chain_id=lmchain.id_) ]) stix_pkg.add_indicator(indicator) print(stix_pkg.to_xml(encoding=None))
def main(): f = File() f.add_hash("4EC0027BEF4D7E1786A04D021FA8A67F") indicator = Indicator() indicator.title = "File Hash Example" indicator.description = "An indicator containing a File observable with an associated hash" indicator.set_producer_identity("The MITRE Corporation") indicator.set_produced_time(datetime.now()) indicator.add_object(f) party_name = PartyName(name_lines=["Foo", "Bar"], person_names=["John Smith", "Jill Smith"], organisation_names=["Foo Inc.", "Bar Corp."]) ident_spec = STIXCIQIdentity3_0(party_name=party_name) identity = CIQIdentity3_0Instance(specification=ident_spec) indicator.set_producer_identity(identity) stix_package = STIXPackage() stix_header = STIXHeader() stix_header.description = "Example 05" stix_package.stix_header = stix_header stix_package.add_indicator(indicator) print(stix_package.to_xml())
def main(): stix_pkg = STIXPackage() # make indicator ind = Indicator() ind.title = "Malicious executable" ind.description = "Resident binary which implements infostealing and credit card grabber" # link to "Installation" phase and kill chain by ID values infect = KillChainPhase(name="Infect Machine") exfil = KillChainPhase(name="Exfiltrate Data") mychain = KillChain(name="Organization-specific Kill Chain") mychain.kill_chain_phases = [infect, exfil] stix_pkg.ttps.kill_chains.append(mychain) stix_pkg.add_indicator(ind) # add referenced phase to indicator ind.kill_chain_phases.append(KillChainPhaseReference(phase_id=infect.phase_id,kill_chain_id = mychain.id_)) print stix_pkg.to_xml()
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(): file_hash = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855' stix_header = STIXHeader(title="File Hash Reputation Service Results", package_intents=["Indicators - Malware Artifacts"]) stix_package = STIXPackage(stix_header=stix_header) indicator = Indicator(title="File Reputation for SHA256=e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855") indicator.add_indicator_type("File Hash Watchlist") file_object = File() file_object.add_hash(Hash(file_hash)) file_object.hashes[0].simple_hash_value.condition = "Equals" file_object.hashes[0].type_.condition = "Equals" indicator.add_observable(file_object) indicator.add_indicated_ttp(TTP(title="Malicious file")) indicator.confidence = Confidence(value=VocabString('75')) indicator.confidence.value.vocab_name = "Percentage" indicator.confidence.value.vocab_reference = "https://en.wikipedia.org/wiki/Percentage" stix_package.add_indicator(indicator) print(stix_package.to_xml(encoding=None))
def stix(json): """ Created a stix file based on a json file that is being handed over """ # Create a new STIXPackage stix_package = STIXPackage() # Create a new STIXHeader stix_header = STIXHeader() # Add Information Source. This is where we will add the tool information. stix_header.information_source = InformationSource() # Create a ToolInformation object. Use the initialization parameters # to set the tool and vendor names. # # Note: This is an instance of cybox.common.ToolInformation and NOT # stix.common.ToolInformation. tool = ToolInformation( tool_name="viper2stix", tool_vendor="The Viper group http://viper.li - developed by Alexander Jaeger https://github.com/deralexxx/viper2stix" ) #Adding your identity to the header identity = Identity() identity.name = Config.get('stix', 'producer_name') stix_header.information_source.identity=identity # Set the Information Source "tools" section to a # cybox.common.ToolInformationList which contains our tool that we # created above. stix_header.information_source.tools = ToolInformationList(tool) stix_header.title = Config.get('stix', 'title') # Set the produced time to now stix_header.information_source.time = Time() stix_header.information_source.time.produced_time = datetime.now() marking_specification = MarkingSpecification() marking_specification.controlled_structure = "../../../descendant-or-self::node()" tlp = TLPMarkingStructure() tlp.color = Config.get('stix', 'TLP') marking_specification.marking_structures.append(tlp) handling = Marking() handling.add_marking(marking_specification) # Set the header description stix_header.description = Config.get('stix', 'description') # Set the STIXPackage header stix_package.stix_header = stix_header stix_package.stix_header.handling = handling try: pp = pprint.PrettyPrinter(indent=5) pp.pprint(json['default']) #for key, value in json['default'].iteritems(): # print key, value for item in json['default']: #logger.debug("item %s", item) indicator = Indicator() indicator.title = "File Hash" indicator.description = ( "An indicator containing a File observable with an associated hash" ) # Create a CyboX File Object f = File() sha_value = item['sha256'] if sha_value is not None: sha256 = Hash() sha256.simple_hash_value = sha_value h = Hash(sha256, Hash.TYPE_SHA256) f.add_hash(h) sha1_value = item['sha1'] if sha_value is not None: sha1 = Hash() sha1.simple_hash_value = sha1_value h = Hash(sha1, Hash.TYPE_SHA1) f.add_hash(h) sha512_value = item['sha512'] if sha_value is not None: sha512 = Hash() sha512.simple_hash_value = sha512_value h = Hash(sha512, Hash.TYPE_SHA512) f.add_hash(h) f.add_hash(item['md5']) #adding the md5 hash to the title as well stix_header.title+=' '+item['md5'] #print(item['type']) f.size_in_bytes=item['size'] f.file_format=item['type'] f.file_name = item['name'] indicator.description = "File hash served by a Viper instance" indicator.add_object(f) stix_package.add_indicator(indicator) except Exception, e: logger.error('Error: %s',format(e)) return False