Пример #1
0
def report_builder(request):
    add_breadcrumb(title="Report Builder", top_level=True, request=request)
    findings = get_authorized_findings(Permissions.Finding_View)
    findings = ReportFindingFilter(request.GET, queryset=findings)
    endpoints = Endpoint.objects.filter(
        finding__active=True,
        finding__verified=True,
        finding__false_p=False,
        finding__duplicate=False,
        finding__out_of_scope=False,
    ).distinct()

    endpoints = EndpointFilter(request.GET,
                               queryset=endpoints,
                               user=request.user)

    in_use_widgets = [ReportOptions(request=request)]
    available_widgets = [
        CoverPage(request=request),
        TableOfContents(request=request),
        WYSIWYGContent(request=request),
        FindingList(request=request, findings=findings),
        EndpointList(request=request, endpoints=endpoints),
        PageBreak()
    ]
    return render(request, 'dojo/report_builder.html', {
        "available_widgets": available_widgets,
        "in_use_widgets": in_use_widgets
    })
Пример #2
0
def report_findings(request):
    findings = Finding.objects.filter()

    findings = ReportFindingFilter(request.GET, queryset=findings)

    title_words = get_words_for_field(Finding, 'title')
    component_words = get_words_for_field(Finding, 'component_name')

    paged_findings = get_page_items(
        request,
        findings.qs.distinct().order_by('numerical_severity'), 25)

    product_type = None
    if 'test__engagement__product__prod_type' in request.GET:
        p = request.GET.getlist('test__engagement__product__prod_type', [])
        if len(p) == 1:
            product_type = get_object_or_404(Product_Type, id=p[0])

    return render(
        request, 'dojo/report_findings.html', {
            "findings": paged_findings,
            "filtered": findings,
            "title_words": title_words,
            "component_words": component_words,
            "title": "finding-list",
        })
