Example #1
0
def test_create_bundle_invalid(indicator, malware, relationship):
    with pytest.raises(ValueError) as excinfo:
        stix2.Bundle(objects=[1])
    assert excinfo.value.reason == "This property may only contain a dictionary or object"

    with pytest.raises(ValueError) as excinfo:
        stix2.Bundle(objects=[{}])
    assert excinfo.value.reason == "This property may only contain a non-empty dictionary or object"

    with pytest.raises(ValueError) as excinfo:
        stix2.Bundle(objects=[{'type': 'bundle'}])
    assert excinfo.value.reason == 'This property may not contain a Bundle object'
Example #2
0
def test_custom_property_dict_in_bundled_object():
    custom_identity = {
        'type': 'identity',
        'id': 'identity--311b2d2d-f010-5473-83ec-1edf84858f4c',
        'created': '2015-12-21T19:59:11Z',
        'name': 'John Smith',
        'identity_class': 'individual',
        'x_foo': 'bar',
    }
    with pytest.raises(stix2.exceptions.ExtraPropertiesError):
        bundle = stix2.Bundle(custom_identity)

    bundle = stix2.Bundle(custom_identity, allow_custom=True)
    assert bundle.objects[0].x_foo == "bar"
    assert '"x_foo": "bar"' in str(bundle)
Example #3
0
def test_empty_bundle():
    bundle = stix2.Bundle()

    assert bundle.type == "bundle"
    assert bundle.id.startswith("bundle--")
    assert bundle.spec_version == "2.0"
    assert bundle.objects is None
Example #4
0
def test_bundle_id_must_start_with_bundle():
    with pytest.raises(ValueError) as excinfo:
        bundle = stix2.Bundle(id='my-prefix--')

    assert str(
        excinfo.value
    ) == "Invalid value for Bundle 'id': must start with 'bundle--'."
Example #5
0
def test_bundle_with_wrong_spec_version():
    with pytest.raises(ValueError) as excinfo:
        bundle = stix2.Bundle(spec_version="1.2")

    assert str(
        excinfo.value
    ) == "Invalid value for Bundle 'spec_version': must equal '2.0'."
Example #6
0
def test_bundle_with_wrong_type():
    with pytest.raises(stix2.exceptions.InvalidValueError) as excinfo:
        stix2.Bundle(type="not-a-bundle")

    assert excinfo.value.cls == stix2.Bundle
    assert excinfo.value.prop_name == "type"
    assert excinfo.value.reason == "must equal 'bundle'."
    assert str(excinfo.value) == "Invalid value for Bundle 'type': must equal 'bundle'."
Example #7
0
def test_bundle_id_must_start_with_bundle():
    with pytest.raises(stix2.exceptions.InvalidValueError) as excinfo:
        stix2.Bundle(id='my-prefix--')

    assert excinfo.value.cls == stix2.Bundle
    assert excinfo.value.prop_name == "id"
    assert excinfo.value.reason == "must start with 'bundle--'."
    assert str(excinfo.value) == "Invalid value for Bundle 'id': must start with 'bundle--'."
Example #8
0
def test_bundle_with_wrong_spec_version():
    with pytest.raises(stix2.exceptions.InvalidValueError) as excinfo:
        stix2.Bundle(spec_version="1.2")

    assert excinfo.value.cls == stix2.Bundle
    assert excinfo.value.prop_name == "spec_version"
    assert excinfo.value.reason == "must equal '2.0'."
    assert str(excinfo.value) == "Invalid value for Bundle 'spec_version': must equal '2.0'."
Example #9
0
def test_empty_bundle():
    bundle = stix2.Bundle()

    assert bundle.type == "bundle"
    assert bundle.id.startswith("bundle--")
    assert bundle.spec_version == "2.0"
    with pytest.raises(AttributeError):
        assert bundle.objects
Example #10
0
def test_custom_properties_object_in_bundled_object():
    obj = stix2.Identity(name="John Smith",
                         identity_class="individual",
                         custom_properties={
                             "x_foo": "bar",
                         })
    bundle = stix2.Bundle(obj, allow_custom=True)

    assert bundle.objects[0].x_foo == "bar"
    assert '"x_foo": "bar"' in str(bundle)
Example #11
0
def test_custom_property_in_bundled_object():
    identity = stix2.Identity(
        name="John Smith",
        identity_class="individual",
        x_foo="bar",
        allow_custom=True,
    )
    bundle = stix2.Bundle(identity, allow_custom=True)

    assert bundle.objects[0].x_foo == "bar"
    assert '"x_foo": "bar"' in str(bundle)
Example #12
0
def test_custom_properties_dict_in_bundled_object():
    custom_identity = {
        'type': 'identity',
        'id': 'identity--311b2d2d-f010-5473-83ec-1edf84858f4c',
        'created': '2015-12-21T19:59:11Z',
        'name': 'John Smith',
        'identity_class': 'individual',
        'custom_properties': {
            'x_foo': 'bar',
        },
    }
    bundle = stix2.Bundle(custom_identity)

    assert bundle.objects[0].x_foo == "bar"
    assert '"x_foo": "bar"' in str(bundle)
Example #13
0
def ExportProject():
    items = filestoarr2("alph")
    if not items:
        tk.messagebox.showwarning(
            "Error",
            "Current project seems empty. There is nothing to export.")
        return
    bpath = tk.filedialog.asksaveasfilename(
        title="Export entire project into a STIX2 Bundle file.",
        defaultextension=".json",
        filetypes=[("json file", "*.json")])
    if bpath:
        bundle = stix2.Bundle(items)
        file = open(bpath, "w")
        file.write(str(bundle))
        file.close()
        tk.messagebox.showinfo(
            "Success",
            "Current project was exported into a STIX2 Bundle file.")
