Пример #1
0
def count_by_type(request):
    try:
        if request.method != 'GET':
            return HttpResponseNotAllowed(['GET'])

        ret_types = [
            ('Packages', StixFiles.objects.count()),
            ('Campaigns', StixCampaigns.objects.count()),
            ('Incidents', StixIncidents.objects.count()),
            ('Indicators', StixIndicators.objects.count()),
            ('Observables', StixObservables.objects.count()),
            ('Threat Actors', StixThreatActors.objects.count()),
            ('Exploit Targets', StixExploitTargets.objects.count()),
            ('Courses Of Action', StixCoursesOfAction.objects.count()),
            ('TTPs', StixTTPs.objects.count()),
        ]
        resp = get_normal_response_json()
        resp['data'] = []
        for ret_type in ret_types:
            type_, count_ = ret_type
            d = {'type': type_, 'count': count_}
            resp['data'].append(d)
        return JsonResponse(resp)
    except Exception as e:
        traceback.print_exc()
        return error(e)
Пример #2
0
def stix_file_l1_info(request,package_id):
    try:
        if request.method != 'GET':
            return HttpResponseNotAllowed(['GET'])
        #認証する
        user = authentication(request)
        if user is None:
            return error(Exception('You have no permission for this operation.'))
     
        #該当するキャッシュを検索する
        caches = ObservableCaches.objects.filter(package_id=package_id)
        #返却データを作成する
        data = []
        for cache in caches:
            r = {
                'type'          :   cache.type,
                'value'         :   cache.value,
                'observable_id' :   cache.observable_id,
            }
            data.append(r)
        #response data 作成
        resp = get_normal_response_json()
        resp['data'] = data
        return JsonResponse(resp)
    except Exception as e:
        traceback.print_exc()
        return error(e)
Пример #3
0
def package_name_list(request):
    LIMIT_KEY = 'limit'
    try:
        if request.method != 'GET':
            return HttpResponseNotAllowed(['GET'])
        #認証する
        user = authentication(request)
        if user is None:
            return error(Exception('You have no permission for this operation.'))

        #全取得
        stix_files = StixFiles.objects.filter(Q(is_post_sns__ne=False)).only('package_name','package_id').order_by('package_name')
                
        #limit取得
        try:
            limit = int(request.GET[LIMIT_KEY])
        except:
            limit = None
        #指定があれば上位の指定数だけを返却する
        if limit is not None:
            stix_files = stix_files[:limit]
            
        rsp_stix_files = []
        #返却データ作成
        for stix_file in stix_files:
            rsp_stix_files.append(stix_file.get_rest_api_package_name_info())
        resp = get_normal_response_json()
        resp['data'] = rsp_stix_files
        return JsonResponse(resp)
    except Exception as e:
        traceback.print_exc()
        return error(e)
Пример #4
0
def matched_packages(request):
    PACKAGE_ID_KEY = 'package_id'
    EXACT_KEY = 'exact'
    SIMILAR_IPV4_KEY = 'similar_ipv4'
    SIMILAR_DOMAIN_KEY = 'similar_domain'
    try:
        if request.method != 'GET':
            return HttpResponseNotAllowed(['GET'])

        package_id = request.GET[PACKAGE_ID_KEY]
        exact = get_boolean_value(request.GET, EXACT_KEY, True)
        similar_ipv4 = get_boolean_value(request.GET, SIMILAR_IPV4_KEY, False)
        similar_domain = get_boolean_value(request.GET, SIMILAR_DOMAIN_KEY,
                                           False)

        ret = get_matched_packages(package_id,
                                   exact=exact,
                                   similar_ipv4=similar_ipv4,
                                   similar_domain=similar_domain)
        resp = get_normal_response_json()
        resp['data'] = ret
        return JsonResponse(resp)
    except Exception as e:
        traceback.print_exc()
        return error(e)