Пример #3
0
def generate_report(request, obj):
    user = Dojo_User.objects.get(id=request.user.id)
    product_type = None
    product = None
    engagement = None
    test = None
    endpoint = None
    endpoints = None
    endpoint_all_findings = None
    endpoint_monthly_counts = None
    endpoint_active_findings = None
    accepted_findings = None
    open_findings = None
    closed_findings = None
    verified_findings = None
    report_title = None
    report_subtitle = None
    report_info = "Generated By %s on %s" % (user.get_full_name(), (
        timezone.now().strftime("%m/%d/%Y %I:%M%p %Z")))

    if type(obj).__name__ == "Product":
        if request.user.is_staff or check_auth_users_list(request.user, obj):
            pass  # user is authorized for this product
        else:
            raise PermissionDenied
    elif type(obj).__name__ == "Endpoint":
        if request.user.is_staff or check_auth_users_list(request.user, obj):
            pass  # user is authorized for this product
        else:
            raise PermissionDenied
    elif type(obj).__name__ == "QuerySet" or type(
            obj).__name__ == "CastTaggedQuerySet":
        # authorization taken care of by only selecting findings from product user is authed to see
        pass
    else:
        if not request.user.is_staff:
            raise PermissionDenied

    report_format = request.GET.get('report_type', 'AsciiDoc')
    include_finding_notes = int(request.GET.get('include_finding_notes', 0))
    include_finding_images = int(request.GET.get('include_finding_images', 0))
    include_executive_summary = int(
        request.GET.get('include_executive_summary', 0))
    include_table_of_contents = int(
        request.GET.get('include_table_of_contents', 0))
    generate = "_generate" in request.GET
    report_name = str(obj)
    report_type = type(obj).__name__
    add_breadcrumb(title="Generate Report", top_level=False, request=request)
    if type(obj).__name__ == "Product_Type":
        product_type = obj
        filename = "product_type_finding_report.pdf"
        template = "dojo/product_type_pdf_report.html"
        report_name = "Product Type Report: " + str(product_type)
        report_title = "Product Type Report"
        report_subtitle = str(product_type)

        findings = ReportFindingFilter(
            request.GET,
            prod_type=product_type,
            queryset=prefetch_related_findings_for_report(
                Finding.objects.filter(
                    test__engagement__product__prod_type=product_type)))
        products = Product.objects.filter(
            prod_type=product_type,
            engagement__test__finding__in=findings.qs).distinct()
        engagements = Engagement.objects.filter(
            product__prod_type=product_type,
            test__finding__in=findings.qs).distinct()
        tests = Test.objects.filter(
            engagement__product__prod_type=product_type,
            finding__in=findings.qs).distinct()
        if len(findings.qs) > 0:
            start_date = timezone.make_aware(
                datetime.combine(findings.qs.last().date, datetime.min.time()))
        else:
            start_date = timezone.now()

        end_date = timezone.now()

        r = relativedelta(end_date, start_date)
        months_between = (r.years * 12) + r.months
        # include current month
        months_between += 1

        endpoint_monthly_counts = get_period_counts_legacy(
            findings.qs.order_by('numerical_severity'),
            findings.qs.order_by('numerical_severity'),
            None,
            months_between,
            start_date,
            relative_delta='months')

        context = {
            'product_type':
            product_type,
            'products':
            products,
            'engagements':
            engagements,
            'tests':
            tests,
            'report_name':
            report_name,
            'endpoint_opened_per_month':
            endpoint_monthly_counts['opened_per_period']
            if endpoint_monthly_counts is not None else [],
            'endpoint_active_findings':
            findings.qs.order_by('numerical_severity'),
            'findings':
            findings.qs.order_by('numerical_severity'),
            'include_finding_notes':
            include_finding_notes,
            'include_finding_images':
            include_finding_images,
            'include_executive_summary':
            include_executive_summary,
            'include_table_of_contents':
            include_table_of_contents,
            'user':
            user,
            'team_name':
            settings.TEAM_NAME,
            'title':
            report_title,
            'host':
            report_url_resolver(request),
            'user_id':
            request.user.id
        }

    elif type(obj).__name__ == "Product":
        product = obj
        filename = "product_finding_report.pdf"
        template = "dojo/product_pdf_report.html"
        report_name = "Product Report: " + str(product)
        report_title = "Product Report"
        report_subtitle = str(product)
        findings = ReportFindingFilter(
            request.GET,
            product=product,
            queryset=prefetch_related_findings_for_report(
                Finding.objects.filter(test__engagement__product=product)))
        ids = set(finding.id for finding in findings.qs)
        engagements = Engagement.objects.filter(
            test__finding__id__in=ids).distinct()
        tests = Test.objects.filter(finding__id__in=ids).distinct()
        ids = get_endpoint_ids(
            Endpoint.objects.filter(product=product).distinct())
        endpoints = Endpoint.objects.filter(id__in=ids)
        context = {
            'product': product,
            'engagements': engagements,
            'tests': tests,
            'report_name': report_name,
            'findings': findings.qs.order_by('numerical_severity'),
            'include_finding_notes': include_finding_notes,
            'include_finding_images': include_finding_images,
            'include_executive_summary': include_executive_summary,
            'include_table_of_contents': include_table_of_contents,
            'user': user,
            'team_name': settings.TEAM_NAME,
            'title': report_title,
            'endpoints': endpoints,
            'host': report_url_resolver(request),
            'user_id': request.user.id
        }

    elif type(obj).__name__ == "Engagement":
        logger.debug('generating report for Engagement')
        engagement = obj
        findings = ReportFindingFilter(
            request.GET,
            engagement=engagement,
            queryset=prefetch_related_findings_for_report(
                Finding.objects.filter(test__engagement=engagement)))
        report_name = "Engagement Report: " + str(engagement)
        filename = "engagement_finding_report.pdf"
        template = 'dojo/engagement_pdf_report.html'
        report_title = "Engagement Report"
        report_subtitle = str(engagement)

        ids = set(finding.id for finding in findings.qs)
        tests = Test.objects.filter(finding__id__in=ids).distinct()
        ids = get_endpoint_ids(
            Endpoint.objects.filter(product=engagement.product).distinct())
        endpoints = Endpoint.objects.filter(id__in=ids)

        context = {
            'engagement': engagement,
            'tests': tests,
            'report_name': report_name,
            'findings': findings.qs.order_by('numerical_severity'),
            'include_finding_notes': include_finding_notes,
            'include_finding_images': include_finding_images,
            'include_executive_summary': include_executive_summary,
            'include_table_of_contents': include_table_of_contents,
            'user': user,
            'team_name': settings.TEAM_NAME,
            'title': report_title,
            'host': report_url_resolver(request),
            'user_id': request.user.id,
            'endpoints': endpoints
        }

    elif type(obj).__name__ == "Test":
        test = obj
        findings = ReportFindingFilter(
            request.GET,
            engagement=test.engagement,
            queryset=prefetch_related_findings_for_report(
                Finding.objects.filter(test=test)))
        filename = "test_finding_report.pdf"
        template = "dojo/test_pdf_report.html"
        report_name = "Test Report: " + str(test)
        report_title = "Test Report"
        report_subtitle = str(test)

        context = {
            'test': test,
            'report_name': report_name,
            'findings': findings.qs.order_by('numerical_severity'),
            'include_finding_notes': include_finding_notes,
            'include_finding_images': include_finding_images,
            'include_executive_summary': include_executive_summary,
            'include_table_of_contents': include_table_of_contents,
            'user': user,
            'team_name': settings.TEAM_NAME,
            'title': report_title,
            'host': report_url_resolver(request),
            'user_id': request.user.id
        }

    elif type(obj).__name__ == "Endpoint":
        endpoint = obj
        host = endpoint.host_no_port
        report_name = "Endpoint Report: " + host
        report_type = "Endpoint"
        endpoints = Endpoint.objects.filter(
            host__regex="^" + host + ":?",
            product=endpoint.product).distinct()
        filename = "endpoint_finding_report.pdf"
        template = 'dojo/endpoint_pdf_report.html'
        report_title = "Endpoint Report"
        report_subtitle = host
        findings = ReportFindingFilter(
            request.GET,
            queryset=prefetch_related_findings_for_report(
                Finding.objects.filter(endpoints__in=endpoints)))

        context = {
            'endpoint': endpoint,
            'endpoints': endpoints,
            'report_name': report_name,
            'findings': findings.qs.order_by('numerical_severity'),
            'include_finding_notes': include_finding_notes,
            'include_finding_images': include_finding_images,
            'include_executive_summary': include_executive_summary,
            'include_table_of_contents': include_table_of_contents,
            'user': user,
            'team_name': get_system_setting('team_name'),
            'title': report_title,
            'host': report_url_resolver(request),
            'user_id': request.user.id
        }
    elif type(obj).__name__ == "QuerySet" or type(
            obj).__name__ == "CastTaggedQuerySet":
        findings = ReportAuthedFindingFilter(
            request.GET,
            queryset=prefetch_related_findings_for_report(obj).distinct())
        filename = "finding_report.pdf"
        report_name = 'Finding'
        report_type = 'Finding'
        template = 'dojo/finding_pdf_report.html'
        report_title = "Finding Report"
        report_subtitle = ''

        context = {
            'findings': findings.qs.order_by('numerical_severity'),
            'report_name': report_name,
            'include_finding_notes': include_finding_notes,
            'include_finding_images': include_finding_images,
            'include_executive_summary': include_executive_summary,
            'include_table_of_contents': include_table_of_contents,
            'user': user,
            'team_name': settings.TEAM_NAME,
            'title': report_title,
            'host': report_url_resolver(request),
            'user_id': request.user.id
        }
    else:
        raise Http404()

    report_form = ReportOptionsForm()

    if generate:
        report_form = ReportOptionsForm(request.GET)
        if report_format == 'AsciiDoc':
            return render(
                request, 'dojo/asciidoc_report.html', {
                    'product_type': product_type,
                    'product': product,
                    'engagement': engagement,
                    'test': test,
                    'endpoint': endpoint,
                    'findings': findings.qs.order_by('numerical_severity'),
                    'include_finding_notes': include_finding_notes,
                    'include_finding_images': include_finding_images,
                    'include_executive_summary': include_executive_summary,
                    'include_table_of_contents': include_table_of_contents,
                    'user': user,
                    'team_name': settings.TEAM_NAME,
                    'title': report_title,
                    'user_id': request.user.id,
                    'host': report_url_resolver(request),
                    'context': context,
                })

        elif report_format == 'PDF':
            if 'regen' in request.GET:
                # we should already have a report object, lets get and use it
                report = get_object_or_404(Report, id=request.GET['regen'])
                report.datetime = timezone.now()
                report.status = 'requested'
                if report.requester.username != request.user.username:
                    report.requester = request.user
            else:
                # lets create the report object and send it in to celery task
                report = Report(name=report_name,
                                type=report_type,
                                format='PDF',
                                requester=request.user,
                                task_id='tbd',
                                options=request.path + "?" +
                                request.GET.urlencode())
            report.save()
            async_pdf_report.delay(report=report,
                                   template=template,
                                   filename=filename,
                                   report_title=report_title,
                                   report_subtitle=report_subtitle,
                                   report_info=report_info,
                                   context=context,
                                   uri=request.build_absolute_uri(
                                       report.get_url()))
            messages.add_message(request,
                                 messages.SUCCESS,
                                 'Your report is building.',
                                 extra_tags='alert-success')

            return HttpResponseRedirect(reverse('reports'))

        elif report_format == 'HTML':
            return render(
                request, template, {
                    'product_type': product_type,
                    'product': product,
                    'engagement': engagement,
                    'report_name': report_name,
                    'test': test,
                    'endpoint': endpoint,
                    'endpoints': endpoints,
                    'findings': findings.qs.order_by('numerical_severity'),
                    'include_finding_notes': include_finding_notes,
                    'include_finding_images': include_finding_images,
                    'include_executive_summary': include_executive_summary,
                    'include_table_of_contents': include_table_of_contents,
                    'user': user,
                    'team_name': settings.TEAM_NAME,
                    'title': report_title,
                    'user_id': request.user.id,
                    'host': "",
                    'context': context,
                })

        else:
            raise Http404()
    paged_findings = get_page_items(request,
                                    findings.qs.order_by('numerical_severity'),
                                    25)

    product_tab = None
    if engagement:
        product_tab = Product_Tab(engagement.product.id,
                                  title="Engagement Report",
                                  tab="engagements")
        product_tab.setEngagement(engagement)
    elif test:
        product_tab = Product_Tab(test.engagement.product.id,
                                  title="Test Report",
                                  tab="engagements")
        product_tab.setEngagement(test.engagement)
    elif product:
        product_tab = Product_Tab(product.id,
                                  title="Product Report",
                                  tab="findings")
    elif endpoints:
        product_tab = Product_Tab(endpoint.product.id,
                                  title="Endpoint Report",
                                  tab="endpoints")

    return render(
        request, 'dojo/request_report.html', {
            'product_type': product_type,
            'product': product,
            'product_tab': product_tab,
            'engagement': engagement,
            'test': test,
            'endpoint': endpoint,
            'findings': findings,
            'paged_findings': paged_findings,
            'report_form': report_form,
            'context': context,
        })