Example #14
0
import stix2

indicator = stix2.Indicator(
    id="indicator--d81f86b9-975b-4c0b-875e-810c5ad45a4f",
    created="2014-06-29T13:49:37.079Z",
    modified="2014-06-29T13:49:37.079Z",
    name="Malicious site hosting downloader",
    description=
    "This organized threat actor group operates to create profit from all types of crime.",
    labels=["malicious-activity"],
    pattern="[url:value = 'http://x4z9arb.cn/4712/']",
    valid_from="2014-06-29T13:49:37.079000Z")

foothold = stix2.KillChainPhase(
    kill_chain_name="mandiant-attack-lifecycle-model",
    phase_name="establish-foothold")

malware = stix2.Malware(
    id="malware--162d917e-766f-4611-b5d6-652791454fca",
    created="2014-06-30T09:15:17.182Z",
    modified="2014-06-30T09:15:17.182Z",
    name="x4z9arb backdoor",
    labels=["backdoor", "remote-access-trojan"],
    description=
    "This malware attempts to download remote files after establishing a foothold as a backdoor.",
    kill_chain_phases=[foothold])

relationship = stix2.Relationship(indicator, 'indicates', malware)

bundle = stix2.Bundle(objects=[indicator, malware, relationship])
Example #15
0
def test_create_bundle_with_positional_args(indicator, malware, relationship):
    bundle = stix2.Bundle(indicator, malware, relationship)

    assert str(bundle) == EXPECTED_BUNDLE
