当前位置: 首页>>代码示例>>Python>>正文


Python STIXPackage.from_xml方法代码示例

本文整理汇总了Python中stix.core.STIXPackage.from_xml方法的典型用法代码示例。如果您正苦于以下问题:Python STIXPackage.from_xml方法的具体用法?Python STIXPackage.from_xml怎么用?Python STIXPackage.from_xml使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在stix.core.STIXPackage的用法示例。


在下文中一共展示了STIXPackage.from_xml方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: file_to_stix

# 需要导入模块: from stix.core import STIXPackage [as 别名]
# 或者: from stix.core.STIXPackage import from_xml [as 别名]
def file_to_stix(file_):
    '''transform files into stix packages'''
    try:
        stix_package = STIXPackage.from_xml(file_)
    except UnsupportedVersionError as ex:
        updated = ramrod.update(file_)
        updated_xml = updated.document.as_stringio()
        stix_package = STIXPackage.from_xml(updated_xml)
    return stix_package
开发者ID:Soltra,项目名称:cti-stats,代码行数:11,代码来源:cti.py

示例2: taxii_content_block_to_stix

# 需要导入模块: from stix.core import STIXPackage [as 别名]
# 或者: from stix.core.STIXPackage import from_xml [as 别名]
def taxii_content_block_to_stix(content_block):
    '''transform taxii content blocks into stix packages'''
    xml = StringIO(content_block.content)
    try:
        stix_package = STIXPackage.from_xml(xml)
    except UnsupportedVersionError as ex:
        updated = ramrod.update(xml)
        updated_xml = updated.document.as_stringio()
        stix_package = STIXPackage.from_xml(updated_xml)
    xml.close()
    return stix_package
开发者ID:Soltra,项目名称:cti-stats,代码行数:13,代码来源:cti.py

示例3: load_stix_package

# 需要导入模块: from stix.core import STIXPackage [as 别名]
# 或者: from stix.core.STIXPackage import from_xml [as 别名]
    def load_stix_package(self, stix_file):
        """Helper for loading and updating (if required) a STIX package."""
        try:
            package = STIXPackage.from_xml(stix_file)
        except UnsupportedVersionError:
            updated = ramrod.update(stix_file, to_='1.1.1')
            document = updated.document.as_stringio()
            try:
                package = STIXPackage.from_xml(document)
            except Exception:
                package = None
        except Exception:
            package = None

        return package
开发者ID:MISP,项目名称:cti-toolkit,代码行数:17,代码来源:base.py

示例4: build_report

# 需要导入模块: from stix.core import STIXPackage [as 别名]
# 或者: from stix.core.STIXPackage import from_xml [as 别名]
def build_report(fname):
    """ parse the provided STIX package and create a 
        CB Feed Report that includes all suitable observables
        as CB IOCs """

    # The python STIX libs are pedantic about document versions.  See
    # https://github.com/STIXProject/python-stix/issues/124
    # parser = EntityParser()
    # pkg = parser.parse_xml(fname, check_version=False)

    pkg = STIXPackage.from_xml(fname)

    iocs = {}
    if pkg.observables:
        iocs = parse_observables(pkg.observables.observables)

    if pkg.indicators:
        for indicator in pkg.indicators:
            iocs = merge(iocs, parse_observables(indicator.observables))

    ts = int(time.mktime(pkg.timestamp.timetuple())) if pkg.timestamp else int(time.mktime(time.gmtime()))
    fields = {'iocs': iocs,
              'score': 100,  # does STIX have a severity field?
              'timestamp': ts,
              'link': 'http://stix.mitre.org',
              'id': pkg.id_,
              'title': pkg.stix_header.title,
              }

    if len(iocs.keys()) == 0 or all(len(iocs[k]) == 0 for k in iocs):
        print("-> No suitable observables found in {0}; skipping.".format(fname))
        return None

    print("-> Including %s observables from {0}.".format(sum(len(iocs[k]) for k in iocs), fname))
    return CbReport(**fields)