Пример #4
0
def report_widget_factory(json_data=None,
                          request=None,
                          user=None,
                          finding_notes=False,
                          finding_images=False,
                          host=None):
    selected_widgets = OrderedDict()
    widgets = json.loads(json_data)
    for idx, widget in enumerate(widgets):
        if list(widget.keys())[0] == 'page-break':
            selected_widgets[list(widget.keys())[0] + '-' +
                             str(idx)] = PageBreak()
        if list(widget.keys())[0] == 'endpoint-list':
            endpoints = Endpoint.objects.filter(
                finding__active=True,
                finding__verified=True,
                finding__false_p=False,
                finding__duplicate=False,
                finding__out_of_scope=False,
            ).distinct()
            d = QueryDict(mutable=True)
            for item in widget.get(list(widget.keys())[0]):
                if item['name'] in d:
                    d.getlist(item['name']).append(item['value'])
                else:
                    d[item['name']] = item['value']
            from dojo.endpoint.views import get_endpoint_ids
            ids = get_endpoint_ids(endpoints)

            endpoints = Endpoint.objects.filter(id__in=endpoints)
            endpoints = EndpointFilter(d,
                                       queryset=endpoints,
                                       user=request.user)
            user_id = user.id if user is not None else None
            endpoints = EndpointList(request=request,
                                     endpoints=endpoints,
                                     finding_notes=finding_notes,
                                     finding_images=finding_images,
                                     host=host,
                                     user_id=user_id)

            selected_widgets[list(widget.keys())[0] + '-' +
                             str(idx)] = endpoints

        if list(widget.keys())[0] == 'finding-list':
            findings = Finding.objects.all()
            d = QueryDict(mutable=True)
            for item in widget.get(list(widget.keys())[0]):
                if item['name'] in d:
                    d.getlist(item['name']).append(item['value'])
                else:
                    d[item['name']] = item['value']

            findings = ReportFindingFilter(d, queryset=findings)
            user_id = user.id if user is not None else None
            selected_widgets[list(widget.keys())[0] + '-' +
                             str(idx)] = FindingList(
                                 request=request,
                                 findings=findings,
                                 finding_notes=finding_notes,
                                 finding_images=finding_images,
                                 host=host,
                                 user_id=user_id)

        if list(widget.keys())[0] == 'wysiwyg-content':
            wysiwyg_content = WYSIWYGContent(request=request)
            wysiwyg_content.title = \
                next((item for item in widget.get(list(widget.keys())[0]) if item["name"] == 'heading'), None)['value']
            wysiwyg_content.content = \
                next((item for item in widget.get(list(widget.keys())[0]) if item["name"] == 'hidden_content'), None)['value']
            selected_widgets[list(widget.keys())[0] + '-' +
                             str(idx)] = wysiwyg_content
        if list(widget.keys())[0] == 'report-options':
            options = ReportOptions(request=request)
            options.include_finding_notes = \
                next((item for item in widget.get(list(widget.keys())[0]) if item["name"] == 'include_finding_notes'), None)[
                    'value']
            options.include_finding_images = \
                next((item for item in widget.get(list(widget.keys())[0]) if item["name"] == 'include_finding_images'), None)[
                    'value']
            options.report_type = \
                next((item for item in widget.get(list(widget.keys())[0]) if item["name"] == 'report_type'), None)['value']
            options.report_name = \
                next((item for item in widget.get(list(widget.keys())[0]) if item["name"] == 'report_name'), None)['value']
            selected_widgets[list(widget.keys())[0]] = options
        if list(widget.keys())[0] == 'table-of-contents':
            toc = TableOfContents(request=request)
            toc.title = next((item
                              for item in widget.get(list(widget.keys())[0])
                              if item["name"] == 'heading'), None)['value']
            toc.depth = next((item
                              for item in widget.get(list(widget.keys())[0])
                              if item["name"] == 'depth'), None)['value']
            toc.depth = int(toc.depth) + 1
            selected_widgets[list(widget.keys())[0]] = toc
        if list(widget.keys())[0] == 'cover-page':
            cover_page = CoverPage(request=request)
            cover_page.title = next(
                (item for item in widget.get(list(widget.keys())[0])
                 if item["name"] == 'heading'), None)['value']
            cover_page.sub_heading = \
                next((item for item in widget.get(list(widget.keys())[0]) if item["name"] == 'sub_heading'), None)['value']
            cover_page.meta_info = \
                next((item for item in widget.get(list(widget.keys())[0]) if item["name"] == 'meta_info'), None)['value']
            selected_widgets[list(widget.keys())[0]] = cover_page

    return selected_widgets