Пример #5
0
def latest_stix_count_by_community(request):
    LASTEST_DAYS_KEY = 'latest_days'
    DEFAULT_LATEST_DAYS = 7
    try:
        if request.method != 'GET':
            return HttpResponseNotAllowed(['GET'])
        #認証する
        user = authentication(request)
        if user is None:
            return error(Exception('You have no permission for this operation.'))
        #最新何日からカウントするか取得する
        try:
            latest_days = int(request.GET[LASTEST_DAYS_KEY])
        except:
            latest_days = DEFAULT_LATEST_DAYS
        #返却データ作成
        resp = get_normal_response_json()
        resp['data'] = []
        #communityごとにカウントする
        for community in Communities.objects.all():
            count = count_by_community(community,latest_days)
            d = {
                'community' :   community.name,
                'count'     :   count
            }
            resp['data'].append(d)
        return JsonResponse(resp)
    except Exception as e:
        traceback.print_exc()
        return error(e)
Пример #6
0
def sighting(request, observed_data_id):
    # apikey認証
    ctirs_auth_user = authentication(request)
    if ctirs_auth_user is None:
        return error(Exception('You have no permission for this operation.'))
    first_seen = get_api_stix_files_v2_sighting_first_seen(request)
    last_seen = get_api_stix_files_v2_sighting_last_seen(request)
    count = get_api_stix_files_v2_sighting_count(request)
    # first_seen, last_seen, optional とも option
    try:
        if request.method != 'POST':
            return HttpResponseNotAllowed(['POST'])

        # SightingObjects 作成
        sighting_id, content = StixSightings.create_by_observed_id(
            first_seen, last_seen, count, observed_data_id, ctirs_auth_user)

        resp = get_normal_response_json()
        d = {}
        d['sighting_object_id'] = sighting_id
        d['sighting_object_json'] = content
        resp['data'] = d
        return JsonResponse(resp, status=201, safe=False)

    except Exception as e:
        traceback.print_exc()
        return error(e)
Пример #7
0
def _get_object_main(request, object_id):
    object_ = get_object(object_id)
    resp = get_normal_response_json()
    if object_:
        resp['data'] = object_
    else:
        resp['data'] = None
    return JsonResponse(resp, status=200, safe=False)
Пример #8
0
def get_stix_files_id(request, package_id):
    try:
        stix_file = StixFiles.objects.get(package_id=package_id)
        resp = get_normal_response_json()
        resp['data'] = stix_file.to_dict()
        return JsonResponse(resp)
    except Exception as e:
        traceback.print_exc()
        return error(e)
Пример #9
0
def stix_file_stix(request, package_id):
    try:
        if request.method != 'GET':
            return HttpResponseNotAllowed(['GET'])
        resp = get_normal_response_json()
        stix_file = StixFiles.objects.get(package_id=package_id)
        resp['data'] = _get_stix_content_dict(stix_file)
        return JsonResponse(resp)
    except Exception as e:
        traceback.print_exc()
        return error(e)
Пример #10
0
def communities(request):
    try:
        if request.method != 'GET':
            return HttpResponseNotAllowed(['GET'])

        resp = get_normal_response_json()
        resp['data'] = []
        for community in Communities.objects.all():
            resp['data'].append(community.to_dict())
        return JsonResponse(resp)
    except Exception as e:
        traceback.print_exc()
        return error(e)
Пример #11
0
def _delete_object_main(request, object_id):
    doc = _get_document(object_id)
    if not doc:
        return error(Exception(object_id + ' does not exist.'))
    try:
        delete_stix_file_package_id_document_info(doc.package_id)
        resp = get_normal_response_json()
        resp['data'] = {'remove_package_id': doc.package_id}
        return JsonResponse(resp, status=200, safe=False)
    except Exception as e:
        import traceback
        traceback.print_exc()
        return error(e)