Example #16
0
def test_create_bundle(indicator, malware, relationship):
    bundle = stix2.Bundle(objects=[indicator, malware, relationship])

    assert str(bundle) == EXPECTED_BUNDLE
    def run(self):
        self.helper.log_info("Fetching data CYBERCRIME-TRACKER.NET...")
        tlp = self.helper.api.marking_definition.read(
            filters=[
                {"key": "definition", "values": "TLP:{}".format(self.connector_tlp)}
            ]
        )
        while True:
            try:
                # Get the current timestamp and check
                timestamp = int(time.time())
                current_state = self.helper.get_state()

                if current_state is not None and "last_run" in current_state:
                    last_run = current_state["last_run"]
                    self.helper.log_info(
                        "Connector last run: {}".format(
                            datetime.datetime.utcfromtimestamp(last_run).strftime(
                                "%Y-%m-%d %H:%M:%S"
                            )
                        )
                    )
                else:
                    last_run = None
                    self.helper.log_info("Connector has never run")

                # Run if it is the first time or we are past the interval

                if last_run is None or ((timestamp - last_run) > self.interval):
                    self.helper.log_info("Connector will run!")
                    now = datetime.datetime.utcfromtimestamp(timestamp)
                    friendly_name = "MITRE run @ " + now.strftime("%Y-%m-%d %H:%M:%S")
                    work_id = self.helper.api.work.initiate_work(
                        self.helper.connect_id, friendly_name
                    )

                    # Get Feed Content
                    feed = feedparser.parse(self.feed_url)

                    self.helper.log_info(
                        "Found: {} entries.".format(len(feed["entries"]))
                    )

                    self.feed_summary = {
                        "Source": feed["feed"]["title"],
                        "Date": self._time_to_datetime(
                            feed["feed"]["published_parsed"]
                        ),
                        "Details": feed["feed"]["subtitle"],
                        "Link": feed["feed"]["link"],
                    }

                    # Create the bundle
                    bundle_objects = list()

                    organization = stix2.Identity(
                        id=OpenCTIStix2Utils.generate_random_stix_id("identity"),
                        name="CYBERCRIME-TRACKER.NET",
                        identity_class="organization",
                        description="Tracker collecting and sharing daily updates of C2 IPs/Urls. http://cybercrime-tracker.net",
                    )
                    bundle_objects.append(organization)
                    for entry in feed["entries"]:
                        parsed_entry = self.parse_feed_entry(entry)
                        external_reference = stix2.ExternalReference(
                            source_name="{}".format(self.feed_summary["Source"]),
                            url=parsed_entry["ext_link"],
                        )
                        indicator_pattern = self.gen_indicator_pattern(parsed_entry)
                        malware = stix2.Malware(
                            id=OpenCTIStix2Utils.generate_random_stix_id("malware"),
                            is_family=True,
                            name=parsed_entry["type"],
                            description="{} malware.".format(parsed_entry["type"]),
                        )
                        bundle_objects.append(malware)
                        indicator = None
                        if self.create_indicators:
                            indicator = stix2.Indicator(
                                id=OpenCTIStix2Utils.generate_random_stix_id(
                                    "indicator"
                                ),
                                name=parsed_entry["url"],
                                description="C2 URL for: {}".format(
                                    parsed_entry["type"]
                                ),
                                labels=["C2 Server"],
                                pattern_type="stix",
                                pattern=indicator_pattern,
                                valid_from=parsed_entry["date"],
                                created=parsed_entry["date"],
                                modified=parsed_entry["date"],
                                created_by_ref=organization.id,
                                object_marking_refs=[tlp["standard_id"]],
                                external_references=[external_reference],
                                custom_properties={
                                    "x_opencti_main_observable_type": "Url"
                                },
                            )
                            bundle_objects.append(indicator)
                            relation = stix2.Relationship(
                                id=OpenCTIStix2Utils.generate_random_stix_id(
                                    "relationship"
                                ),
                                source_ref=indicator.id,
                                target_ref=malware.id,
                                relationship_type="indicates",
                                start_time=self._time_to_datetime(
                                    entry["published_parsed"]
                                ),
                                stop_time=self._time_to_datetime(
                                    entry["published_parsed"]
                                )
                                + datetime.timedelta(0, 3),
                                description="URLs associated to: "
                                + parsed_entry["type"],
                                confidence=self.confidence_level,
                                created_by_ref=organization.id,
                                object_marking_refs=[tlp["standard_id"]],
                                created=parsed_entry["date"],
                                modified=parsed_entry["date"],
                                external_references=[external_reference],
                            )
                            bundle_objects.append(relation)
                        if self.create_observables:
                            observable_url = SimpleObservable(
                                id=OpenCTIStix2Utils.generate_random_stix_id(
                                    "x-opencti-simple-observable"
                                ),
                                key="Url.value",
                                labels=["C2 Server"],
                                value=parsed_entry["url"],
                                created_by_ref=organization.id,
                                object_marking_refs=[tlp["standard_id"]],
                                external_references=[external_reference],
                            )
                            bundle_objects.append(observable_url)
                            observable_ip = SimpleObservable(
                                id=OpenCTIStix2Utils.generate_random_stix_id(
                                    "x-opencti-simple-observable"
                                ),
                                key="IPv4-Addr.value",
                                labels=["C2 Server"],
                                value=parsed_entry["ip"],
                                created_by_ref=organization.id,
                                object_marking_refs=[tlp["standard_id"]],
                                external_references=[external_reference],
                            )
                            bundle_objects.append(observable_ip)
                            observable_domain = None
                            if "domain" in parsed_entry.keys():
                                observable_domain = SimpleObservable(
                                    id=OpenCTIStix2Utils.generate_random_stix_id(
                                        "x-opencti-simple-observable"
                                    ),
                                    key="Domain-Name.value",
                                    labels=["C2 Server"],
                                    value=parsed_entry["domain"],
                                    created_by_ref=organization.id,
                                    object_marking_refs=[tlp["standard_id"]],
                                    external_references=[external_reference],
                                )
                                bundle_objects.append(observable_domain)

                            if indicator is not None:
                                relationship_1 = stix2.Relationship(
                                    id=OpenCTIStix2Utils.generate_random_stix_id(
                                        "relationship"
                                    ),
                                    relationship_type="based-on",
                                    created_by_ref=organization.id,
                                    source_ref=indicator.id,
                                    target_ref=observable_url.id,
                                )
                                bundle_objects.append(relationship_1)
                                relationship_2 = stix2.Relationship(
                                    id=OpenCTIStix2Utils.generate_random_stix_id(
                                        "relationship"
                                    ),
                                    relationship_type="based-on",
                                    created_by_ref=organization.id,
                                    source_ref=indicator.id,
                                    target_ref=observable_ip.id,
                                )
                                bundle_objects.append(relationship_2)
                                if observable_domain is not None:
                                    relationship_3 = stix2.Relationship(
                                        id=OpenCTIStix2Utils.generate_random_stix_id(
                                            "relationship"
                                        ),
                                        relationship_type="based-on",
                                        created_by_ref=organization.id,
                                        source_ref=indicator.id,
                                        target_ref=observable_domain.id,
                                    )
                                    bundle_objects.append(relationship_3)

                    # create stix bundle
                    bundle = stix2.Bundle(objects=bundle_objects)
                    # send data
                    self.helper.send_stix2_bundle(
                        bundle=bundle.serialize(),
                        update=self.update_existing_data,
                        work_id=work_id,
                    )

                    # Store the current timestamp as a last run
                    message = (
                        "Connector successfully run,  storing last_run as: {}".format(
                            str(timestamp)
                        )
                    )
                    self.helper.log_info(message)
                    self.helper.set_state({"last_run": timestamp})
                    self.helper.api.work.to_processed(work_id, message)
                    self.helper.log_info(
                        "Last_run stored, next run in: {} seconds.".format(
                            str(round(self.interval, 2))
                        )
                    )
                    time.sleep(60)
                else:
                    new_interval = self.interval - (timestamp - last_run)
                    self.helper.log_info(
                        "Connector will not run. \
                            Next run in: {} seconds.".format(
                            str(round(new_interval, 2))
                        )
                    )
                    time.sleep(60)

            except (KeyboardInterrupt, SystemExit):
                self.helper.log_info("Connector stop")
                exit(0)
            except Exception as e:
                self.helper.log_error(str(e))
                time.sleep(60)
Example #18
0
def test_custom_property_object_in_bundled_object():
    bundle = stix2.Bundle(IDENTITY_CUSTOM_PROP, allow_custom=True)

    assert bundle.objects[0].x_foo == "bar"
    assert '"x_foo": "bar"' in str(bundle)
Example #19
0
def test_bundle_with_wrong_type():
    with pytest.raises(ValueError) as excinfo:
        bundle = stix2.Bundle(type="not-a-bundle")

    assert str(excinfo.value
               ) == "Invalid value for Bundle 'type': must equal 'bundle'."
