示例#1
0
 def create_stix_identity(self, obj):
     idenfitier = 'ce1sus:Group-{0}'.format(obj.creator_group.uuid)
     if idenfitier in self.seen_groups:
         identity = Identity()
         identity.idref = idenfitier
     else:
         identity = Identity()
         identity.id_ = idenfitier
         identity.name = obj.creator_group.name
         self.seen_groups.append(idenfitier)
     return identity
示例#2
0
def build_stix():
    # setup stix document
    stix_package = STIXPackage()

    # 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 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.effects = Effects("Unintended Access")
    breach.impact_assessment = impact

    # add the victim
    victim = Identity()
    victim.name = "CyberTech Dynamics"
    breach.add_victim(victim)

    # add the impact
    impact = ImpactAssessment()
    impact.effects = Effects("Financial Loss")
    breach.impact_assessment = impact

    stix_package.add_incident(breach)

    return stix_package
示例#3
0
def getSTIXObject():
    # setup stix document
    stix_package = STIXPackage()

    # add incident and confidence
    breach = Incident()
    breach.description = "Parity Wallet Hacked"
    breach.confidence = "High" # investigators were able to thoroughly validate the incident, Low means not yet validated

    # stamp with reporter
    breach.reporter = InformationSource()
    breach.reporter.description = "https://paritytech.io/blog/security-alert.html"

    breach.reporter.time = Time()
    breach.reporter.time.produced_time = datetime.strptime("2017-11-08","%Y-%m-%d") # when they submitted it

    breach.reporter.identity = Identity()
    breach.reporter.identity.name = "parity technologies ltd"

    # set incident-specific timestamps
    breach.time = incidentTime()
    breach.title = "The Multi-sig Hack"
    breach.time.initial_compromise = datetime.strptime("2017-11-06", "%Y-%m-%d")
    breach.time.incident_discovery = datetime.strptime("2017-11-08", "%Y-%m-%d")
    #breach.time.restoration_achieved = datetime.strptime("2012-08-10", "%Y-%m-%d")
    breach.time.incident_reported = datetime.strptime("2017-11-08", "%Y-%m-%d")

    # add the impact
    impact = ImpactAssessment()
    impact.effects = Effects("Estimated Loss of $280m in Ether")
    breach.impact_assessment = impact

    # add the victim
    victim = Identity()
    victim.name = "Cappasity"
    breach.add_victim(victim)
    victim2 = Identity()
    victim2.name = "Who else ?"
    breach.add_victim(victim2)

    # add Information Sources
    infoSource = InformationSource();
    infoSource.add_description("https://news.ycombinator.com/item?id=15642856")
    infoSource.add_description("https://www.theregister.co.uk/2017/11/10/parity_280m_ethereum_wallet_lockdown_hack/")
    breach.Information_Source = infoSource;

    stix_package.add_incident(breach)
    return stix_package
示例#4
0
def main():
    ioc = etree.parse('6d2a1b03-b216-4cd8-9a9e-8827af6ebf93.ioc')

    stix_package = STIXPackage()

    ttp = TTP()
    malware_instance = MalwareInstance()
    malware_instance.names = ['Zeus', 'twexts', 'sdra64', 'ntos']
    
    ttp = TTP(title="Zeus")
    ttp.behavior = Behavior()
    ttp.behavior.add_malware_instance(malware_instance)

    indicator = Indicator(title="Zeus", description="Finds Zeus variants, twexts, sdra64, ntos")

    tm = OpenIOCTestMechanism()
    tm.ioc = ioc
    tm.producer = InformationSource(identity=Identity(name="Yara"))
    time = Time()
    time.produced_time = "0001-01-01T00:00:00"
    tm.producer.time = time
    tm.producer.references = ["http://openioc.org/iocs/6d2a1b03-b216-4cd8-9a9e-8827af6ebf93.ioc"]
    indicator.test_mechanisms = [tm]

    indicator.add_indicated_ttp(TTP(idref=ttp.id_))

    stix_package.add_indicator(indicator)
    stix_package.add_ttp(ttp)
    
    print stix_package.to_xml()
def main():
    stix_package = STIXPackage()
    ttp_phishing = TTP(title="Phishing")

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

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

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

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

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

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

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

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

    print stix_package.to_xml()