Пример #5
0
def report_generate(request, obj, options):
    user = Dojo_User.objects.get(id=request.user.id)
    product_type = None
    product = None
    engagement = None
    test = None
    endpoint = None
    endpoints = None
    endpoint_all_findings = None
    endpoint_monthly_counts = None
    endpoint_active_findings = None
    accepted_findings = None
    open_findings = None
    closed_findings = None
    verified_findings = None
    report_title = None
    report_subtitle = None

    include_finding_notes = False
    include_finding_images = False
    include_executive_summary = False
    include_table_of_contents = False

    report_info = "Generated By %s on %s" % (user.get_full_name(), (
        timezone.now().strftime("%m/%d/%Y %I:%M%p %Z")))

    # generate = "_generate" in request.GET
    report_name = str(obj)
    report_type = type(obj).__name__

    include_finding_notes = options.get('include_finding_notes', False)
    include_finding_images = options.get('include_finding_images', False)
    include_executive_summary = options.get('include_executive_summary', False)
    include_table_of_contents = options.get('include_table_of_contents', False)

    if type(obj).__name__ == "Product_Type":
        product_type = obj

        report_name = "Product Type Report: " + str(product_type)
        report_title = "Product Type Report"
        report_subtitle = str(product_type)

        findings = ReportFindingFilter(
            request.GET,
            queryset=Finding.objects.filter(
                test__engagement__product__prod_type=product_type).distinct(
                ).prefetch_related('test', 'test__engagement__product',
                                   'test__engagement__product__prod_type'))
        products = Product.objects.filter(
            prod_type=product_type,
            engagement__test__finding__in=findings.qs).distinct()
        engagements = Engagement.objects.filter(
            product__prod_type=product_type,
            test__finding__in=findings.qs).distinct()
        tests = Test.objects.filter(
            engagement__product__prod_type=product_type,
            finding__in=findings.qs).distinct()
        if len(findings.qs) > 0:
            start_date = timezone.make_aware(
                datetime.combine(findings.qs.last().date, datetime.min.time()))
        else:
            start_date = timezone.now()

        end_date = timezone.now()

        r = relativedelta(end_date, start_date)
        months_between = (r.years * 12) + r.months
        # include current month
        months_between += 1

        endpoint_monthly_counts = get_period_counts_legacy(
            findings.qs.order_by('numerical_severity'),
            findings.qs.order_by('numerical_severity'),
            None,
            months_between,
            start_date,
            relative_delta='months')

    elif type(obj).__name__ == "Product":
        product = obj

        report_name = "Product Report: " + str(product)
        report_title = "Product Report"
        report_subtitle = str(product)
        findings = ReportFindingFilter(
            request.GET,
            queryset=Finding.objects.filter(
                test__engagement__product=product).distinct().prefetch_related(
                    'test', 'test__engagement__product',
                    'test__engagement__product__prod_type'))
        ids = set(finding.id for finding in findings.qs)
        engagements = Engagement.objects.filter(
            test__finding__id__in=ids).distinct()
        tests = Test.objects.filter(finding__id__in=ids).distinct()
        ids = get_endpoint_ids(
            Endpoint.objects.filter(product=product).distinct())
        endpoints = Endpoint.objects.filter(id__in=ids)

    elif type(obj).__name__ == "Engagement":
        engagement = obj
        findings = ReportFindingFilter(
            request.GET,
            queryset=Finding.objects.filter(
                test__engagement=engagement, ).prefetch_related(
                    'test', 'test__engagement__product',
                    'test__engagement__product__prod_type').distinct())
        report_name = "Engagement Report: " + str(engagement)

        report_title = "Engagement Report"
        report_subtitle = str(engagement)

        ids = set(finding.id for finding in findings.qs)
        tests = Test.objects.filter(finding__id__in=ids).distinct()
        ids = get_endpoint_ids(
            Endpoint.objects.filter(product=engagement.product).distinct())
        endpoints = Endpoint.objects.filter(id__in=ids)

    elif type(obj).__name__ == "Test":
        test = obj
        findings = ReportFindingFilter(
            request.GET,
            queryset=Finding.objects.filter(test=test).prefetch_related(
                'test', 'test__engagement__product',
                'test__engagement__product__prod_type').distinct())
        report_name = "Test Report: " + str(test)
        report_title = "Test Report"
        report_subtitle = str(test)

    elif type(obj).__name__ == "Endpoint":
        endpoint = obj
        host = endpoint.host_no_port
        report_name = "Endpoint Report: " + host
        report_type = "Endpoint"
        endpoints = Endpoint.objects.filter(
            host__regex="^" + host + ":?",
            product=endpoint.product).distinct()
        report_title = "Endpoint Report"
        report_subtitle = host
        findings = ReportFindingFilter(
            request.GET,
            queryset=Finding.objects.filter(
                endpoints__in=endpoints, ).prefetch_related(
                    'test', 'test__engagement__product',
                    'test__engagement__product__prod_type').distinct())

    elif type(obj).__name__ == "QuerySet":
        findings = ReportAuthedFindingFilter(
            request.GET,
            queryset=obj.prefetch_related(
                'test', 'test__engagement__product',
                'test__engagement__product__prod_type').distinct(),
            user=request.user)
        report_name = 'Finding'
        report_type = 'Finding'
        report_title = "Finding Report"
        report_subtitle = ''

    else:
        raise Http404()

    result = {
        'product_type': product_type,
        'product': product,
        'engagement': engagement,
        'report_name': report_name,
        'report_info': report_info,
        'test': test,
        'endpoint': endpoint,
        'endpoints': endpoints,
        'findings': findings.qs.order_by('numerical_severity'),
        'include_table_of_contents': include_table_of_contents,
        'user': user,
        'team_name': settings.TEAM_NAME,
        'title': 'Generate Report',
        'user_id': request.user.id,
        'host': report_url_resolver(request),
    }

    finding_notes = []
    finding_images = []

    if include_finding_images:
        for finding in findings.qs.order_by('numerical_severity'):
            images = finding.images.all()
            if images:
                finding_images.append({
                    "finding_id": finding,
                    "images": images
                })
        result['finding_images'] = finding_images

    if include_finding_notes:
        for finding in findings.qs.order_by('numerical_severity'):
            notes = finding.notes.all()
            if notes:
                finding_notes.append({
                    "finding_id": finding,
                    "notes": notes.filter(
                        private=False)  # fetching only public notes for report
                })
        result['finding_notes'] = finding_notes

    # Generating Executive summary based on obj type
    if include_executive_summary and type(obj).__name__ != "Endpoint":
        executive_summary = {}

        # Declare all required fields for executive summary
        engagement_name = None
        engagement_target_start = None
        engagement_target_end = None
        test_type_name = None
        test_target_start = None
        test_target_end = None
        test_environment_name = "unknown"  # a default of "unknown"
        test_strategy_ref = None
        total_findings = 0

        if type(obj).__name__ == "Product_Type":
            for prod_typ in obj.prod_type.all():
                engmnts = prod_typ.engagement_set.all()
                if engmnts:
                    for eng in engmnts:
                        if eng.name:
                            engagement_name = eng.name
                        engagement_target_start = eng.target_start
                        if eng.target_end:
                            engagement_target_end = eng.target_end
                        else:
                            engagement_target_end = "ongoing"
                        if eng.test_set.all():
                            for t in eng.test_set.all():
                                test_type_name = t.test_type.name
                                if test.environment:
                                    test_environment_name = t.environment.name
                                test_target_start = t.target_start
                                if t.target_end:
                                    test_target_end = t.target_end
                                else:
                                    test_target_end = "ongoing"
                            if eng.test_strategy:
                                test_strategy_ref = eng.test_strategy
                            else:
                                test_strategy_ref = ""
                total_findings = len(findings.qs.all())

        elif type(obj).__name__ == "Product":
            engs = obj.engagement_set.all()
            if engs:
                for eng in engs:
                    if eng.name:
                        engagement_name = eng.name
                    engagement_target_start = eng.target_start
                    if eng.target_end:
                        engagement_target_end = eng.target_end
                    else:
                        engagement_target_end = "ongoing"

                    if eng.test_set.all():
                        for t in eng.test_set.all():
                            test_type_name = t.test_type.name
                            if t.environment:
                                test_environment_name = t.environment.name
                    if eng.test_strategy:
                        test_strategy_ref = eng.test_strategy
                    else:
                        test_strategy_ref = ""
                total_findings = len(findings.qs.all())

        elif type(obj).__name__ == "Engagement":
            eng = obj
            if eng.name:
                engagement_name = eng.name
            engagement_target_start = eng.target_start
            if eng.target_end:
                engagement_target_end = eng.target_end
            else:
                engagement_target_end = "ongoing"

            if eng.test_set.all():
                for t in eng.test_set.all():
                    test_type_name = t.test_type.name
                    if t.environment:
                        test_environment_name = t.environment.name
            if eng.test_strategy:
                test_strategy_ref = eng.test_strategy
            else:
                test_strategy_ref = ""
            total_findings = len(findings.qs.all())

        elif type(obj).__name__ == "Test":
            t = obj
            test_type_name = t.test_type.name
            test_target_start = t.target_start
            if t.target_end:
                test_target_end = t.target_end
            else:
                test_target_end = "ongoing"
            total_findings = len(findings.qs.all())
            if t.engagement.name:
                engagement_name = t.engagement.name
            engagement_target_start = t.engagement.target_start
            if t.engagement.target_end:
                engagement_target_end = t.engagement.target_end
            else:
                engagement_target_end = "ongoing"
        else:
            pass  # do nothing

        executive_summary = {
            'engagement_name': engagement_name,
            'engagement_target_start': engagement_target_start,
            'engagement_target_end': engagement_target_end,
            'test_type_name': test_type_name,
            'test_target_start': test_target_start,
            'test_target_end': test_target_end,
            'test_environment_name': test_environment_name,
            'test_strategy_ref': test_strategy_ref,
            'total_findings': total_findings
        }
        # End of executive summary generation

        result['executive_summary'] = executive_summary

    return result
