Exemplo n.º 1
0
def upload_attach(request, email_id):
    """
    Upload an attachment for an email.

    :param request: Django request object (Required)
    :type request: :class:`django.http.HttpRequest`
    :param email_id: The ObjectId of the email to upload attachment for.
    :type email_id: str
    :returns: :class:`django.http.HttpResponse`
    """

    if request.method == 'POST':
        form = UploadFileForm(request.user, request.POST, request.FILES)
        if form.is_valid():
            cleaned_data = form.cleaned_data
            analyst = request.user.username
            users_sources = user_sources(analyst)
            method = cleaned_data['method'] or "Add to Email"
            bucket_list = cleaned_data.get(form_consts.Common.BUCKET_LIST_VARIABLE_NAME)
            ticket = cleaned_data.get(form_consts.Common.TICKET_VARIABLE_NAME)
            email_addr = None
            if request.POST.get('email'):
                email_addr = request.user.email
            email = Email.objects(id=email_id, source__name__in=users_sources).first()
            if not email:
                return render_to_response('file_upload_response.html',
                                          {'response': json.dumps({'success': False,
                                                                   'message': "Could not find email."})},
                                          RequestContext(request))
            result = create_email_attachment(email,
                                             cleaned_data,
                                             analyst,
                                             cleaned_data['source'],
                                             method,
                                             cleaned_data['reference'],
                                             cleaned_data['campaign'],
                                             cleaned_data['confidence'],
                                             bucket_list,
                                             ticket,
                                             request.FILES.get('filedata',None),
                                             request.POST.get('filename', None),
                                             request.POST.get('md5', None),
                                             email_addr,
                                             cleaned_data['inherit_sources'])

            # If successful, tell the browser to redirect back to this email.
            if result['success']:
                result['redirect_url'] = reverse('crits.emails.views.email_detail', args=[email_id])
            return render_to_response('file_upload_response.html',
                                      {'response': json.dumps(result)},
                                      RequestContext(request))
        else:
            form.fields['related_md5'].widget = forms.HiddenInput() #hide field so it doesn't reappear
            return render_to_response('file_upload_response.html',
                                      {'response': json.dumps({'success': False,
                                                               'form': form.as_table()})},
                                      RequestContext(request))
    else:
        return HttpResponseRedirect(reverse('crits.emails.views.email_detail',
                                            args=[email_id]))
Exemplo n.º 2
0
def upload_sample(request, event_id):
    """
    Upload a sample to associate with this event.

    :param request: Django request object (Required)
    :type request: :class:`django.http.HttpRequest`
    :param event_id: The ObjectId of the event to associate with this sample.
    :type event_id: str
    :returns: :class:`django.http.HttpResponse`, :class:`django.http.HttpResponse`
    """

    if request.method == 'POST':  # and request.is_ajax():
        form = UploadFileForm(request.user, request.POST, request.FILES)
        if form.is_valid():
            email = None
            if request.POST.get('email'):
                email = request.user.email

            result = add_sample_for_event(event_id, form.cleaned_data,
                                          request.user.username,
                                          request.FILES.get('filedata', None),
                                          request.POST.get('filename', None),
                                          request.POST.get('md5', None), email,
                                          form.cleaned_data['inherit_sources'])
            if result['success']:
                result['redirect_url'] = reverse(
                    'crits.events.views.view_event', args=[event_id])
            return render_to_response('file_upload_response.html',
                                      {'response': json.dumps(result)},
                                      RequestContext(request))
        else:
            form.fields['related_md5'].widget = forms.HiddenInput(
            )  #hide field so it doesn't reappear
            return render_to_response(
                'file_upload_response.html', {
                    'response':
                    json.dumps({
                        'success': False,
                        'form': form.as_table()
                    })
                }, RequestContext(request))
    else:
        return HttpResponseRedirect(
            reverse('crits.events.views.view_event', args=[event_id]))
Exemplo n.º 3
0
Arquivo: views.py Projeto: ckane/crits
def upload_sample(request, event_id):
    """
    Upload a sample to associate with this event.

    :param request: Django request object (Required)
    :type request: :class:`django.http.HttpRequest`
    :param event_id: The ObjectId of the event to associate with this sample.
    :type event_id: str
    :returns: :class:`django.http.HttpResponse`, :class:`django.http.HttpResponse`
    """

    if request.method == 'POST':    # and request.is_ajax():
        form = UploadFileForm(request.user, request.POST, request.FILES)
        if form.is_valid():
            email = None
            if request.POST.get('email'):
                email = request.user.email

            result = add_sample_for_event(event_id,
                                          form.cleaned_data,
                                          request.user.username,
                                          request.FILES.get('filedata', None),
                                          request.POST.get('filename', None),
                                          request.POST.get('md5', None),
                                          email,
                                          form.cleaned_data['inherit_sources'])
            if result['success']:
                result['redirect_url'] = reverse('crits.events.views.view_event', args=[event_id])
            return render_to_response('file_upload_response.html',
                                      {'response': json.dumps(result)},
                                      RequestContext(request))
        else:
            form.fields['related_md5'].widget = forms.HiddenInput() #hide field so it doesn't reappear
            return render_to_response('file_upload_response.html',
                                      {'response': json.dumps({'success': False,
                                                               'form': form.as_table()})},
                                      RequestContext(request))
    else:
        return HttpResponseRedirect(reverse('crits.events.views.view_event',
                                            args=[event_id]))