Пример #12
0
def package_list_for_sharing_table(request):
    try:
        if request.method != 'GET':
            return HttpResponseNotAllowed(['GET'])

        iDisplayLength = int(request.GET['iDisplayLength'])
        iDisplayStart = int(request.GET['iDisplayStart'])
        sSearch = request.GET['sSearch']
        sort_col = int(request.GET['iSortCol'])
        sort_dir = request.GET['sSortDir']

        order_query = None
        SORT_INDEX_PACKAGE_NAME = 3

        if sort_col == SORT_INDEX_PACKAGE_NAME:
            order_query = 'package_name'

        if order_query is not None:
            if sort_dir == 'desc':
                order_query = '-' + order_query

        community_objects = Communities.objects.filter(name__icontains=sSearch)
        objects = StixFiles.objects.filter(
            Q(package_name__icontains=sSearch)
            | Q(input_community__in=community_objects)) \
            .order_by(order_query)
        objects = objects.filter(Q(is_post_sns__ne=False))

        data = []
        for d in objects[iDisplayStart:(iDisplayStart + iDisplayLength)]:
            r = {}
            r['comment'] = d.comment
            r['package_name'] = d.package_name
            r['package_id'] = d.package_id
            r['version'] = d.version
            try:
                r['input_community'] = d.input_community.name
            except BaseException:
                r['input_community'] = ''
            data.append(r)

        r_data = {}
        r_data['iTotalRecords'] = StixFiles.objects.count()
        r_data['iTotalDisplayRecords'] = objects.count()
        r_data['data'] = data
        resp = get_normal_response_json()
        resp['data'] = r_data
        return JsonResponse(resp)
    except Exception as e:
        traceback.print_exc()
        return error(e)
Пример #13
0
def package_list(request):
    REQUIRED_COMMENT_KEY = 'required_comment'
    LIMIT_KEY = 'limit'
    ORDER_BY_KEY = 'order_by'
    DEFAULT_ORDER_BY = 'package_name'
    try:
        if request.method != 'GET':
            return HttpResponseNotAllowed(['GET'])
        # 認証する
        user = authentication(request)
        if user is None:
            return error(
                Exception('You have no permission for this operation.'))

        required_comment = False
        if (REQUIRED_COMMENT_KEY in request.GET):
            if request.GET[REQUIRED_COMMENT_KEY].lower() == 'true':
                required_comment = True

        # 全取得
        stix_files = StixFiles.objects.filter()
        # order_by指定があればソートする
        # それ以外に場合はpackage_nameを辞書順でソートする
        if (ORDER_BY_KEY in request.GET):
            try:
                stix_files = stix_files.order_by(request.GET[ORDER_BY_KEY])
            except BaseException:
                stix_files = stix_files.order_by(DEFAULT_ORDER_BY)
        else:
            stix_files = stix_files.order_by(DEFAULT_ORDER_BY)

        # limit取得
        try:
            limit = int(request.GET[LIMIT_KEY])
        except BaseException:
            limit = None
        # 指定があれば上位の指定数だけを返却する
        if limit is not None:
            stix_files = stix_files[:limit]

        rsp_stix_files = []
        # 返却データ作成
        for stix_file in stix_files:
            rsp_stix_files.append(
                stix_file.get_rest_api_document_info(required_comment))
        resp = get_normal_response_json()
        resp['data'] = rsp_stix_files
        return JsonResponse(resp)
    except Exception as e:
        traceback.print_exc()
        return error(e)
Пример #14
0
def stix_file_stix(request,package_id):
    try:
        if request.method != 'GET':
            return HttpResponseNotAllowed(['GET'])
        #認証する
        user = authentication(request)
        if user is None:
            return error(Exception('You have no permission for this operation.'))
        resp = get_normal_response_json()
        stix_file = StixFiles.objects.get(package_id=package_id)
        resp['data'] = _get_stix_content_dict(stix_file)
        return JsonResponse(resp)
    except Exception as e:
        traceback.print_exc()
        return error(e)
Пример #15
0
def get_stix_files_id(request,package_id):
    try:
        #認証する
        user = authentication(request)
        if user is None:
            return error(Exception('You have no permission for this operation.'))
        #検索
        stix_file = StixFiles.objects.get(package_id=package_id)
        #response data 作成
        resp = get_normal_response_json()
        resp['data'] = stix_file.to_dict()
        return JsonResponse(resp)
    except Exception as e:
        traceback.print_exc()
        return error(e)
Пример #16
0
def get_language_contents(request, object_ref):
    try:
        object_modified = request.GET['object_modified']
        objects = StixLanguageContents.objects.filter(
            Q(object_ref=object_ref)
            & Q(object_modified=object_modified)).order_by('-modified')
        language_contents = []
        for o_ in objects:
            language_contents.append(o_.object_)
        resp = get_normal_response_json()
        resp['data'] = language_contents
        return JsonResponse(resp)
    except Exception as e:
        traceback.print_exc()
        return error(e)