示例#6
0
 def add_victim(self, victim):
     if not victim:
         return
     elif isinstance(victim, Identity):
         self.victims.append(victim)
     else:
         self.victims.append(Identity(name=victim))
示例#7
0
    def generate_indicators(self, count):
        '''Generate a list of STIX Indicators'''
        indicators = []
        for i in range(0, count):
            indicator = Indicator(title='Multiple indicator types')
            indicator.set_producer_identity(Identity(name='Secret Source'))
            indicator.set_produced_time(datetime.today())
            indicator.add_indicator_type(choice(['Malware Artifacts', 'C2', 'Exfiltration']))
            indicator.add_short_description('Short description...')
            indicator.add_description('Long description...')
            indicator.confidence = Confidence(choice(['High', 'Medium', 'Low', 'None', 'Unknown']))
            kill_chain_phase = choice(LMCO_KILL_CHAIN_PHASES)
            indicator.kill_chain_phases = KillChainPhasesReference(
                [KillChainPhaseReference(name=kill_chain_phase.name)])
            ips = self.gen_ips(randint(0, 5))
            for ip in ips:
                indicator.add_observable(ip)

            # user_agents = self.gen_user_agents(randint(0, 5))
            # for ua in user_agents:
            #     indicator.add_observable(ua)

            # fqnds = self.gen_fqdns(randint(0, 5))
            # for f in fqnds:
            #     indicator.add_observable(f)

            # urls = self.gen_urls(randint(0, 5))
            # for u in urls:
            #     indicator.add_observable(u)

            indicators.append(indicator)

        return indicators
示例#8
0
 def add_persona(self, persona):
     if not persona:
         return
     elif isinstance(persona, Identity):
         self._personas.append(persona)
     else:
         self._personas.append(Identity(name=persona))
def main():

    rule = """
rule silent_banker : banker
{
    meta:
        description = "This is just an example"
        thread_level = 3
        in_the_wild = true

    strings:
        $a = {6A 40 68 00 30 00 00 6A 14 8D 91}
        $b = {8D 4D B0 2B C1 83 C0 27 99 6A 4E 59 F7 F9}
        $c = "UVODFRYSIHLNWPEJXQZAKCBGMT"

    condition:
        $a or $b or $c
}
"""

    stix_package = STIXPackage()

    indicator = Indicator(title="silent_banker",
                          description="This is just an example")

    tm = YaraTestMechanism()
    tm.rule = rule
    tm.producer = InformationSource(identity=Identity(name="Yara"))
    tm.producer.references = ["http://plusvic.github.io/yara/"]
    indicator.test_mechanisms = TestMechanisms([tm])

    stix_package.add_indicator(indicator)

    print(stix_package.to_xml(encoding=None))
def main():

    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())
示例#11
0
def to_source(obj):

    from stix.common import InformationSource, Identity

    mySource = InformationSource()
    mySource.time = Time(obj.request.date)
    mySource.description = obj.request.rfi
    mySource.identity = Identity(name=obj.request.source)

    for item in obj.response:
        itemSource = InformationSource()
        itemSource.time = Time(item.date)
        itemSource.identity = Identity(name=item.source)
        itemSource.description = item.rfi
        mySource.add_contributing_source(itemSource)

    return mySource