Exemplo n.º 4
0
def upload_file(request):
    """
    Upload a new sample.

    :param request: Django request object (Required)
    :type request: :class:`django.http.HttpRequest`
    :returns: :class:`django.http.HttpResponse`
    """

    if request.method == 'POST':
        form = UploadFileForm(request.user, request.POST, request.FILES)
        email_errmsg = None
        if form.is_valid():
            campaign = form.cleaned_data['campaign']
            confidence = form.cleaned_data['confidence']
            source = form.cleaned_data['source']
            reference = form.cleaned_data['reference']
            try:
                if request.FILES:
                    sample_md5 = handle_uploaded_file(
                        request.FILES['filedata'],
                        source,
                        reference,
                        form.cleaned_data['file_format'],
                        form.cleaned_data['password'],
                        user=request.user.username,
                        campaign=campaign,
                        confidence=confidence,
                        parent_md5 = form.cleaned_data['parent_md5'],
                        bucket_list=form.cleaned_data[form_consts.Common.BUCKET_LIST_VARIABLE_NAME],
                        ticket=form.cleaned_data[form_consts.Common.TICKET_VARIABLE_NAME])
                else:
                    filename = request.POST['filename'].strip()
                    md5 = request.POST['md5'].strip().lower()
                    sample_md5 = handle_uploaded_file(
                        None,
                        source,
                        reference,
                        form.cleaned_data['file_format'],
                        None,
                        user=request.user.username,
                        campaign=campaign,
                        confidence=confidence,
                        parent_md5 = form.cleaned_data['parent_md5'],
                        filename=filename,
                        md5=md5,
                        bucket_list=form.cleaned_data[form_consts.Common.BUCKET_LIST_VARIABLE_NAME],
                        ticket=form.cleaned_data[form_consts.Common.TICKET_VARIABLE_NAME],
                        is_return_only_md5=False)

                if 'email' in request.POST:
                    for s in sample_md5:
                        email_errmsg = mail_sample(s, [request.user.email])
            except ZipFileError, zfe:
                return render_to_response('file_upload_response.html',
                                          {'response': json.dumps({'success': False,
                                                                   'message': zfe.value})},
                                          RequestContext(request))
            else:
                response = {'success': False,
                            'message': 'Unknown error; unable to upload file.'}
                if len(sample_md5) > 1:
                    filedata = request.FILES['filedata']
                    message = ('<a href="%s">View Uploaded Samples.</a>'
                               % reverse('crits.samples.views.view_upload_list',
                                         args=[filedata.name, sample_md5]))
                    response = {'success': True,
                                'message': message }
                elif len(sample_md5) == 1:
                    md5_response = None
                    if not request.FILES:
                        response['success'] = sample_md5[0].get('success', False)
                        if(response['success'] == False):
                            response['message'] = sample_md5[0].get('message', response.get('message'))
                        else:
                            md5_response = sample_md5[0].get('object').md5
                    else:
                        md5_response = sample_md5[0]
                        response['success'] = True

                    if md5_response != None:
                        response['message'] = ('File uploaded successfully. <a href="%s">View Sample.</a>'
                                               % reverse('crits.samples.views.detail',
                                                         args=[md5_response]))

                if email_errmsg is not None:
                    msg = "<br>Error sending email: %s" % email_errmsg
                    response['message'] = response['message'] + msg

                return render_to_response("file_upload_response.html",
                                          {'response': json.dumps(response)},
                                          RequestContext(request))
        else:
            return render_to_response('file_upload_response.html',
                                      {'response': json.dumps({'success': False,
                                                               'form': form.as_table()})},
                                      RequestContext(request))