Example #20
0
def csvtostix(file_type, file_name):
    count = 0
    data = {}
    labels = ""
    maldesc = ''
    malname = ''
    tot_file_path = ''
    url = []
    domain = []
    filename = []
    ip = []
    md5 = []
    registry = []
    email = []
    indlist = []
    rellist = []
    sha1 = []
    sha256 = []
    m = datetime.datetime.now()
    c = m.strftime("%Y-%m-%d %H:%M:%S.{}".format(str(m).split('.')[1][:3]) +
                   "Z")
    m = m.strftime("%Y-%m-%d %H:%M:%S.{}".format(str(m).split('.')[1][:3]) +
                   "Z")
    malware = stix2.Malware(created=c,
                            modified=m,
                            name=malname,
                            labels=labels,
                            description=maldesc)
    try:
        each_data = []
        if file_type == "-f":
            each_data = []
            with open(file_name, "r") as f:
                csv_reader = csv.reader(f, delimiter=',')
                fields = csv_reader.next()
                tab = -1
                for i in fields:
                    #print(i)
                    samp = []
                    tab += 1
                    with open(file_name, "r") as f:
                        csv_reader = csv.reader(f, delimiter=',')
                        for lines in csv_reader:
                            if lines[tab].strip():
                                if lines[tab] not in fields:
                                    samp.append(lines[tab].strip())
                    data[i] = samp
                    #print(data)
        elif file_type == "-F":
            each_data = []
            indiv_data = []
            if os.path.exists(file_name):
                for eachfile in os.walk(file_name):
                    for each_file in eachfile[2]:
                        with open(file_name + '/' + each_file, "r") as f:
                            csv_reader = csv.reader(f, delimiter=',')
                            fields = csv_reader.next()
                            tab = -1
                            for i in fields:
                                samp1 = []
                                tab += 1
                                with open(file_name, "r") as f:
                                    csv_reader = csv.reader(f, delimiter=',')
                                    for lines in csv_reader:
                                        if lines[tab].strip():
                                            if lines[tab] not in fields:
                                                samp1.append(
                                                    lines[tab].strip())
                                data[i].extend(samp1)

            else:
                print(
                    "please enter a valid folder containing json files with valid folder path"
                )
                print(
                    "Usage : python csvtostix.py <-f>/<-F> file_name/folder_name"
                )
                print(" Example : python csvtostix.py -f APT34.csv")
                print(
                    " Example : python csvtostix.py -F /home/user/Desktop/IOC_files/"
                )
                print(
                    "Submit the folder, which does not contain any subfolders")
                sys.exit()

        else:
            print(
                "Please enter the command as -f (for file) or -F (for folder) followed by File name or Folder name  with sapce"
            )
            print(
                "Usage : python csvtostix.py <-f>/<-F> file_name/folder_name")
            print(" Example : python csvtostix.py -f APT34.csv")
            print(
                " Example : python csvtostix.py -F /home/user/Desktop/IOC_files/"
            )
            sys.exit()

        #print(data)
        if data:
            domain = data.get("Domain", "")
            filepath1 = data.get("FilePath", "")
            sha1 = data.get("SHA1", "")
            registry = data.get("RegistryPath", "")
            filename = data.get("FileName", "")
            url = data.get("URL", "")
            ip = data.get("IPAddress", "")
            filename1 = data.get("FileName", "")
            #filename = filename1 + filepath1
            filename = filename1
            sha256 = data.get("SHA256", "")
            md5 = data.get("MD5", "")

            for each_ip in ip:
                indicator = stix2.Indicator(created=c,
                                            modified=m,
                                            name='IP',
                                            description=" ",
                                            labels=["malicious-activity"],
                                            pattern="[ipv4-addr:value = '" +
                                            each_ip.strip() + "']",
                                            valid_from=c)
                if indicator not in indlist:
                    indlist.append(indicator)
            for each_url in url:
                indicator = stix2.Indicator(
                    created=c,
                    modified=m,
                    name='url',
                    description=" ",
                    labels=["malicious-activity"],
                    pattern="[url:value = 'http://" +
                    each_url.split('//')[-1].split('/')[0].strip("'") + "'" +
                    "]",
                    valid_from=c)
                if indicator not in indlist:
                    indlist.append(indicator)
            for each_domain in domain:
                indicator = stix2.Indicator(
                    created=c,
                    modified=m,
                    name='domain-name',
                    description=" ",
                    labels=["malicious-activity"],
                    pattern="[domain-name:value = '" +
                    each_domain.split('//')[-1].split('/')[0].strip("'") +
                    "']",
                    valid_from=c)
                if indicator not in indlist:
                    indlist.append(indicator)

            for each_filename in filename:
                tot_file_path = ''
                exact_name = each_filename.split('\\')
                split_path_name = each_filename.split('\\')[0:-1]
                if split_path_name:
                    for path in split_path_name:
                        tot_file_path = tot_file_path + '\\\\' + path
                if len(exact_name) > 1:
                    indicator = stix2.Indicator(
                        created=c,
                        modified=m,
                        name='file',
                        description=" ",
                        labels=["malicious-activity"],
                        #pattern="[file:name = '" + each_filename.split('\\')[-1].strip("'") + "']",
                        pattern="[file:name = '" +
                        each_filename.split('\\')[-1].strip("'") +
                        "' AND file:parent_directory_ref.path = '" +
                        tot_file_path + "']",
                        valid_from=c)
                else:
                    indicator = stix2.Indicator(created=c,
                                                modified=m,
                                                name='file',
                                                description=" ",
                                                labels=["malicious-activity"],
                                                pattern="[file:name = '" +
                                                each_filename.strip("'") +
                                                "']",
                                                valid_from=c)

                if indicator not in indlist:
                    indlist.append(indicator)
            for each_registry in registry:
                each_registry = each_registry.replace("\\", "\\\\")
                indicator = stix2.Indicator(
                    created=c,
                    modified=m,
                    name='win-registry-key',
                    description=" ",
                    labels=["malicious-activity"],
                    pattern="[windows-registry-key:key = '" + each_registry +
                    "']",
                    valid_from=c)
                if indicator not in indlist:
                    indlist.append(indicator)

            for each_md5 in md5:
                each_md5 = re.sub(r'[^A-Za-z0-9]+', '', each_md5)
                indicator = stix2.Indicator(created=c,
                                            modified=m,
                                            name='MD5',
                                            description=" ",
                                            labels=["malicious-activity"],
                                            pattern="[file:hashes.md5 = '" +
                                            each_md5.strip() + "']",
                                            valid_from=c)
                if indicator not in indlist:
                    indlist.append(indicator)

            for each_sha1 in sha1:
                each_sha1 = re.sub(r'[^A-Za-z0-9]+', '', each_sha1)
                indicator = stix2.Indicator(
                    created=c,
                    modified=m,
                    name='MD5',
                    description=" ",
                    labels=["malicious-activity"],
                    pattern="[file:hashes.'SHA-1' = '" + each_sha1.strip() +
                    "']",
                    valid_from=c)
                if indicator not in indlist:
                    indlist.append(indicator)
            for each_sha256 in sha256:
                each_sha256 = re.sub(r'[^A-Za-z0-9]+', '', each_sha256)
                indicator = stix2.Indicator(
                    created=c,
                    modified=m,
                    name='MD5',
                    description=" ",
                    labels=["malicious-activity"],
                    pattern="[file:hashes.'SHA-256' = '" +
                    each_sha256.strip() + "']",
                    valid_from=c)
                if indicator not in indlist:
                    indlist.append(indicator)

            print(len(indlist))

            obj_range = int((len(indlist) / 50)) + 1

            ind1 = 0
            ind2 = 50
            print(obj_range)
            for num in range(obj_range):
                new_list = []
                if (ind2 - ind1) != 50:
                    new_list = indlist[ind1:]
                else:
                    new_list = indlist[ind1:ind2]
                for ind in new_list:
                    print(ind)
                    count += 1
                    val = 'relationship' + str(count)
                    val = stix2.Relationship(ind, 'indicates', malware)
                    rellist.append(val)
                    IOC = stix2.Bundle(objects=[malware] + rellist + new_list)
                if IOC:
                    print(type(num))
                    print(num)

                    num = str(num)
                    if sys.argv[1].split("/")[-1]:
                        with open(
                                sys.argv[1].split("/")[-1].split(".")[0] +
                                '_' + str(int(num) + 1) + '.ioc', 'w') as fp:
                            fp.write(json.dumps(json.loads(str(IOC)),
                                                indent=2))
                            fp.close()
                    elif sys.argv[1].split("/")[-2]:
                        with open(
                                sys.argv[1].split("/")[-2].split(".")[0] +
                                '_' + str(int(num) + 1) + '+.ioc', 'w') as fp:
                            fp.write(json.dumps(json.loads(str(IOC)),
                                                indent=2))
                            fp.close()
                    else:
                        with open(
                                sys.argv[1].split("/")[0].split(".")[0] + '_' +
                                str(int(num) + 1) + '+.ioc', 'w') as fp:
                            fp.write(json.dumps(json.loads(str(IOC)),
                                                indent=2))
                            fp.close()
                else:
                    pass
                ind1 = ind1 + 50
                ind2 = ind2 + 50
                rellist = []
        else:
            print(
                "please enter a valid file/folder containing json files containing indicator data"
            )
            print(
                "Usage : python csvtostix.py <-f>/<-F> file_name/folder_name")
            print(" Example : python csvtostix.py -f APT34.csv")
            print(
                " Example : python csvtostix.py -F /home/user/Desktop/IOC_files/"
            )
    except IOError as err:
        print(
            "please enter a valid folder containing csv files with valid folder path"
        )
        print("Usage : python csvtostix.py <-f>/<-F> file_name/folder_name")
        print(" Example : python csvtostix.py -f APT34.csv")
        print(
            " Example : python csvtostix.py -F /home/user/Desktop/IOC_files/")
        print("Submit the folder, which does not contain any subfolders")
    except Exception as e:
        print(traceback.format_exc())
        print(e)
    return
    contact_information="*****@*****.**",
    labels=["Cyber Security"],
    sectors=["technology"]
)