开发者ID:carbonblack,项目名称:cbfeeds,代码行数:37,代码来源:stix_to_feed.py

示例5: main

# 需要导入模块: from stix.core import STIXPackage [as 别名]
# 或者: from stix.core.STIXPackage import from_xml [as 别名]
def main():
  stix_package = STIXPackage.from_xml('sample-incidents.xml')

  data = {
    'incidents': {
    }
  }

  ttps = {}
  for ttp in stix_package.ttps:
    ttps[ttp.id_] = ttp
    data['incidents'][ttp.title] = []

  observables = {}
  for observable in stix_package.observables.observables:
    observables[observable.id_] = observable

  for incident in stix_package.incidents:
    ip = observables[incident.related_observables[0].item.idref].object_.properties.address_value.value
    ttp = ttps[incident.leveraged_ttps[0].item.idref]
    time = incident.time.first_malicious_action.value.isoformat()

    data['incidents'][ttp.title].append({
      'ip': ip,
      'time': time
    })

  print data
开发者ID:bschmoker,项目名称:stixproject.github.io,代码行数:30,代码来源:incident-consumer.py

示例6: main

# 需要导入模块: from stix.core import STIXPackage [as 别名]
# 或者: from stix.core.STIXPackage import from_xml [as 别名]
def main():
    stix_package = STIXPackage.from_xml("file-hash-reputation.xml")

    for indicator in stix_package.indicators:
        print "Hash: " + indicator.observable.object_.properties.hashes[0].simple_hash_value.value
        print "Reputation: " + indicator.confidence.value.value
        print "TTP: " + indicator.indicated_ttps[0].item.title
开发者ID:clever-crow-consulting,项目名称:stixproject.github.io,代码行数:9,代码来源:file-hash-reputation_consumer.py

示例7: strip_observables

# 需要导入模块: from stix.core import STIXPackage [as 别名]
# 或者: from stix.core.STIXPackage import from_xml [as 别名]
def strip_observables(pkg_path):
    '''Strips observable from a package, support multiple structures'''
    result = Observables()
    pkg = STIXPackage.from_xml(pkg_path)
    processed = []
    for ind in pkg.indicators:
        if ind.composite_indicator_expression:
            """The indicator is a compsite structure, this references other indicators, which reference the observables..."""
            cyboxobject = ObservableComposition()
            cyboxobject.operator = str(ind.observable_composition_operator)
            for x in ind.composite_indicator_expression:
                """For every indicator in the composite list, get referenced indicator"""
                ref_ind = getindicator_by_id(pkg, str(x._idref))
                if ref_ind.observables:
                    for y in ref_ind.observables:
                        """For every referenced observable, get the object"""
                        ref_obs = getobservable_by_id(pkg, y._idref)
                        if ref_obs:
                            cyboxobject.add(ref_obs)
                            processed.append(ref_obs.id_)
            result.add(cyboxobject)
        if ind.observables:
            for x in ind.observables:
                if x is not None:
                    if x.id_ not in processed:
                        result.add(x)
                        processed.append(x.id_)
    if pkg.observables:
        for x in pkg.observables:
            if x is not None:
                if x.id_ not in processed:
                    result.add(x)
    scanfile = open(os.path.join(iocname,"scan.json"),'w')
    scanfile.write(json.dumps(walkobservables(result).to_dict(), indent=4))
    scanfile.close()
开发者ID:molmar,项目名称:hades_ioc_scanner,代码行数:37,代码来源:stixparser.py

示例8: main

