Exemplo n.º 1
0
def home(request):
    """
		Name: home
		Desc: Main GUI view

	"""

    # Forms:Job,target and relay creation
    create_job_form = CreateJob(request=request, prefix="create_job")
    create_target_form = CreateTarget(request=request, prefix="create_target")
    create_relay_form = CreateRelay(request=request, prefix="create_relay")

    if request.method == "POST":

        # Remove a relay
        if "delete_relay_id" in request.POST:

            try:

                Relay.objects.get(pk=request.POST["delete_relay_id"]).delete()

            except ObjectDoesNotExist, e:

                pass

        # Create new relay
        if "create_relay-name" in request.POST:

            # Actuator creation
            create_relay_form = CreateRelay(request.POST,
                                            request=request,
                                            prefix="create_relay")
            if create_relay_form.is_valid():

                host = create_relay_form.save()
                host.save()

            # TODO - Call a sync here

        # Job Creations
        if "create_job-raw_message" in request.POST:

            new_job = Job(capability=Capability.objects.get(
                pk=request.POST["create_job-capability"]),
                          target=Target.objects.get(
                              pk=request.POST["create_job-target"]),
                          raw_message="Pending",
                          status=JobStatus.objects.get(status="Pending"),
                          created_by=request.user)

            new_job.save()

            # Now we have a pk - update the id

            command = json.loads(request.POST["create_job-raw_message"])
            command["modifiers"]["command-ref"] = new_job.id

            logger.info("Job Created\n%s" % json.dumps(command))

            new_job.raw_message = json.dumps(command, sort_keys=True,
                                             indent=4).replace(
                                                 "\t", u'\xa0\xa0\xa0\xa0\xa0')
            new_job.save()

        # Target Creations

        namespace_url = getattr(settings, "NAMESPACE_URL", None)
        namespace_id = getattr(settings, "NAMESPACE_ID", None)

        set_id_namespace(Namespace(namespace_url, namespace_id))

        if "create_target-cybox_type" in request.POST:

            cybox_type = CybOXType.objects.get(
                pk=request.POST["create_target-cybox_type"])

            if cybox_type.identifier == "cybox:NetworkConnectionObjectType":

                obs = NetworkConnection()

                # Source
                sock = SocketAddress()
                sock.ip_address = request.POST["create_target-source_address"]
                sock.ip_address.category = "ipv4-addr"
                sock.ip_address.condition = "Equals"
                sport = Port()
                sport.port_value = int(
                    request.POST["create_target-source_port"])
                sock.port = sport
                obs.source_socket_address = sock

                # Dest
                sock = SocketAddress()
                sock.ip_address = request.POST[
                    "create_target-destination_address"]
                sock.ip_address.category = "ipv4-addr"
                sock.ip_address.condition = "Equals"
                dport = Port()
                dport.port_value = int(
                    request.POST["create_target-destination_port"])
                sock.port = dport
                obs.destination_socket_address = sock

                name = "Network Connection %s:%s -> %s:%s (%s)" % (
                    request.POST["create_target-source_address"],
                    request.POST["create_target-source_port"],
                    request.POST["create_target-destination_address"],
                    request.POST["create_target-destination_port"],
                    request.POST["create_target-protocol"])

                raw_message = Observable(item=obs, title=name).to_json()

            elif cybox_type.identifier == "cybox:AddressObjectType":

                name = "Address %s " % (request.POST["create_target-address"])
                raw_message = Observable(item=Address(
                    address_value=request.POST["create_target-address"],
                    category=Address.CAT_IPV4),
                                         title=name).to_json()

            elif cybox_type.identifier == "cybox:URIObjectType":
                name = "URI %s " % (request.POST["create_target-uri"])
                obs = URI()
                obs.value = request.POST["create_target-uri"]
                obs.type_ = URI.TYPE_URL
                obs.condition = "Equals"
                raw_message = Observable(item=obs, title=name).to_json()

            elif cybox_type.identifier == "cybox:EmailMessageObjectType":
                name = "Email %s " % (
                    request.POST["create_target-email_subject"])
                obs = EmailMessage()
                obs.raw_body = request.POST["create_target-email_message"]
                obs.header = EmailHeader()
                obs.header.subject = request.POST[
                    "create_target-email_subject"]
                obs.header.subject.condition = "StartsWith"
                obs.header.to = request.POST["create_target-email_to"]
                obs.header.from_ = request.POST["create_target-email_from"]
                raw_message = Observable(item=obs, title=name).to_json()
            else:

                # Should never reach here
                raw_message = {}
                name = "Undefined Object"

            create_target_form = CreateTarget(request.POST,
                                              request=request,
                                              prefix="create_target")

            if create_target_form.is_valid():

                target = create_target_form.save(commit=False)

                target.name = name

                target.raw_message = raw_message

                target.save()