Exemplo n.º 5
0
def upload_file(request, related_md5=None):
    """
    Upload a new sample.

    :param request: Django request object (Required)
    :type request: :class:`django.http.HttpRequest`
    :param related_md5: The MD5 of a related sample.
    :type related_md5: str
    :returns: :class:`django.http.HttpResponse`
    """
    if request.method == 'POST':
        form = UploadFileForm(request.user, request.POST, request.FILES)
        email_errmsg = None
        if form.is_valid():
            response = {
                'success': False,
                'message': 'Unknown error; unable to upload file.'
            }
            inherited_source = None
            backdoor = form.cleaned_data['backdoor']
            campaign = form.cleaned_data['campaign']
            confidence = form.cleaned_data['confidence']
            source = form.cleaned_data['source_name']
            source_method = form.cleaned_data['source_method']
            source_reference = form.cleaned_data['source_reference']
            source_tlp = form.cleaned_data['source_tlp']
            user = request.user
            description = form.cleaned_data['description']
            related_id = form.cleaned_data.get('related_id', None)
            related_type = form.cleaned_data.get('related_type', None)
            relationship_type = form.cleaned_data.get('relationship_type',
                                                      None)

            if related_md5:
                reload_page = True
            else:
                reload_page = False
                related_md5 = form.cleaned_data['related_md5']

            if related_md5:
                related_sample = Sample.objects(md5=related_md5).first()
                if not related_sample:
                    response['message'] = (
                        "Upload Failed. Unable to locate related sample. %s" %
                        related_md5)
                    return render(request, "file_upload_response.html",
                                  {'response': json.dumps(response)})
                # If selected, new sample inherits the campaigns of the related sample.
                if form.cleaned_data['inherit_campaigns']:
                    if campaign:
                        related_sample.campaign.append(
                            EmbeddedCampaign(name=campaign,
                                             confidence=confidence,
                                             analyst=user))
                    campaign = related_sample.campaign
                # If selected, new sample inherits the sources of the related sample
                if form.cleaned_data['inherit_sources']:
                    inherited_source = related_sample.source

            elif related_id:
                related_obj = class_from_id(related_type, related_id)
                if not related_obj:
                    response['success'] = False
                    response['message'] = (
                        "Upload Failed. Unable to locate related Item")
                    return render(
                        request,
                        "file_upload_response.html",
                        {'response': json.dumps(response)},
                    )

                else:
                    if form.cleaned_data['inherit_campaigns']:
                        if campaign:
                            related_obj.campaign.append(
                                EmbeddedCampaign(name=campaign,
                                                 confidence=confidence,
                                                 analyst=user))
                        campaign = related_obj.campaign

                    if form.cleaned_data['inherit_sources']:
                        inherited_source = related_obj.source

            backdoor_name = None
            backdoor_version = None
            if backdoor:
                backdoor = backdoor.split('|||')
                if len(backdoor) == 2:
                    (backdoor_name,
                     backdoor_version) = backdoor[0], backdoor[1]

            try:
                if request.FILES:
                    result = handle_uploaded_file(
                        request.FILES['filedata'],
                        source,
                        source_method=source_method,
                        source_reference=source_reference,
                        source_tlp=source_tlp,
                        file_format=form.cleaned_data['file_format'],
                        password=form.cleaned_data['password'],
                        user=user,
                        campaign=campaign,
                        confidence=confidence,
                        related_md5=related_md5,
                        related_id=related_id,
                        related_type=related_type,
                        relationship_type=relationship_type,
                        bucket_list=form.cleaned_data[
                            form_consts.Common.BUCKET_LIST_VARIABLE_NAME],
                        ticket=form.cleaned_data[
                            form_consts.Common.TICKET_VARIABLE_NAME],
                        inherited_source=inherited_source,
                        backdoor_name=backdoor_name,
                        backdoor_version=backdoor_version,
                        description=description)
                else:
                    result = handle_uploaded_file(
                        None,
                        source,
                        source_method=source_method,
                        source_reference=source_reference,
                        source_tlp=source_tlp,
                        file_format=form.cleaned_data['file_format'],
                        password=None,
                        user=user,
                        campaign=campaign,
                        confidence=confidence,
                        related_md5=related_md5,
                        related_id=related_id,
                        related_type=related_type,
                        relationship_type=relationship_type,
                        filename=request.POST['filename'].strip(),
                        md5=request.POST['md5'].strip().lower(),
                        sha1=request.POST['sha1'].strip().lower(),
                        sha256=request.POST['sha256'].strip().lower(),
                        bucket_list=form.cleaned_data[
                            form_consts.Common.BUCKET_LIST_VARIABLE_NAME],
                        ticket=form.cleaned_data[
                            form_consts.Common.TICKET_VARIABLE_NAME],
                        inherited_source=inherited_source,
                        is_return_only_md5=False,
                        backdoor_name=backdoor_name,
                        backdoor_version=backdoor_version,
                        description=description)

            except ZipFileError, zfe:
                return render(
                    request, 'file_upload_response.html', {
                        'response':
                        json.dumps({
                            'success': False,
                            'message': zfe.value
                        })
                    })
            else:
                # zip file upload, etc; result is a list of strings (1 hash per file)
                if len(result) > 0 and not isinstance(result[0], dict):
                    filedata = request.FILES['filedata']
                    message = ('<a href="%s">View Uploaded Samples.</a>' %
                               reverse('crits-samples-views-view_upload_list',
                                       args=[filedata.name, result]))
                    response = {'success': True, 'message': message}
                    md5_response = result
                # regular file upload; result is a list with a single dict
                else:
                    response['success'] = result[0].get('success', False)
                    response['message'] = result[0].get(
                        'message', response.get('message'))
                    try:
                        md5_response = [result[0].get('object').md5]
                    except:
                        md5_response = None

                if response['success']:
                    if request.POST.get('email') and md5_response:
                        for s in md5_response:
                            email_errmsg = mail_sample(s, [request.user.email])
                            if email_errmsg is not None:
                                msg = "<br>Error emailing sample %s: %s\n" % (
                                    s, email_errmsg)
                                response['message'] = response['message'] + msg
                    if reload_page:
                        response['redirect_url'] = reverse(
                            'crits-samples-views-detail', args=[related_md5])
                return render(request, "file_upload_response.html",
                              {'response': json.dumps(response)})
        else:
            if related_md5:  #if this is a 'related' upload, hide field so it doesn't reappear
                form.fields['related_md5'].widget = forms.HiddenInput()
            return render(
                request, 'file_upload_response.html', {
                    'response':
                    json.dumps({
                        'success': False,
                        'form': form.as_table()
                    })
                })
