def to_cybox(self, exclude=None): """ Convert an email to a CybOX Observables. Pass parameter exclude to specify fields that should not be included in the returned object. Returns a tuple of (CybOX object, releasability list). To get the cybox object as xml or json, call to_xml() or to_json(), respectively, on the resulting CybOX object. """ if exclude == None: exclude = [] observables = [] obj = EmailMessage() # Assume there is going to be at least one header obj.header = EmailHeader() if 'message_id' not in exclude: obj.header.message_id = String(self.message_id) if 'subject' not in exclude: obj.header.subject = String(self.subject) if 'sender' not in exclude: obj.header.sender = Address(self.reply_to, Address.CAT_EMAIL) if 'reply_to' not in exclude: obj.header.reply_to = Address(self.reply_to, Address.CAT_EMAIL) if 'x_originating_ip' not in exclude: obj.header.x_originating_ip = Address(self.x_originating_ip, Address.CAT_IPV4) if 'raw_body' not in exclude: obj.raw_body = self.raw_body if 'raw_header' not in exclude: obj.raw_header = self.raw_header #copy fields where the names differ between objects if 'helo' not in exclude and 'email_server' not in exclude: obj.email_server = String(self.helo) if ('from_' not in exclude and 'from' not in exclude and 'from_address' not in exclude): obj.header.from_ = EmailAddress(self.from_address) if 'date' not in exclude and 'isodate' not in exclude: obj.header.date = DateTime(self.isodate) observables.append(Observable(obj)) return (observables, self.releasability)
def __create_dns_query_object(self, domain, record_type, nameserver=None): """Creates a CybOX DNSQueryType Object""" question = DNSQuestion() question.qname = self.__create_domain_name_object(domain) question.qtype = String(record_type) question.qclass = String('IN') query = DNSQuery() query.successful = False query.question = question return query
def test_pattern_multiple_all(self): s = String(["foo", "bar", "baz"]) s.condition = "Equals" s.apply_condition = "ALL" # If we change @apply_condition from the default, it should match # that value. self.assertTrue(b'apply_condition="ALL"' in s.to_xml())
def test_unicode_string(self): s = u("A Unicode \ufffd string") string = String(s) unicode_string = six.text_type(string) self.assertEqual(s, unicode_string) self.assertEqual(s.encode("utf-8"), unicode_string.encode("utf-8")) self.assertTrue(s.encode("utf-8") in string.to_xml())
def __parse_email_message(self, msg): """ Parses the supplied message Returns a map of message parts expressed as cybox objects. Keys: 'message', 'files', 'urls' """ files = [] url_list = [] domain_list = [] message = EmailMessage() # Headers are required (for now) message.header = self.__create_cybox_headers(msg) if self.include_attachments: files = self.__create_cybox_files(msg) message.attachments = Attachments() for f in files: message.attachments.append(f.parent.id_) f.add_related(message, "Contained_Within", inline=False) if self.include_raw_headers: raw_headers_str = self.__get_raw_headers(msg).strip() if raw_headers_str: message.raw_header = String(raw_headers_str) # need this for parsing urls AND raw body text raw_body = "\n".join(self.__get_raw_body_text(msg)).strip() if self.include_raw_body and raw_body: message.raw_body = String(raw_body) if self.include_urls: (url_list, domain_list) = self.__parse_urls(raw_body) if url_list: links = Links() for u in url_list: links.append(LinkReference(u.parent.id_)) if links: message.links = links # Return a list of all objects we've built return [message] + files + url_list + domain_list
def cybox_object_http(obj): http_session = HTTPSession() hh = HTTPRequestResponse() hc = HTTPClientRequest() if obj.client_request.message_body: hm = HTTPMessage() hm.lenght = len(obj.client_request.message_body) hm.message_body = String(obj.client_request.message_body) hc.http_message_body = hm rh = HTTPRequestHeader() if obj.client_request.raw_header: rh.raw_header = String(obj.client_request.raw_header) hhf = HTTPRequestHeaderFields() hhf.user_agent = String(obj.client_request.user_agent) host_field = HostField() host_field.domain_name = URI(value=obj.client_request.domain_name) port = Port() port.port_value = PositiveInteger(obj.client_request.port.port) host_field.port = port hhf.host = host_field rh.parsed_header = hhf hc.http_request_header = rh hl = HTTPRequestLine() hl.http_method = String(obj.client_request.request_method) hl.version = String(obj.client_request.request_version) hl.value = String(obj.client_request.request_uri) hc.http_request_line = hl hh.http_client_request = hc http_session.http_request_response = [hh] return http_session
def __create_dns_record_object(self, domain, record_type, nameserver=None): """Creates a CybOX DNSRecordType Object""" record = self.__get_dns_record(domain, record_type, nameserver) if not record: return None dns_record = DNSRecord() dns_record.domain_name = self.__create_domain_name_object(record.get('Domain_Name')) dns_record.ip_address = self.__create_ip_address_object(record.get('IP_Address')) dns_record.entry_type = String(record.get('Entry_Type')) dns_record.flags = HexBinary(record.get('Flags')) dns_record.record_data = record.get('Record_Data') return dns_record
def test_subject_TypedField(self): h = EmailHeader() # Set using actual object h.subject = String("Howdy") self.assertEqual(String, type(h.subject)) # Set using implied cast h.subject = "Howdy" self.assertEqual(String, type(h.subject)) s = "http://badsubject.com" bad_object = URI(s) self.assertRaises(ValueError, setattr, h, 'subject', bad_object)
def test_observable_init(self): # Can pass an Object into the Observable constructor o = Object() obs = Observable(o) # Can pass an Event into the Observable constructor e = Event() obs = Observable(e) # Can pass an ObservableComposition into the Observable constructor oc = ObservableComposition() obs = Observable(oc) # Can pass an ObjectProperties subclass into the Observable constructor a = Address() obs = Observable(a) # Cannot pass a String into the Observable constructor. s = String() self.assertRaises(TypeError, Observable, s)
def __create_cybox_headers(self, msg): """ Returns a CybOX EmailHeaderType object """ if self.__verbose_output: sys.stderr.write("** parsing headers\n") headers = EmailHeader() if 'received' in self.headers: headers.received_lines = self._parse_received_headers(msg) if 'to' in self.headers: headers.to = _get_email_recipients(msg['to']) if 'cc' in self.headers: headers.cc = _get_email_recipients(msg['cc']) if 'bcc' in self.headers: headers.bcc = _get_email_recipients(msg['bcc']) if 'from' in self.headers: headers.from_ = _get_single_email_address(msg['from']) if 'sender' in self.headers: headers.sender = _get_single_email_address(msg['sender']) if 'reply-to' in self.headers: headers.reply_to = _get_single_email_address(msg['reply-to']) if 'subject' in self.headers: headers.subject = String(msg['subject']) if 'in-reply-to' in self.headers: headers.in_reply_to = String(msg['in-reply-to']) if 'errors-to' in self.headers: headers.errors_to = String(msg['errors-to']) if 'date' in self.headers: headers.date = DateTime(msg['date']) if 'message-id' in self.headers: headers.message_id = String(msg['message-id']) if 'boundary' in self.headers: headers.boundary = String(msg['boundary']) if 'content-type' in self.headers: headers.content_type = String(msg['content-type']) if 'mime-version' in self.headers: headers.mime_version = String(msg['mime-version']) if 'precedence' in self.headers: headers.precedence = String(msg['precedence']) if 'user-agent' in self.headers: headers.user_agent = String(msg['user-agent']) if 'x-mailer' in self.headers: headers.x_mailer = String(msg['x-mailer']) if 'x-originating-ip' in self.headers: headers.x_originating_ip = Address(msg['x-originating-ip'], Address.CAT_IPV4) if 'x-priority' in self.headers: headers.x_priority = String(msg['x-priority']) return headers
def __create_cybox_headers(self, msg): """ Returns a CybOX EmailHeaderType object """ if self.__verbose_output: sys.stderr.write("** parsing headers\n") headers = EmailHeader() if 'received' in self.headers: lines = self._parse_received_headers(msg) if lines: headers.received_lines = lines if 'to' in self.headers: headers.to = _get_email_recipients(msg['to']) if msg['delivered-to'] and not headers.to: headers.to = _get_email_recipients(msg['delivered-to']) if 'cc' in self.headers: headers.cc = _get_email_recipients(msg['cc']) if 'bcc' in self.headers: headers.bcc = _get_email_recipients(msg['bcc']) if 'from' in self.headers: headers.from_ = _get_single_email_address(msg['from']) if 'sender' in self.headers: headers.sender = _get_single_email_address(msg['sender']) if 'reply-to' in self.headers: headers.reply_to = _get_single_email_address(msg['reply-to']) if 'subject' in self.headers and 'subject' in msg: headers.subject = String(msg['subject']) if 'in-reply-to' in self.headers and 'in-reply-to' in msg: headers.in_reply_to = String(msg['in-reply-to']) if 'errors-to' in self.headers and 'errors-to' in msg: headers.errors_to = String(msg['errors-to']) if 'date' in self.headers and 'date' in msg: headers.date = DateTime(msg['date']) if 'message-id' in self.headers and 'message-id' in msg: headers.message_id = String(msg['message-id']) if 'boundary' in self.headers and 'boundary' in msg: headers.boundary = String(msg['boundary']) if 'content-type' in self.headers and 'content-type' in msg: headers.content_type = String(msg['content-type']) if 'mime-version' in self.headers and 'mime-version' in msg: headers.mime_version = String(msg['mime-version']) if 'precedence' in self.headers and 'precedence' in msg: headers.precedence = String(msg['precedence']) if 'user-agent' in self.headers and 'user-agent' in msg: headers.user_agent = String(msg['user-agent']) if 'x-mailer' in self.headers and 'x-mailer' in msg: headers.x_mailer = String(msg['x-mailer']) if 'x-originating-ip' in self.headers and msg['x-originating-ip']: headers.x_originating_ip = Address(msg['x-originating-ip'], Address.CAT_IPV4) if 'x-priority' in self.headers and 'x-priority' in msg: #Must be a digit - pull one out of anything that could be a string such as 3 (Normal) import re priority = '' for p in re.findall(r'\d+',msg['x-priority']): if p.isdigit(): priority = p if priority: headers.x_priority = String(priority) return headers
def test_unicode_string(self): s = "A Unicode \ufffd string" string = String(s) self.assertEqual(s, str(string)) self.assertEqual(s.encode("utf-8"), str(string))
def test_coerce_to_string(self): val = "abc1234" s = String(val) self.assertEqual(val, s.value) self.assertEqual(val, six.text_type(s))
def to_cybox_observable(obj, exclude=None, bin_fmt="raw"): """ Convert a CRITs TLO to a CybOX Observable. :param obj: The TLO to convert. :type obj: :class:`crits.core.crits_mongoengine.CRITsBaseAttributes` :param exclude: Attributes to exclude. :type exclude: list :param bin_fmt: The format for the binary (if applicable). :type bin_fmt: str """ type_ = obj._meta['crits_type'] if type_ == 'Certificate': custom_prop = Property( ) # make a custom property so CRITs import can identify Certificate exports custom_prop.name = "crits_type" custom_prop.description = "Indicates the CRITs type of the object this CybOX object represents" custom_prop._value = "Certificate" obje = File() # represent cert information as file obje.md5 = obj.md5 obje.file_name = obj.filename obje.file_format = obj.filetype obje.size_in_bytes = obj.size obje.custom_properties = CustomProperties() obje.custom_properties.append(custom_prop) obs = Observable(obje) obs.description = obj.description data = obj.filedata.read() if data: # if cert data available a = Artifact(data, Artifact.TYPE_FILE) # create artifact w/data a.packaging.append(Base64Encoding()) obje.add_related(a, "Child_Of") # relate artifact to file return ([obs], obj.releasability) elif type_ == 'Domain': obje = DomainName() obje.value = obj.domain obje.type_ = obj.record_type return ([Observable(obje)], obj.releasability) elif type_ == 'Email': if exclude == None: exclude = [] observables = [] obje = EmailMessage() # Assume there is going to be at least one header obje.header = EmailHeader() if 'message_id' not in exclude: obje.header.message_id = String(obj.message_id) if 'subject' not in exclude: obje.header.subject = String(obj.subject) if 'sender' not in exclude: obje.header.sender = Address(obj.sender, Address.CAT_EMAIL) if 'reply_to' not in exclude: obje.header.reply_to = Address(obj.reply_to, Address.CAT_EMAIL) if 'x_originating_ip' not in exclude: obje.header.x_originating_ip = Address(obj.x_originating_ip, Address.CAT_IPV4) if 'x_mailer' not in exclude: obje.header.x_mailer = String(obj.x_mailer) if 'boundary' not in exclude: obje.header.boundary = String(obj.boundary) if 'raw_body' not in exclude: obje.raw_body = obj.raw_body if 'raw_header' not in exclude: obje.raw_header = obj.raw_header #copy fields where the names differ between objects if 'helo' not in exclude and 'email_server' not in exclude: obje.email_server = String(obj.helo) if ('from_' not in exclude and 'from' not in exclude and 'from_address' not in exclude): obje.header.from_ = EmailAddress(obj.from_address) if 'date' not in exclude and 'isodate' not in exclude: obje.header.date = DateTime(obj.isodate) obje.attachments = Attachments() observables.append(Observable(obje)) return (observables, obj.releasability) elif type_ == 'Indicator': observables = [] obje = make_cybox_object(obj.ind_type, obj.value) observables.append(Observable(obje)) return (observables, obj.releasability) elif type_ == 'IP': obje = Address() obje.address_value = obj.ip if obj.ip_type == IPTypes.IPv4_ADDRESS: obje.category = "ipv4-addr" elif obj.ip_type == IPTypes.IPv6_ADDRESS: obje.category = "ipv6-addr" elif obj.ip_type == IPTypes.IPv4_SUBNET: obje.category = "ipv4-net" elif obj.ip_type == IPTypes.IPv6_SUBNET: obje.category = "ipv6-subnet" return ([Observable(obje)], obj.releasability) elif type_ == 'PCAP': obje = File() obje.md5 = obj.md5 obje.file_name = obj.filename obje.file_format = obj.contentType obje.size_in_bytes = obj.length obs = Observable(obje) obs.description = obj.description art = Artifact(obj.filedata.read(), Artifact.TYPE_NETWORK) art.packaging.append(Base64Encoding()) obje.add_related(art, "Child_Of") # relate artifact to file return ([obs], obj.releasability) elif type_ == 'RawData': obje = Artifact(obj.data.encode('utf-8'), Artifact.TYPE_FILE) obje.packaging.append(Base64Encoding()) obs = Observable(obje) obs.description = obj.description return ([obs], obj.releasability) elif type_ == 'Sample': if exclude == None: exclude = [] observables = [] f = File() for attr in ['md5', 'sha1', 'sha256']: if attr not in exclude: val = getattr(obj, attr, None) if val: setattr(f, attr, val) if obj.ssdeep and 'ssdeep' not in exclude: f.add_hash(Hash(obj.ssdeep, Hash.TYPE_SSDEEP)) if 'size' not in exclude and 'size_in_bytes' not in exclude: f.size_in_bytes = UnsignedLong(obj.size) if 'filename' not in exclude and 'file_name' not in exclude: f.file_name = obj.filename # create an Artifact object for the binary if it exists if 'filedata' not in exclude and bin_fmt: data = obj.filedata.read() if data: # if sample data available a = Artifact(data, Artifact.TYPE_FILE) # create artifact w/data if bin_fmt == "zlib": a.packaging.append(ZlibCompression()) a.packaging.append(Base64Encoding()) elif bin_fmt == "base64": a.packaging.append(Base64Encoding()) f.add_related(a, "Child_Of") # relate artifact to file if 'filetype' not in exclude and 'file_format' not in exclude: #NOTE: this doesn't work because the CybOX File object does not # have any support built in for setting the filetype to a # CybOX-binding friendly object (e.g., calling .to_dict() on # the resulting CybOX object fails on this field. f.file_format = obj.filetype observables.append(Observable(f)) return (observables, obj.releasability) else: return (None, None)
from cybox.objects.win_executable_file_object import PEHeaders from cybox.objects.win_executable_file_object import PEImport from cybox.objects.win_executable_file_object import PEImportList from cybox.objects.win_executable_file_object import PEImportedFunction from cybox.objects.win_executable_file_object import PEImportedFunctions from cybox.objects.win_executable_file_object import PEResourceList from cybox.objects.win_executable_file_object import PESectionList from cybox.objects.win_executable_file_object import DOSHeader from cybox.objects.win_executable_file_object import Entropy from cybox.objects.win_executable_file_object import PEFileHeader from cybox.objects.win_executable_file_object import HashList from cybox.objects.win_executable_file_object import PEOptionalHeader # https://cybox.readthedocs.org/en/stable/_modules/cybox/objects/win_executable_file_object.html#PEBuildInformation build_information = PEBuildInformation() build_information.compiler_name = String('') build_information.compiler_version = String('') build_information.linker_name = String('') build_information.linker_version = String('') # https://cybox.readthedocs.org/en/stable/_modules/cybox/common/digitalsignature.html#DigitalSignature digital_signature = DigitalSignature() digital_signature.certificate_issuer = String('') digital_signature.certificate_subject = String('') digital_signature.signature_description = String('') digital_signature.signature_exists = None digital_signature.signature_verified = None # https://cybox.readthedocs.org/en/stable/_modules/cybox/objects/win_executable_file_object.html#PEExports exports = PEExports() exports.exported_functions = PEExportedFunctions()
def test_string(self): s = String("test_string") self.assertEqual(s.datatype, "string") self.assertEqual(s.value, "test_string")
def test_pattern_multiple(self): s = String(["foo", "bar", "baz"]) s.condition = "Equals" # @apply_condition should be set when there is a @condition and the # value is a list. self.assertTrue(b'apply_condition="ANY"' in s.to_xml())
def test_pattern_single(self): s = String("foo") s.condition = "Equals" # @apply_condition should not be set if the value is not a list. self.assertFalse(b'apply_condition' in s.to_xml())
def test_instance_multiple_all(self): s = String(["foo", "bar", "baz"]) s.apply_condition = "ALL" # Even though we set it, this is not a pattern so @apply_condition # shouldn't be output. self.assertFalse(b'apply_condition' in s.to_xml())
def test_instance_multiple(self): s = String(["foo", "bar", "baz"]) # @apply_condition should not be set on instances. self.assertFalse(b'apply_condition' in s.to_xml())
def test_instance_single(self): s = String("foo") # @apply_condition should not be set on instances. self.assertFalse(b'apply_condition' in s.to_xml())
def __create_whois_object(self, domain): """ Creates a CybOX WHOISObjectType object """ if not domain: return None if(self.__verbose_output): sys.stderr.write("** creating Whois object for: %s\n" % domain) if self.http_whois: record = self.__get_whois_record_http(domain) else: record = self.__get_whois_record(domain) if not record: return None whois = WhoisEntry() record['status'] = ['OK' if status == 'ACTIVE' else status for status in record['status']] #Only build registrar info objects if we have the relevant info if (record['registrar'] or record['whois_server'] or record['registrar_address'] or record['referral_url'] or record['registrar_contacts']): registrar = WhoisRegistrar() registrar.name = String(record.get('registrar')) registrar.address = String(record.get('registrar_address')) registrar.whois_server = URI(record.get('whois_server')) registrar.referral_url = URI(record.get('referral_url')) contacts = WhoisContacts() for email in record['registrar_contacts']: contact = WhoisContact() contact.contact_type = 'ADMIN' contact.name = String(record.get('registrar')) contact.email_address = EmailAddress(email) contacts.append(contact) registrar.contacts = contacts whois.registrar_info = registrar whois.domain_name = self.__create_domain_name_object(record.get('domain_name')) nservers = WhoisNameservers() for url in record.get('name_servers', []): nservers.append(self.__create_url_object(url)) if nservers: whois.nameservers = nservers status = WhoisStatuses() for s in record.get('status', []): status.append(WhoisStatus(s)) if status: whois.status = status whois.updated_date = DateTime(record.get('updated_date')) whois.creation_date = DateTime(record.get('creation_date')) whois.expiration_date = DateTime(record.get('expiration_date')) return whois
def make_cybox_object(type_, value=None): """ Converts type_, name, and value to a CybOX object instance. :param type_: The object type. :type type_: str :param value: The object value. :type value: str :returns: CybOX object """ if type_ == IndicatorTypes.USER_ID: acct = Account() acct.description = value return acct elif type_ in IPTypes.values(): if type_ == IPTypes.IPV4_ADDRESS: name = 'ipv4-addr' elif type_ == IPTypes.IPV6_ADDRESS: name = 'ipv6-addr' elif type_ == IPTypes.IPV4_SUBNET: name = 'ipv4-net' elif type_ == IPTypes.IPV6_SUBNET: name = 'ipv6-net' return Address(category=name, address_value=value) elif type_ == IndicatorTypes.API_KEY: api = API() api.description = value return api elif type_ == IndicatorTypes.DOMAIN: obj = DomainName() obj.value = value elif type_ == IndicatorTypes.USER_AGENT: obj = HTTPRequestHeaderFields() obj.user_agent = value return obj elif type_ == IndicatorTypes.MUTEX: m = Mutex() m.named = True m.name = String(value) return m elif type_ in (IndicatorTypes.SOURCE_PORT, IndicatorTypes.DEST_PORT): p = Port() try: p.port_value = PositiveInteger(value) except ValueError: # XXX: Raise a better exception... raise UnsupportedCybOXObjectTypeError(type_, name) return p elif type_ == IndicatorTypes.PROCESS_NAME: p = Process() p.name = String(value) return p elif type_ == IndicatorTypes.URI: r = URI() r.type_ = 'URL' r.value = value return r elif type_ in (IndicatorTypes.REGISTRY_KEY, IndicatorTypes.REG_KEY_CREATED, IndicatorTypes.REG_KEY_DELETED, IndicatorTypes.REG_KEY_ENUMERATED, IndicatorTypes.REG_KEY_MONITORED, IndicatorTypes.REG_KEY_OPENED): obj = WinRegistryKey() obj.key = value return obj """ The following are types that are listed in the 'Indicator Type' box of the 'New Indicator' dialog in CRITs. These types, unlike those handled above, cannot be written to or read from CybOX at this point. The reason for the type being omitted is written as a comment inline. This can (and should) be revisited as new versions of CybOX are released. NOTE: You will have to update the corresponding make_crits_object function with handling for the reverse direction. In the mean time, these types will raise unsupported errors. """ #elif type_ == "Device": # No CybOX API #elif type_ == "DNS Cache": # No CybOX API #elif type_ == "GUI": # revisit when CRITs supports width & height specification #elif type_ == "HTTP Session": # No good mapping between CybOX/CRITs #elif type_ == "Linux Package": # No CybOX API #elif type_ == "Network Packet": # No good mapping between CybOX/CRITs #elif type_ == "Network Route Entry": # No CybOX API #elif type_ == "Network Route": # No CybOX API #elif type_ == "Network Subnet": # No CybOX API #elif type_ == "Semaphore": # No CybOX API #elif type_ == "Socket": # No good mapping between CybOX/CRITs #elif type_ == "UNIX File": # No CybOX API #elif type_ == "UNIX Network Route Entry": # No CybOX API #elif type_ == "UNIX Pipe": # No CybOX API #elif type_ == "UNIX Process": # No CybOX API #elif type_ == "UNIX User Account": # No CybOX API #elif type_ == "UNIX Volume": # No CybOX API #elif type_ == "User Session": # No CybOX API #elif type_ == "Whois": # No good mapping between CybOX/CRITs #elif type_ == "Win Computer Account": # No CybOX API #elif type_ == "Win Critical Section": # No CybOX API #elif type_ == "Win Executable File": # No good mapping between CybOX/CRITs #elif type_ == "Win File": # No good mapping between CybOX/CRITs #elif type_ == "Win Kernel": # No CybOX API #elif type_ == "Win Mutex": # No good mapping between CybOX/CRITs #elif type_ == "Win Network Route Entry": # No CybOX API #elif type_ == "Win Pipe": # No good mapping between CybOX/CRITs #elif type_ == "Win Prefetch": # No CybOX API #elif type_ == "Win Semaphore": # No CybOX API #elif type_ == "Win System Restore": # No CybOX API #elif type_ == "Win Thread": # No good mapping between CybOX/CRITs #elif type_ == "Win Waitable Timer": # No CybOX API raise UnsupportedCybOXObjectTypeError(type_, name)
def test_string_with_comma(self): s = String("test_string,") s2 = cybox.test.round_trip(s) self.assertEqual(s, s2)
def test_double_encode(self): s = String(UNICODE_STR) s2 = round_trip(s)
def test_list_of_strings_with_comma(self): s = String([u("string,1"), u("string,1"), u("string,3")]) s2 = cybox.test.round_trip(s) self.assertEqual(s, s2)
def test_delimiter(self): s = String(["string1", "string2"]) s.delimiter = "##delim##" self.assertTrue(b"##comma##" not in s.to_xml()) self.assertTrue(b"string1##delim##string2" in s.to_xml())
def make_cybox_object(type_, name=None, value=None): """ Converts type_, name, and value to a CybOX object instance. :param type_: The object type. :type type_: str :param name: The object name. :type name: str :param value: The object value. :type value: str :returns: CybOX object """ if type_ == "Account": acct = Account() acct.description = value return acct elif type_ == "Address": return Address(category=name, address_value=value) elif type_ == "Email Message": e = EmailMessage() e.raw_body = value return e elif type_ == "API": api = API() api.description = value return api elif type_ == "Artifact": if name == "Data Region": atype = Artifact.TYPE_GENERIC elif name == 'FileSystem Fragment': atype = Artifact.TYPE_FILE_SYSTEM elif name == 'Memory Region': atype = Artifact.TYPE_MEMORY else: raise UnsupportedCybOXObjectTypeError(type_, name) return Artifact(value, atype) elif type_ == "Code": obj = Code() obj.code_segment = value obj.type = name return obj elif type_ == "Disk": disk = Disk() disk.disk_name = type_ disk.type = name return disk elif type_ == "Disk Partition": disk = DiskPartition() disk.device_name = type_ disk.type = name return disk elif type_ == "DNS Query": r = URI() r.value = value dq = DNSQuestion() dq.qname = r d = DNSQuery() d.question = dq return d elif type_ == "DNS Record": # DNS Record indicators in CRITs are just a free form text box, there # is no good way to map them into the attributes of a DNSRecord cybox # object. So just stuff it in the description until someone tells me # otherwise. d = StructuredText(value=value) dr = DNSRecord() dr.description = d return dr elif type_ == "GUI Dialogbox": obj = GUIDialogbox() obj.box_text = value return obj elif type_ == "GUI Window": obj = GUIWindow() obj.window_display_name = value return obj elif type_ == "HTTP Request Header Fields" and name and name == "User-Agent": # TODO/NOTE: HTTPRequestHeaderFields has a ton of fields for info. # we should revisit this as UI is reworked or CybOX is improved. obj = HTTPRequestHeaderFields() obj.user_agent = value return obj elif type_ == "Library": obj = Library() obj.name = value obj.type = name return obj elif type_ == "Memory": obj = Memory() obj.memory_source = value return obj elif type_ == "Mutex": m = Mutex() m.named = True m.name = String(value) return m elif type_ == "Network Connection": obj = NetworkConnection() obj.layer7_protocol = value return obj elif type_ == "Pipe": p = Pipe() p.named = True p.name = String(value) return p elif type_ == "Port": p = Port() try: p.port_value = PositiveInteger(value) except ValueError: # XXX: Raise a better exception... raise UnsupportedCybOXObjectTypeError(type_, name) return p elif type_ == "Process": p = Process() p.name = String(value) return p elif type_ == "String": c = Custom() c.custom_name = "crits:String" c.description = ("This is a generic string used as the value of an " "Indicator or Object within CRITs.") c.custom_properties = CustomProperties() p1 = Property() p1.name = "value" p1.description = "Generic String" p1.value = value c.custom_properties.append(p1) return c elif type_ == "System": s = System() s.hostname = String(value) return s elif type_ == "URI": r = URI() r.type_ = name r.value = value return r elif type_ == "User Account": obj = UserAccount() obj.username = value return obj elif type_ == "Volume": obj = Volume() obj.name = value return obj elif type_ == "Win Driver": w = WinDriver() w.driver_name = String(value) return w elif type_ == "Win Event Log": obj = WinEventLog() obj.log = value return obj elif type_ == "Win Event": w = WinEvent() w.name = String(value) return w elif type_ == "Win Handle": obj = WinHandle() obj.type_ = name obj.object_address = value return obj elif type_ == "Win Kernel Hook": obj = WinKernelHook() obj.description = value return obj elif type_ == "Win Mailslot": obj = WinMailslot() obj.name = value return obj elif type_ == "Win Network Share": obj = WinNetworkShare() obj.local_path = value return obj elif type_ == "Win Process": obj = WinProcess() obj.window_title = value return obj elif type_ == "Win Registry Key": obj = WinRegistryKey() obj.key = value return obj elif type_ == "Win Service": obj = WinService() obj.service_name = value return obj elif type_ == "Win System": obj = WinSystem() obj.product_name = value return obj elif type_ == "Win Task": obj = WinTask() obj.name = value return obj elif type_ == "Win User Account": obj = WinUser() obj.security_id = value return obj elif type_ == "Win Volume": obj = WinVolume() obj.drive_letter = value return obj elif type_ == "X509 Certificate": obj = X509Certificate() obj.raw_certificate = value return obj """ The following are types that are listed in the 'Indicator Type' box of the 'New Indicator' dialog in CRITs. These types, unlike those handled above, cannot be written to or read from CybOX at this point. The reason for the type being omitted is written as a comment inline. This can (and should) be revisited as new versions of CybOX are released. NOTE: You will have to update the corresponding make_crits_object function with handling for the reverse direction. In the mean time, these types will raise unsupported errors. """ #elif type_ == "Device": # No CybOX API #elif type_ == "DNS Cache": # No CybOX API #elif type_ == "GUI": # revisit when CRITs supports width & height specification #elif type_ == "HTTP Session": # No good mapping between CybOX/CRITs #elif type_ == "Linux Package": # No CybOX API #elif type_ == "Network Packet": # No good mapping between CybOX/CRITs #elif type_ == "Network Route Entry": # No CybOX API #elif type_ == "Network Route": # No CybOX API #elif type_ == "Network Subnet": # No CybOX API #elif type_ == "Semaphore": # No CybOX API #elif type_ == "Socket": # No good mapping between CybOX/CRITs #elif type_ == "UNIX File": # No CybOX API #elif type_ == "UNIX Network Route Entry": # No CybOX API #elif type_ == "UNIX Pipe": # No CybOX API #elif type_ == "UNIX Process": # No CybOX API #elif type_ == "UNIX User Account": # No CybOX API #elif type_ == "UNIX Volume": # No CybOX API #elif type_ == "User Session": # No CybOX API #elif type_ == "Whois": # No good mapping between CybOX/CRITs #elif type_ == "Win Computer Account": # No CybOX API #elif type_ == "Win Critical Section": # No CybOX API #elif type_ == "Win Executable File": # No good mapping between CybOX/CRITs #elif type_ == "Win File": # No good mapping between CybOX/CRITs #elif type_ == "Win Kernel": # No CybOX API #elif type_ == "Win Mutex": # No good mapping between CybOX/CRITs #elif type_ == "Win Network Route Entry": # No CybOX API #elif type_ == "Win Pipe": # No good mapping between CybOX/CRITs #elif type_ == "Win Prefetch": # No CybOX API #elif type_ == "Win Semaphore": # No CybOX API #elif type_ == "Win System Restore": # No CybOX API #elif type_ == "Win Thread": # No good mapping between CybOX/CRITs #elif type_ == "Win Waitable Timer": # No CybOX API raise UnsupportedCybOXObjectTypeError(type_, name)