Пример #17
0
def communities(request):
    try:
        if request.method != 'GET':
            return HttpResponseNotAllowed(['GET'])
        #認証する
        user = authentication(request)
        if user is None:
            return error(Exception('You have no permission for this operation.'))
        resp = get_normal_response_json()
        resp['data'] = []
        for community in Communities.objects.all():
            resp['data'].append(community.to_dict())
        return JsonResponse(resp)
    except Exception as e:
        traceback.print_exc()
        return error(e)
Пример #18
0
def language_contents(request):
    try:
        if request.method != 'GET':
            return HttpResponseNotAllowed(['GET'])
        object_ref = request.GET['object_ref']
        object_modified = request.GET['object_modified']
        objects = StixLanguageContents.objects.filter(
            Q(object_ref=object_ref)
            & Q(object_modified=object_modified)).order_by('-modified')
        language_contents = []
        for o_ in objects:
            language_contents.append(o_.object_)
        resp = get_normal_response_json()
        resp['data'] = language_contents
        return JsonResponse(resp)
    except Exception as e:
        traceback.print_exc()
        return error(e)
Пример #19
0
def latest_package_list(request):
    DEFAULT_LATEST_NUM = 10
    try:
        if request.method != 'GET':
            return HttpResponseNotAllowed(['GET'])

        try:
            num = int(request.GET['num'])
        except BaseException:
            num = DEFAULT_LATEST_NUM

        resp = get_normal_response_json()
        resp['data'] = []
        for stix_file in StixFiles.objects.order_by('-produced')[:num]:
            resp['data'].append(stix_file.get_rest_api_document_info())
        return JsonResponse(resp)
    except Exception as e:
        traceback.print_exc()
        return error(e)
Пример #20
0
def get_object_main(request, object_id):
    # apikey認証
    ctirs_auth_user = authentication(request)
    if ctirs_auth_user is None:
        return error(Exception('You have no permission for this operation.'))
    try:
        if request.method != 'GET':
            return HttpResponseNotAllowed(['GET'])
        object_ = get_object(object_id)
        resp = get_normal_response_json()
        if object_ is None:
            resp['data'] = None
        else:
            resp['data'] = object_
        return JsonResponse(resp, status=200, safe=False)
    except Exception as e:
        import traceback
        traceback.print_exc()
        return error(e)
Пример #21
0
def stix_file_l1_info(request, package_id):
    try:
        if request.method != 'GET':
            return HttpResponseNotAllowed(['GET'])

        caches = ObservableCaches.objects.filter(package_id=package_id)
        data = []
        for cache in caches:
            r = {
                'type': cache.type,
                'value': cache.value,
                'observable_id': cache.observable_id,
            }
            data.append(r)
        resp = get_normal_response_json()
        resp['data'] = data
        return JsonResponse(resp)
    except Exception as e:
        traceback.print_exc()
        return error(e)
Пример #22
0
def latest_stix_count_by_community(request):
    LASTEST_DAYS_KEY = 'latest_days'
    DEFAULT_LATEST_DAYS = 7
    try:
        if request.method != 'GET':
            return HttpResponseNotAllowed(['GET'])

        try:
            latest_days = int(request.GET[LASTEST_DAYS_KEY])
        except BaseException:
            latest_days = DEFAULT_LATEST_DAYS
        resp = get_normal_response_json()
        resp['data'] = []
        for community in Communities.objects.all():
            count = count_by_community(community, latest_days)
            d = {'community': community.name, 'count': count}
            resp['data'].append(d)
        return JsonResponse(resp)
    except Exception as e:
        traceback.print_exc()
        return error(e)