示例#12
0
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())
示例#13
0
def cvebuild(var):
    """Search for a CVE ID and return a STIX formatted response."""
    cve = CVESearch()
    data = json.loads(cve.id(var))
    if data:
        try:
            from stix.utils import set_id_namespace
            namespace = {NS: NS_PREFIX}
            set_id_namespace(namespace)
        except ImportError:
            from mixbox.idgen import set_id_namespace
            from mixbox.namespaces import Namespace
            namespace = Namespace(NS, NS_PREFIX, "")
            set_id_namespace(namespace)

        pkg = STIXPackage()
        pkg.stix_header = STIXHeader()
        pkg = STIXPackage()
        pkg.stix_header = STIXHeader()

        pkg.stix_header.handling = _marking()

        # Define the exploit target
        expt = ExploitTarget()
        expt.title = data['id']
        expt.description = data['summary']
        expt.information_source = InformationSource(identity=Identity(
            name="National Vulnerability Database"))

        # Add the vulnerability object to the package object
        expt.add_vulnerability(_vulnbuild(data))

        # Add the COA object to the ET object
        for coa in COAS:
            expt.potential_coas.append(
                CourseOfAction(idref=coa['id'], timestamp=expt.timestamp))

        # Do some TTP stuff with CAPEC objects
        if TTPON is True:
            try:
                for i in data['capec']:
                    pkg.add_ttp(_buildttp(i, expt))
            except KeyError:
                pass

        expt.add_weakness(_weakbuild(data))

        # Add the exploit target to the package object
        pkg.add_exploit_target(expt)

        xml = pkg.to_xml()
        title = pkg.id_.split(':', 1)[-1]
        # If the function is not imported then output the xml to a file.
        if __name__ == '__main__':
            _postconstruct(xml, title)
        return xml
    else:
        sys.exit("[-] Error retrieving details for " + var)
示例#14
0
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
示例#15
0
def to_stix_sightings(obj):
    from stix.indicator.sightings import Sighting
    from stix.common import InformationSource, Identity

    mySighting = Sighting()
    mySighting.source = InformationSource()

    if obj.sightings.sighting:
        itemSighting = InformationSource()
        itemSighting.time = Time(obj.sightings.date)
        itemSighting.identity = Identity(name=settings.COMPANY_NAME)
        mySighting.source.add_contributing_source(itemSighting)

    for each in obj.sightings.instances:
        itemSighting = InformationSource()
        itemSighting.time = Time(each.date)
        itemSighting.identity = Identity(name=each.name)
        mySighting.source.add_contributing_source(itemSighting)

    return mySighting
示例#16
0
def genData_VictimTargeting(data):
    from stix.common.vocabs import InformationType, SystemType
    from stix.common.identity import Identity

    from stix.ttp.victim_targeting import VictimTargeting
    objVictimTargeting = VictimTargeting()
    objVictimTargeting.identity = Identity(name=data['target'])

    objVictimTargeting.targeted_systems = [SystemType.TERM_USERS]
    objVictimTargeting.targeted_information = InformationType.TERM_INFORMATION_ASSETS_USER_CREDENTIALS

    return (objVictimTargeting)
示例#17
0
def _buildttp(data):
    ttp = TTP()
    ttp.title = data['name']
    ttp.description = data['description']
    attack_pattern = AttackPattern()
    attack_pattern.capec_id = "CAPEC-" + str(data['id'])
    attack_pattern.title = data['name']
    attack_pattern.description = data['description']
    ttp.behavior = Behavior()
    ttp.behavior.add_attack_pattern(attack_pattern)
    ttp.information_source = InformationSource()
    ttp.information_source.identity = Identity()
    ttp.information_source.identity.name = "The MITRE Corporation"
    ttp.information_source.references = data['references']
    return ttp
示例#18
0
def to_stix_information_source(obj):

    from stix.common import InformationSource, Identity

    mySource = InformationSource()

    for item in obj.source:
        for each in item.instances:
            itemSource = InformationSource()
            itemSource.time = Time(each.date)
            itemSource.identity = Identity(name=item.name)
            itemSource.add_description(each.reference)
            itemSource.add_description(each.method)
            mySource.add_contributing_source(itemSource)

    return mySource
示例#19
0
    def set_producer_identity(self, identity):
        '''
        Sets the name of the producer of this indicator.
        The identity param can be a string (name) or an Identity
        instance.
        '''
        if not self.producer:
            self.producer = InformationSource()

        if isinstance(identity, Identity):
            self.producer.identity = identity
        else:
            if not self.producer.identity:
                self.producer.identity = Identity()

            self.producer.identity.name = identity # assume it's a string
