Example #1
0
    def processAndSubmit(self):
        # Create SDO's / Cyber Obs
        ext_ref = ExternalReference(
            source_name=f"Cuckoo Sandbox Report {str(self.report.info.id)}",
            url=f"{self.cuckoo_url}/analysis/{str(self.report.info.id)}/summary",
            external_id=str(self.report.info.id),
        )

        if self.report.network.hosts:
            ips = self.createIPObs(self.report.network.hosts)
        else:
            ips = []

        if self.report.network.domains:
            fqdns = self.createDNSObs(self.report.network.domains)
        else:
            fqdns = [[], []]

        if self.report.process:
            processes = self.createProcessObs(self.report.process)
        else:
            processes = []

        if self.EnableRegKeys:
            if self.report.behavior:
                if self.report.behavior.regkey_written:
                    registry_keys = self.createRegKeysObs(
                        self.report.behavior.regkey_written
                    )
                else:
                    registry_keys = None
            else:
                registry_keys = None
        else:
            registry_keys = None

        if self.EnableNetTraffic:
            if self.report.network:
                network_traffic = self.createNetTrafficObs(self.report.network)
            else:
                network_traffic = None
        else:
            network_traffic = None

        if self.report.dropped:
            dropped_binaries = self.createBinarieObs(self.report.dropped)
        else:
            dropped_binaries = []

        if self.report.signatures:
            AttackPatterns = self.getAttackPatterns(self.report.signatures)
        else:
            AttackPatterns = []

        self.helper.log_info(fqdns)

        # Get all IDs from ATPs/CyberObs
        IDs = self.get_related(
            ips,
            fqdns[0],
            processes,
            network_traffic,
            dropped_binaries,
            AttackPatterns,
            registry_keys,
        )

        # Create Main binary and link All ATPs/Cyber Obs
        payload = self.createPrimaryBinary(self.report.target.file, ext_ref)
        payload_relations = []
        bundle_ids = []
        for ID in IDs:
            try:
                IDx = ID.id
                bundle_ids.append(
                    ID
                )  # Get list for bundle w/o Attack Patterns that exisit
            except:
                IDx = ID
            payload_relations.append(
                Relationship(
                    relationship_type="related-to",
                    source_ref=payload[0].id,
                    target_ref=IDx,
                )
            )
        for ATP in AttackPatterns:
            payload_relations.append(
                Relationship(
                    relationship_type="related-to",
                    source_ref=payload[0].id,
                    target_ref=ATP,
                )
            )
        IDs.append(payload[0])  # Add Observeable
        IDs.append(payload[1])  # Add Indicator
        bundle_ids.append(payload[0])
        bundle_ids.append(payload[1])
        payload_relations.append(payload[2])

        if int(self.report.info.score) >= self.ReportScore:
            # Create Report and link All ATPs/Cyber Obs/Payload
            report = self.createCuckooReport(self.report, IDs, ext_ref)
            b = Bundle(
                report, bundle_ids, payload_relations, fqdns[1]
            )  # fqdns[1] is the Resolves-to relations
        else:
            b = Bundle(bundle_ids, payload_relations, fqdns[1])

        self.helper.send_stix2_bundle(b.serialize())

        return None