Exemplo n.º 6
0
def upload_file(request, related_md5=None):
    """
    Upload a new sample.

    :param request: Django request object (Required)
    :type request: :class:`django.http.HttpRequest`
    :param related_md5: The MD5 of a related sample.
    :type related_md5: str
    :returns: :class:`django.http.HttpResponse`
    """

    if request.method == 'POST':
        form = UploadFileForm(request.user, request.POST, request.FILES)
        email_errmsg = None
        if form.is_valid():
            response = {
                'success': False,
                'message': 'Unknown error; unable to upload file.'
            }
            inherited_source = None
            backdoor = form.cleaned_data['backdoor']
            campaign = form.cleaned_data['campaign']
            confidence = form.cleaned_data['confidence']
            source = form.cleaned_data['source']
            method = form.cleaned_data['method']
            reference = form.cleaned_data['reference']
            analyst = request.user.username

            if related_md5:
                reload_page = True
            else:
                reload_page = False
                related_md5 = form.cleaned_data['related_md5']

            if related_md5:
                related_sample = Sample.objects(md5=related_md5).first()
                if not related_sample:
                    response[
                        'message'] = "Upload Failed. Unable to locate related sample."
                    return render_to_response(
                        "file_upload_response.html",
                        {'response': json.dumps(response)},
                        RequestContext(request))
                # If selected, new sample inherits the campaigns of the related sample.
                if form.cleaned_data['inherit_campaigns']:
                    if campaign:
                        related_sample.campaign.append(
                            EmbeddedCampaign(name=campaign,
                                             confidence=confidence,
                                             analyst=analyst))
                    campaign = related_sample.campaign
                # If selected, new sample inherits the sources of the related sample
                if form.cleaned_data['inherit_sources']:
                    inherited_source = related_sample.source

            backdoor_name = None
            backdoor_version = None
            if backdoor:
                backdoor = backdoor.split('|||')
                if len(backdoor) == 2:
                    (backdoor_name,
                     backdoor_version) = backdoor[0], backdoor[1]

            try:
                if request.FILES:
                    result = handle_uploaded_file(
                        request.FILES['filedata'],
                        source,
                        method=method,
                        reference=reference,
                        file_format=form.cleaned_data['file_format'],
                        password=form.cleaned_data['password'],
                        user=analyst,
                        campaign=campaign,
                        confidence=confidence,
                        related_md5=related_md5,
                        bucket_list=form.cleaned_data[
                            form_consts.Common.BUCKET_LIST_VARIABLE_NAME],
                        ticket=form.cleaned_data[
                            form_consts.Common.TICKET_VARIABLE_NAME],
                        inherited_source=inherited_source,
                        backdoor_name=backdoor_name,
                        backdoor_version=backdoor_version)
                else:
                    result = handle_uploaded_file(
                        None,
                        source,
                        method=method,
                        reference=reference,
                        file_format=form.cleaned_data['file_format'],
                        password=None,
                        user=analyst,
                        campaign=campaign,
                        confidence=confidence,
                        related_md5=related_md5,
                        filename=request.POST['filename'].strip(),
                        md5=request.POST['md5'].strip().lower(),
                        sha1=request.POST['sha1'].strip().lower(),
                        sha256=request.POST['sha256'].strip().lower(),
                        bucket_list=form.cleaned_data[
                            form_consts.Common.BUCKET_LIST_VARIABLE_NAME],
                        ticket=form.cleaned_data[
                            form_consts.Common.TICKET_VARIABLE_NAME],
                        inherited_source=inherited_source,
                        is_return_only_md5=False,
                        backdoor_name=backdoor_name,
                        backdoor_version=backdoor_version)

            except ZipFileError, zfe:
                return render_to_response(
                    'file_upload_response.html', {
                        'response':
                        json.dumps({
                            'success': False,
                            'message': zfe.value
                        })
                    }, RequestContext(request))
            else:
                if len(result) > 1:
                    filedata = request.FILES['filedata']
                    message = ('<a href="%s">View Uploaded Samples.</a>' %
                               reverse('crits.samples.views.view_upload_list',
                                       args=[filedata.name, result]))
                    response = {'success': True, 'message': message}
                    md5_response = result
                elif len(result) == 1:
                    md5_response = None
                    if not request.FILES:
                        response['success'] = result[0].get('success', False)
                        if (response['success'] == False):
                            response['message'] = result[0].get(
                                'message', response.get('message'))
                        else:
                            md5_response = [result[0].get('object').md5]
                    else:
                        md5_response = [result[0]]
                        response['success'] = True

                    if md5_response != None:
                        response['message'] = (
                            'File uploaded successfully. <a href="%s">View Sample.</a>'
                            % reverse('crits.samples.views.detail',
                                      args=md5_response))

                if response['success']:
                    if request.POST.get('email'):
                        for s in md5_response:
                            email_errmsg = mail_sample(s, [request.user.email])
                            if email_errmsg is not None:
                                msg = "<br>Error emailing sample %s: %s\n" % (
                                    s, email_errmsg)
                                response['message'] = response['message'] + msg
                    if reload_page:
                        response['redirect_url'] = reverse(
                            'crits.samples.views.detail', args=[related_md5])
                return render_to_response("file_upload_response.html",
                                          {'response': json.dumps(response)},
                                          RequestContext(request))
        else:
            if related_md5:  #if this is a 'related' upload, hide field so it doesn't reappear
                form.fields['related_md5'].widget = forms.HiddenInput()
            return render_to_response(
                'file_upload_response.html', {
                    'response':
                    json.dumps({
                        'success': False,
                        'form': form.as_table()
                    })
                }, RequestContext(request))