indicator = stix2.Indicator(
    id="indicator--9299f726-ce06-492e-8472-2b52ccb53191",
    created_by_ref="identity--39012926-a052-44c4-ae48-caaf4a10ee6e",
    created="2017-02-27T13:57:10.515Z",
    modified="2017-02-27T13:57:10.515Z",
    name="Malicious URL",
    description="This URL is potentially associated with malicious activity and is listed on several blacklist sites.",
    labels=["malicious-activity"],
    pattern="[url:value = 'http://paypa1.banking.com']",
    valid_from="2015-06-29T09:10:15.915Z"
)

sighting = stix2.Sighting(
    id="sighting--8356e820-8080-4692-aa91-ecbe94006833",
    created_by_ref="identity--5206ba14-478f-4b0b-9a48-395f690c20a2",
    created="2017-02-28T19:37:11.213Z",
    modified="2017-02-28T19:37:11.213Z",
    first_seen="2017-02-27T21:37:11.213Z",
    last_seen="2017-02-27T21:37:11.213Z",
    count=1,
    sighting_of_ref="indicator--9299f726-ce06-492e-8472-2b52ccb53191",
    where_sighted_refs=["identity--5206ba14-478f-4b0b-9a48-395f690c20a2"]
)

bundle = stix2.Bundle(objects=[indicator, identityAlpha, identityBeta, sighting])
Example #22
0
def generate_report():
    istihbarat_no = 0
    cyber_threads_infos = []
    attack_patterns = []
    sti_list = []

    records = get_all_records(settings.traffic_table_name,
                              settings.prediction_column_name)
    unique_records = unique_lists_from_multidimensional_array(records)

    identity = stiv.Identity(
        name=
        "Veri Madenciligi Temelli Siber Tehdit Istihbarati Tez Calismasi Onerilen Sistemin Uygulamasi - Suleyman Muhammed ARIKAN",
        identity_class="individual")
    sti_list.append(identity)

    predictions = [record[1] for record in unique_records]
    unique_predictions = set(predictions)

    for attack in unique_predictions:
        attact_pattern = stiv.AttackPattern(name=attack,
                                            created_by_ref=identity.id)
        attack_patterns.append(attact_pattern)
        sti_list.append(attact_pattern)

    cyber_threads_infos.append(
        "intelligence_id-prediction-source_host-source_port-destination_port-protocol"
        + "\n")
    for record in records:
        if str(record[1]) != settings.unknown_class_value:
            cyber_thread_info = str(record[1]) + "-" + str(
                record[5]) + "-" + str(int(float(record[3]))) + "-" + str(
                    int(float(record[4]))) + "-" + settings.protocols_list[
                        int(record[8]) - 1] + "\n"
            cyber_threads_infos.append(cyber_thread_info)

            istihbarat_no = istihbarat_no + 1
            indicator_name = str(
                istihbarat_no) + " numaralı istihbarat - " + str(record[5])
            indicator_label = ["malicious-activity"]
            indicator_pattern = "[network-traffic:src_ref.type = 'ipv4-addr' AND "
            indicator_pattern = indicator_pattern + "network-traffic:src_ref.value = '" + str(
                record[5]) + "' AND "
            indicator_pattern = indicator_pattern + "network-traffic:src_port = " + str(
                int(float(record[3]))) + " AND "
            indicator_pattern = indicator_pattern + "network-traffic:dst_port = " + str(
                int(float(record[4]))) + " AND "
            indicator_pattern = indicator_pattern + "network-traffic:protocols[*] = '" + settings.protocols_list[
                int(record[8]) - 1] + "']"

            indicator = stiv.Indicator(name=indicator_name,
                                       labels=indicator_label,
                                       pattern=indicator_pattern,
                                       created_by_ref=identity.id)
            sti_list.append(indicator)

            attack_pattern = get_attack_pattern(attack_patterns,
                                                str(record[1]))
            relationship = stiv.Relationship(relationship_type='indicates',
                                             source_ref=indicator.id,
                                             target_ref=attack_pattern.id)
            sti_list.append(relationship)

    stiv_bundle = stiv.Bundle(sti_list)

    file_name = datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S-%f")

    fo = open("raporlar/" + file_name + ".txt", "x")
    istihbarat_no = 0
    for cti in cyber_threads_infos:
        if (istihbarat_no != 0):
            cti = str(istihbarat_no) + "-" + cti
        fo.write(cti)
        istihbarat_no = istihbarat_no + 1
    fo.close()

    fo_stiv = open("raporlar/" + file_name + ".json", "x")
    fo_stiv.write(stiv_bundle.serialize())
    fo_stiv.close()
    return file_name