Example #2
0
def post_language_contents(request, object_ref, ctirs_auth_user):
    try:
        j = json.loads(request.body)
        #S-TIP Identity 作成する
        stip_identity = _get_stip_identname(request.user)
        #bundle 作成
        bundle = Bundle(stip_identity)
        #参照元の obejct を取得
        object_ = get_object(object_ref)
        if object_ is None:
            return error(
                Exception('No document. (object_ref=%s)' % (object_ref)))

        for language_content in j[u'language_contents']:
            selector_str = language_content[u'selector']
            content_value = language_content[u'content']
            language = language_content[u'language']
            try:
                selector_elems = selector_str.split('.')
                last_elem = object_
                #selector の 要素をチェックする
                if len(selector_elems) == 1:
                    #selector が . でつながられていない場合
                    last_selector = selector_str
                    last_elem = is_exist_objects(selector_str, last_elem)
                else:
                    #selector が . でつながられている場合は最後までたどる
                    for selector in selector_elems[:-1]:
                        last_selector = selector
                        last_elem = is_exist_objects(selector, last_elem)
                        if last_elem is None:
                            raise Exception('selector is invalid: ' +
                                            str(selector_str))

                if isinstance(last_elem, list) == True:
                    #空要素で初期化し、該当 index の要素だけ上書きする
                    lc_lists = [''] * len(last_elem)
                    lc_lists[get_list_index_from_selector(
                        selector_elems[-1])] = content_value
                    content = lc_lists
                    selector = '.'.join(selector_elems[:-1])
                elif isinstance(last_elem, dict) == True:
                    #空辞書で初期化し、該当 index の要素だけ上書きする
                    content = {}
                    content[selector_elems[-1]] = content_value
                    selector = '.'.join(selector_elems[:-1])
                else:
                    #list ではない
                    content = content_value
                    selector = last_selector
            except Exception as e:
                traceback.print_exc()
                raise e

            contents = {}
            contents[language] = {selector: content}
            language_content = LanguageContent(
                created_by_ref=stip_identity,
                object_ref=object_ref,
                object_modified=object_[u'modified'],
                contents=contents)
            bundle.objects.append(language_content)

        #viaを取得
        via = Vias.get_via_rest_api_upload(uploader=ctirs_auth_user.id)
        community = Communities.get_default_community()
        #stixファイルを一時ファイルに出力
        stix_file_path = tempfile.mktemp(suffix='.json')
        with open(stix_file_path, 'wb+') as fp:
            fp.write(
                bundle.serialize(indent=4, ensure_ascii=False).encode('utf-8'))
        #登録処理
        regist(stix_file_path, community, via)
        resp = get_normal_response_json()
        bundle_json = json.loads(str(bundle))
        resp['data'] = {'bundle': bundle_json}
        return JsonResponse(resp, status=201, safe=False)
    except Exception as e:
        traceback.print_exc()
        return error(e)
Example #3
0
def post_language_contents(request, object_ref, ctirs_auth_user):
    try:
        j = json.loads(request.body)
        stip_identity = _get_stip_identname(request.user)
        bundle = Bundle(stip_identity)
        object_ = get_object(object_ref)
        if object_ is None:
            return error(
                Exception('No document. (object_ref=%s)' % (object_ref)))

        for language_content in j['language_contents']:
            selector_str = language_content['selector']
            content_value = language_content['content']
            language = language_content['language']
            try:
                selector_elems = selector_str.split('.')
                last_elem = object_
                if len(selector_elems) == 1:
                    last_selector = selector_str
                    last_elem = is_exist_objects(selector_str, last_elem)
                else:
                    for selector in selector_elems[:-1]:
                        last_selector = selector
                        last_elem = is_exist_objects(selector, last_elem)
                        if last_elem is None:
                            raise Exception('selector is invalid: ' +
                                            str(selector_str))

                if isinstance(last_elem, list):
                    lc_lists = [''] * len(last_elem)
                    lc_lists[get_list_index_from_selector(
                        selector_elems[-1])] = content_value
                    content = lc_lists
                    selector = '.'.join(selector_elems[:-1])
                elif isinstance(last_elem, dict):
                    content = {}
                    content[selector_elems[-1]] = content_value
                    selector = '.'.join(selector_elems[:-1])
                else:
                    content = content_value
                    selector = last_selector
            except Exception as e:
                traceback.print_exc()
                raise e

            contents = {}
            contents[language] = {selector: content}
            language_content = LanguageContent(
                created_by_ref=stip_identity,
                object_ref=object_ref,
                object_modified=object_['modified'],
                contents=contents)
            bundle.objects.append(language_content)

        via = Vias.get_via_rest_api_upload(uploader=ctirs_auth_user.id)
        community = Communities.get_default_community()
        stix_file_path = tempfile.mktemp(suffix='.json')
        with open(stix_file_path, 'wb+') as fp:
            fp.write(bundle.serialize(indent=4, ensure_ascii=False)).encode()
        regist(stix_file_path, community, via)
        resp = get_normal_response_json()
        bundle_json = json.loads(str(bundle))
        resp['data'] = {'bundle': bundle_json}
        return JsonResponse(resp, status=201, safe=False)
    except Exception as e:
        traceback.print_exc()
        return error(e)