Exemplo n.º 7
0
def upload_attach(request, email_id):
    """
    Upload an attachment for an email.

    :param request: Django request object (Required)
    :type request: :class:`django.http.HttpRequest`
    :param email_id: The ObjectId of the email to upload attachment for.
    :type email_id: str
    :returns: :class:`django.http.HttpResponse`
    """

    redirect = reverse('crits-emails-views-email_detail', args=[email_id])
    user = request.user

    if request.method != 'POST':
        return HttpResponseRedirect(redirect)

    file_form = UploadFileForm(request.user, request.POST, request.FILES)
    json_reply = {'success': False}

    if not file_form.is_valid():
        file_form.fields['related_md5_event'].widget = forms.HiddenInput() #hide field so it doesn't reappear
        json_reply['form'] = file_form.as_table()
        return render(request, 'file_upload_response.html', {'response': json.dumps(json_reply)})

    if not user.has_access_to(EmailACL.ADD_ATTACHMENT):
        json_reply['message'] = "User does not have permission to upload attachment."
        return render(request, 'file_upload_response.html',
                                  {'response': json.dumps(json_reply)})


    analyst = request.user.username
    users_sources = user_sources(analyst)
    method = file_form.cleaned_data['method'] or "Add to Email"
    bucket_list = file_form.cleaned_data.get(form_consts.Common.BUCKET_LIST_VARIABLE_NAME)
    ticket = file_form.cleaned_data.get(form_consts.Common.TICKET_VARIABLE_NAME)
    email_addr = None


    if request.POST.get('email'):
        email_addr = request.user.email
    email = Email.objects(id=email_id,
                          source__name__in=users_sources).first()
    if not email:
        json_reply['message'] = "Could not find email."
        return render(request, 'file_upload_response.html', {'response': json.dumps(json_reply)})

    result = create_email_attachment(email,
                                     file_form,
                                     analyst,
                                     file_form.cleaned_data['source'],
                                     method,
                                     file_form.cleaned_data['reference'],
                                     file_form.cleaned_data['campaign'],
                                     file_form.cleaned_data['confidence'],
                                     bucket_list,
                                     ticket,
                                     request.FILES.get('filedata'),
                                     request.POST.get('filename'),
                                     request.POST.get('md5'),
                                     email_addr,
                                     file_form.cleaned_data['inherit_sources'])

    # If successful, tell the browser to redirect back to this email.
    if result['success']:
        result['redirect_url'] = redirect
    return render(request, 'file_upload_response.html', {'response': json.dumps(result)})