Exemplo n.º 2
0
 def setUp(self):
     ioc_ns = Namespace("http://schemas.mandiant.com/2010/ioc",
                        "mandiant-openioc", '')
     idgen.set_id_namespace(ioc_ns)
Exemplo n.º 3
0
def main():

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

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

    # La description strutturiamola come segue
    # <IOC PRODUCER> - <Descrizione della minaccia/campagna> - <URL (if any)>
    DESCRIPTION = "D3Lab - Malspam Gootkit con dropper da 450+ MB - https://www.d3lab.net/malspam-gootkit-con-dropper-da-450-mb/"

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

    # read IoC files
    file_sha256 = "CS-sha256.txt"
    sha256 = loaddata(file_sha256)

    file_md5 = "CS-md5.txt"
    md5 = loaddata(file_md5)

    file_sha1 = "CS-sha1.txt"
    sha1 = loaddata(file_sha1)

    file_domains = "CS-domain.txt"
    domains = loaddata(file_domains)

    file_urls = "CS-url.txt"
    urls = loaddata(file_urls)

    file_ips = "CS-ipv4.txt"
    ips = loaddata(file_ips)

    file_emails = "CS-email.txt"
    emails = loaddata(file_emails)

    # 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")

    print "Reading IoC sha256 file..."
    p = re.compile(r"^[0-9a-f]{64}$", re.IGNORECASE)
    for idx, sha256 in enumerate(sha256):
        m = p.match(sha256)
        if m:
            filei = File()
            filei.add_hash(Hash(sha256))

            obsi = Observable(filei)
            indicatorHASH.add_observable(obsi)
        else:
            print " Malformed sha256: " + sha256
    print

    print "Reading IoC md5 file..."
    p = re.compile(r"^[0-9a-f]{32}$", re.IGNORECASE)
    for idx, md5 in enumerate(md5):
        m = p.match(md5)
        if m:
            filej = File()
            filej.add_hash(Hash(md5))

            obsj = Observable(filej)
            indicatorHASH.add_observable(obsj)
        else:
            print " Malformed md5: " + md5
    print

    print "Reading IoC sha1 file..."
    p = re.compile(r"^[0-9a-f]{40}$", re.IGNORECASE)
    for idx, sha1 in enumerate(sha1):
        m = p.match(sha1)
        if m:
            filek = File()
            filek.add_hash(Hash(sha1))

            obsk = Observable(filek)
            indicatorHASH.add_observable(obsk)
        else:
            print " Malformed sha1: " + sha1
    print

    # DOMAIN indicators
    indiDOMAIN = Indicator()
    indiDOMAIN.title = MyTITLE + " - DOMAIN"
    indiDOMAIN.add_indicator_type("Domain Watchlist")

    print "Reading IoC domains file..."
    for idu, domains in enumerate(domains):
        if validators.domain(domains):
            url = URI()
            url.value = domains
            url.type_ = URI.TYPE_DOMAIN
            url.condition = "Equals"

            obsu = Observable(url)
            indiDOMAIN.add_observable(obsu)
        else:
            print " Malformed domain: " + domains
    print

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

    print "Reading IoC url file..."
    for idu, urls in enumerate(urls):
        if validators.url(urls):
            url = URI()
            url.value = urls
            url.type_ = URI.TYPE_URL
            url.condition = "Equals"

            obsu = Observable(url)
            indiURL.add_observable(obsu)
        else:
            print " Malformed url: " + urls
    print

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

    print "Reading IoC IP file..."
    for idu, ips in enumerate(ips):
        if validators.ipv4(ips):
            ip = Address()
            ip.address_value = ips

            obsu = Observable(ip)
            indiIP.add_observable(obsu)
        else:
            print " Malformed IP: " + ips
    print

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

    print "Reading IoC email file..."
    for idu, emails in enumerate(emails):
        if validators.email(emails):
            email = EmailAddress()
            email.address_value = emails

            obsu = Observable(email)
            indiEMAIL.add_observable(obsu)
        else:
            print " Malformed email: " + emails
    print

    # add all indicators
    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
