def test_list_findings(self):
     project_name = 'unittesting'
     test_data = list_findings(project_name)
     expected_output = [
         '422286126', '436992569', '463461507', '463558592', '457497316'
     ]
     assert expected_output == test_data
    def resolve_total_findings(self, info):
        """Resolve total findings attribute."""
        finding_ids = finding_domain.filter_deleted_findings(
            project_domain.list_findings(self.name))
        findings_loader = info.context.loaders['finding']
        findings = findings_loader.load_many(finding_ids).then(
            lambda findings: [finding for finding in findings
                              if finding.current_state != 'DELETED'])
        self.total_findings = findings.then(len)

        return self.total_findings
    def resolve_findings(self, info):
        """Resolve findings attribute."""
        util.cloudwatch_log(info.context, 'Security: Access to {project} '
                            'findings'.format(project=self.name))
        finding_ids = finding_domain.filter_deleted_findings(
            project_domain.list_findings(self.name))
        findings_loader = info.context.loaders['finding']
        self.findings = findings_loader.load_many(finding_ids).then(
            lambda findings: [finding for finding in findings
                              if finding.current_state != 'DELETED'])

        return self.findings
def delete_project(project):
    """Delete project information."""
    project = project.lower()
    are_users_removed = remove_all_users_access(project)
    are_findings_masked = [
        finding_domain.mask_finding(finding_id)
        for finding_id in project_domain.list_findings(project)]
    update_project_state_db = project_domain.update(project, {'project_status': 'FINISHED'})
    is_project_deleted = all([
        are_findings_masked, are_users_removed, update_project_state_db])
    util.invalidate_cache(project)

    return is_project_deleted
    def resolve_max_severity(self, info):
        """Resolve maximum severity attribute."""
        finding_ids = finding_domain.filter_deleted_findings(
            project_domain.list_findings(self.name))
        findings_loader = info.context.loaders['finding']

        self.max_severity = findings_loader.load_many(finding_ids).then(
            lambda findings: max([
                finding.severity_score for finding in findings
                if finding.current_state != 'DELETED'])
            if findings else 0)

        return self.max_severity
    def resolve_closed_vulnerabilities(self, info):
        """Resolve closed vulnerabilities attribute."""
        finding_ids = finding_domain.filter_deleted_findings(
            project_domain.list_findings(self.name))
        vulns_loader = info.context.loaders['vulnerability']

        self.closed_vulnerabilities = vulns_loader.load_many(finding_ids).then(
            lambda findings: sum([
                len([vuln for vuln in vulns
                     if vuln_domain.get_current_state(vuln) == 'closed' and
                     (vuln.current_approval_status != 'PENDING' or
                      vuln.last_approved_status)])
                for vulns in findings
            ]))

        return self.closed_vulnerabilities
def project_to_pdf(request, lang, project, doctype):
    "Export a project to a PDF"
    assert project.strip()
    if not has_access_to_project(request.session['username'],
                                 project, request.session['role']):
        util.cloudwatch_log(request, 'Security: Attempted to export project'
                                     ' pdf without permission')
        return util.response([], 'Access denied', True)
    else:
        user = request.session['username'].split('@')[0]
        validator = validation_project_to_pdf(request, lang, doctype)
        if validator is not None:
            return validator
        findings = finding_domain.get_findings(
            project_domain.list_findings(project.lower()))
        findings = [cast_new_vulnerabilities(
            get_open_vuln_by_type(finding['findingId'], request), finding)
            for finding in findings]
        description = project_domain.get_description(project.lower())

        pdf_maker = CreatorPDF(lang, doctype)
        secure_pdf = SecurePDF()
        findings_ord = util.ord_asc_by_criticidad(findings)
        findings = pdf_evidences(findings_ord)
        report_filename = ''
        if doctype == 'tech':
            pdf_maker.tech(findings, project, description)
            report_filename = secure_pdf.create_full(user,
                                                     pdf_maker.out_name,
                                                     project)
        else:
            return HttpResponse(
                'Disabled report generation', content_type='text/html')
        if not os.path.isfile(report_filename):
            rollbar.report_message(
                'Couldn\'t generate pdf report', 'error', request)
            return HttpResponse(
                'Couldn\'t generate pdf report', content_type='text/html')
        with open(report_filename, 'rb') as document:
            response = HttpResponse(document.read(),
                                    content_type='application/pdf')
            response['Content-Disposition'] = \
                'inline;filename={}_IT.pdf'.format(project)
        return response
def project_to_xls(request, lang, project):
    "Create the technical report"
    username = request.session['username'].split("@")[0]
    if project.strip() == "":
        rollbar.report_message(
            'Error: Empty fields in project', 'error', request)
        return util.response([], 'Empty fields', True)
    if not has_access_to_project(request.session['username'],
                                 project, request.session['role']):
        util.cloudwatch_log(
            request,
            'Security: Attempted to export project xls without permission')
        return util.response([], 'Access denied', True)
    if lang not in ["es", "en"]:
        rollbar.report_message('Error: Unsupported language', 'error', request)
        return util.response([], 'Unsupported language', True)
    findings = finding_domain.get_findings(
        project_domain.list_findings(project.lower()))
    if findings:
        findings = [cast_new_vulnerabilities(
            get_open_vuln_by_type(finding['findingId'], request), finding)
            for finding in findings]
    else:
        rollbar.report_message(
            'Project {} does not have findings in dynamo'.format(project),
            'warning',
            request)
        return util.response([], 'Empty fields', True)
    data = util.ord_asc_by_criticidad(findings)
    it_report = ITReport(project, data, username)
    filepath = it_report.result_filename
    reports.set_xlsx_password(filepath, time.strftime('%d%m%Y') + username)

    with open(filepath, 'rb') as document:
        response = HttpResponse(document.read())
        response['Content-Type'] = ('application/vnd.openxmlformats'
                                    '-officedocument.spreadsheetml.sheet')
        response['Content-Disposition'] = 'inline;filename={}.xlsx'.format(
            project)
    return response
Example #9
0
def reset_expired_accepted_findings():
    """ Update treatment if acceptance date expires """
    rollbar.report_message('Warning: Function to update treatment if'
                           'acceptance date expires is running', 'warning')
    today = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    projects = project_domain.get_active_projects()
    for project in projects:
        findings = finding_domain.get_findings(
            finding_domain.filter_deleted_findings(
                project_domain.list_findings(project)))
        for finding in findings:
            finding_id = finding.get('findingId')
            historic_treatment = finding.get('historicTreatment', [{}])
            is_accepted_expired = historic_treatment[-1].get('acceptance_date', today) < today
            is_undefined_accepted_expired = (
                historic_treatment[-1].get('treatment') == 'ACCEPTED_UNDEFINED' and
                historic_treatment[-1].get('acceptance_status') == 'SUBMITTED' and
                datetime.strptime(historic_treatment[-1].get('date'), "%Y-%m-%d %H:%M:%S")
                + timedelta(days=5) <= datetime.strptime(today, "%Y-%m-%d %H:%M:%S"))
            if is_accepted_expired or is_undefined_accepted_expired:
                updated_values = {'treatment': 'NEW'}
                finding_domain.update_treatment(finding_id, updated_values, '')
                util.invalidate_cache(finding_id)