Example #4
0
def get_stix2_bundle(indicators,
                     ttps,
                     tas,
                     title,
                     content,
                     stix2_titles=[],
                     stix2_contents=[],
                     stip_user=None):

    # S-TIP Identity 作成する
    stip_identity = _get_stip_identname(stip_user)

    # Report と StipSns に格納する granular_markings を取得する
    granular_markings = _make_granular_markings(stix2_titles[0],
                                                stix2_contents[0],
                                                stip_user.language)

    # 共通 lang
    common_lang = stip_user.language

    # StipSns Object (Custom Object)
    stip_sns = StipSns(lang=common_lang,
                       granular_markings=granular_markings,
                       post_type='post',
                       created_by_ref=stip_identity,
                       name=title,
                       description=content)

    # ReportObject
    report = Report(lang=common_lang,
                    granular_markings=granular_markings,
                    name=title,
                    description=content,
                    created_by_ref=stip_identity,
                    published=datetime.datetime.now(tz=pytz.utc),
                    report_types=['threat-report'],
                    object_refs=[stip_sns])

    # language-content 作成
    if granular_markings is None:
        # S-TIP オブジェクト用の language-content 作成
        language_contents = _get_language_contents(stix2_titles,
                                                   stix2_contents)
        if common_lang in language_contents:
            del language_contents[common_lang]

        s_tip_lc = LanguageContent(created_by_ref=stip_identity,
                                   object_ref=stip_sns,
                                   object_modified=stip_sns.created,
                                   contents=language_contents)

        # Report オブジェクト用の language-content 作成
        report_lc = LanguageContent(object_ref=report,
                                    created_by_ref=stip_identity,
                                    object_modified=report.created,
                                    contents=language_contents)
        # bundle 作成
        bundle = Bundle(stip_identity, report, stip_sns, s_tip_lc, report_lc)
    else:
        # granular_markings が存在するときは language-content は作成しない
        # bundle 作成
        bundle = Bundle(stip_identity, report, stip_sns)

    # objects に Vulnerability 追加
    for ttp in ttps:
        bundle.objects.append(_get_vulnerability_object(ttp, stip_identity))

    # objects に ThreatActor 追加
    for ta in tas:
        bundle.objects.append(_get_threat_actor_object(ta, stip_identity))

    # objects に Indicator 追加
    for indicator in indicators:
        indicator_o = _get_indicator_object(indicator, stip_identity)
        if indicator_o is not None:
            bundle.objects.append(indicator_o)
    return bundle