Exemplo n.º 4
0
def load_stix(stix):
    # Just save the pain and load it if the first character is a <
    log.debug("Loading STIX...")
    if sys.version_info < (3, 5):
        json_exception = ValueError
    else:
        json_exception = json.JSONDecodeError

    if isinstance(stix, STIXPackage):
        log.debug("Argument was already STIX package, ignoring.")
        # Oh cool we're ok
        # Who tried to load this? Honestly.
        return stix

    elif hasattr(stix, 'read'):
        log.debug("Argument has 'read' attribute, assuming file-like.")

        # It's a file!
        # But somehow, sometimes, reading it returns a bytes stream
        # and the loader dies on python 3.4.
        # Luckily, STIXPackage.from_json (which is mixbox.Entity.from_json)
        # will happily load a string.
        # So we're going to play dirty.

        data = stix.read()
        log.debug("Read file, type %s.", type(data))

        if isinstance(data, bytes):
            data = data.decode()
        try:
            log.debug("Attempting to load from JSON...")
            # Try loading from JSON
            stix_package = STIXPackage.from_json(data)
        except json_exception:
            log.debug("Attempting to load from XML...")
            # Ok then try loading from XML
            # Loop zoop
            # Read the STIX into an Etree
            stix.seek(0)
            stix_xml = etree.fromstring(stix.read())

            ns_map = stix_xml.nsmap

            # Remove any "marking" sections because the US-Cert is evil
            log.debug("Removing Marking elements...")
            pattern = ".//{http://data-marking.mitre.org/Marking-1}Marking"
            for element in stix_xml.findall(pattern):
                element.getparent().remove(element)

            log.debug("Writing cleaned XML to Tempfile")
            f = SpooledTemporaryFile(max_size=10 * 1024)
            f.write(etree.tostring(stix_xml))
            f.seek(0)

            # Pray to anything you hold sacred
            ns_objmap = map(lambda x: Namespace(ns_map[x], x), ns_map)

            for ns in ns_objmap:
                log.debug("Trying to add namespace %s", ns)
                try:
                    nsparser.STIX_NAMESPACES.add_namespace(ns)
                    mixbox.namespaces.register_namespace(ns)
                except Exception as ex:
                    log.exception(ex)
            try:
                log.debug("Attempting to read clean XML into STIX...")
                stix_package = STIXPackage.from_xml(f)
            except Exception as ex:
                # No joy. Quit.
                log.fatal("Could not :<")
                log.exception(ex)
                f.seek(0)
                with open("FAILED_STIX.xml", "wb") as g:
                    g.write(f.read())
                raise STIXLoadError("Could not load stix file. {}".format(ex))

        return stix_package

    elif isinstance(stix, (str, bytes)):
        if isinstance(stix, bytes):
            stix = stix.decode()

        # It's text, we'll need to use a temporary file

        # Create a temporary file to load from
        # Y'know I should probably give it a max size before jumping to disk
        # idk, 10MB? Sounds reasonable.
        f = SpooledTemporaryFile(max_size=10 * 1024)

        # O I have idea for sneak
        # Will be very sneak
        # Write the (probably) XML to file
        f.write(stix.encode("utf-8"))

        # Reset the file so we can read from it
        f.seek(0)

        # AHA SNEAK DIDN'T EXPECT RECURSION DID YOU
        return load_stix(f)