Exemplo n.º 8
0
Arquivo: views.py Projeto: 0x3a/crits
def upload_file(request, related_md5=None):
    """
    Upload a new sample.

    :param request: Django request object (Required)
    :type request: :class:`django.http.HttpRequest`
    :param related_md5: The MD5 of a related sample.
    :type related_md5: str
    :returns: :class:`django.http.HttpResponse`
    """

    if request.method == 'POST':
        form = UploadFileForm(request.user, request.POST, request.FILES)
        email_errmsg = None
        if form.is_valid():
            response = {'success': False,
                        'message': 'Unknown error; unable to upload file.'}
            inherited_source = None
            backdoor = form.cleaned_data['backdoor']
            campaign = form.cleaned_data['campaign']
            confidence = form.cleaned_data['confidence']
            source = form.cleaned_data['source']
            method = form.cleaned_data['method']
            reference = form.cleaned_data['reference']
            analyst = request.user.username

            if related_md5:
                reload_page = True
            else:
                reload_page = False
                related_md5 = form.cleaned_data['related_md5']

            if related_md5:
                related_sample = Sample.objects(md5=related_md5).first()
                if not related_sample:
                    response['message'] = "Upload Failed. Unable to locate related sample."
                    return render_to_response("file_upload_response.html",
                                              {'response': json.dumps(response)},
                                              RequestContext(request))
                # If selected, new sample inherits the campaigns of the related sample.
                if form.cleaned_data['inherit_campaigns']:
                    if campaign:
                        related_sample.campaign.append(EmbeddedCampaign(name=campaign, confidence=confidence, analyst=analyst))
                    campaign = related_sample.campaign
                # If selected, new sample inherits the sources of the related sample
                if form.cleaned_data['inherit_sources']:
                    inherited_source = related_sample.source

            backdoor_name = None
            backdoor_version = None
            if backdoor:
                backdoor = backdoor.split('|||')
                if len(backdoor) == 2:
                    (backdoor_name, backdoor_version) = backdoor[0], backdoor[1]

            try:
                if request.FILES:
                    result = handle_uploaded_file(
                        request.FILES['filedata'],
                        source,
                        method,
                        reference,
                        form.cleaned_data['file_format'],
                        form.cleaned_data['password'],
                        analyst,
                        campaign,
                        confidence,
                        related_md5,
                        bucket_list=form.cleaned_data[form_consts.Common.BUCKET_LIST_VARIABLE_NAME],
                        ticket=form.cleaned_data[form_consts.Common.TICKET_VARIABLE_NAME],
                        inherited_source=inherited_source,
                        backdoor_name=backdoor_name,
                        backdoor_version=backdoor_version)
                else:
                    result = handle_uploaded_file(
                        None,
                        source,
                        method,
                        reference,
                        form.cleaned_data['file_format'],
                        None,
                        analyst,
                        campaign,
                        confidence,
                        related_md5 = related_md5,
                        filename=request.POST['filename'].strip(),
                        md5=request.POST['md5'].strip().lower(),
                        bucket_list=form.cleaned_data[form_consts.Common.BUCKET_LIST_VARIABLE_NAME],
                        ticket=form.cleaned_data[form_consts.Common.TICKET_VARIABLE_NAME],
                        inherited_source=inherited_source,
                        is_return_only_md5=False,
                        backdoor_name=backdoor_name,
                        backdoor_version=backdoor_version)

            except ZipFileError, zfe:
                return render_to_response('file_upload_response.html',
                                          {'response': json.dumps({'success': False,
                                                                   'message': zfe.value})},
                                          RequestContext(request))
            else:
                if len(result) > 1:
                    filedata = request.FILES['filedata']
                    message = ('<a href="%s">View Uploaded Samples.</a>'
                               % reverse('crits.samples.views.view_upload_list',
                                         args=[filedata.name, result]))
                    response = {'success': True,
                                'message': message }
                    md5_response = result
                elif len(result) == 1:
                    md5_response = None
                    if not request.FILES:
                        response['success'] = result[0].get('success', False)
                        if(response['success'] == False):
                            response['message'] = result[0].get('message', response.get('message'))
                        else:
                            md5_response = [result[0].get('object').md5]
                    else:
                        md5_response = [result[0]]
                        response['success'] = True

                    if md5_response != None:
                        response['message'] = ('File uploaded successfully. <a href="%s">View Sample.</a>'
                                               % reverse('crits.samples.views.detail',
                                                         args=md5_response))

                if response['success']:
                    if request.POST.get('email'):
                        for s in md5_response:
                            email_errmsg = mail_sample(s, [request.user.email])
                            if email_errmsg is not None:
                                msg = "<br>Error emailing sample %s: %s\n" % (s, email_errmsg)
                                response['message'] = response['message'] + msg
                    if reload_page:
                        response['redirect_url'] = reverse('crits.samples.views.detail', args=[related_md5])
                return render_to_response("file_upload_response.html",
                                          {'response': json.dumps(response)},
                                          RequestContext(request))
        else:
            if related_md5: #if this is a 'related' upload, hide field so it doesn't reappear
                form.fields['related_md5'].widget = forms.HiddenInput()
            return render_to_response('file_upload_response.html',
                                      {'response': json.dumps({'success': False,
                                                               'form': form.as_table()})},
                                      RequestContext(request))
