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 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)
def main(): alpha_package = STIXPackage() alpha_package.stix_header = STIXHeader() alpha_package.stix_header.title = "Report on Adversary Alpha's Campaign against the Industrial Control Sector" alpha_package.stix_header.package_intents = "Campaign Characterization" alpha_package.stix_header.handling = Marking() alpha_marking = MarkingSpecification() alpha_marking.controlled_structure = "../../../../node()" alpha_tlp_marking = TLPMarkingStructure() alpha_tlp_marking.color = "AMBER" alpha_marking.marking_structures.append(alpha_tlp_marking) alpha_package.stix_header.handling.add_marking(alpha_marking) rat_package = STIXPackage() rat_package.stix_header = STIXHeader() rat_package.stix_header.title = "Indicators for Malware DrownedRat" rat_package.stix_header.package_intents = "Indicators - Malware Artifacts" rat_package.stix_header.handling = Marking() rat_marking = MarkingSpecification() rat_marking.controlled_structure = "../../../../node()" rat_tlp_marking = TLPMarkingStructure() rat_tlp_marking.color = "RED" alpha_marking.marking_structures.append(rat_tlp_marking) rat_package.stix_header.handling.add_marking(rat_marking) stix_package = STIXPackage() info_src = InformationSource() info_src.identity = Identity(name="Government Sharing Program - GSP") stix_package.stix_header = STIXHeader(information_source=info_src) stix_package.related_packages.append(alpha_package) stix_package.related_packages.append(rat_package) print stix_package.to_xml()
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 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)
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
def to_stix(infile): """Converts the `infile` OpenIOC xml document into a STIX Package. Args: infile: OpenIOC xml filename to translate Returns: stix.core.STIXPackage object """ observables = to_cybox(infile) # Build Indicators from the Observable objects indicators = [_observable_to_indicator_stix(o) for o in observables] # Wrap the created Observables in a STIX Package/Indicator stix_package = STIXPackage() # Set the Indicators collection stix_package.indicators = indicators # Create and write the STIX Header. Warning: these fields have been # deprecated in STIX v1.2! stix_header = STIXHeader() stix_header.package_intent = PackageIntent.TERM_INDICATORS_MALWARE_ARTIFACTS stix_header.description = "CybOX-represented Indicators Translated from OpenIOC File" stix_package.stix_header = stix_header return stix_package
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 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(): 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 _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(): # Creamos el indicador con la información de la que disponemos threatActor = ThreatActor() threatActor.title = "Ip/Domain/Hostname" threatActor.description = ("A threatActor commited with malicious tasks") threatActor.information_source = ("Malshare") threatActor.timestamp = ("01/05/2019") threatActor.identity = ("106.113.123.197") threatActor.types = ("eCrime Actor - Spam Service") # Creamos el indicador con la información de la que disponemos indicator = Indicator() indicator.title = "Risk Score" indicator.description = ( "An indicator containing the appropriate Risk Score") indicator.set_produced_time("01/05/2019") indicator.likely_impact = ("Risk Score: 2(Medium)") # Creamos el reporte en STIX, con una brve descripción stix_package = STIXPackage() stix_header = STIXHeader() stix_header.description = "Feeds in STIX format with their Risk Scores" stix_package.stix_header = stix_header # Añadimos al reporte el indicador que hemos construido antes stix_package.add(threatActor) stix_package.add(indicator) # Imprimimos el xml en pantalla print(stix_package.to_xml())
def generateMainPackage(events): stix_package = STIXPackage() stix_header = STIXHeader() stix_header.title="Export from " + namespace[1] + " MISP" stix_header.package_intents="Threat Report" stix_package.stix_header = stix_header return stix_package
def main(hash_value, title, description, confidence_value): # Create a CyboX File Object f = File() # This automatically detects that it's an MD5 hash based on the length f.add_hash(hash_value) # Create an Indicator with the File Hash Object created above. indicator = Indicator() indicator.title = title indicator.description = (description) indicator.confidence = confidence_value indicator.set_producer_identity("Information Security") indicator.set_produced_time(utils.dates.now()) # Add The File Object to the Indicator. This will promote the CybOX Object # to a CybOX Observable internally. indicator.add_object(f) # Create a STIX Package stix_package = STIXPackage() # Create the STIX Header and add a description. stix_header = STIXHeader() stix_header.description = description stix_package.stix_header = stix_header # Add our Indicator object. The add() method will inspect the input and # append it to the `stix_package.indicators` collection. stix_package.add(indicator) # Print the XML! with open('FileHash_indicator.xml', 'w') as the_file: the_file.write(stix_package.to_xml().decode('utf-8'))
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(): # Create our CybOX Simple Hash Value shv = Hash() shv.simple_hash_value = "4EC0027BEF4D7E1786A04D021FA8A67F" # Create a CybOX File Object and add the Hash we created above. f = File() h = Hash(shv, Hash.TYPE_MD5) f.add_hash(h) # Create the STIX Package stix_package = STIXPackage() # Create the STIX Header and add a description. stix_header = STIXHeader() stix_header.description = "Simple File Hash Observable Example" stix_package.stix_header = stix_header # Add the File Hash Observable to the STIX Package. The add() method will # inspect the input and add it to the top-level stix_package.observables # collection. stix_package.add(f) # Print the XML! print(stix_package.to_xml())
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 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(): # Create a new STIXPackage stix_package = STIXPackage() # Create a new STIXHeader stix_header = STIXHeader() # Add Information Source. This is where we will add the tool information. stix_header.information_source = InformationSource() # Create a ToolInformation object. Use the initialization parameters # to set the tool and vendor names. # # Note: This is an instance of cybox.common.ToolInformation and NOT # stix.common.ToolInformation. tool = ToolInformation(tool_name="python-stix", tool_vendor="The MITRE Corporation") # Set the Information Source "tools" section to a # cybox.common.ToolInformationList which contains our tool that we # created above. stix_header.information_source.tools = ToolInformationList(tool) # Set the header description stix_header.description = "Example" # Set the STIXPackage header stix_package.stix_header = stix_header # Print the XML! print(stix_package.to_xml()) # Print the dictionary! pprint(stix_package.to_dict())
def main(args): if len(args) < 4: sys.exit("Invalid parameters") baseURL = args[1] if not baseURL: baseURL = 'https://www.misp-project.org' orgname = args[2] orgname = re.sub('[\W]+', '', orgname.replace(" ", "_")) NS_DICT[baseURL] = orgname try: idgen.set_id_namespace(Namespace(baseURL, orgname)) except TypeError: idgen.set_id_namespace(Namespace(baseURL, orgname, "MISP")) stix_package = STIXPackage() stix_header = STIXHeader() stix_header.title = "Export from {} MISP".format(args[2]) stix_header.package_intents = "Threat Report" stix_package.stix_header = stix_header stix_package.version = "1.1.1" stix_package.timestamp = datetime.datetime.now() if args[3] == 'json': stix_string = stix_package.to_json()[:-1] stix_string += ', "related_packages": [' else: stix_string = stix_package.to_xml(auto_namespace=False, ns_dict=NS_DICT, schemaloc_dict=SCHEMALOC_DICT) stix_string = stix_string.decode().replace("</stix:STIX_Package>\n", "") print(stix_string)
def generateMainPackage(events): stix_package = STIXPackage() stix_header = STIXHeader() stix_header.title = "Export from " + namespace[1] + " MISP" stix_header.package_intents = "Threat Report" stix_package.stix_header = stix_header return stix_package
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 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(): 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 to_stix(infile): """Converts the `infile` OpenIOC xml document into a STIX Package. Args: infile: OpenIOC xml filename to translate Returns: stix.core.STIXPackage object """ observables = to_cybox(infile) # Build Indicators from the Observable objects indicators = [_observable_to_indicator_stix(o) for o in observables] # Wrap the created Observables in a STIX Package/Indicator stix_package = STIXPackage() # Set the Indicators collection stix_package.indicators = Indicators(indicators) # Create and write the STIX Header. Warning: these fields have been # deprecated in STIX v1.2! stix_header = STIXHeader() stix_header.package_intent = PackageIntent.TERM_INDICATORS_MALWARE_ARTIFACTS stix_header.description = "CybOX-represented Indicators Translated from OpenIOC File" stix_package.stix_header = stix_header return stix_package
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 main(): # Crea un objeto vía CybOX f = File() # Asocia el hash a dicho objeto, la tipología del hash la detecta automáticamente en función de su amplitud f.add_hash("8994a4713713e4683117e35d8689ea24") # Creamos el indicador con la información de la que disponemos indicator = Indicator() indicator.title = "Feeds and Risk Score" indicator.description = ( "An indicator containing the feed and the appropriate Risk Score" ) indicator.set_producer_identity("Malshare") indicator.set_produced_time("01/05/2019") indicator.likely_impact = ("Risk Score: 4(Critical)") # Asociamos el hash anterior a nuestro indicador indicator.add_object(f) # Creamos el reporte en STIX, con una brve descripción stix_package = STIXPackage() stix_header = STIXHeader() stix_header.description = "Feeds in STIX format with their Risk Scores" stix_package.stix_header = stix_header # Añadimos al reporte el indicador que hemos construido antes stix_package.add(indicator) # Imprimimos el xml en pantalla print(stix_package.to_xml())
def main(): # Create a CyboX File Object f = File() # This automatically detects that it's an MD5 hash based on the length f.add_hash("4EC0027BEF4D7E1786A04D021FA8A67F") # Create an Indicator with the File Hash Object created above. indicator = Indicator() indicator.title = "File Hash Example" indicator.description = ( "An indicator containing a File observable with an associated hash" ) indicator.set_producer_identity("The MITRE Corporation") indicator.set_produced_time(utils.dates.now()) # Add The File Object to the Indicator. This will promote the CybOX Object # to a CybOX Observable internally. indicator.add_object(f) # Create a STIX Package stix_package = STIXPackage() # Create the STIX Header and add a description. stix_header = STIXHeader() stix_header.description = "File Hash Indicator Example" stix_package.stix_header = stix_header # Add our Indicator object. The add() method will inspect the input and # append it to the `stix_package.indicators` collection. stix_package.add(indicator) # Print the XML! print(stix_package.to_xml())
def buildSTIX(ident,confid,restconfid, effect, resteffect,typeIncident,resttype,asset,restasset,hashPkg): # IMPLEMENTATION WORKAROUND - # restConfid --> header.description # resteffect --> breach.description # resttype --> reporter.description # restasset --> reporter.identity.name # setup stix document stix_package = STIXPackage() stix_header = STIXHeader() stix_header.description = restconfid # "Example description" stix_package.stix_header = stix_header # add incident and confidence breach = Incident(id_=ident) breach.description = resteffect # "Intrusion into enterprise network" breach.confidence = Confidence() breach.confidence.value=confid breach._binding_class.xml_type = typeIncident # stamp with reporter breach.reporter = InformationSource() breach.reporter.description = resttype #"The person who reported it" breach.reporter.time = Time() breach.reporter.time.produced_time = datetime.strptime("2014-03-11","%Y-%m-%d") # when they submitted it breach.reporter.identity = Identity() breach.reporter.identity.name = restasset # "Sample Investigations, LLC" # set incident-specific timestamps breach.time = incidentTime() breach.title = "Breach of CyberTech Dynamics" breach.time.initial_compromise = datetime.strptime("2012-01-30", "%Y-%m-%d") breach.time.incident_discovery = datetime.strptime("2012-05-10", "%Y-%m-%d") breach.time.restoration_achieved = datetime.strptime("2012-08-10", "%Y-%m-%d") breach.time.incident_reported = datetime.strptime("2012-12-10", "%Y-%m-%d") # add the impact #impact = ImpactAssessment() #impact.add_effect("Unintended Access") #breach.impact_assessment = impact affected_asset = AffectedAsset() affected_asset.description = "Database server at hr-data1.example.com" affected_asset.type_ = asset breach.affected_assets = affected_asset #print("asset type: %s"%(breach.affected_assets[0].type_)) # add the victim breach.add_victim (hashPkg) # add the impact impact = ImpactAssessment() impact.add_effect(effect) breach.impact_assessment = impact stix_package.add_incident(breach) #print("hey, I've got an incident! list size=%s"%(len(stix_package._incidents))) # Print the XML! #print(stix_package.to_xml()) return stix_package
def init_stix(self): stix_package = STIXPackage() stix_header = STIXHeader() info_source = InformationSource() info_source.description = 'HAR file analysis of visit to malicious URL' stix_header.information_source = info_source stix_package.stix_header = stix_header return stix_package
def init_stix(self): stix_package = STIXPackage() stix_header = STIXHeader() info_source = InformationSource() info_source.description = 'HAR file analysis of visit to malicious URL' stix_header.information_source = info_source stix_package.stix_header = stix_header return stix_package
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 __init__(self, description='unknown', *args, **kwargs): self._description = description stix_package = STIXPackage() stix_header = STIXHeader() stix_header.description = self._description stix_package.stix_header = stix_header self._handle = stix_package
def main(): # Create a CybOX File Object with a contained hash f = File() f.add_hash("4EC0027BEF4D7E1786A04D021FA8A67F") # Create an Indicator with the File Hash Object created above. indicator = Indicator() indicator.title = "File Hash Example" indicator.description = ( "An indicator containing a File observable with an associated hash") indicator.set_producer_identity("The MITRE Corporation") indicator.set_produced_time(utils.dates.now()) # Add The File Object to the Indicator. This will promote the CybOX Object # to a CybOX Observable internally. indicator.add_object(f) # Build our STIX CIQ Identity object party_name = stix_ciq.PartyName(name_lines=("Foo", "Bar"), person_names=("John Smith", "Jill Smith"), organisation_names=("Foo Inc.", "Bar Corp.")) ident_spec = stix_ciq.STIXCIQIdentity3_0(party_name=party_name) ident_spec.add_electronic_address_identifier("*****@*****.**") ident_spec.add_free_text_line("Demonstrating Free Text!") ident_spec.add_contact_number("555-555-5555") ident_spec.add_contact_number("555-555-5556") # Build and add a CIQ Address addr = stix_ciq.Address(free_text_address='1234 Example Lane.', country='USA', administrative_area='An Admin Area') ident_spec.add_address(addr) identity = stix_ciq.CIQIdentity3_0Instance(specification=ident_spec) # Set the Indicator producer identity to our CIQ Identity indicator.set_producer_identity(identity) # Build our STIX Package stix_package = STIXPackage() # Build a STIX Header and add a description stix_header = STIXHeader() stix_header.description = "STIX CIQ Identity Extension Example" # Set the STIX Header on our STIX Package stix_package.stix_header = stix_header # Add our Indicator object. The add() method will inspect the input and # append it to the `stix_package.indicators` collection. stix_package.add(indicator) # Print the XML! print(stix_package.to_xml()) # Print a dictionary! pprint(stix_package.to_dict())
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 __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 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_stix(iocs): """ Export the tagged items in STIX format. BROKE! """ observables_doc = None stix_package = STIXPackage() stix_header = STIXHeader() stix_header.description = filename stix_package.stix_header = stix_header for ioc in iocs['md5']: observable = cybox_helper.create_file_hash_observable('', value) observables.append(observable) stix_package.add_observable(observable) indicators.append(value) if t == 'ipv4': if not value in indicators: observable = cybox_helper.create_ipv4_observable(value) observables.append(observable) stix_package.add_observable(observable) indicators.append(value) elif t == 'domain': if not value in indicators: observable = cybox_helper.create_domain_name_observable(value) observables.append(observable) stix_package.add_observable(observable) indicators.append(value) elif t == 'url': if not value in indicators: observable = cybox_helper.create_url_observable(value) observables.append(observable) stix_package.add_observable(observable) indicators.append(value) elif t == 'email': if not value in indicators: observable = cybox_helper.create_email_address_observable(value) observables.append(observable) stix_package.add_observable(observable) indicators.append(value) if len(observables) > 0: if not filename.endswith('.xml'): filename = "%s.xml" % filename #add .xml extension if missing # end if with open(filename, "wb") as f: stix_xml = stix_package.to_xml() f.write(stix_xml)
def build_stix( input_dict ): # setup stix document stix_package = STIXPackage() stix_header = STIXHeader() stix_header.description = "Incident report for " + input_dict['organization'] stix_header.add_package_intent ("Incident") # Add handling requirements if needed if input_dict['sensitive'] == "True": mark = SimpleMarkingStructure() mark.statement = "Sensitive" mark_spec = MarkingSpecification() mark_spec.marking_structures.append(mark) stix_header.handling = Marking(mark_spec) stix_package.stix_header = stix_header # add incident and confidence incident = Incident() incident.description = input_dict['description'] incident.confidence = input_dict['confidence'] # add incident reporter incident.reporter = InformationSource() incident.reporter.description = "Person who reported the incident" incident.reporter.time = Time() incident.reporter.time.produced_time = datetime.strptime(input_dict['timestamp'], "%Y-%m-%d") # when they submitted it incident.reporter.identity = Identity() incident.reporter.identity.name = input_dict['submitter'] # incident time is a complex object with support for a bunch of different "when stuff happened" items incident.time = incidentTime() incident.title = "Breach of " + input_dict['organization'] incident.time.incident_discovery = datetime.strptime(input_dict['timestamp'], "%Y-%m-%d") # when they submitted it # add the impact impact = ImpactAssessment() impact.add_effect(input_dict['damage']) incident.impact_assessment = impact #Add the thing that was stolen jewels = AffectedAsset() jewels.type_ = input_dict['asset'] incident.add_affected_asset (jewels) # add the victim incident.add_victim (input_dict['organization']) stix_package.add_incident(incident) return stix_package
def buildSTIX(ident,confid,restconfid, effect, resteffect,typeIncident,resttype,asset,restasset,hashPkg): # IMPLEMENTATION WORKAROUND - # restConfid --> header.description # resteffect --> breach.description # resttype --> reporter.description # restasset --> reporter.identity.name # setup stix document stix_package = STIXPackage() stix_header = STIXHeader() stix_header.description = restconfid # "Example description" stix_package.stix_header = stix_header # add incident and confidence breach = Incident(id_=ident) breach.description = resteffect # "Intrusion into enterprise network" breach.confidence = Confidence() breach.confidence.value=confid print("confidence set to %s"%(str(breach.confidence.value))) breach._binding_class.xml_type = typeIncident print("incident set to %s"%(str(breach._binding_class.xml_type))) # stamp with reporter breach.reporter = InformationSource() breach.reporter.description = resttype #"The person who reported it" breach.reporter.time = Time() breach.reporter.time.produced_time = datetime.strptime("2014-03-11","%Y-%m-%d") # when they submitted it breach.reporter.identity = Identity() breach.reporter.identity.name = restasset # set incident-specific timestamps breach.time = incidentTime() breach.title = "Breach of Company Dynamics" breach.time.initial_compromise = datetime.strptime("2012-01-30", "%Y-%m-%d") breach.time.incident_discovery = datetime.strptime("2012-05-10", "%Y-%m-%d") breach.time.restoration_achieved = datetime.strptime("2012-08-10", "%Y-%m-%d") breach.time.incident_reported = datetime.strptime("2012-12-10", "%Y-%m-%d") affected_asset = AffectedAsset() affected_asset.description = "Database server at hr-data1.example.com" affected_asset.type_ = asset breach.affected_assets = affected_asset # add the victim breach.add_victim (hashPkg) # add the impact impact = ImpactAssessment() impact.add_effect(effect) breach.impact_assessment = impact stix_package.add_incident(breach) return stix_package
def main(): stix_package = STIXPackage() stix_header = STIXHeader() # Add tool information stix_header.information_source = InformationSource() stix_header.information_source.tools = ToolInformationList() stix_header.information_source.tools.append(ToolInformation("python-stix ex_04.py", "The MITRE Corporation")) stix_header.description = "Example " stix_package.stix_header = stix_header print(stix_package.to_xml()) print(stix_package.to_dict())
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 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
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 test_utf16_roundtrip(self): sh = STIXHeader() sh.title = UNICODE_STR sp = STIXPackage() sp.stix_header = sh # serialize as utf-16 xml16 = sp.to_xml(encoding='utf-16') # deserialize as utf-16 sp2 = STIXPackage.from_xml(StringIO(xml16), encoding='utf-16') sh2 = sp2.stix_header # check that the titles align self.assertEqual(sh.title, sh2.title)
def main(): shv = Hash() shv.simple_hash_value = "4EC0027BEF4D7E1786A04D021FA8A67F" f = File() h = Hash(shv, Hash.TYPE_MD5) f.add_hash(h) stix_package = STIXPackage() stix_header = STIXHeader() stix_header.description = "Example 03" stix_package.stix_header = stix_header stix_package.add_observable(f) print(stix_package.to_xml())
def test_utf16_roundtrip(self): sh = STIXHeader() sh.title = UNICODE_STR sp = STIXPackage() sp.stix_header = sh # serialize as utf-16 xml16 = sp.to_xml(encoding="utf-16") # deserialize as utf-16 sp2 = STIXPackage.from_xml(StringIO(xml16), encoding="utf-16") sh2 = sp2.stix_header # check that the titles align self.assertEqual(sh.title, sh2.title)
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
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
def main(): shv = Hash() shv.simple_hash_value = "4EC0027BEF4D7E1786A04D021FA8A67F" f = File() h = Hash(shv, Hash.TYPE_MD5) f.add_hash(h) stix_package = STIXPackage() stix_header = STIXHeader() stix_header.description = "Example 03" stix_package.stix_header = stix_header stix_package.add_observable(f) 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 build_stix( ): # setup stix document stix_package = STIXPackage() stix_header = STIXHeader() stix_header.description = "Sample breach report" stix_header.add_package_intent ("Incident") stix_package.stix_header = stix_header # add incident and confidence breach = Incident() breach.description = "Intrusion into enterprise network" breach.confidence = "High" # stamp with reporter breach.reporter = InformationSource() breach.reporter.description = "The person who reported it" breach.reporter.time = Time() breach.reporter.time.produced_time = datetime.strptime("2014-03-11","%Y-%m-%d") # when they submitted it breach.reporter.identity = Identity() breach.reporter.identity.name = "Sample Investigations, LLC" # set incident-specific timestamps breach.time = incidentTime() breach.title = "Breach of Cyber Tech Dynamics" breach.time.initial_compromise = datetime.strptime("2012-01-30", "%Y-%m-%d") breach.time.incident_discovery = datetime.strptime("2012-05-10", "%Y-%m-%d") breach.time.restoration_achieved = datetime.strptime("2012-08-10", "%Y-%m-%d") breach.time.incident_reported = datetime.strptime("2012-12-10", "%Y-%m-%d") # add the impact impact = ImpactAssessment() impact.add_effect("Unintended Access") breach.impact_assessment = impact # add the victim breach.add_victim ("Cyber Tech Dynamics") stix_package.add_incident(breach) return stix_package
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