Exemplo n.º 5
0
 def setUp(self):
     ioc_ns = Namespace(
         "http://stix.mitre.org/extensions/TestMechanism#OpenIOC2010-1",
         "stix-openioc", '')
     idgen.set_id_namespace(ioc_ns)
def main(argv):

    ######################################################################
    # Se non impostati da command line vengono utilizzati i seguenti valori per TITLE, DESCRIPTION, IDENTITY
    # Il title e' ID univoco della minaccia (es. Cobalt / Danabot / APT28)
    TITLE = raw_input("Insert Title Ioc:")

    # La description strutturiamola come segue
    # <IOC PRODUCER> - <Descrizione della minaccia/campagna> - <URL (if any)>
    DESCRIPTION = raw_input("Insert Decription:")

    # La sorgente che ha generato l'IoC con riferimento a Cyber Saiyan Community
    IDENTITY = raw_input("Insert User Identity:")

    # File degli IoC
    IOCFILE = raw_input("Add IoC Source File:")

    # Prefisso STIX output files STIX 1.2 e STIX 2
    OUTFILEPREFIX = "package"

    # Short Description - UNUSED
    #SHORT = "Emotet"
    ######################################################################

    VERBOSE = 0

    # UTF8 encode
    TITLE = TITLE.encode('utf8')
    DESCRIPTION = DESCRIPTION.encode('utf8')
    IDENTITY = IDENTITY.encode('utf8')

    print "\nStix File generation in progress...."
    #print (TITLE) #"TITLE: " + TITLE
    #print (DESCRIPTION) #"DESCRIPTION: " + DESCRIPTION
    #print (IDENTITY) #"IDENTITY: " + IDENTITY
    #print (IOCFILE) #"IOC FILE: " + IOCFILE
    #print "---------------------"

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

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

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

    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)

    # HASH indicators
    indicatorHASH = Indicator()
    indicatorHASH.title = TITLE + " - HASH"
    indicatorHASH.add_indicator_type("File Hash Watchlist")

    # DOMAIN indicators
    indiDOMAIN = Indicator()
    indiDOMAIN.title = TITLE + " - DOMAIN"
    indiDOMAIN.add_indicator_type("Domain Watchlist")

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

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

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

    ########################
    # Build STIX 2 file
    pattern_sha256 = []
    pattern_md5 = []
    pattern_sha1 = []
    pattern_domain = []
    pattern_url = []
    pattern_ip = []
    pattern_email = []

    # Marking
    marking_def_white = stix2.MarkingDefinition(definition_type="tlp",
                                                definition={"tlp": "WHITE"})

    # campagna
    # [TODO] aggiungere tutti i campi dello STIX 1.2 (es. IDENTITY)
    campaign_MAIN = stix2.Campaign(created=timestamp,
                                   modified=timestamp,
                                   name=TITLE,
                                   description=DESCRIPTION,
                                   first_seen=timestamp,
                                   objective="TBD")

    ########################
    # Read IoC file
    ioc = loaddata(IOCFILE)

    if (VERBOSE): print "Reading IoC file " + IOCFILE + "..."
    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:
            # STIX 1.2
            filei = File()
            filei.add_hash(Hash(ioc))

            obsi = Observable(filei)
            indicatorHASH.add_observable(obsi)
            if (VERBOSE): print "SHA256: " + ioc
            notfound = 0

            # STIX 2
            pattern_sha256.append("[file:hashes.'SHA-256' = '" + ioc +
                                  "'] OR ")

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

            obsj = Observable(filej)
            indicatorHASH.add_observable(obsj)
            if (VERBOSE): print "MD5: " + ioc
            notfound = 0

            # STIX 2
            pattern_md5.append("[file:hashes.'MD5' = '" + ioc + "'] OR ")

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

            obsk = Observable(filek)
            indicatorHASH.add_observable(obsk)
            if (VERBOSE): print "SHA1: " + ioc
            notfound = 0

            # STIX 2
            pattern_sha1.append("[file:hashes.'SHA1' = '" + ioc + "'] OR ")

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

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

            # STIX 2
            pattern_domain.append("[domain-name:value = '" + ioc + "'] OR ")

        #url
        if validators.url(ioc) and notfound:
            # STIX 1.2
            url = URI()
            url.value = ioc
            url.type_ = URI.TYPE_URL
            url.condition = "Equals"

            obsu = Observable(url)
            indiURL.add_observable(obsu)
            if (VERBOSE): print "URL: " + ioc
            notfound = 0

            # STIX 2
            pattern_url.append("[url:value = '" + ioc + "'] OR ")

        #ip
        if validators.ipv4(ioc) and notfound:
            # STIX 1.2
            ip = Address()
            ip.address_value = ioc

            obsu = Observable(ip)
            indiIP.add_observable(obsu)
            if (VERBOSE): print "IP: " + ioc
            notfound = 0

            # STIX 2
            pattern_ip.append("[ipv4-addr:value = '" + ioc + "'] OR ")

        #email
        if validators.email(ioc) and notfound:
            # STIX 1.2
            email = EmailAddress()
            email.address_value = ioc

            obsu = Observable(email)
            indiEMAIL.add_observable(obsu)

            if (VERBOSE): print "Email: " + ioc
            notfound = 0

            # STIX 2
            pattern_email.append("[email-message:from_ref.value = '" + ioc +
                                 "'] OR ")

    ########################
    # add all indicators to STIX 1.2
    wrapper.add_indicator(indicatorHASH)
    wrapper.add_indicator(indiDOMAIN)
    wrapper.add_indicator(indiURL)
    wrapper.add_indicator(indiIP)
    wrapper.add_indicator(indiEMAIL)

    ########################
    # prepare for STIX 2
    bundle_objects = [campaign_MAIN, marking_def_white]

    if len(pattern_sha256) != 0:
        stix2_sha256 = "".join(pattern_sha256)
        stix2_sha256 = stix2_sha256[:-4]

        indicator_SHA256 = stix2.Indicator(
            name=TITLE + " - SHA256",
            created=timestamp,
            modified=timestamp,
            description=DESCRIPTION,
            labels=["malicious-activity"],
            pattern=stix2_sha256,
            object_marking_refs=[marking_def_white])
        relationship_indicator_SHA256 = stix2.Relationship(
            indicator_SHA256, 'indicates', campaign_MAIN)
        bundle_objects.append(indicator_SHA256)
        bundle_objects.append(relationship_indicator_SHA256)

    if len(pattern_md5) != 0:
        stix2_md5 = "".join(pattern_md5)
        stix2_md5 = stix2_md5[:-4]

        indicator_MD5 = stix2.Indicator(
            name=TITLE + " - MD5",
            created=timestamp,
            modified=timestamp,
            description=DESCRIPTION,
            labels=["malicious-activity"],
            pattern=stix2_md5,
            object_marking_refs=[marking_def_white])
        relationship_indicator_MD5 = stix2.Relationship(
            indicator_MD5, 'indicates', campaign_MAIN)
        bundle_objects.append(indicator_MD5)
        bundle_objects.append(relationship_indicator_MD5)

    if len(pattern_sha1) != 0:
        stix2_sha1 = "".join(pattern_sha1)
        stix2_sha1 = stix2_sha1[:-4]

        indicator_SHA1 = stix2.Indicator(
            name=TITLE + " - SHA1",
            created=timestamp,
            modified=timestamp,
            description=DESCRIPTION,
            labels=["malicious-activity"],
            pattern=stix2_sha1,
            object_marking_refs=[marking_def_white])
        relationship_indicator_SHA1 = stix2.Relationship(
            indicator_SHA1, 'indicates', campaign_MAIN)
        bundle_objects.append(indicator_SHA1)
        bundle_objects.append(relationship_indicator_SHA1)

    if len(pattern_domain) != 0:
        stix2_domain = "".join(pattern_domain)
        stix2_domain = stix2_domain[:-4]

        indicator_DOMAINS = stix2.Indicator(
            name=TITLE + " - DOMAINS",
            created=timestamp,
            modified=timestamp,
            description=DESCRIPTION,
            labels=["malicious-activity"],
            pattern=stix2_domain,
            object_marking_refs=[marking_def_white])
        relationship_indicator_DOMAINS = stix2.Relationship(
            indicator_DOMAINS, 'indicates', campaign_MAIN)
        bundle_objects.append(indicator_DOMAINS)
        bundle_objects.append(relationship_indicator_DOMAINS)

    if len(pattern_url) != 0:
        stix2_url = "".join(pattern_url)
        stix2_url = stix2_url[:-4]

        indicator_URLS = stix2.Indicator(
            name=TITLE + " - URL",
            created=timestamp,
            modified=timestamp,
            description=DESCRIPTION,
            labels=["malicious-activity"],
            pattern=stix2_url,
            object_marking_refs=[marking_def_white])
        relationship_indicator_URLS = stix2.Relationship(
            indicator_URLS, 'indicates', campaign_MAIN)
        bundle_objects.append(indicator_URLS)
        bundle_objects.append(relationship_indicator_URLS)

    if len(pattern_ip) != 0:
        stix2_ip = "".join(pattern_ip)
        stix2_ip = stix2_ip[:-4]

        indicator_IPS = stix2.Indicator(
            name=TITLE + " - IPS",
            created=timestamp,
            modified=timestamp,
            description=DESCRIPTION,
            labels=["malicious-activity"],
            pattern=stix2_ip,
            object_marking_refs=[marking_def_white])
        relationship_indicator_IPS = stix2.Relationship(
            indicator_IPS, 'indicates', campaign_MAIN)
        bundle_objects.append(indicator_IPS)
        bundle_objects.append(relationship_indicator_IPS)

    if len(pattern_email) != 0:
        stix2_email = "".join(pattern_email)
        stix2_email = stix2_email[:-4]

        indicator_EMAILS = stix2.Indicator(
            name=TITLE + " - EMAILS",
            created=timestamp,
            modified=timestamp,
            description=DESCRIPTION,
            labels=["malicious-activity"],
            pattern=stix2_email,
            object_marking_refs=[marking_def_white])
        relationship_indicator_EMAILS = stix2.Relationship(
            indicator_EMAILS, 'indicates', campaign_MAIN)
        bundle_objects.append(indicator_EMAILS)
        bundle_objects.append(relationship_indicator_EMAILS)

    # creo il bunble STIX 2
    bundle = stix2.Bundle(objects=bundle_objects)

    ########################
    # save to STIX 1.2 file
    print
    print "Writing STIX 1.2 package: " + OUTFILEPREFIX + ".stix"
    f = open(OUTFILEPREFIX + ".stix", "w")
    f.write(wrapper.to_xml())
    f.close()

    ########################
    # save to STIX 2 file
    print "Writing STIX 2 package: " + OUTFILEPREFIX + ".stix2"
    g = open(OUTFILEPREFIX + ".stix2", "w")
    sys.stdout = g
    print bundle