Exemplo n.º 9
0
def upload_file(request):
    """
    Upload a new sample.

    :param request: Django request object (Required)
    :type request: :class:`django.http.HttpRequest`
    :returns: :class:`django.http.HttpResponse`
    """

    if request.method == 'POST':
        form = UploadFileForm(request.user, request.POST, request.FILES)
        email_errmsg = None
        if form.is_valid():
            campaign = form.cleaned_data['campaign']
            confidence = form.cleaned_data['confidence']
            source = form.cleaned_data['source']
            reference = form.cleaned_data['reference']
            try:
                if request.FILES:
                    sample_md5 = handle_uploaded_file(
                        request.FILES['filedata'],
                        source,
                        reference,
                        form.cleaned_data['file_format'],
                        form.cleaned_data['password'],
                        user=request.user.username,
                        campaign=campaign,
                        confidence=confidence,
                        parent_md5=form.cleaned_data['parent_md5'],
                        bucket_list=form.cleaned_data[
                            form_consts.Common.BUCKET_LIST_VARIABLE_NAME],
                        ticket=form.cleaned_data[
                            form_consts.Common.TICKET_VARIABLE_NAME])
                else:
                    filename = request.POST['filename'].strip()
                    md5 = request.POST['md5'].strip().lower()
                    sample_md5 = handle_uploaded_file(
                        None,
                        source,
                        reference,
                        form.cleaned_data['file_format'],
                        None,
                        user=request.user.username,
                        campaign=campaign,
                        confidence=confidence,
                        parent_md5=form.cleaned_data['parent_md5'],
                        filename=filename,
                        md5=md5,
                        bucket_list=form.cleaned_data[
                            form_consts.Common.BUCKET_LIST_VARIABLE_NAME],
                        ticket=form.cleaned_data[
                            form_consts.Common.TICKET_VARIABLE_NAME],
                        is_return_only_md5=False)

                if 'email' in request.POST:
                    for s in sample_md5:
                        email_errmsg = mail_sample(s, [request.user.email])
            except ZipFileError, zfe:
                return render_to_response(
                    'file_upload_response.html', {
                        'response':
                        json.dumps({
                            'success': False,
                            'message': zfe.value
                        })
                    }, RequestContext(request))
            else:
                response = {
                    'success': False,
                    'message': 'Unknown error; unable to upload file.'
                }
                if len(sample_md5) > 1:
                    filedata = request.FILES['filedata']
                    message = ('<a href="%s">View Uploaded Samples.</a>' %
                               reverse('crits.samples.views.view_upload_list',
                                       args=[filedata.name, sample_md5]))
                    response = {'success': True, 'message': message}
                elif len(sample_md5) == 1:
                    md5_response = None
                    if not request.FILES:
                        response['success'] = sample_md5[0].get(
                            'success', False)
                        if (response['success'] == False):
                            response['message'] = sample_md5[0].get(
                                'message', response.get('message'))
                        else:
                            md5_response = sample_md5[0].get('object').md5
                    else:
                        md5_response = sample_md5[0]
                        response['success'] = True

                    if md5_response != None:
                        response['message'] = (
                            'File uploaded successfully. <a href="%s">View Sample.</a>'
                            % reverse('crits.samples.views.detail',
                                      args=[md5_response]))

                if email_errmsg is not None:
                    msg = "<br>Error sending email: %s" % email_errmsg
                    response['message'] = response['message'] + msg

                return render_to_response("file_upload_response.html",
                                          {'response': json.dumps(response)},
                                          RequestContext(request))
        else:
            return render_to_response(
                'file_upload_response.html', {
                    'response':
                    json.dumps({
                        'success': False,
                        'form': form.as_table()
                    })
                }, RequestContext(request))