示例#20
0
    def convert(self, stix_id_prefix='', published_only=True, **kw_arg):
        self.parse(**kw_arg)

        stix_packages = []
        for event in self.events:
            if published_only:
                if not event.published:
                    continue
            # id generator
            package_id = self.get_misp_pacakge_id(stix_id_prefix, event)
            stix_package = STIXPackage(timestamp=event.dt, id_=package_id)
            stix_header = STIXHeader()

            # set identity information
            identity = Identity(name=self.identity_name)
            information_source = InformationSource(identity=identity)
            stix_header.information_source = information_source

            tlp = None
            for tag in event.tags:
                if tag.tlp is not None:
                    tlp = tag.tlp
                    break

            if tlp is not None:
                # TLP for Generic format
                tlp_marking_structure = TLPMarkingStructure()
                tlp_marking_structure.color = tlp
                marking_specification = MarkingSpecification()
                marking_specification.marking_structures = tlp_marking_structure
                marking_specification.controlled_structure = '../../../../descendant-or-self::node() | ../../../../descendant-or-self::node()/@*'

                marking = Marking()
                marking.add_marking(marking_specification)
                stix_header.handling = marking

            stix_header.title = event.info
            stix_header.description = event.info
            stix_header.short_description = event.info
            for attribute in event.attributes:
                stix_package.add_indicator(attribute.convert())
            stix_package.stix_header = stix_header
            stix_packages.append(stix_package)

        return stix_packages
示例#21
0
    def set_producer_identity(self, identity):
        """Sets the name of the producer of this indicator.

        This is the same as calling
        ``indicator.producer.identity.name = identity``.

        If the ``producer`` property is ``None``, it will be initialized to
        an instance of
        :class:`stix.common.information_source.InformationSource`.

        If the ``identity`` property of the ``producer`` instance is ``None``,
        it will be initialized to an instance of
        :class:`stix.common.identity.Identity`.

        Note:
            if the `identity` parameter is not an instance
            :class:`stix.common.identity.Identity` an attempt will be made
            to convert it to one.

        Args:
            identity: An instance of ``str`` or
                ``stix.common.identity.Identity``.

        """
        def unset_producer_identity():
            try:
                self.producer.identity.name = None
            except AttributeError:
                pass

        if not identity:
            unset_producer_identity()
            return

        if not self.producer:
            self.producer = InformationSource()

        if isinstance(identity, Identity):
            self.producer.identity = identity
            return

        if not self.producer.identity:
            self.producer.identity = Identity()

        self.producer.identity.name = str(identity)
示例#22
0
def to_stix_indicator(obj):
    """
    Creates a STIX Indicator object from a CybOX object.

    Returns the STIX Indicator and the original CRITs object's
    releasability list.
    """
    from stix.indicator import Indicator as S_Ind
    from stix.common.identity import Identity
    ind = S_Ind()
    obs, releas = to_cybox_observable(obj)
    for ob in obs:
        ind.add_observable(ob)
    #TODO: determine if a source wants its name shared. This will
    #   probably have to happen on a per-source basis rather than a per-
    #   object basis.
    identity = Identity(name=settings.COMPANY_NAME)
    ind.set_producer_identity(identity)

    return (ind, releas)
def main():
    stix_package = STIXPackage()

    # Build the Exploit Target
    vuln = Vulnerability()
    vuln.cve_id = "CVE-2014-0160"
    vuln.add_reference("http://heartbleed.com/")

    et = ExploitTarget(title="Heartbleed")
    et.add_vulnerability(vuln)

    stix_package.add_exploit_target(et)

    # Build the TTP
    ttp = TTP(title="Generic Heartbleed Exploits")
    ttp.exploit_targets.append(ExploitTarget(idref=et.id_))

    stix_package.add_ttp(ttp)

    # Build the indicator
    indicator = Indicator(title="Snort Signature for Heartbleed")
    indicator.confidence = Confidence("High")

    tm = SnortTestMechanism()
    tm.rules = [
        """alert tcp any any -> any any (msg:"FOX-SRT - Flowbit - TLS-SSL Client Hello"; flow:established; dsize:< 500; content:"|16 03|"; depth:2; byte_test:1, <=, 2, 3; byte_test:1, !=, 2, 1; content:"|01|"; offset:5; depth:1; content:"|03|"; offset:9; byte_test:1, <=, 3, 10; byte_test:1, !=, 2, 9; content:"|00 0f 00|"; flowbits:set,foxsslsession; flowbits:noalert; threshold:type limit, track by_src, count 1, seconds 60; reference:cve,2014-0160; classtype:bad-unknown; sid: 21001130; rev:9;)""",
        """alert tcp any any -> any any (msg:"FOX-SRT - Suspicious - TLS-SSL Large Heartbeat Response"; flow:established; flowbits:isset,foxsslsession; content:"|18 03|"; depth: 2; byte_test:1, <=, 3, 2; byte_test:1, !=, 2, 1; byte_test:2, >, 200, 3; threshold:type limit, track by_src, count 1, seconds 600; reference:cve,2014-0160; classtype:bad-unknown; sid: 21001131; rev:5;)"""
    ]
    tm.efficacy = "Low"
    tm.producer = InformationSource(identity=Identity(name="FOX IT"))
    tm.producer.references = [
        "http://blog.fox-it.com/2014/04/08/openssl-heartbleed-bug-live-blog/"
    ]
    indicator.test_mechanisms = TestMechanisms([tm])
    indicator.add_indicated_ttp(TTP(idref=ttp.id_))

    stix_package.add_indicator(indicator)

    print(stix_package.to_xml(encoding=None))