Example #23
0
def filestobundle():  #prepei kai logika 8a exoume idi chdir()
    items = []
    for folder in getFolderArray():
        for file in getFilesJsonExt(folder):
            items.append(stix2.parse(filetoitem(folder + "/" + file)))
    return stix2.Bundle(items), items
Example #24
0
def test_create_bundle_with_arg_listarg_and_kwarg(indicator, malware,
                                                  relationship):
    bundle = stix2.Bundle([indicator], malware, objects=[relationship])

    assert str(bundle) == EXPECTED_BUNDLE
Example #25
0
def test_create_bundle2(indicator, malware, relationship):
    bundle = stix2.Bundle(objects=[indicator, malware, relationship])

    assert json.loads(bundle.serialize()) == EXPECTED_BUNDLE_DICT
Example #26
0
def test_create_bundle1(indicator, malware, relationship):
    bundle = stix2.Bundle(objects=[indicator, malware, relationship])

    assert str(bundle) == EXPECTED_BUNDLE
    assert bundle.serialize(pretty=True) == EXPECTED_BUNDLE
Example #27
0
malware = stix2.Malware(id="malware--d1c612bc-146f-4b65-b7b0-9a54a14150a4",
                        created="2015-04-23T11:12:34.760Z",
                        modified="2015-04-23T11:12:34.760Z",
                        name="Poison Ivy Variant d1c6",
                        labels=["remote-access-trojan"],
                        kill_chain_phases=[init_comp])

ref = stix2.ExternalReference(
    source_name="capec",
    description="phishing",
    url="https://capec.mitre.org/data/definitions/98.html",
    external_id="CAPEC-98")

attack_pattern = stix2.AttackPattern(
    id="attack-pattern--8ac90ff3-ecf8-4835-95b8-6aea6a623df5",
    created="2015-05-07T14:22:14.760Z",
    modified="2015-05-07T14:22:14.760Z",
    name="Phishing",
    description="Spear phishing used as a delivery mechanism for malware.",
    kill_chain_phases=[init_comp],
    external_references=[ref])

relationship1 = stix2.Relationship(threat_actor, 'uses', malware)
relationship2 = stix2.Relationship(threat_actor, 'uses', attack_pattern)
relationship3 = stix2.Relationship(threat_actor, 'attributed-to', identity)

bundle = stix2.Bundle(objects=[
    threat_actor, malware, attack_pattern, identity, relationship1,
    relationship2, relationship3
])
import stix2

threat_actor = stix2.ThreatActor(
    id="threat-actor--dfaa8d77-07e2-4e28-b2c8-92e9f7b04428",
    created="2014-11-19T23:39:03.893Z",
    modified="2014-11-19T23:39:03.893Z",
    name="Disco Team Threat Actor Group",
    description=
    "This organized threat actor group operates to create profit from all types of crime.",
    labels=["crime-syndicate"],
    aliases=["Equipo del Discoteca"],
    roles=["agent"],
    goals=["Steal Credit Card Information"],
    sophistication="expert",
    resource_level="organization",
    primary_motivation="personal-gain")