Exemplo n.º 7
0
from stix.core import STIXPackage, STIXHeader

# python-cybox
from cybox.common import Time
from cybox.objects.uri_object import URI
from cybox.objects.file_object import File
from cybox.objects.address_object import Address
from cybox.objects.domain_name_object import DomainName
from cybox.bindings import domain_name_object, file_object, uri_object, address_object
from stix.utils import nsparser
import mixbox.namespaces
from mixbox.namespaces import Namespace
from mixbox import fields

ADDITIONAL_NAMESPACES = [
    Namespace('http://us-cert.gov/ciscp', 'CISCP',
              'http://www.us-cert.gov/sites/default/files/STIX_Namespace/ciscp_vocab_v1.1.1.xsd')
]

class StixIndicator:
    def __init__(self, ioctype, value, title, descr, produced_time):
        self.value = value
        self.title = title
        self.descr = str(descr)
        self.type = ioctype
        self.timestamp = produced_time

    def __str__(self):
        return "[%s] value: %s" % (self.type, self.value)

    @property
    def type(self):
Exemplo n.º 8
0
# Copyright (c) 2018, The MITRE Corporation
# All rights reserved

# Compatible with MAEC v4.1

from mixbox.namespaces import Namespace, NamespaceSet, register_namespace

NS_MAEC_BUNDLE = Namespace(
    'http://maec.mitre.org/XMLSchema/maec-bundle-4', 'maecBundle',
    'http://maec.mitre.org/language/version4.1/maec_bundle_schema.xsd')