Пример #6
0
def generate_report(request, obj, host_view=False):
    user = Dojo_User.objects.get(id=request.user.id)
    product_type = None
    product = None
    engagement = None
    test = None
    endpoint = None
    endpoints = None
    accepted_findings = None
    open_findings = None
    closed_findings = None
    verified_findings = None
    report_title = None
    report_subtitle = None
    report_info = "Generated By %s on %s" % (user.get_full_name(), (
        timezone.now().strftime("%m/%d/%Y %I:%M%p %Z")))

    if type(obj).__name__ == "Product_Type":
        if settings.FEATURE_AUTHORIZATION_V2:
            user_has_permission_or_403(request.user, obj,
                                       Permissions.Product_Type_View)
        else:
            if not (request.user.is_staff
                    or check_auth_users_list(request.user, obj)):
                raise PermissionDenied
    elif type(obj).__name__ == "Product":
        if settings.FEATURE_AUTHORIZATION_V2:
            user_has_permission_or_403(request.user, obj,
                                       Permissions.Product_View)
        else:
            if not (request.user.is_staff
                    or check_auth_users_list(request.user, obj)):
                raise PermissionDenied
    elif type(obj).__name__ == "Engagement":
        if settings.FEATURE_AUTHORIZATION_V2:
            user_has_permission_or_403(request.user, obj,
                                       Permissions.Engagement_View)
        else:
            if not (request.user.is_staff
                    or check_auth_users_list(request.user, obj)):
                raise PermissionDenied
    elif type(obj).__name__ == "Test":
        if settings.FEATURE_AUTHORIZATION_V2:
            user_has_permission_or_403(request.user, obj,
                                       Permissions.Test_View)
        else:
            if not (request.user.is_staff
                    or check_auth_users_list(request.user, obj)):
                raise PermissionDenied
    elif type(obj).__name__ == "Endpoint":
        if settings.FEATURE_AUTHORIZATION_V2:
            user_has_permission_or_403(request.user, obj,
                                       Permissions.Endpoint_View)
        else:
            if not (request.user.is_staff
                    or check_auth_users_list(request.user, obj)):
                raise PermissionDenied
    elif type(obj).__name__ == "QuerySet" or type(
            obj).__name__ == "CastTaggedQuerySet":
        # authorization taken care of by only selecting findings from product user is authed to see
        pass
    else:
        if not request.user.is_staff:
            raise PermissionDenied

    report_format = request.GET.get('report_type', 'AsciiDoc')
    include_finding_notes = int(request.GET.get('include_finding_notes', 0))
    include_finding_images = int(request.GET.get('include_finding_images', 0))
    include_executive_summary = int(
        request.GET.get('include_executive_summary', 0))
    include_table_of_contents = int(
        request.GET.get('include_table_of_contents', 0))
    include_disclaimer = int(request.GET.get('include_disclaimer', 0))
    disclaimer = get_system_setting('disclaimer')
    if include_disclaimer and len(disclaimer) == 0:
        disclaimer = 'Please configure in System Settings.'
    generate = "_generate" in request.GET
    report_name = str(obj)
    report_type = type(obj).__name__
    add_breadcrumb(title="Generate Report", top_level=False, request=request)
    if type(obj).__name__ == "Product_Type":
        product_type = obj
        template = "dojo/product_type_pdf_report.html"
        report_name = "Product Type Report: " + str(product_type)
        report_title = "Product Type Report"
        report_subtitle = str(product_type)

        findings = ReportFindingFilter(
            request.GET,
            prod_type=product_type,
            queryset=prefetch_related_findings_for_report(
                Finding.objects.filter(
                    test__engagement__product__prod_type=product_type)))
        products = Product.objects.filter(
            prod_type=product_type,
            engagement__test__finding__in=findings.qs).distinct()
        engagements = Engagement.objects.filter(
            product__prod_type=product_type,
            test__finding__in=findings.qs).distinct()
        tests = Test.objects.filter(
            engagement__product__prod_type=product_type,
            finding__in=findings.qs).distinct()
        if len(findings.qs) > 0:
            start_date = timezone.make_aware(
                datetime.combine(findings.qs.last().date, datetime.min.time()))
        else:
            start_date = timezone.now()

        end_date = timezone.now()

        r = relativedelta(end_date, start_date)
        months_between = (r.years * 12) + r.months
        # include current month
        months_between += 1

        endpoint_monthly_counts = get_period_counts_legacy(
            findings.qs.order_by('numerical_severity'),
            findings.qs.order_by('numerical_severity'),
            None,
            months_between,
            start_date,
            relative_delta='months')

        context = {
            'product_type':
            product_type,
            'products':
            products,
            'engagements':
            engagements,
            'tests':
            tests,
            'report_name':
            report_name,
            'endpoint_opened_per_month':
            endpoint_monthly_counts['opened_per_period']
            if endpoint_monthly_counts is not None else [],
            'endpoint_active_findings':
            findings.qs.distinct().order_by('numerical_severity'),
            'findings':
            findings.qs.distinct().order_by('numerical_severity'),
            'include_finding_notes':
            include_finding_notes,
            'include_finding_images':
            include_finding_images,
            'include_executive_summary':
            include_executive_summary,
            'include_table_of_contents':
            include_table_of_contents,
            'include_disclaimer':
            include_disclaimer,
            'disclaimer':
            disclaimer,
            'user':
            user,
            'team_name':
            settings.TEAM_NAME,
            'title':
            report_title,
            'host':
            report_url_resolver(request),
            'user_id':
            request.user.id
        }

    elif type(obj).__name__ == "Product":
        product = obj
        template = "dojo/product_pdf_report.html"
        report_name = "Product Report: " + str(product)
        report_title = "Product Report"
        report_subtitle = str(product)
        findings = ReportFindingFilter(
            request.GET,
            product=product,
            queryset=prefetch_related_findings_for_report(
                Finding.objects.filter(test__engagement__product=product)))
        ids = set(finding.id for finding in findings.qs)
        engagements = Engagement.objects.filter(
            test__finding__id__in=ids).distinct()
        tests = Test.objects.filter(finding__id__in=ids).distinct()
        endpoints = Endpoint.objects.filter(product=product).distinct()
        context = {
            'product': product,
            'engagements': engagements,
            'tests': tests,
            'report_name': report_name,
            'findings': findings.qs.distinct().order_by('numerical_severity'),
            'include_finding_notes': include_finding_notes,
            'include_finding_images': include_finding_images,
            'include_executive_summary': include_executive_summary,
            'include_table_of_contents': include_table_of_contents,
            'include_disclaimer': include_disclaimer,
            'disclaimer': disclaimer,
            'user': user,
            'team_name': settings.TEAM_NAME,
            'title': report_title,
            'endpoints': endpoints,
            'host': report_url_resolver(request),
            'user_id': request.user.id
        }

    elif type(obj).__name__ == "Engagement":
        logger.debug('generating report for Engagement')
        engagement = obj
        findings = ReportFindingFilter(
            request.GET,
            engagement=engagement,
            queryset=prefetch_related_findings_for_report(
                Finding.objects.filter(test__engagement=engagement)))
        report_name = "Engagement Report: " + str(engagement)
        template = 'dojo/engagement_pdf_report.html'
        report_title = "Engagement Report"
        report_subtitle = str(engagement)

        ids = set(finding.id for finding in findings.qs)
        tests = Test.objects.filter(finding__id__in=ids).distinct()
        endpoints = Endpoint.objects.filter(
            product=engagement.product).distinct()

        context = {
            'engagement': engagement,
            'tests': tests,
            'report_name': report_name,
            'findings': findings.qs.distinct().order_by('numerical_severity'),
            'include_finding_notes': include_finding_notes,
            'include_finding_images': include_finding_images,
            'include_executive_summary': include_executive_summary,
            'include_table_of_contents': include_table_of_contents,
            'include_disclaimer': include_disclaimer,
            'disclaimer': disclaimer,
            'user': user,
            'team_name': settings.TEAM_NAME,
            'title': report_title,
            'host': report_url_resolver(request),
            'user_id': request.user.id,
            'endpoints': endpoints
        }

    elif type(obj).__name__ == "Test":
        test = obj
        findings = ReportFindingFilter(
            request.GET,
            engagement=test.engagement,
            queryset=prefetch_related_findings_for_report(
                Finding.objects.filter(test=test)))
        template = "dojo/test_pdf_report.html"
        report_name = "Test Report: " + str(test)
        report_title = "Test Report"
        report_subtitle = str(test)

        context = {
            'test': test,
            'report_name': report_name,
            'findings': findings.qs.distinct().order_by('numerical_severity'),
            'include_finding_notes': include_finding_notes,
            'include_finding_images': include_finding_images,
            'include_executive_summary': include_executive_summary,
            'include_table_of_contents': include_table_of_contents,
            'include_disclaimer': include_disclaimer,
            'disclaimer': disclaimer,
            'user': user,
            'team_name': settings.TEAM_NAME,
            'title': report_title,
            'host': report_url_resolver(request),
            'user_id': request.user.id
        }

    elif type(obj).__name__ == "Endpoint":
        endpoint = obj
        if host_view:
            report_name = "Endpoint Host Report: " + endpoint.host
            endpoints = Endpoint.objects.filter(
                host=endpoint.host, product=endpoint.product).distinct()
            report_title = "Endpoint Host Report"
            report_subtitle = endpoint.host
        else:
            report_name = "Endpoint Report: " + str(endpoint)
            endpoints = Endpoint.objects.filter(pk=endpoint.id).distinct()
            report_title = "Endpoint Report"
            report_subtitle = str(endpoint)
        report_type = "Endpoint"
        template = 'dojo/endpoint_pdf_report.html'
        findings = ReportFindingFilter(
            request.GET,
            queryset=prefetch_related_findings_for_report(
                Finding.objects.filter(endpoints__in=endpoints)))

        context = {
            'endpoint': endpoint,
            'endpoints': endpoints,
            'report_name': report_name,
            'findings': findings.qs.distinct().order_by('numerical_severity'),
            'include_finding_notes': include_finding_notes,
            'include_finding_images': include_finding_images,
            'include_executive_summary': include_executive_summary,
            'include_table_of_contents': include_table_of_contents,
            'include_disclaimer': include_disclaimer,
            'disclaimer': disclaimer,
            'user': user,
            'team_name': get_system_setting('team_name'),
            'title': report_title,
            'host': report_url_resolver(request),
            'user_id': request.user.id
        }
    elif type(obj).__name__ == "QuerySet" or type(
            obj).__name__ == "CastTaggedQuerySet":
        findings = ReportFindingFilter(
            request.GET,
            queryset=prefetch_related_findings_for_report(obj).distinct())
        report_name = 'Finding'
        report_type = 'Finding'
        template = 'dojo/finding_pdf_report.html'
        report_title = "Finding Report"
        report_subtitle = ''

        context = {
            'findings': findings.qs.distinct().order_by('numerical_severity'),
            'report_name': report_name,
            'include_finding_notes': include_finding_notes,
            'include_finding_images': include_finding_images,
            'include_executive_summary': include_executive_summary,
            'include_table_of_contents': include_table_of_contents,
            'include_disclaimer': include_disclaimer,
            'disclaimer': disclaimer,
            'user': user,
            'team_name': settings.TEAM_NAME,
            'title': report_title,
            'host': report_url_resolver(request),
            'user_id': request.user.id
        }
    else:
        raise Http404()

    report_form = ReportOptionsForm()

    if generate:
        report_form = ReportOptionsForm(request.GET)
        if report_format == 'AsciiDoc':
            return render(
                request, 'dojo/asciidoc_report.html', {
                    'product_type':
                    product_type,
                    'product':
                    product,
                    'engagement':
                    engagement,
                    'test':
                    test,
                    'endpoint':
                    endpoint,
                    'findings':
                    findings.qs.distinct().order_by('numerical_severity'),
                    'include_finding_notes':
                    include_finding_notes,
                    'include_finding_images':
                    include_finding_images,
                    'include_executive_summary':
                    include_executive_summary,
                    'include_table_of_contents':
                    include_table_of_contents,
                    'include_disclaimer':
                    include_disclaimer,
                    'disclaimer':
                    disclaimer,
                    'user':
                    user,
                    'team_name':
                    settings.TEAM_NAME,
                    'title':
                    report_title,
                    'user_id':
                    request.user.id,
                    'host':
                    report_url_resolver(request),
                    'host_view':
                    host_view,
                    'context':
                    context,
                })
        elif report_format == 'HTML':
            return render(
                request, template, {
                    'product_type':
                    product_type,
                    'product':
                    product,
                    'engagement':
                    engagement,
                    'report_name':
                    report_name,
                    'test':
                    test,
                    'endpoint':
                    endpoint,
                    'endpoints':
                    endpoints,
                    'findings':
                    findings.qs.distinct().order_by('numerical_severity'),
                    'include_finding_notes':
                    include_finding_notes,
                    'include_finding_images':
                    include_finding_images,
                    'include_executive_summary':
                    include_executive_summary,
                    'include_table_of_contents':
                    include_table_of_contents,
                    'include_disclaimer':
                    include_disclaimer,
                    'disclaimer':
                    disclaimer,
                    'user':
                    user,
                    'team_name':
                    settings.TEAM_NAME,
                    'title':
                    report_title,
                    'user_id':
                    request.user.id,
                    'host':
                    "",
                    'host_view':
                    host_view,
                    'context':
                    context,
                })

        else:
            raise Http404()
    paged_findings = get_page_items(
        request,
        findings.qs.distinct().order_by('numerical_severity'), 25)

    product_tab = None
    if engagement:
        product_tab = Product_Tab(engagement.product.id,
                                  title="Engagement Report",
                                  tab="engagements")
        product_tab.setEngagement(engagement)
    elif test:
        product_tab = Product_Tab(test.engagement.product.id,
                                  title="Test Report",
                                  tab="engagements")
        product_tab.setEngagement(test.engagement)
    elif product:
        product_tab = Product_Tab(product.id,
                                  title="Product Report",
                                  tab="findings")
    elif endpoints:
        if host_view:
            product_tab = Product_Tab(endpoint.product.id,
                                      title="Endpoint Host Report",
                                      tab="endpoints")
        else:
            product_tab = Product_Tab(endpoint.product.id,
                                      title="Endpoint Report",
                                      tab="endpoints")

    return render(
        request, 'dojo/request_report.html', {
            'product_type': product_type,
            'product': product,
            'product_tab': product_tab,
            'engagement': engagement,
            'test': test,
            'endpoint': endpoint,
            'findings': findings,
            'paged_findings': paged_findings,
            'report_form': report_form,
            'host_view': host_view,
            'context': context,
        })