identity = stix2.Identity(
    id="identity--733c5838-34d9-4fbf-949c-62aba761184c",
    created="2016-08-23T18:05:49.307Z",
    modified="2016-08-23T18:05:49.307Z",
    name="Disco Team",
    description=
    "Disco Team is the name of an organized threat actor crime-syndicate.",
    identity_class="organization",
    contact_information="*****@*****.**")

relationship = stix2.Relationship(threat_actor, 'attributed-to', identity)

bundle = stix2.Bundle(objects=[threat_actor, identity, relationship])
Example #29
0
    def fetch_and_send(self):
        timestamp = int(time.time())
        now = datetime.utcfromtimestamp(timestamp)
        friendly_name = "Cyber Threat Coalition run @ " + now.strftime(
            "%Y-%m-%d %H:%M:%S"
        )
        work_id = self.helper.api.work.initiate_work(
            self.helper.connect_id, friendly_name
        )
        bundle_objects = list()

        # create an identity for the coalition team
        organization = stix2.Identity(
            id=OpenCTIStix2Utils.generate_random_stix_id("identity"),
            name="Cyber Threat Coalition Team",
            identity_class="organization",
            description="Team of Experts collecting and sharing pandemic related "
            "cyber threat intelligence during the COVID-19 crisis time",
        )

        # add organization in bundle
        bundle_objects.append(organization)
        report_object_refs = list()

        for collection in ["domain", "ip", "url", "hash"]:
            # fetch backlist
            url = self.cyber_threat_coalition_base_url + "/" + str(collection) + ".txt"
            response = requests.get(url=url)
            if response.status_code != 200:
                raise Exception(
                    "Unable to fetch {0} blacklist, server returned status: {1}",
                    collection,
                    response.status_code,
                )
            pattern_type = "stix"
            labels = ["COVID-19", "malicious-activity"]
            # parse content
            for data in response.iter_lines(decode_unicode=True):
                observable_type = None
                observable_resolver = None
                if data and not data.startswith("#"):
                    if collection == "domain":
                        observable_resolver = "Domain-Name"
                        observable_type = "Domain-Name"
                    elif collection == "ip":
                        observable_resolver = "IPv4-Addr"
                        observable_type = "IPv4-Addr"
                    elif collection == "url":
                        observable_resolver = "Url"
                        observable_type = "Url"
                        data = urllib.parse.quote(data, "/:")
                    elif collection == "hash":
                        observable_resolver = self.get_hash_type()
                        observable_type = "File"
                    indicator = None
                    if observable_resolver is None or observable_type is None:
                        return
                    if self.cyber_threat_coalition_create_indicators:
                        indicator = stix2.Indicator(
                            id=OpenCTIStix2Utils.generate_random_stix_id("indicator"),
                            name=data,
                            pattern_type=pattern_type,
                            pattern=self._INDICATOR_PATTERN[observable_resolver].format(
                                data
                            ),
                            labels=labels,
                            created_by_ref=organization,
                            object_marking_refs=[stix2.TLP_WHITE],
                            custom_properties={
                                "x_opencti_main_observable_type": observable_type,
                            },
                        )
                        bundle_objects.append(indicator)
                        report_object_refs.append(indicator["id"])
                    if self.cyber_threat_coalition_create_observables:
                        observable = SimpleObservable(
                            id=OpenCTIStix2Utils.generate_random_stix_id(
                                "x-opencti-simple-observable"
                            ),
                            key=observable_type
                            + "."
                            + ".".join(self._OBSERVABLE_PATH[observable_resolver]),
                            value=data,
                            labels=labels,
                            created_by_ref=organization,
                            object_marking_refs=[stix2.TLP_WHITE],
                        )
                        bundle_objects.append(observable)
                        report_object_refs.append(observable["id"])
                        if indicator is not None:
                            relationship = stix2.Relationship(
                                id=OpenCTIStix2Utils.generate_random_stix_id(
                                    "relationship"
                                ),
                                relationship_type="based-on",
                                created_by_ref=organization,
                                source_ref=indicator.id,
                                target_ref=observable.id,
                            )
                            bundle_objects.append(relationship)
                            report_object_refs.append(relationship["id"])

        # create a global threat report
        report_uuid = "report--552b3ae6-8522-409d-8b72-a739bc1926aa"
        report_external_reference = stix2.ExternalReference(
            source_name="Cyber Threat Coalition",
            url="https://www.cyberthreatcoalition.org",
            external_id="COVID19-CTC",
        )
        if report_object_refs:
            stix_report = stix2.Report(
                id=report_uuid,
                name="COVID-19 Cyber Threat Coalition (CTC) BlackList",
                type="report",
                description="This report represents the whole COVID-19 CTC blacklist.",
                published=datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ"),
                created_by_ref=organization,
                object_marking_refs=[stix2.TLP_WHITE],
                labels=labels,
                external_references=[report_external_reference],
                object_refs=report_object_refs,
            )
            # add report in bundle
            bundle_objects.append(stix_report)

        # create stix bundle
        bundle = stix2.Bundle(objects=bundle_objects)

        # send data
        self.helper.send_stix2_bundle(
            bundle=bundle.serialize(), update=self.update_existing_data, work_id=work_id
        )
        return work_id