Exemplo n.º 10
0
def upload_file(request, related_md5=None):
    """
    Upload a new sample.

    :param request: Django request object (Required)
    :type request: :class:`django.http.HttpRequest`
    :param related_md5: The MD5 of a related sample.
    :type related_md5: str
    :returns: :class:`django.http.HttpResponse`
    """
    if request.method == 'POST':
        form = UploadFileForm(request.user, request.POST, request.FILES)
        email_errmsg = None
        if form.is_valid():
            response = {'success': False,
                        'message': 'Unknown error; unable to upload file.'}
            inherited_source = None
            backdoor = form.cleaned_data['backdoor']
            campaign = form.cleaned_data['campaign']
            confidence = form.cleaned_data['confidence']
            source = form.cleaned_data['source_name']
            source_method = form.cleaned_data['source_method']
            source_reference = form.cleaned_data['source_reference']
            source_tlp = form.cleaned_data['source_tlp']
            user = request.user
            description = form.cleaned_data['description']
            related_id = form.cleaned_data.get('related_id', None)
            related_type = form.cleaned_data.get('related_type', None)
            relationship_type = form.cleaned_data.get('relationship_type', None)

            if related_md5:
                reload_page = True
            else:
                reload_page = False
                related_md5 = form.cleaned_data['related_md5']

            if related_md5:
                related_sample = Sample.objects(md5=related_md5).first()
                if not related_sample:
                    response['message'] = ("Upload Failed. Unable to locate related sample. %s" % related_md5)
                    return render(request, "file_upload_response.html", {'response': json.dumps(response)})
                # If selected, new sample inherits the campaigns of the related sample.
                if form.cleaned_data['inherit_campaigns']:
                    if campaign:
                        related_sample.campaign.append(EmbeddedCampaign(name=campaign, confidence=confidence, analyst=user))
                    campaign = related_sample.campaign
                # If selected, new sample inherits the sources of the related sample
                if form.cleaned_data['inherit_sources']:
                    inherited_source = related_sample.source

            elif related_id:
                related_obj = class_from_id(related_type, related_id)
                if not related_obj:
                    response['success'] = False
                    response['message'] = ("Upload Failed. Unable to locate related Item")
                    return render(request, "file_upload_response.html",{'response': json.dumps(response)}, )

                else:
                    if form.cleaned_data['inherit_campaigns']:
                        if  campaign:
                            related_obj.campaign.append(EmbeddedCampaign(name=campaign, confidence=confidence, analyst=user))
                        campaign = related_obj.campaign

                    if form.cleaned_data['inherit_sources']:
                        inherited_source = related_obj.source

            backdoor_name = None
            backdoor_version = None
            if backdoor:
                backdoor = backdoor.split('|||')
                if len(backdoor) == 2:
                    (backdoor_name, backdoor_version) = backdoor[0], backdoor[1]

            try:
                if request.FILES:
                    result = handle_uploaded_file(
                        request.FILES['filedata'],
                        source,
                        source_method=source_method,
                        source_reference=source_reference,
                        source_tlp=source_tlp,
                        file_format=form.cleaned_data['file_format'],
                        password=form.cleaned_data['password'],
                        user=user,
                        campaign=campaign,
                        confidence=confidence,
                        related_md5=related_md5,
                        related_id=related_id,
                        related_type=related_type,
                        relationship_type=relationship_type,
                        bucket_list=form.cleaned_data[form_consts.Common.BUCKET_LIST_VARIABLE_NAME],
                        ticket=form.cleaned_data[form_consts.Common.TICKET_VARIABLE_NAME],
                        inherited_source=inherited_source,
                        backdoor_name=backdoor_name,
                        backdoor_version=backdoor_version,
                        description=description)
                else:
                    result = handle_uploaded_file(
                        None,
                        source,
                        source_method=source_method,
                        source_reference=source_reference,
                        source_tlp=source_tlp,
                        file_format=form.cleaned_data['file_format'],
                        password=None,
                        user=user,
                        campaign=campaign,
                        confidence=confidence,
                        related_md5 = related_md5,
                        related_id=related_id,
                        related_type=related_type,
                        relationship_type=relationship_type,
                        filename=request.POST['filename'].strip(),
                        md5=request.POST['md5'].strip().lower(),
                        sha1=request.POST['sha1'].strip().lower(),
                        sha256=request.POST['sha256'].strip().lower(),
                        bucket_list=form.cleaned_data[form_consts.Common.BUCKET_LIST_VARIABLE_NAME],
                        ticket=form.cleaned_data[form_consts.Common.TICKET_VARIABLE_NAME],
                        inherited_source=inherited_source,
                        is_return_only_md5=False,
                        backdoor_name=backdoor_name,
                        backdoor_version=backdoor_version,
                        description=description)

            except ZipFileError, zfe:
                return render(request, 'file_upload_response.html', {'response': json.dumps({'success': False,
                                'message': zfe.value})})
            else:
                # zip file upload, etc; result is a list of strings (1 hash per file)
                if len(result) > 0 and not isinstance(result[0], dict):
                    filedata = request.FILES['filedata']
                    message = ('<a href="%s">View Uploaded Samples.</a>'
                               % reverse('crits-samples-views-view_upload_list',
                                         args=[filedata.name, result]))
                    response = {'success': True,
                                'message': message }
                    md5_response = result
                # regular file upload; result is a list with a single dict
                else:
                    response['success'] = result[0].get('success', False)
                    response['message'] = result[0].get('message',
                                                        response.get('message'))
                    try:
                        md5_response = [result[0].get('object').md5]
                    except:
                        md5_response = None

                if response['success']:
                    if request.POST.get('email') and md5_response:
                        for s in md5_response:
                            email_errmsg = mail_sample(s, [request.user.email])
                            if email_errmsg is not None:
                                msg = "<br>Error emailing sample %s: %s\n" % (s, email_errmsg)
                                response['message'] = response['message'] + msg
                    if reload_page:
                        response['redirect_url'] = reverse('crits-samples-views-detail', args=[related_md5])
                return render(request, "file_upload_response.html", {'response': json.dumps(response)})
        else:
            if related_md5: #if this is a 'related' upload, hide field so it doesn't reappear
                form.fields['related_md5'].widget = forms.HiddenInput()
            return render(request, 'file_upload_response.html', {'response': json.dumps({'success': False,
                        'form': form.as_table()})})