示例#24
0
def setProd(target, org):
    ident = Identity(name=org)
    information_source = InformationSource(identity = ident)
    target.producer = information_source
示例#25
0
def setRep(target, org):
    ident = Identity(name=org)
    information_source = InformationSource(identity = ident)
    target.reporter = information_source
示例#26
0
def setSrc(target, org):
    ident = Identity(name=org)
    information_source = InformationSource(identity = ident)
    target.information_source = information_source
示例#27
0
    def toStixXml(self, confidence, efficacy):
        """
        This method converts a list of FASGuard generated Snort rules  into a STIX
        compliant XML string ready for output. It first converts the object
        into a hash of the right format and then converts it into XML using
        STIXPackage.from_dict and to_xml on the resulting object.

        Arguments:

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

        Returns:

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

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

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

        stix_package.add_exploit_target(et)

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

        stix_package.add_ttp(ttp)

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

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

        stix_package.add_indicator(indicator)

        return stix_package.to_xml()

        # stixDict = {'campaigns': [{}],
        #             'courses_of_action': [{}],
        #             'exploit_targets': [{}],
        #             'id': 'INSERT_PACKAGE_ID_HERE'}
        # stixDict['indicators'] = [{'indicator':
        #                            {'title':
        #                             'Automatically Generated FASGuard Signatures',
        #                             'test_mechanisms':
        #                             {'test_mechanism':
        #                              {'efficacy':'Low',
        #                               'producer':
        #                               {'Identity':'FASGuard'},
        #                               'rule':'xyz'}}}}
        # ]
        stix_package = STIXPackage.from_dict(stixDict)
        stix_xml = stix_package.to_xml()
        return stix_xml
示例#28
0
    def build(self):
        self.stix_header.title = self.pulse["name"]
        self.stix_header.description = self.pulse["description"]
        self.stix_header.short_description = "%spulse/%s" % (
            PULSE_SERVER_BASE, str(self.pulse["id"]))
        self.stix_header.package_intents.append(PackageIntent.TERM_INDICATORS)
        self.stix_header.information_source = InformationSource()
        self.stix_header.information_source.time = Time()
        self.stix_header.information_source.description = "Alienvault OTX - https://otx.alienvault.com/"
        self.stix_header.information_source.time.produced_time = self.pulse[
            "modified"]
        self.stix_header.information_source.identity = Identity()
        self.stix_header.information_source.identity.name = "Alienvault OTX"

        self.stix_package.stix_header = self.stix_header

        hashes = []
        addresses = []
        domains = []
        urls = []
        mails = []

        for p_indicator in self.pulse["indicators"]:
            if p_indicator["type"] in self.hash_translation:
                new_ind = Indicator()
                new_ind.description = p_indicator["description"]
                new_ind.title = "%s from %spulse/%s" % (
                    p_indicator["indicator"], PULSE_SERVER_BASE,
                    str(self.pulse["id"]))
                file_ = File()
                hash_ = Hash(p_indicator["indicator"],
                             self.hash_translation[p_indicator["type"]])
                file_.add_hash(hash_)
                observable_ = Observable(file_)

            elif p_indicator["type"] in self.address_translation:
                new_ind = Indicator()
                new_ind.description = p_indicator["description"]
                new_ind.title = "%s from %spulse/%s" % (
                    p_indicator["indicator"], PULSE_SERVER_BASE,
                    str(self.pulse["id"]))
                ipv4_ = Address.from_dict({
                    'address_value':
                    p_indicator["indicator"],
                    'category':
                    self.address_translation[p_indicator["type"]]
                })
                observable_ = Observable(ipv4_)

            elif p_indicator["type"] in self.name_translation:
                new_ind = Indicator()
                new_ind.description = p_indicator["description"]
                new_ind.title = "%s from %spulse/%s" % (
                    p_indicator["indicator"], PULSE_SERVER_BASE,
                    str(self.pulse["id"]))
                domain_ = DomainName.from_dict({
                    'value':
                    p_indicator["indicator"],
                    'type':
                    'FQDN'
                })
                observable_ = Observable(domain_)

            elif p_indicator["type"] == "URL":
                new_ind = Indicator()
                new_ind.description = p_indicator["description"]
                new_ind.title = "%s from %spulse/%s" % (
                    p_indicator["indicator"], PULSE_SERVER_BASE,
                    str(self.pulse["id"]))
                url_ = URI.from_dict({
                    'value': p_indicator["indicator"],
                    'type': URI.TYPE_URL
                })
                observable_ = Observable(url_)

            elif p_indicator["type"] == "email":
                email_ = Address.from_dict({
                    'address_value':
                    p_indicator["indicator"],
                    'category':
                    Address.CAT_EMAIL
                })
                observable_ = Observable(email_)

            #elif p_indicator["type"] == "CVE":
            #    vuln_ = Vulnerability()
            #    vuln_.cveid = p_indicator["indicator"].upper()
            #    observable_ = Observable(vuln_)

            elif p_indicator["type"] == "Mutex":
                mutex_ = Mutex.from_dict({
                    'named': True,
                    'name': p_indicator["indicator"]
                })
                observable_ = Observable(mutex_)

            elif p_indicator["type"] == "CIDR":
                nrange = IP(p_indicator["indicator"])
                nrange_values = nrange.strNormal(3).replace("-", ",")
                ipv4_ = Address.from_dict({
                    'address_value': nrange_values,
                    'category': Address.CAT_IPV4
                })
                ipv4_.address_value.condition = "InclusiveBetween"
                observable_ = Observable(ipv4_)

            else:
                continue

            mind = Indicator()
            mind.description = p_indicator["description"]
            mind.title = "%s from %spulse/%s" % (p_indicator["indicator"],
                                                 PULSE_SERVER_BASE,
                                                 str(self.pulse["id"]))
            observable_.title = "%s - %s" % (p_indicator["type"],
                                             p_indicator["indicator"])
            mind.add_observable(observable_)
            self.stix_package.add_indicator(mind)
示例#29
0
 def _fix_value(self, value):
     return Identity(name=value)
示例#30
0
def main():

    ######################################################################
    # MODIFICARE LE VARIABILI SEGUENTI

    # Il title e' ID univoco della minaccia (es. Cobalt / Danabot / APT28)
    MyTITLE = "GandCrab"

    # La description strutturiamola come segue
    # <IOC PRODUCER> - <Descrizione della minaccia/campagna> - <URL (if any)>
    DESCRIPTION = "CERT-PA - Nuova campagna di Cyber-Estorsione basata su ransomware GandCrab - https://www.cert-pa.it/notizie/nuova-campagna-di-cyber-estorsione-basata-su-ransomware-gandcrab/"

    # La sorgente che ha generato l'IoC con riferimento a Cyber Saiyan Community 
    IDENTITY = "CERT-PA via Cyber Saiyan Community"
    #
    ######################################################################

    # Build STIX file
    info_src = InformationSource()
    info_src.identity = Identity(name=IDENTITY)

    NAMESPACE = Namespace("https://infosharing.cybersaiyan.it", "CYBERSAIYAN")
    set_id_namespace(NAMESPACE)

    timestamp = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')
    SHORT = timestamp

    wrapper = STIXPackage()
    
    marking_specification = MarkingSpecification()
    marking_specification.controlled_structure = "//node() | //@*"
    tlp = TLPMarkingStructure()
    tlp.color = "WHITE"
    marking_specification.marking_structures.append(tlp)
    
    handling = Marking()
    handling.add_marking(marking_specification)
    
    wrapper.stix_header = STIXHeader(information_source=info_src, title=MyTITLE.encode(encoding='UTF-8', errors='replace'), description=DESCRIPTION.encode(encoding='UTF-8', errors='replace'), short_description=SHORT.encode(encoding='UTF-8', errors='replace'))
    wrapper.stix_header.handling = handling
    
    # HASH indicators
    indicatorHASH = Indicator()
    indicatorHASH.title = MyTITLE + " - HASH"
    indicatorHASH.add_indicator_type("File Hash Watchlist")
    
    # DOMAIN indicators
    indiDOMAIN = Indicator()
    indiDOMAIN.title = MyTITLE + " - DOMAIN"
    indiDOMAIN.add_indicator_type("Domain Watchlist")

    # URL indicators
    indiURL = Indicator()
    indiURL.title = MyTITLE + " - URL"
    indiURL.add_indicator_type("URL Watchlist")

    # IP indicators
    indiIP = Indicator()
    indiIP.title = MyTITLE + " - IP"
    indiIP.add_indicator_type("IP Watchlist")

    # EMAIL indicators
    indiEMAIL = Indicator()
    indiEMAIL.title = MyTITLE + " - EMAIL"
    indiEMAIL.add_indicator_type("Malicious E-mail")

    # Read IoC file
    file_ioc = "CS-ioc.txt"
    ioc = loaddata(file_ioc)

    print "Reading IoC file..."
    for idx, ioc in enumerate(ioc):
        notfound = 1
        
        # sha256
        p = re.compile(r"^[0-9a-f]{64}$", re.IGNORECASE)
        m = p.match(ioc)
        if m and notfound:
            filei = File()
            filei.add_hash(Hash(ioc))
        
            obsi = Observable(filei)
            indicatorHASH.add_observable(obsi)
            print "SHA256: " + ioc
            notfound = 0

        #md5
        p = re.compile(r"^[0-9a-f]{32}$", re.IGNORECASE)
        m = p.match(ioc)
        if m and notfound:
            filej = File()
            filej.add_hash(Hash(ioc))
        
            obsj = Observable(filej)
            indicatorHASH.add_observable(obsj)
            print "MD5: " + ioc
            notfound = 0

        #sha1
        p = re.compile(r"^[0-9a-f]{40}$", re.IGNORECASE)
        m = p.match(ioc)
        if m and notfound:
            filek = File()
            filek.add_hash(Hash(ioc))
        
            obsk = Observable(filek)
            indicatorHASH.add_observable(obsk)
            print "SHA1: " + ioc
            notfound = 0

        #domains
        if validators.domain(ioc) and notfound:
            url = URI()
            url.value = ioc
            url.type_ =  URI.TYPE_DOMAIN
            url.condition = "Equals"

            obsu = Observable(url)
            indiDOMAIN.add_observable(obsu)
            print "DOMAIN: " + ioc
            notfound = 0

        #url
        if validators.url(ioc) and notfound:
            url = URI()
            url.value = ioc
            url.type_ =  URI.TYPE_URL
            url.condition = "Equals"
            
            obsu = Observable(url)
            indiURL.add_observable(obsu)
            print "URL: " + ioc
            notfound = 0

        #ip
        if validators.ipv4(ioc) and notfound:
            ip = Address()
            ip.address_value = ioc
        
            obsu = Observable(ip)
            indiIP.add_observable(obsu)
            print "IP: " + ioc
            notfound = 0

    # add all indicators to STIX
    wrapper.add_indicator(indicatorHASH)
    wrapper.add_indicator(indiDOMAIN)
    wrapper.add_indicator(indiURL)
    wrapper.add_indicator(indiIP)
    wrapper.add_indicator(indiEMAIL)
   
    # print STIX file to stdout
    print "Writing STIX package: package.stix"
    f = open ("package.stix", "w")
    f.write (wrapper.to_xml())
    f.close ()
    print