Пример #23
0
def package_list(request):
    REQUIRED_COMMENT_KEY = 'required_comment'
    LIMIT_KEY = 'limit'
    ORDER_BY_KEY = 'order_by'
    DEFAULT_ORDER_BY = 'package_name'
    try:
        if request.method != 'GET':
            return HttpResponseNotAllowed(['GET'])

        required_comment = False
        if (REQUIRED_COMMENT_KEY in request.GET):
            if request.GET[REQUIRED_COMMENT_KEY].lower() == 'true':
                required_comment = True

        stix_files = StixFiles.objects.filter()
        if (ORDER_BY_KEY in request.GET):
            try:
                stix_files = stix_files.order_by(request.GET[ORDER_BY_KEY])
            except BaseException:
                stix_files = stix_files.order_by(DEFAULT_ORDER_BY)
        else:
            stix_files = stix_files.order_by(DEFAULT_ORDER_BY)

        try:
            limit = int(request.GET[LIMIT_KEY])
        except BaseException:
            limit = None
        if limit is not None:
            stix_files = stix_files[:limit]

        rsp_stix_files = []
        for stix_file in stix_files:
            rsp_stix_files.append(
                stix_file.get_rest_api_document_info(required_comment))
        resp = get_normal_response_json()
        resp['data'] = rsp_stix_files
        return JsonResponse(resp)
    except Exception as e:
        traceback.print_exc()
        return error(e)
Пример #24
0
def language_contents(request):
    try:
        if request.method != 'GET':
            return HttpResponseNotAllowed(['GET'])
        #認証する
        user = authentication(request)
        if user is None:
            return error(Exception('You have no permission for this operation.'))
        #表示する長さ
        object_ref = request.GET['object_ref']
        object_modified = request.GET['object_modified']
        objects = StixLanguageContents.objects.filter(
            Q(object_ref=object_ref)&
            Q(object_modified=object_modified)).order_by('-modified')
        language_contents = []
        for o_ in objects:
            language_contents.append(o_.object_)
        resp = get_normal_response_json()
        resp['data'] = language_contents
        return JsonResponse(resp)
    except Exception as e:
        traceback.print_exc()
        return error(e)    
Пример #25
0
def latest_package_list(request):
    DEFAULT_LATEST_NUM = 10
    try:
        if request.method != 'GET':
            return HttpResponseNotAllowed(['GET'])
        #認証する
        user = authentication(request)
        if user is None:
            return error(Exception('You have no permission for this operation.'))
        try:
            num = int(request.GET['num'])
        except:
            num = DEFAULT_LATEST_NUM
       
        resp = get_normal_response_json()
        resp['data'] = []
        #producedを降順でソート
        for stix_file in  StixFiles.objects.order_by('-produced')[:num]:
            resp['data'] .append(stix_file.get_rest_api_document_info())
        return JsonResponse(resp)
    except Exception as e:
        traceback.print_exc()
        return error(e)
Пример #26
0
def search_bundle(request):
    SEARCH_KEY_OBJECT_ID = 'match[object_id]'
    try:
        if request.method != 'GET':
            return HttpResponseNotAllowed(['GET'])
        package_id_list = []
        if SEARCH_KEY_OBJECT_ID in request.GET.keys():
            object_id = request.GET[SEARCH_KEY_OBJECT_ID]
            doc = _get_document(object_id)
            package_id_list.append(doc.package_id)
        else:
            for doc in StixFiles.objects.filter(
                    version__startswith='2.').order_by('-modified'):
                if doc.package_id not in package_id_list:
                    package_id_list.append(doc.package_id)
        resp = get_normal_response_json()
        d = {}
        d['package_id_list'] = package_id_list
        resp['data'] = d
        return JsonResponse(resp, safe=False)
    except Exception as e:
        import traceback
        traceback.print_exc()
        return error(e)
Пример #27
0
def package_name_list(request):
    LIMIT_KEY = 'limit'
    try:
        if request.method != 'GET':
            return HttpResponseNotAllowed(['GET'])

        stix_files = StixFiles.objects.filter(Q(is_post_sns__ne=False)).only(
            'package_name', 'package_id').order_by('package_name')
        try:
            limit = int(request.GET[LIMIT_KEY])
        except BaseException:
            limit = None
        if limit is not None:
            stix_files = stix_files[:limit]

        rsp_stix_files = []
        for stix_file in stix_files:
            rsp_stix_files.append(stix_file.get_rest_api_package_name_info())
        resp = get_normal_response_json()
        resp['data'] = rsp_stix_files
        return JsonResponse(resp)
    except Exception as e:
        traceback.print_exc()
        return error(e)