Example #5
0
def get_post_stix2_bundle(indicators,
                          ttps,
                          tas,
                          title,
                          content,
                          tlp,
                          referred_url,
                          sharing_range,
                          stix2_titles=[],
                          stix2_contents=[],
                          x_stip_sns_attachment_refs=None,
                          stip_user=None):

    # S-TIP Identity 作成する
    individual_identity = _get_individual_identity(stip_user)
    organization_identity = _get_organization_identity(stip_user)

    # x_stip_sns_author
    x_stip_sns_author = _get_x_stip_sns_author(stip_user)

    # x_stip_sns_post
    x_stip_sns_post = _get_x_stip_sns_post(title, content, tlp, sharing_range,
                                           referred_url)

    # x_stip_sns_object_ref
    x_stip_sns_object_ref = None
    # x_stip_sns_tags
    x_stip_sns_tags = None
    # x_stip_sns_indicators
    x_stip_sns_indicators = None
    # x_stip_sns_identity
    x_stip_sns_identity = _get_x_stip_sns_identity()
    # x_stip_sns_tool
    x_stip_sns_tool = _get_x_stip_sns_tool()

    # Report Object 用 object_refs
    report_object_refs = []

    # TLP marking_object 取得
    tlp_marking_object = _get_tlp_markings(tlp)

    # bundle 作成
    bundle = Bundle(individual_identity, tlp_marking_object)
    if organization_identity:
        bundle.objects.append(organization_identity)
        bundle.objects.append(
            _get_relationship_between_individual_to_organization(
                individual_identity, organization_identity))

    # objects に Vulnerability 追加
    for ttp in ttps:
        vulnerablity_object = _get_vulnerability_object(
            ttp, individual_identity, tlp_marking_object)
        bundle.objects.append(vulnerablity_object)
        report_object_refs.append(vulnerablity_object)

    # objects に ThreatActor 追加
    for ta in tas:
        ta_object = _get_threat_actor_object(ta, individual_identity,
                                             tlp_marking_object)
        bundle.objects.append(ta_object)
        report_object_refs.append(ta_object)

    # objects に Indicator 追加
    for indicator in indicators:
        indicator_o = _get_indicator_object(indicator, individual_identity,
                                            tlp_marking_object)
        if indicator_o is not None:
            bundle.objects.append(indicator_o)
            report_object_refs.append(indicator_o)

    # 共通 lang
    common_lang = stip_user.language
    # Report と StipSns に格納する granular_markings を取得する
    if len(stix2_titles) > 0 and len(stix2_contents) > 0:
        granular_markings = _make_granular_markings(stix2_titles[0],
                                                    stix2_contents[0],
                                                    stip_user.language)
    else:
        granular_markings = None

    # StipSns Object (Custom Object)
    stip_sns = StipSns(lang=common_lang,
                       granular_markings=granular_markings,
                       object_marking_refs=[tlp_marking_object],
                       created_by_ref=individual_identity,
                       name=title,
                       description=content,
                       x_stip_sns_type='post',
                       x_stip_sns_author=x_stip_sns_author,
                       x_stip_sns_post=x_stip_sns_post,
                       x_stip_sns_attachment_refs=x_stip_sns_attachment_refs,
                       x_stip_sns_object_ref=x_stip_sns_object_ref,
                       x_stip_sns_tags=x_stip_sns_tags,
                       x_stip_sns_indicators=x_stip_sns_indicators,
                       x_stip_sns_identity=x_stip_sns_identity,
                       x_stip_sns_tool=x_stip_sns_tool)
    report_object_refs.append(stip_sns)
    bundle.objects.append(stip_sns)

    # ReportObject
    published = format_stix2_datetime(datetime.datetime.now(tz=pytz.utc))
    report = Report(lang=common_lang,
                    granular_markings=granular_markings,
                    object_marking_refs=[tlp_marking_object],
                    name=title,
                    description=content,
                    created_by_ref=individual_identity,
                    published=published,
                    report_types=['threat-report'],
                    object_refs=report_object_refs)
    bundle.objects.append(report)

    # language-content 作成
    if granular_markings is None:
        # S-TIP オブジェクト用の language-content 作成
        language_contents = _get_language_contents(stix2_titles,
                                                   stix2_contents)
        if common_lang in language_contents:
            del language_contents[common_lang]

        if language_contents != {}:
            s_tip_lc = LanguageContent(created_by_ref=individual_identity,
                                       object_ref=stip_sns,
                                       object_modified=stip_sns.created,
                                       contents=language_contents)
            bundle.objects.append(s_tip_lc)

            # Report オブジェクト用の language-content 作成
            report_lc = LanguageContent(object_ref=report,
                                        created_by_ref=individual_identity,
                                        object_modified=report.created,
                                        contents=language_contents)
            bundle.objects.append(report_lc)
    return bundle