Example #30
0
    def process_reports(self, reports):
        if reports is None:
            printer.error("No results")
            return

        for report in reports:
            name = report["name"]
            id = report["id"]
            stix2_objects = []
            stix2_object_refs = []

            # FFS AV, consistency!
            if 'tlp' in report:
                tlp_id = REF_TLPS[report['tlp'].upper()]
            elif 'TLP' in report:
                tlp_id = REF_TLPS[report['TLP'].upper()]
            else:
                tlp_id = REF_TLPS['WHITE']

            sectors = report['industries']
            if sectors:
                unmatched_sectors = []
                added_sector = False

                for sector in [html.unescape(x.upper()) for x in sectors]:
                    sector_name = None
                    sector_id = None

                    if sector in SECTOR_MAPPINGS:
                        # sector_ids.append(self.octi_sectors[SECTOR_MAPPINGS[sector]])
                        sector_name = SECTOR_MAPPINGS[sector]
                        try:
                            sector_id = self.octi_sectors[
                                SECTOR_MAPPINGS[sector]]
                        except Exception as e:
                            printer.error(e)
                            continue
                    else:
                        printer.debug(f"Looking for sector {sector}")
                        match = difflib.get_close_matches(
                            sector, self.octi_sectors.keys(), 1)
                        if not len(match):
                            printer.error(
                                f"Unable to determine a matching sector for {sector}"
                            )
                            unmatched_sectors.append(sector)
                            continue
                        # sector_ids.append(self.octi_sectors[match[0]])
                        sector_name = match[0]
                        sector_id = self.octi_sectors[match[0]]

                    if sector_name is not None:
                        s = stix2.Identity(id=sector_id,
                                           name=sector_name,
                                           identity_class='class',
                                           custom_properties={
                                               'x_opencti_identity_type':
                                               'sector'
                                           })
                        printer.debug(f"Adding sector {sector_name}")
                        stix2_objects.append(s)
                        stix2_object_refs.append(s)
                        added_sector = True

                if not added_sector:
                    printer.warn("Adding 'UNKNOWN' placeholder sector")
                    s = stix2.Identity(id=self.octi_sectors["UNKNOWN"],
                                       name="Unknown",
                                       identity_class='class',
                                       custom_properties={
                                           'x_opencti_identity_type': 'sector'
                                       })
                    stix2_objects.append(s)
                    stix2_object_refs.append(s)

                description = report['description']
                if len(unmatched_sectors):
                    description = description + "\n\n###\nUnable to find a match for the following sectors, " \
                                                "please review manually:\n - " + '\n - '.join(unmatched_sectors)

                printer.info(f"Generating STIX2 for {name} ({id})")

                author = stix2.Identity(name=report['author_name'],
                                        identity_class='organization')
                stix2_objects.append(author)

                adversary = None
                if report['adversary']:
                    printer.debug("Adding adversary {}".format(
                        report['adversary']))
                    adversary = stix2.IntrusionSet(name=report['adversary'])
                    stix2_object_refs.append(adversary)
                    stix2_objects.append(adversary)

                if report['targeted_countries']:
                    for country in report['targeted_countries']:
                        printer.debug(f"Adding country {country}")
                        c = stix2.Identity(name=country,
                                           identity_class='organization',
                                           custom_properties={
                                               'x_opencti_identity_type':
                                               'country'
                                           })
                        stix2_objects.append(c)
                        stix2_object_refs.append(c)

                external_refs = []
                for eref in report['references']:
                    external_refs.append(
                        stix2.ExternalReference(source_name=tldextract.extract(
                            eref).registered_domain,
                                                url=eref))

                indicators = report["indicators"]
                if indicators:
                    for indicator in indicators:
                        resolved_type = self.resolve_type(
                            indicator["type"].lower())
                        if resolved_type != None and indicator["is_active"]:

                            observable_type = resolved_type
                            observable_value = indicator["indicator"]
                            pattern_type = 'stix'

                            try:
                                if observable_type in PATTERNTYPES:
                                    pattern_type = observable_type
                                elif observable_type not in OPENCTISTIX2:
                                    printer.info("Not in stix2 dict")
                                else:
                                    if 'transform' in OPENCTISTIX2[
                                            observable_type]:
                                        if OPENCTISTIX2[observable_type][
                                                'transform'][
                                                    'operation'] == 'remove_string':
                                            observable_value = observable_value.replace(
                                                OPENCTISTIX2[observable_type]
                                                ['transform']['value'], '')
                                    lhs = stix2.ObjectPath(
                                        OPENCTISTIX2[observable_type]['type'],
                                        OPENCTISTIX2[observable_type]['path'])
                                    observable_value = stix2.ObservationExpression(
                                        stix2.EqualityComparisonExpression(
                                            lhs, observable_value))
                            except Exception as e:
                                printer.error(e)
                                printer.info(
                                    "Could not determine suitable pattern")

                            try:

                                indicator_obj = stix2.Indicator(
                                    name=indicator["indicator"],
                                    description=indicator["description"],
                                    pattern=str(observable_value),
                                    valid_from=indicator["created"],
                                    labels=['malicious-activity'],
                                    created_by_ref=author,
                                    object_marking_refs=[tlp_id],
                                    custom_properties={
                                        'x_opencti_observable_type':
                                        resolved_type,
                                        'x_opencti_observable_value':
                                        indicator["indicator"],
                                        'x_opencti_pattern_type':
                                        pattern_type
                                    })
                                stix2_object_refs.append(indicator_obj)
                                stix2_objects.append(indicator_obj)
                            except Exception as e:
                                printer.error(e)
                                printer.info("Couldn't fetch indicator")

                else:
                    printer.error("No indicators")

                report = stix2.Report(name=name,
                                      description=description,
                                      created_by_ref=author,
                                      labels=['threat-report'],
                                      published=report['created'],
                                      created=report['created'],
                                      modified=report['modified'],
                                      object_refs=stix2_object_refs,
                                      object_marking_refs=[tlp_id],
                                      external_references=external_refs)
                stix2_objects.append(report)
                bundle = stix2.Bundle(stix2_objects).serialize()
                if not self.dryrun:
                    self.opencti_connector_helper.send_stix2_bundle(
                        bundle, None, True, False)
                    printer.info("Sending to OpenCTI")
                #printer.debug(str(bundle))

            else:
                printer.debug(f"No sectors, disregarding '{name}'")