Пример #28
0
def contents_and_edges(request):
    PACKAGE_ID_KEY = 'package_id'
    COMPARED_PACKAGE_IDS_KEY = 'compared_package_ids'
    EXACT_KEY = 'exact'
    SIMILAR_IPV4_KEY = 'similar_ipv4'
    SIMILAR_DOMAIN_KEY = 'similar_domain'
    try:
        if request.method != 'GET':
            return HttpResponseNotAllowed(['GET'])

        package_id = request.GET[PACKAGE_ID_KEY]
        compared_package_ids = request.GET.getlist(COMPARED_PACKAGE_IDS_KEY)
        exact = get_boolean_value(request.GET, EXACT_KEY, True)
        similar_ipv4 = get_boolean_value(request.GET, SIMILAR_IPV4_KEY, False)
        similar_domain = get_boolean_value(request.GET, SIMILAR_DOMAIN_KEY,
                                           False)

        edges = []

        fuzzy_infos = _get_fuzzy_matched_info(package_id)
        for fuzzy_info in fuzzy_infos:
            if fuzzy_info.end_node['package_id'] not in compared_package_ids:
                continue
            start_node = fuzzy_info.start_node
            end_node = fuzzy_info.end_node
            edge = {
                'edge_type': fuzzy_info.reason['title'],
                'start_node': start_node,
                'end_node': end_node,
                'reason': fuzzy_info.reason,
            }
            edges.append(edge)

        if exact:
            end_infos = _get_exact_matched_info(package_id)
            for end_info in end_infos:
                if end_info.package_id not in compared_package_ids:
                    continue
                end_node = {
                    'package_id': end_info.package_id,
                    'node_id': end_info.node_id
                }

                if hasattr(end_info, 'start_collection'):
                    collection = end_info.start_collection
                else:
                    collection = type(end_info)
                if collection == IndicatorV2Caches:
                    start_caches = collection.objects.filter(
                        package_id=package_id, pattern=end_info.pattern)
                elif collection == LabelCaches:
                    start_caches = collection.objects.filter(
                        package_id=package_id, label__iexact=end_info.label)
                elif collection == CustomObjectCaches:
                    if hasattr(end_info, 'start_type'):
                        start_type = end_info.start_type
                    else:
                        start_type = end_info.type
                    start_caches = collection.objects.filter(
                        package_id=package_id,
                        type=start_type,
                        value=end_info.value)
                else:
                    start_caches = collection.objects.filter(
                        package_id=package_id,
                        type=end_info.type,
                        value=end_info.value)
                for start_cache in start_caches:
                    start_node = {
                        'package_id': package_id,
                        'node_id': start_cache.node_id
                    }
                    edge = {
                        'edge_type': EXACT_EDGE_TYPE,
                        'start_node': start_node,
                        'end_node': end_node
                    }
                    edges.append(edge)

        if similar_ipv4:
            end_infos = _get_similar_ipv4(package_id)
            for end_info in end_infos:
                end_cache = end_info['cache']
                if end_cache.package_id not in compared_package_ids:
                    continue
                end_node = {
                    'package_id': end_cache.package_id,
                    'node_id': end_cache.node_id
                }
                source_value = end_info['source_value']
                start_caches = ObservableCaches.objects.filter(
                    package_id=package_id,
                    type=end_cache.type,
                    value=source_value)
                for start_cache in start_caches:
                    start_node = {
                        'package_id': package_id,
                        'node_id': start_cache.node_id
                    }
                    edge_type = _get_ipv4_similarity_type(
                        start_cache, end_cache)
                    edge = {
                        'edge_type': edge_type,
                        'start_node': start_node,
                        'end_node': end_node
                    }
                    edges.append(edge)

        if similar_domain:
            end_infos = _get_similar_domain(package_id)
            for end_info in end_infos:
                end_cache = end_info['cache']
                if end_cache.package_id not in compared_package_ids:
                    continue
                end_node = {
                    'package_id': end_cache.package_id,
                    'node_id': end_cache.node_id
                }
                source_value = end_info['source_value']
                start_caches = ObservableCaches.objects.filter(
                    package_id=package_id,
                    type=end_cache.type,
                    value=source_value)
                for start_cache in start_caches:
                    edge_type = _get_domain_similarity_type(
                        start_cache, end_cache)
                    if edge_type is None:
                        continue
                    start_node = {
                        'package_id': package_id,
                        'node_id': start_cache.node_id
                    }
                    edge = {
                        'edge_type': edge_type,
                        'start_node': start_node,
                        'end_node': end_node
                    }
                    edges.append(edge)

        contents = []
        contents.append(_get_contents_item(package_id))
        for compared_package_id in compared_package_ids:
            contents.append(_get_contents_item(compared_package_id))

        data = {}
        data['contents'] = contents
        data['edges'] = edges

        resp = get_normal_response_json()
        resp['data'] = data
        return JsonResponse(resp)
    except Exception as e:
        traceback.print_exc()
        return error(e)