# 需要导入模块: from stix.core import STIXPackage [as 别名]
# 或者: from stix.core.STIXPackage import from_xml [as 别名]
def main():
    stix_package = STIXPackage.from_xml('sample-combined.xml')

    data = {
        'incidents': {
        }
    }

    ttps = {}
    for ttp in stix_package.ttps:
        ttps[ttp.id_] = ttp
        data['incidents'][ttp.title] = []

    observables = {}
    for observable in stix_package.observables.observables:
        observables[observable.id_] = observable

    indicators = {}
    for indicator in stix_package.indicators:
        indicators[indicator.id_] = indicator

    for incident in stix_package.incidents:
        ip = observables[incident.related_observables[0].item.idref].object_.properties.address_value.value
        ttp = ttps[incident.leveraged_ttps[0].item.idref]
        time = incident.time.first_malicious_action.value.isoformat()
        address_value = indicators[incident.related_indicators[0].item.idref].observable.object_.properties.address_value

        data['incidents'][ttp.title].append({
            'ip': ip,
            'time': time,
            'pattern': "IP %(condition)s(%(ip)s)" % {'condition': address_value.condition, 'ip': address_value.value}
        })

    print(data)
开发者ID:STIXProject,项目名称:stixproject.github.io,代码行数:36,代码来源:combined-consumer.py

示例9: main

# 需要导入模块: from stix.core import STIXPackage [as 别名]
# 或者: from stix.core.STIXPackage import from_xml [as 别名]
def main():
    stix_package = STIXPackage.from_xml('snort-test-mechanism.xml')

    ttps = {}
    for ttp in stix_package.ttps.ttps:
        ttps[ttp.id_] = ttp

    ets = {}
    for et in stix_package.exploit_targets:
        ets[et.id_] = et

    for indicator in stix_package.indicators:
        print "== INDICATOR =="
        print "Title: " + indicator.title
        print "Confidence: " + indicator.confidence.value.value

        for indicated_ttp in indicator.indicated_ttps:
            ttp = ttps[indicated_ttp.item.idref] # Resolve the TTP by idref
            et = ets[ttp.exploit_targets[0].item.idref] # Resolve the ET by idref
            print "Indicated TTP: " + ttp.title + " (" + et.vulnerabilities[0].cve_id + ")"

        for tm in indicator.test_mechanisms:
            print "Producer: " + tm.producer.identity.name
            print "Efficacy: " + tm.efficacy.value.value
            for rule in tm.rules:
                print "Rule: " + rule.value
开发者ID:andreisirghi,项目名称:stixproject.github.io,代码行数:28,代码来源:snort-test-mechanism-consumer.py

示例10: poll_feed

# 需要导入模块: from stix.core import STIXPackage [as 别名]
# 或者: from stix.core.STIXPackage import from_xml [as 别名]
def poll_feed(settings,subscription):
    """ polls a TAXII feed"""
    client = tc.HttpClient()
    client.set_auth_type(tc.HttpClient.AUTH_BASIC)
    client.set_use_https(True)
    client.set_auth_credentials({'username': settings['username'], 'password': settings['password']})

    msg_id=uuid.uuid4().hex
    poll_request1 = tm11.PollRequest(message_id=msg_id,collection_name=settings['subscriptions'][subscription]['collection_name'],subscription_id=settings['subscriptions'][subscription]['subscription_id'])
    poll_xml=poll_request1.to_xml()
    http_resp = client.call_taxii_service2(settings['server'], '/taxii-data/', VID_TAXII_XML_11, poll_xml)
    taxii_message = t.get_message_from_http_response(http_resp, poll_request1.message_id)
    observables={}
    
    indicators = json.loads(taxii_message.to_json())
    if 'content_blocks' in indicators.keys():
        for indicator in indicators['content_blocks']:
            open('/tmp/indicator.xml','w').write(indicator['content'])
            indi=STIXPackage.from_xml('/tmp/indicator.xml').to_dict()
            if 'observables' in indi.keys():
                for obs in indi['observables']['observables']:
                    if 'object' in obs.keys():
                        ot=obs['object']['properties']['xsi:type']
                        if ot in settings['supported_objects'].keys() and not ot in observables.keys():
                            observables[ot]=[]
                        if ot in settings['supported_objects'].keys() and settings['supported_objects'][ot] in obs['object']['properties'].keys():
                            # note, you will only be able to process one property per object type, but you also know there's only one property you can process
                            try:
                                observables[ot].append(obs['object']['properties'][settings['supported_objects'][ot]])
                            except:
                                print "[-] you're dumb"
                                print supported_objects[ot], "not in:", obs['object']
    return observables