NS_MAEC_PACKAGE = Namespace(
    'http://maec.mitre.org/XMLSchema/maec-package-2', 'maecPackage',
    'http://maec.mitre.org/language/version4.1/maec_package_schema.xsd')
NS_MAEC_VOCABS = Namespace(
    'http://maec.mitre.org/default_vocabularies-1', 'maecVocabs',
    'http://maec.mitre.org/language/version4.1/maec_default_vocabularies.xsd')

MAEC_NAMESPACES = NamespaceSet()

# Magic to automatically register all Namespaces defined in this module.
for k, v in dict(globals()).items():
    if k.startswith('NS_'):
        register_namespace(v)
        MAEC_NAMESPACES.add_namespace(v)
def main():
    mydata = loaddata()

    #    NAMESPACE = {sanitizer(mydata["NSXURL"]) : sanitizer(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["filename"]) + ": " + sanitizer(
        mydata["hashes"]["md5"])
    ShortDescription = timestamp

    DESCRIPTION = "STIX Report for: " + sanitizer(
        mydata["filename"]) + " - " + sanitizer(mydata["hashes"]["md5"])

    wrapper.stix_header = STIXHeader(information_source=info_src,
                                     title=MyTITLE,
                                     description=DESCRIPTION,
                                     short_description=ShortDescription)
    wrapper.stix_header.handling = handling

    fileobj = File()
    fileobj.file_name = sanitizer(mydata["filename"])
    fileobj.file_format = sanitizer(mydata["file_type"])
    fileobj.size_in_bytes = sanitizer(mydata["file_size"])
    fileobj.add_hash(Hash(sanitizer(mydata["hashes"]["md5"])))
    fileobj.add_hash(Hash(sanitizer(mydata["hashes"]["sha1"])))
    fileobj.add_hash(Hash(sanitizer(mydata["hashes"]["sha256"])))

    observable = Observable(fileobj)

    if "URL_file_hosting" in mydata:
        for idx, mydata["URL_file_hosting"] in enumerate(
                mydata["URL_file_hosting"]):
            url = URI()
            url.value = sanitizer(mydata["URL_file_hosting"])
            url.type_ = URI.TYPE_URL
            url.condition = "Equals"

            fileobj.add_related(url, "Downloaded_From")

    indicator = Indicator()
    indicator.title = MyTITLE
    indicator.add_indicator_type("File Hash Watchlist")
    indicator.add_observable(observable)

    wrapper.add_indicator(indicator)
    print(wrapper.to_xml())
Exemplo n.º 10
0
from cybox.objects.file_object import File
from stix.exploit_target import Vulnerability
from cybox.objects.mutex_object import Mutex
from cybox.common import Hash
from stix.indicator import Indicator, CompositeIndicatorExpression
from stix.common import InformationSource, Identity
from cybox.common import Time
from lxml import etree as et
from stix.common.vocabs import PackageIntent
from stix.core import STIXPackage
from mixbox.idgen import set_id_namespace
from mixbox.namespaces import Namespace
from IPy import *

PULSE_SERVER_BASE = "https://otx.alienvault.com/"
STIXNAMESPACE = Namespace("https://otx.alienvault.com", "alienvault-otx")
set_id_namespace(STIXNAMESPACE)


class StixExport:
    def __init__(self, pulse):
        self.stix_package = STIXPackage()
        self.stix_header = STIXHeader()
        self.pulse = pulse
        self.hash_translation = {
            "FileHash-MD5": Hash.TYPE_MD5,
            "FileHash-SHA1": Hash.TYPE_SHA1,
            "FileHash-SHA256": Hash.TYPE_SHA256
        }
        self.address_translation = {
            "IPv4": Address.CAT_IPV4,