Пример #29
0
def l1_info_for_l1table(request):
    try:
        if request.method != 'GET':
            return HttpResponseNotAllowed(['GET'])

        iDisplayLength = int(request.GET['iDisplayLength'])
        iDisplayStart = int(request.GET['iDisplayStart'])
        sSearch = request.GET['sSearch']
        sort_col = int(request.GET['iSortCol'])
        sort_dir = request.GET['sSortDir']
        try:
            aliases_str = request.GET['aliases']
            alias_lists = json.loads(aliases_str)
        except BaseException:
            alias_lists = []

        order_query = None

        SORT_INDEX_TYPE = 0
        SORT_INDEX_VALUE = 1
        SORT_INDEX_PACKAGE_NAME = 2
        SORT_INDEX_TILE = 3
        SORT_INDEX_DESCRIPTION = 4
        SORT_INDEX_TIMESTAMP = 5

        if sort_col == SORT_INDEX_TYPE:
            order_query = 'type'
        elif sort_col == SORT_INDEX_VALUE:
            order_query = 'value'
        elif sort_col == SORT_INDEX_PACKAGE_NAME:
            order_query = 'package_name'
        elif sort_col == SORT_INDEX_TILE:
            order_query = 'title'
        elif sort_col == SORT_INDEX_DESCRIPTION:
            order_query = 'description'
        elif sort_col == SORT_INDEX_TIMESTAMP:
            order_query = 'produced'

        if order_query is not None:
            if sort_dir == 'desc':
                order_query = '-' + order_query

        tmp_sSearches = list(set(sSearch.split(' ')))
        if '' in tmp_sSearches:
            tmp_sSearches.remove('')

        sSearches = []
        for item in tmp_sSearches:
            sSearches.append(item)
            for alias_list in alias_lists:
                if item in alias_list:
                    sSearches.extend(alias_list)

        sSearches = list(set(sSearches))

        filters = Q()
        for sSearch in sSearches:
            filters = filters | Q(type__icontains=sSearch)
            filters = filters | Q(value__icontains=sSearch)
            filters = filters | Q(package_name__icontains=sSearch)
            filters = filters | Q(title__icontains=sSearch)
            filters = filters | Q(description__icontains=sSearch)
        objects = ObservableCaches.objects.filter(filters).order_by(
            order_query)

        data = []
        for d in objects[iDisplayStart:(iDisplayStart + iDisplayLength)]:
            r = {}
            r['type'] = d.type
            r['value'] = d.value
            r['package_name'] = d.package_name
            r['package_id'] = d.stix_file.package_id
            r['title'] = d.title
            r['description'] = d.description
            r['created'] = str(d.created)
            r['stix_v2'] = d.stix_file.is_stix_v2()
            r['observable_id'] = d.observable_id
            data.append(r)

        r_data = {}
        r_data['iTotalRecords'] = ObservableCaches.objects.count()
        r_data['iTotalDisplayRecords'] = objects.count()
        r_data['data'] = data
        resp = get_normal_response_json()
        resp['data'] = r_data
        return JsonResponse(resp)
    except Exception as e:
        traceback.print_exc()
        return error(e)
Пример #30
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['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_
                # 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):
                    # 空要素で初期化し、該当 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):
                    # 空辞書で初期化し、該当 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_['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()
        # 登録処理
        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)