开发者ID:3rdpaw,项目名称:nyx,代码行数:35,代码来源:soltra.py

示例11: pre_import_stix

# 需要导入模块: from stix.core import STIXPackage [as 别名]
# 或者: from stix.core.STIXPackage import from_xml [as 别名]
def pre_import_stix(file, cluster=None):
    from stix.core import STIXPackage

    pkg = STIXPackage()
    pkg = pkg.from_xml(file)

    reports = pkg.reports
    header = None
    timestamp = ""
    try:
        header = reports[0].header
        timestamp = reports[0].timestamp
    except:
        header = pkg.header
    # sc = header_to_subcluster(header)
    sc = {"name": header.title, "description": header.description, "firstseen": timestamp}

    """
    campaigns= pkg.campaigns
    for campaign in campaigns:
        s = campaign_to_subcluster(campaign)
        if not s in sc:
            sc.append(s)
    """
    # ttp = pkg.ttps
    obs = pkg.observables
    if sc:
        sc["node"] = []
        sc = obs_to_node(obs, sc)
        sc["cluster"] = cluster

    return sc
开发者ID:S03D4-164,项目名称:Hiryu,代码行数:34,代码来源:stix_import.py

示例12: test_parsed_namespaces

# 需要导入模块: from stix.core import STIXPackage [as 别名]
# 或者: from stix.core.STIXPackage import from_xml [as 别名]
    def test_parsed_namespaces(self):
        """Test that non-default namespaces make it through the parse-serialize
        process.

        """
        xml = (
            """<stix:STIX_Package
                    xmlns:TEST="a:test"
                    xmlns:FOO="a:foo"
                    xmlns:BAR="a:bar"
                    xmlns:cybox="http://cybox.mitre.org/cybox-2"
                    xmlns:cyboxCommon="http://cybox.mitre.org/common-2"
                    xmlns:cyboxVocabs="http://cybox.mitre.org/default_vocabularies-2"
                    xmlns:example="http://example.com"
                    xmlns:stix="http://stix.mitre.org/stix-1"
                    xmlns:stixCommon="http://stix.mitre.org/common-1"
                    xmlns:stixVocabs="http://stix.mitre.org/default_vocabularies-1"
                    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                    id="example:Package-e2454ee8-e59c-43ac-a085-46ae4516fd6e"
                    version="1.2"
                    timestamp="2015-04-09T14:22:25.620831+00:00"/>"""
        )

        sio = StringIO(xml)
        p = STIXPackage.from_xml(sio)

        serialized = p.to_xml()
        e = lxml.etree.XML(serialized)
        self.assertEqual(e.nsmap.get('TEST'), 'a:test')
        self.assertEqual(e.nsmap.get('FOO'), 'a:foo')
        self.assertEqual(e.nsmap.get('BAR'), 'a:bar')
开发者ID:shinsec,项目名称:python-stix,代码行数:33,代码来源:nsparser_test.py

示例13: main

# 需要导入模块: from stix.core import STIXPackage [as 别名]
# 或者: from stix.core.STIXPackage import from_xml [as 别名]
def main():
    poll_response = 'file-hash-rep-poll-response.xml'
    f = open(poll_response, 'r')
    msg = tm11.get_message_from_xml(f.read())

    requested_hash = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
    requested_hash_type = 'MD5'

    #Iterate over the content blocks
    for content_block in msg.content_blocks:
        if content_block.content_binding.binding_id != CB_STIX_XML_111:
            raise ValueError('Something other than STIX 1.1.1 was attempted!')

        # Deserialize the STIX_Package
        stix_package = STIXPackage.from_xml(StringIO(content_block.content))
        indicator = get_first_matching_indicator(stix_package, requested_hash, requested_hash_type)
        indicated_ttp = get_first_parseable_indicated_ttp(indicator)
        confidence = indicated_ttp.confidence.value
        ttp = get_indicated_ttp(stix_package, indicated_ttp.id_)
        if ttp.title != 'Malicious File':
            raise ValueError('Don\'t know how to handle that TTP')


        if confidence in ('High','Medium'):
            print "DO NOT OPEN THE FILE"
        elif confidence in ('Low', 'Unknown'):
            print "THINK TWICE ABOUT OPENING THE FILE"
        elif confidence in ('None', ):
            print "Go ahead!"
        else:
            raise ValueError("Unknown confidence: %s!" % confidence)
开发者ID:TAXIIProject,项目名称:taxiiproject.github.io,代码行数:33,代码来源:file-hash-rep-parse-response.py

示例14: test_duplicate_ns_prefix

# 需要导入模块: from stix.core import STIXPackage [as 别名]
# 或者: from stix.core.STIXPackage import from_xml [as 别名]
    def test_duplicate_ns_prefix(self):
        """Test that duplicate namespace prefix mappings raise errors.

        """
        p = STIXPackage()
        bad = {'bad:ns': 'stix'}  # 'stix' is already default ns prefix

        self.assertRaises(
            nsparser.DuplicatePrefixError,
            p.to_xml,
            ns_dict=bad
        )

        # Build a valid stix document that has a default namespace remapped
        # to another namespace. We remap 'cybox' to a bogus ns here.
        xml = (
            """<stix:STIX_Package
                    xmlns:cybox="THISISGONNABEPROBLEM"
                    xmlns:stix="http://stix.mitre.org/stix-1"
                    version="1.2"
                    timestamp="2015-04-09T14:22:25.620831+00:00"/>"""
        )

        sio = StringIO(xml)
        p = STIXPackage.from_xml(sio)

        # Exporting should raise an error.
        self.assertRaises(
            nsparser.DuplicatePrefixError,
            p.to_xml
        )
开发者ID:shinsec,项目名称:python-stix,代码行数:33,代码来源:nsparser_test.py

示例15: _main

# 需要导入模块: from stix.core import STIXPackage [as 别名]
# 或者: from stix.core.STIXPackage import from_xml [as 别名]
def _main(first=True):
    if first:
        begin = datetime.datetime.now(tzutc()) - timedelta(days=int(days))
    else:
        try:
            begin = _readTimestamp()
        except IOError:
            print("[-] No timestamp file found have you 'first_run'?")
            sys.exit(0)

    end = datetime.datetime.now(tzutc())

    poll_params1 = tm11.PollParameters(
        allow_asynch=False,
        response_type=RT_COUNT_ONLY,
        content_bindings=[tm11.ContentBinding(binding_id=CB_STIX_XML_11)],
    )

    try:
        poll_req3 = tm11.PollRequest(
            message_id='PollReq03',
            collection_name=collection,
            poll_parameters=poll_params1,
            exclusive_begin_timestamp_label=begin,
            inclusive_end_timestamp_label=end,
        )
    except ValueError:
        print("[-] Invalid timestamp file")
        sys.exit(0)

    except Exception:
        print("[-] Error with PollRequest")

    poll_xml = poll_req3.to_xml()

    http_resp = client.call_taxii_service2(
        server, path, VID_TAXII_XML_11,
        poll_xml, port=port)
    taxii_message = t.get_message_from_http_response(
        http_resp, poll_req3.message_id)
    if taxii_message.message_type == MSG_POLL_RESPONSE:
        if taxii_message.content_blocks:
            try:
                for content in taxii_message.content_blocks:
                    package_io = StringIO(content.content)
                    pkg = STIXPackage.from_xml(package_io)
                    title = pkg.id_.split(':', 1)[-1]
                    with open(title + ".xml", "w") as text_file:
                        text_file.write(content.content)
                    print("[+] Successfully generated " + title)
            except Exception:
                print("[-] Error with TAXII response")
        else:
            print("[+] No content returned")
        _saveTimestamp(str(end))
    else:
        print("[-] Error with TAXII response")
开发者ID:certuk,项目名称:certuk-common,代码行数:59,代码来源:poller.py


注:本文中的stix.core.STIXPackage.from_xml方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。