#
# Security Response Tool Implementation
#
# Copyright (C) 2017-2018 Wind River Systems
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# Please run flake8 on this file before sending patches
import os
import logging
from datetime import datetime, timedelta
import csv
from openpyxl import Workbook
from openpyxl import load_workbook
from openpyxl.styles import Border, Side, PatternFill, Font, GradientFill, Alignment
from openpyxl.utils import get_column_letter
from orm.models import Cve, CveSource, Vulnerability, Investigation, Defect, Product
from orm.models import Package
from orm.models import SRTool, SrtSetting
from orm.models import PublishSet, DefectHistory
from orm.models import Notify, ErrorLog
from srtgui.api import readCveDetails, summaryCveDetails
from django.db.models import Q
logger = logging.getLogger("srt")
SRT_BASE_DIR = os.environ.get('SRT_BASE_DIR', '.')
SRT_REPORT_DIR = '%s/reports' % SRT_BASE_DIR
# quick development/debugging support
from srtgui.api import _log
def _log_args(msg, *args, **kwargs):
s = '%s:(' % msg
if args:
for a in args:
s += '%s,' % a
s += '),('
if kwargs:
for key, value in kwargs.items():
s += '(%s=%s),' % (key,value)
s += ')'
_log(s)
###############################################################################
# Excel/openpyxl common look and feel formatting objects
#
#pyxl_border_all = Border(left=thin, right=thin, top=thin, bottom=thin) # , outline=True)
pyxl_thin = Side(border_style="thin")
pyxl_double = Side(border_style="double")
pyxl_border_left = Border(left=pyxl_thin)
pyxl_border_bottom = Border(bottom=pyxl_thin)
pyxl_border_bottom_left = Border(bottom=pyxl_thin, left=pyxl_thin)
pyxl_alignment_left = Alignment(horizontal='left')
pyxl_alignment_right = Alignment(horizontal='right')
pyxl_alignment_wrap = Alignment(wrap_text=True)
pyxl_font_bold = Font(bold=True)
pyxl_font_red = Font(color="A00000",bold=True,size = "13")
pyxl_font_grn = Font(color="00A000",bold=True,size = "13")
pyxl_font_blu = Font(color="0000A0",bold=True,size = "13")
pyxl_font_orn = Font(color="FF6600",bold=True,size = "13")
pyxl_fill_green = PatternFill(start_color="E0FFF0", end_color="E0FFF0", fill_type = "solid")
# Warning: the form "PatternFill(bgColor="xxxxxx", fill_type = "solid")" returns black cells
pyxl_backcolor_red = PatternFill(start_color='FCCDBA', end_color='FCCDBA', fill_type = "solid")
pyxl_backcolor_orn = PatternFill(start_color='FBEAAB', end_color='FBEAAB', fill_type = "solid")
pyxl_backcolor_yel = PatternFill(start_color='FCFDC7', end_color='FCFDC7', fill_type = "solid")
pyxl_backcolor_blu = PatternFill(start_color='C5E2FF', end_color='C5E2FF', fill_type = "solid")
pyxl_backcolor_grn = PatternFill(start_color='D6EDBD', end_color='D6EDBD', fill_type = "solid")
pyxl_cve_fills = [pyxl_backcolor_red,pyxl_backcolor_orn,pyxl_backcolor_yel,pyxl_backcolor_blu,None,None,None]
def pyxl_write_cell(ws,row_num,column_num,value,border=None,font=None,fill=None,alignment=None):
cell = ws.cell(row=row_num, column=column_num)
try:
cell.value = value
if fill:
cell.fill = fill
if alignment:
cell.alignment = alignment
if border:
cell.border = border
if font:
cell.font = font
except Exception as e:
print("ERROR:(%d,%d):%s" % (row_num,column_num,e))
# Optional next column return value
return(column_num+1)
###############################################################################
# Core report support
#
class Report():
def __init__(self, parent_page, *args, **kwargs):
self.parent_page = parent_page
self.report_name = '%s%s' % (parent_page[0].upper(),parent_page[1:])
self.title = self.report_name
self.request = kwargs['request']
def get_context_data(self, *args, **kwargs):
context = {}
context['title'] = self.title
context['parent_page'] = self.parent_page
context['report_name'] = self.report_name
context['report_enable_submit'] = '1'
# global variables
return context
def exec_report(self, *args, **kwargs):
return None
class ManagementReport(Report):
"""Report for the Management Page"""
def __init__(self, parent_page, *args, **kwargs):
_log_args("REPORT_MANAGEMENT_INIT(%s)" % parent_page, *args, **kwargs)
super(ManagementReport, self).__init__(parent_page, *args, **kwargs)
def get_context_data(self, *args, **kwargs):
_log_args("REPORT_MANAGEMENT_CONTEXT", *args, **kwargs)
context = super(ManagementReport, self).get_context_data(*args, **kwargs)
context['report_type_list'] = '\
\
\
\
'
context['report_get_title'] = '1'
context['report_recordrange_list'] = '\
Selected
\
'
context['report_columnrange_list'] = ''
context['report_format_list'] = '\
Text
\
CSV \
(Separator: \
) \
\
'
return context
def exec_report(self, *args, **kwargs):
_log_args("REPORT_MANAGEMENT_EXEC", *args, **kwargs)
super(ManagementReport, self).exec_report(*args, **kwargs)
request_POST = self.request.POST
records = request_POST.get('records', '')
format = request_POST.get('format', '')
title = request_POST.get('title', '')
report_type = request_POST.get('report_type', '')
csv_separator = request_POST.get('csv_separator', 'semi')
report_name = '%s/management_%s_%s.%s' % (SRT_REPORT_DIR,report_type,datetime.today().strftime('%Y%m%d_%H%M'),format)
with open(report_name, 'w') as file:
if 'csv' == format:
tab = ';'
if csv_separator == 'comma': tab = ','
if csv_separator == 'tab': tab = '\t'
else:
tab = " = "
if 'status' == report_type:
if 'txt' == format:
file.write("Report : Management - Summary\n")
file.write("\n")
file.write("%s%s%s\n" % ('cve_total',tab,Cve.objects.all().count()))
file.write("%s%s%s\n" % ('cve_new',tab,Cve.objects.filter(status=Cve.NEW).count()))
file.write("%s%s%s\n" % ('cve_open',tab,Cve.objects.filter( Q(status=Cve.INVESTIGATE) & Q(status=Cve.VULNERABLE) ).count()))
file.write("%s%s%s\n" % ('vulnerability_total',tab,Vulnerability.objects.all().count()))
file.write("%s%s%s\n" % ('vulnerability_open',tab,Vulnerability.objects.filter(outcome=Vulnerability.OPEN).count()))
file.write("%s%s%s\n" % ('vulnerability_critical',tab,Vulnerability.objects.filter(priority=Vulnerability.CRITICAL).count()))
file.write("%s%s%s\n" % ('vulnerability_high',tab,Vulnerability.objects.filter(priority=Vulnerability.HIGH).count()))
file.write("%s%s%s\n" % ('vulnerability_medium',tab,Vulnerability.objects.filter(priority=Vulnerability.MEDIUM).count()))
file.write("%s%s%s\n" % ('vulnerability_low',tab,Vulnerability.objects.filter(priority=Vulnerability.LOW).count()))
file.write("%s%s%s\n" % ('investigation_total',tab,Investigation.objects.all().count()))
file.write("%s%s%s\n" % ('investigation_open',tab,Investigation.objects.filter(outcome=Investigation.OPEN).count()))
file.write("%s%s%s\n" % ('investigation_critical',tab,Investigation.objects.filter(priority=Investigation.CRITICAL).count()))
file.write("%s%s%s\n" % ('investigation_high',tab,Investigation.objects.filter(priority=Investigation.HIGH).count()))
file.write("%s%s%s\n" % ('investigation_medium',tab,Investigation.objects.filter(priority=Investigation.MEDIUM).count()))
file.write("%s%s%s\n" % ('investigation_low',tab,Investigation.objects.filter(priority=Investigation.LOW).count()))
file.write("%s%s%s\n" % ('defect_total',tab,Defect.objects.all().count()))
if 'vulnerabilities' == report_type:
if 'txt' == format:
file.write("Report : Management - Open Vulnerabilities\n")
file.write("\n")
else:
file.write("Name\tStatus\tOutcome\tPriority\tComments\tCVEs\tInvestigations\n")
for v in Vulnerability.objects.filter(outcome=Vulnerability.OPEN):
if 'txt' == format:
file.write("Name: %s\n" % v.name)
file.write(" Status: %s\n" % v.get_status_text)
file.write(" Outcome: %s\n" % v.get_outcome_text)
file.write(" Priority: %s\n" % v.get_priority_text)
file.write(" Comments: %s\n" % v.comments)
file.write(" CVEs: ")
for i,vc in enumerate(v.vulnerability_to_cve.all()):
if i > 0:
file.write(",")
file.write("%s" % vc.cve.name)
file.write("\n")
file.write(" Investigations: ")
for i,investigation in enumerate(Investigation.objects.filter(vulnerability=v)):
if i > 0:
file.write(",")
file.write("%s" % investigation.name)
file.write("\n")
file.write("\n")
else:
file.write("%s\t%s\t%s\t%s\t%s\t" % (v.name,v.get_status_text,v.get_outcome_text,v.get_priority_text,v.comments))
for i,vc in enumerate(v.vulnerability_to_cve.all()):
if i > 0:
file.write(",")
file.write("%s" % vc.cve.name)
file.write("\t")
for i,investigation in enumerate(Investigation.objects.filter(vulnerability=v)):
if i > 0:
file.write(",")
file.write("%s" % investigation.name)
file.write("\n")
if 'investigations' == report_type:
if 'txt' == format:
file.write("Report : Management - Open Vulnerabilities\n")
file.write("\n")
else:
file.write("Name\tStatus\tOutcome\tPriority\tComments\tDefects\n")
for investigation in Investigation.objects.filter(outcome=Vulnerability.OPEN):
if 'txt' == format:
file.write("Name: %s\n" % investigation.name)
file.write(" Status: %s\n" % investigation.get_status_text)
file.write(" Outcome: %s\n" % investigation.get_outcome_text)
file.write(" Priority: %s\n" % investigation.get_priority_text)
file.write(" Comments: %s\n" % investigation.comments)
file.write(" Defects: ")
for i,id in enumerate(investigation.investigation_to_defect.filter(investigation=investigation)):
if i > 0:
file.write(",")
file.write("%s" % id.defect.name)
file.write("\n")
file.write("\n")
else:
file.write("%s\t%s\t%s\t%s\t%s\t" % (investigation.name,investigation.get_status_text,
investigation.get_outcome_text,investigation.get_priority_text,investigation.comments))
for i,id in enumerate(investigation.investigation_to_defect.filter(investigation=investigation)):
if i > 0:
file.write(",")
file.write("%s" % id.defect.name)
file.write("\n")
return report_name,os.path.basename(report_name)
class CveReport(Report):
"""Report for the CVE Page"""
def __init__(self, parent_page, *args, **kwargs):
_log_args("REPORT_CVE_INIT(%s)" % parent_page, *args, **kwargs)
super(CveReport, self).__init__(parent_page, *args, **kwargs)
def get_context_data(self, *args, **kwargs):
_log_args("REPORT_CVE_CONTEXT", *args, **kwargs)
context = super(CveReport, self).get_context_data(*args, **kwargs)
context['report_type_list'] = '\
\
\
'
context['report_get_title'] = '1'
context['report_recordrange_list'] = '\
Selected
\
'
context['report_columnrange_list'] = ''
context['report_format_list'] = '\
Text
\
'
context['report_custom_list'] = '\
CVSS_v2
\
References
\
CPE list
\
'
return context
def exec_report(self, *args, **kwargs):
_log_args("REPORT_CVE_EXEC", *args, **kwargs)
super(CveReport, self).exec_report(*args, **kwargs)
request_POST = self.request.POST
records = request_POST.get('records', '')
format = request_POST.get('format', '')
title = request_POST.get('title', '')
report_type = request_POST.get('report_type', '')
record_list = request_POST.get('record_list', '')
cvss_v2 = request_POST.get('cvss_v2', '')
ref_list = request_POST.get('ref', '')
cpe = request_POST.get('cpe', '')
cve = Cve.objects.get(id=record_list)
report_name = '%s/cve_%s_%s.%s' % (SRT_REPORT_DIR,report_type,datetime.today().strftime('%Y%m%d_%H%M'),format)
with open(report_name, 'w') as file:
if 'csv' == format:
tab = "\t"
else:
tab = " = "
if ('summary' == report_type) or ('audit' == report_type):
if 'txt' == format:
file.write("Report : CVE %s - Summary\n" % cve.name)
file.write("\n")
# Gather the sources for this CVE
cve_sources = CveSource.objects.filter(cve=cve.id).order_by('pk')
if 1 < len(cve_sources):
sources = ''
for cve_source in cve_sources:
sources += '%s ' % cve_source.datasource.source
cveDetails,cve_html = summaryCveDetails(cve,cve_sources)
elif 1 == len(cve_sources):
sources = cve_sources[0].datasource.source
cveDetails = readCveDetails(cve,cve_sources[0].datasource)
cve_html = ''
else:
sources = ''
cveDetails = readCveDetails(cve,None)
cve_html = ''
file.write("%s%s%s\n" % ('source',tab,sources))
file.write("%s%s%s\n" % ('status',tab,cve.status))
file.write("%s%s%s\n" % ('cve_data_type',tab,cve.cve_data_type))
file.write("%s%s%s\n" % ('cve_data_format',tab,cve.cve_data_format))
file.write("%s%s%s\n" % ('cve_data_version',tab,cve.cve_data_version))
file.write("%s%s%s\n" % ('description',tab,cve.description))
file.write("\n")
file.write("CVSS Version 3:\n")
file.write(" %s%s%s\n" % ('cvssV3_baseScore',tab,cve.cvssV3_baseScore))
file.write(" %s%s%s\n" % ('cvssV3_baseSeverity',tab,cve.cvssV3_baseSeverity))
file.write(" %s%s%s\n" % ('cvssV3_vectorString',tab,cveDetails.cvssV3_vectorString))
file.write(" %s%s%s\n" % ('cvssV3_exploitabilityScore',tab,cveDetails.cvssV3_exploitabilityScore))
file.write(" %s%s%s\n" % ('cvssV3_impactScore',tab,cveDetails.cvssV3_impactScore))
file.write(" %s%s%s\n" % ('cvssV3_attackVector',tab,cveDetails.cvssV3_attackVector))
file.write(" %s%s%s\n" % ('cvssV3_attackComplexity',tab,cveDetails.cvssV3_attackComplexity))
file.write(" %s%s%s\n" % ('cvssV3_privilegesRequired',tab,cveDetails.cvssV3_privilegesRequired))
file.write(" %s%s%s\n" % ('cvssV3_userInteraction',tab,cveDetails.cvssV3_userInteraction))
file.write(" %s%s%s\n" % ('cvssV3_scope',tab,cveDetails.cvssV3_scope))
file.write(" %s%s%s\n" % ('cvssV3_confidentialityImpact',tab,cveDetails.cvssV3_confidentialityImpact))
file.write(" %s%s%s\n" % ('cvssV3_integrityImpact',tab,cveDetails.cvssV3_integrityImpact))
file.write(" %s%s%s\n" % ('cvssV3_availabilityImpact',tab,cveDetails.cvssV3_availabilityImpact))
if (cvss_v2):
file.write("\n")
file.write("CVSS Version 2:\n")
file.write(" %s%s%s\n" % ('cvssV2_baseScore',tab,cve.cvssV2_baseScore))
file.write(" %s%s%s\n" % ('cvssV2_severity',tab,cve.cvssV2_severity))
file.write(" %s%s%s\n" % ('cvssV2_vectorString',tab,cveDetails.cvssV2_vectorString))
file.write(" %s%s%s\n" % ('cvssV2_exploitabilityScore',tab,cveDetails.cvssV2_exploitabilityScore))
file.write(" %s%s%s\n" % ('cvssV2_impactScore',tab,cveDetails.cvssV2_impactScore))
file.write(" %s%s%s\n" % ('cvssV2_accessVector',tab,cveDetails.cvssV2_accessVector))
file.write(" %s%s%s\n" % ('cvssV2_accessComplexity',tab,cveDetails.cvssV2_accessComplexity))
file.write(" %s%s%s\n" % ('cvssV2_authentication',tab,cveDetails.cvssV2_authentication))
file.write(" %s%s%s\n" % ('cvssV2_confidentialityImpact',tab,cveDetails.cvssV2_confidentialityImpact))
file.write(" %s%s%s\n" % ('cvssV2_integrityImpact',tab,cveDetails.cvssV2_integrityImpact))
if (ref_list):
file.write("\n")
file.write("References:\n")
for i,ref in enumerate(cve.references.all()):
file.write(" %s\n" % ref.hyperlink)
if (cpe):
file.write("\n")
file.write("CPE Table:\n")
for cpe in cve.cpe_list.split("|"):
if '' == cpe:
file.write(" Configation:\n")
elif '' == cpe:
file.write(" * AND\n")
elif '' == cpe:
file.write(" * OR\n")
else :
file.write(" %s\n" % cpe)
if 'audit' == report_type:
for cv in cve.cve_to_vulnerability.all():
v = cv.vulnerability
file.write("\n")
file.write("-------------------------------------------\n")
file.write("Vulnerability: %s\n" % v.name)
file.write(" Status: %s\n" % v.get_status_text)
file.write(" Outcome: %s\n" % v.get_outcome_text)
file.write(" Priority: %s\n" % v.get_priority_text)
file.write(" Comments: %s\n" % v.comments)
file.write("\n")
file.write(" Investigations:\n")
for investigation in Investigation.objects.filter(vulnerability=v):
file.write(" Name: %s\n" % investigation.name)
file.write(" Status: %s\n" % investigation.get_status_text)
file.write(" Outcome: %s\n" % investigation.get_outcome_text)
file.write(" Priority: %s\n" % investigation.get_priority_text)
file.write(" Defects: ")
for i,id in enumerate(investigation.investigation_to_defect.all()):
if i > 0:
file.write(",")
file.write("%s (%s)" % (id.defect.name,id.defect.get_status_text))
file.write("\n")
file.write("\n")
file.write(" Comments:\n")
for i,vc in enumerate(v.vulnerability_comments.all()):
file.write(" %s (%s): %s\n" % (vc.date,vc.author,vc.comment))
file.write("\n")
file.write(" Audit Trail:\n")
for i,vh in enumerate(v.vulnerability_history.all()):
file.write(" %s (%s): %s\n" % (vh.date,vh.author,vh.comment))
file.write("\n")
else:
file.write("Investigations: no attached investigations as this time\n")
return report_name,os.path.basename(report_name)
class VulnerabilityReport(Report):
"""Report for the Vulnerability Page"""
def __init__(self, parent_page, *args, **kwargs):
_log_args("REPORT_VULNERABILITY_INIT(%s)" % parent_page, *args, **kwargs)
super(VulnerabilityReport, self).__init__(parent_page, *args, **kwargs)
def get_context_data(self, *args, **kwargs):
_log_args("REPORT_VULNERABILITY_CONTEXT", *args, **kwargs)
context = super(VulnerabilityReport, self).get_context_data(*args, **kwargs)
context['report_type_list'] = '\
\
\
'
context['report_get_title'] = '1'
context['report_recordrange_list'] = '\
Selected
\
'
context['report_columnrange_list'] = ''
context['report_format_list'] = '\
Text
\
'
return context
def exec_report(self, *args, **kwargs):
_log_args("REPORT_VULNERABILITY_EXEC", *args, **kwargs)
super(VulnerabilityReport, self).exec_report(*args, **kwargs)
request_POST = self.request.POST
records = request_POST.get('records', '')
format = request_POST.get('format', '')
title = request_POST.get('title', '')
report_type = request_POST.get('report_type', '')
record_list = request_POST.get('record_list', '')
vulnerability = Vulnerability.objects.get(id=record_list)
report_name = '%s/vulnerability_%s_%s.%s' % (SRT_REPORT_DIR,report_type,datetime.today().strftime('%Y%m%d_%H%M'),format)
with open(report_name, 'w') as file:
if 'csv' == format:
tab = "\t"
else:
tab = " = "
if ('summary' == report_type) or ('audit' == report_type):
if 'txt' == format:
file.write("Report : Vulnerability %s - Summary\n" % vulnerability.name)
file.write("\n")
file.write("Vulnerability: %s\n" % vulnerability.name)
file.write(" Status: %s\n" % vulnerability.get_status_text)
file.write(" Outcome: %s\n" % vulnerability.get_outcome_text)
file.write(" Priority: %s\n" % vulnerability.get_priority_text)
file.write(" Comments: %s\n" % vulnerability.comments)
file.write("\n")
file.write("Products:\n")
found_p = False
for i,product in enumerate(Product.objects.all().order_by('order')):
product_header = False
for investigation in Investigation.objects.filter(vulnerability=vulnerability,product=product):
found_p = True
found_i = True
if not product_header:
file.write("%2d) Product: %s\n" % (i+1,investigation.product.long_name))
product_header = True
file.write(" Investigation: %s\n" % investigation.name)
file.write(" Status: %s\n" % investigation.get_status_text)
file.write(" Outcome: %s\n" % investigation.get_outcome_text)
file.write(" Priority: %s\n" % investigation.get_priority_text)
file.write(" Defects: ")
for j,id in enumerate(investigation.investigation_to_defect.all()):
if j > 0:
file.write(",")
file.write("%s (%s)" % (id.defect.name,id.defect.get_status_text))
file.write("\n")
if not found_p:
file.write(" No products found\n")
file.write("\n")
file.write("Comments:\n")
found_c = False
for i,vc in enumerate(vulnerability.vulnerability_comments.all()):
found_c = True
file.write(" %2d) %s (%s): %s\n" % (i,vc.date,vc.author,vc.comment))
if not found_c:
file.write(" No comments found\n")
if 'audit' == report_type:
file.write("\n")
file.write("Audit Trail:\n")
for i,vh in enumerate(vulnerability.vulnerability_history.all()):
file.write(" %2d) %s (%s): %s\n" % (i,vh.date,vh.author,vh.comment))
file.write("\n")
return report_name,os.path.basename(report_name)
class InvestigationReport(Report):
"""Report for the Investigation Page"""
def __init__(self, parent_page, *args, **kwargs):
_log_args("REPORT_INVESTIGATION_INIT(%s)" % parent_page, *args, **kwargs)
super(InvestigationReport, self).__init__(parent_page, *args, **kwargs)
def get_context_data(self, *args, **kwargs):
_log_args("REPORT_INVESTIGATION_CONTEXT", *args, **kwargs)
context = super(InvestigationReport, self).get_context_data(*args, **kwargs)
context['report_type_list'] = '\
\
\
'
context['report_get_title'] = '1'
context['report_recordrange_list'] = '\
Selected
\
'
context['report_columnrange_list'] = ''
context['report_format_list'] = '\
Text
\
'
return context
def exec_report(self, *args, **kwargs):
_log_args("REPORT_INVESTIGATION_EXEC", *args, **kwargs)
super(InvestigationReport, self).exec_report(*args, **kwargs)
request_POST = self.request.POST
records = request_POST.get('records', '')
format = request_POST.get('format', '')
title = request_POST.get('title', '')
report_type = request_POST.get('report_type', '')
record_list = request_POST.get('record_list', '')
investigation = Investigation.objects.get(id=record_list)
report_name = '%s/investigation_%s_%s.%s' % (SRT_REPORT_DIR,report_type,datetime.today().strftime('%Y%m%d_%H%M'),format)
with open(report_name, 'w') as file:
if 'csv' == format:
tab = "\t"
else:
tab = " = "
if ('summary' == report_type) or ('audit' == report_type):
if 'txt' == format:
file.write("Report : Investigation %s - Summary\n" % investigation.name)
file.write("\n")
file.write("Name: %s\n" % investigation.name)
file.write(" Status: %s\n" % investigation.get_status_text)
file.write(" Outcome: %s\n" % investigation.get_outcome_text)
file.write(" Priority: %s\n" % investigation.get_priority_text)
file.write(" Defects: ")
for i,id in enumerate(investigation.investigation_to_defect.all()):
if i > 0:
file.write(",")
file.write("%s (%s)" % (id.defect.name,id.defect.get_status_text))
file.write("\n")
file.write("\n")
file.write("Comments:\n")
found_c = False
for i, ic in enumerate(investigation.investigation_comments.all()):
found_c = True
file.write(" %s (%s): %s\n" % (ic.date,ic.author,ic.comment))
if not found_c:
file.write(" No comments found\n")
if 'audit' == report_type:
file.write("\n")
file.write(" Audit Trail:\n")
for i,ih in enumerate(investigation.investigation_history.all()):
file.write(" %s (%s): %s\n" % (ih.date,ih.author,ih.comment))
file.write("\n")
return report_name,os.path.basename(report_name)
class DefectReport(Report):
"""Report for the Defect Page"""
def __init__(self, parent_page, *args, **kwargs):
_log_args("REPORT_DEFECT_INIT(%s)" % parent_page, *args, **kwargs)
super(DefectReport, self).__init__(parent_page, *args, **kwargs)
def get_context_data(self, *args, **kwargs):
_log_args("REPORT_DEFECT_CONTEXT", *args, **kwargs)
context = super(DefectReport, self).get_context_data(*args, **kwargs)
context['report_type_list'] = '\
\
'
context['report_get_title'] = '1'
context['report_recordrange_list'] = '\
Selected
\
'
context['report_columnrange_list'] = ''
context['report_format_list'] = '\
Text
\
CSV \
(Separator: \
) \
\
'
return context
def exec_report(self, *args, **kwargs):
_log_args("REPORT_DEFECT_EXEC", *args, **kwargs)
super(DefectReport, self).exec_report(*args, **kwargs)
request_POST = self.request.POST
records = request_POST.get('records', '')
format = request_POST.get('format', '')
title = request_POST.get('title', '')
report_type = request_POST.get('report_type', '')
record_list = request_POST.get('record_list', '')
csv_separator = request_POST.get('csv_separator', 'semi')
report_name = '%s/defect_%s_%s.%s' % (SRT_REPORT_DIR,report_type,datetime.today().strftime('%Y%m%d_%H%M'),format)
with open(report_name, 'w') as file:
if 'csv' == format:
tab = ';'
if csv_separator == 'comma': tab = ','
if csv_separator == 'tab': tab = '\t'
else:
tab = ","
if ('summary' == report_type):
if 'csv' == format:
file.write("Name\tSummary\tPriority\tStatus\tResolution\tSRT Priority\tSRT Status\tSRT Outcome\tReleased Version\tURL\tInvestigations\tProduct\n")
if 'txt' == format:
file.write("Report : Defects Table\n")
file.write("\n")
file.write("Name,Summary,Priority,Status,Resolution,SRT Priority,SRT Status,SRT Outcome,Released Version,URL,Investigations,Product\n")
defect = Defect.objects.get(id=record_list)
file.write("%s%s" % (defect.name,tab))
file.write("%s%s" % (defect.summary,tab))
file.write("%s%s" % (defect.get_defect_priority_text,tab))
file.write("%s%s" % (defect.get_defect_status_text,tab))
file.write("%s%s" % (defect.get_defect_resolution_text,tab))
file.write("%s%s" % (defect.get_priority_text,tab))
file.write("%s%s" % (defect.get_status_text,tab))
file.write("%s%s" % (defect.get_outcome_text,tab))
file.write("%s%s" % (defect.release_version,tab))
file.write("%s%s" % (defect.publish,tab))
file.write("%s%s" % (defect.url,tab))
for i,di in enumerate(defect.defect_to_investigation.all()):
if i > 0:
file.write(" ")
file.write("%s" % (di.investigation.name))
file.write("%s" % tab)
tab='' # EOL
file.write("%s%s" % (defect.product.long_name,tab))
file.write("\n")
return report_name,os.path.basename(report_name)
class CvesReport(Report):
"""Report for the CVEs Page"""
def __init__(self, parent_page, *args, **kwargs):
_log_args("REPORT_CVES_INIT(%s)" % parent_page, *args, **kwargs)
super(CvesReport, self).__init__(parent_page, *args, **kwargs)
def get_context_data(self, *args, **kwargs):
_log_args("REPORT_CVES_CONTEXT", *args, **kwargs)
context = super(CvesReport, self).get_context_data(*args, **kwargs)
context['report_type_list'] = '\
\
\
\
\
'
context['report_get_title'] = ''
context['report_recordrange_list'] = '\
Displayed
\
All
\
'
context['report_columnrange_list'] = '\
Default
\
All
\
'
context['report_format_list'] = '\
Text (comma delimited)
\
CSV \
(Separator: \
) \
'
context['report_custom_list'] = '\
CVE name filter =
\
'
return context
def print_row_summary(self,writer,is_header,is_full,cve):
if is_header:
if not is_full:
writer.writerow([
'Name',
'Status',
'Severity (V3)',
'Published',
'Modified',
'Comments',
'Comments Private',
'Vulnerabilities',
'Defects',
'Description',
])
else:
writer.writerow([
'Name',
'Status',
'Score',
'Data Type',
'Data Format',
'Data Version',
'Severity (V3)',
'Severity (V2)',
'Published',
'Modified',
'Comments',
'Comments Private',
'Publish Request',
'Publish Date',
'Vulnerabilities',
'Defects',
'Description',
])
else:
cve_vulnerabilities = ''
for i,cv in enumerate(cve.cve_to_vulnerability.all()):
if i > 0:
cve_vulnerabilities += ' '
cve_vulnerabilities += cv.vulnerability.name
cve_defects = ''
i = 0
for cv in cve.cve_to_vulnerability.all():
for investigation in cv.vulnerability.vulnerability_investigation.all():
for id in investigation.investigation_to_defect.all():
if i > 0:
cve_defects += ' '
i += 1
cve_defects += id.defect.name
if not is_full:
writer.writerow([
cve.name,
cve.get_status_text,
'%s %s' % (cve.cvssV3_baseScore,cve.cvssV3_baseSeverity),
cve.get_publish_text,
cve.lastModifiedDate,
cve.comments,
cve.comments_private,
cve_vulnerabilities,
cve_defects,
cve.description,
])
else:
writer.writerow([
cve.name,
cve.get_status_text,
'%s %s' % (cve.recommend,cve.recommend_list),
cve.cve_data_type,
cve.cve_data_format,
cve.cve_data_version,
'%s %s' % (cve.cvssV3_baseScore,cve.cvssV3_baseSeverity),
'%s %s' % (cve.cvssV2_baseScore,cve.cvssV2_severity),
cve.get_publish_text,
cve.lastModifiedDate,
cve.comments,
cve.comments_private,
cve.get_publish_text,
cve.publishedDate,
cve_vulnerabilities,
cve_defects,
cve.description,
])
def print_row_cve_defects(self,writer,mode,is_full,cve,vulnerability,investigation,defect):
if 'header' == mode:
if not is_full:
writer.writerow([
'Name',
'Status',
'Severity (V3)',
'Published',
'Vulnerability',
'Investigation',
'Investigation Product',
'Investigation Priority',
'Investigation Status',
'Investigation Outcome',
'Defect',
'Defect Priority',
'Defect Status',
'Defect resolution',
])
else:
writer.writerow([
'Name',
'Status',
'Severity (V3)',
'Published',
'Vulnerability',
'Investigation',
'Investigation Product',
'Investigation Priority',
'Investigation Status',
'Investigation Outcome',
'Defect',
'Defect Priority',
'Defect Status',
'Defect resolution',
])
elif 'cve' == mode:
c2v_list = cve.cve_to_vulnerability.all()
if c2v_list:
for cv in c2v_list:
v2i_list = cv.vulnerability.vulnerability_investigation.all()
if v2i_list:
for investigation in v2i_list:
i2d_list = investigation.investigation_to_defect.all()
if i2d_list:
for i2d in investigation.investigation_to_defect.all():
self.print_row_cve_defects(writer,'line',is_full,cve,cv.vulnerability,investigation,i2d.defect)
else:
self.print_row_cve_defects(writer,'line',is_full,cve,cv.vulnerability,investigation,None)
else:
self.print_row_cve_defects(writer,'line',is_full,cve,cv.vulnerability,None,None)
else:
self.print_row_cve_defects(writer,'line',is_full,cve,None,None,None)
else:
if not is_full:
writer.writerow([
cve.name,
cve.get_status_text,
'%s %s' % (cve.cvssV3_baseScore,cve.cvssV3_baseSeverity),
cve.get_publish_text,
vulnerability.name if vulnerability else '',
investigation.name if investigation else '',
investigation.product.long_name if investigation and investigation.product else '',
investigation.get_priority_text if investigation else '',
investigation.get_status_text if investigation else '',
investigation.get_outcome_text if investigation else '',
defect.name if defect else '',
defect.get_priority_text if defect else '',
defect.get_status_text if defect else '',
defect.get_defect_resolution_text if defect else '',
])
else:
writer.writerow([
cve.get_status_text,
'%s %s' % (cve.cvssV3_baseScore,cve.cvssV3_baseSeverity),
cve.get_publish_text,
vulnerability.name if vulnerability else '',
investigation.name if investigation else '',
investigation.product.long_name if investigation and investigation.product else '',
investigation.get_priority_text if investigation else '',
investigation.get_status_text if investigation else '',
investigation.get_outcome_text if investigation else '',
defect.name if defect else '',
defect.get_priority_text if defect else '',
defect.get_status_text if defect else '',
defect.get_defect_resolution_text if defect else '',
])
def exec_report(self, *args, **kwargs):
_log_args("REPORT_CVES_EXEC", *args, **kwargs)
super(CvesReport, self).exec_report(*args, **kwargs)
request_POST = self.request.POST
range_rec = request_POST.get('range', '')
columns = request_POST.get('columns', '')
format = request_POST.get('format', '')
title = request_POST.get('title', '')
report_type = request_POST.get('report_type', '')
record_list = request_POST.get('record_list', '')
name_filter = request_POST.get('name_filter', '').upper()
csv_separator = request_POST.get('csv_separator', 'semi')
report_name = '%s/cves_%s_%s.%s' % (SRT_REPORT_DIR,report_type,datetime.today().strftime('%Y%m%d_%H%M'),format)
if 'csv' == format:
delimiter = ';'
if csv_separator == 'comma': delimiter = ','
if csv_separator == 'tab': delimiter = '\t'
else:
delimiter = ','
with open(report_name, 'w', newline='') as csvfile:
writer = csv.writer(csvfile, delimiter=delimiter,
quotechar='"', quoting=csv.QUOTE_MINIMAL)
if ('summary' == report_type):
self.print_row_summary(writer,True,"all" == columns,None)
if 'displayed' == range_rec:
for id in record_list.split(','):
if not id:
continue
cve = Cve.objects.get(id=id)
if not name_filter or (name_filter in cve.name):
self.print_row_summary(writer,False,"all" == columns,cve)
elif 'all' == range_rec:
if name_filter:
query = Cve.objects.filter(name__contains=name_filter).order_by('name')
else:
query = Cve.objects.all().order_by('name')
for cve in query:
self.print_row_summary(writer,False,"all" == columns,cve)
if ('cve_defects' == report_type):
self.print_row_cve_defects(writer,'header',"all" == columns,None,None,None,None)
if 'displayed' == range_rec:
for id in record_list.split(','):
if not id:
continue
cve = Cve.objects.get(id=id)
if not name_filter or (name_filter in cve.name):
self.print_row_cve_defects(writer,'cve',"all" == columns,cve,None,None,None)
elif 'all' == range_rec:
if name_filter:
query = Cve.objects.filter(name__contains=name_filter).order_by('name')
else:
query = Cve.objects.all().order_by('name')
for cve in query:
self.print_row_cve_defects(writer,'line',"all" == columns,cve,None,None,None)
if report_type in ['year_summary','year_pub_summary']:
columns = ["Year", "CVE_Total", "CVE_HIST", "CVE_NEW", "CVE_RES", "CVE_INV", "CVE_VUL", "CVE_NVUL", "Defect_Total", "DEFECT_HIST", "DEFECT_NEW", "DEFECT_RES", "DEFECT_INV", "DEFECT_VUL", "DEFECT_NVUL","BY_PUBLISH"]
for i,column in enumerate(columns):
csvfile.write("%s%s" % (columns[i],delimiter))
csvfile.write("\n")
summary = {}
YEAR_START = 1999
YEAR_STOP = 2020
for the_year in range(YEAR_START,YEAR_STOP+1):
summary[the_year] = {
'CVE_TOTAL':0,
'CVE_HISTORICAL':0,
'CVE_NEW':0,
'CVE_NEW_RESERVED':0,
'CVE_INVESTIGATE':0,
'CVE_VULNERABLE':0,
'CVE_NOT_VULNERABLE':0,
'DEFECT_TOTAL':0,
'DEFECT_HISTORICAL':0,
'DEFECT_NEW':0,
'DEFECT_NEW_RESERVED':0,
'DEFECT_INVESTIGATE':0,
'DEFECT_VULNERABLE':0,
'DEFECT_NOT_VULNERABLE':0,
'PUBLISH_DATE':0,
}
# Gather historgram on CVE status
error_count = 0
for cve in Cve.objects.all():
# Extract the year created
if (report_type == 'year_pub_summary') and (not cve.status in [SRTool.HISTORICAL]) and cve.publishedDate:
the_year = cve.publishedDate.split('-')[0]
summary[the_year]['PUBLISH_DATE'] += 1
else:
the_year = cve.name.split('-')[1]
if (not the_year[0].isdigit()) or (the_year < '1999') or (the_year > '2020'):
if 10 > error_count:
_log('FOO_CVE_YEARLY:%s,%s' % (cve.name, cve.publishedDate))
error_count += 1
continue
the_year = int(the_year)
# Register the CVE status
summary[the_year]['CVE_TOTAL'] += 1
if cve.status in [SRTool.HISTORICAL]:
summary[the_year]['CVE_HISTORICAL'] += 1
if cve.status in [SRTool.NEW,SRTool.NEW_INACTIVE]:
summary[the_year]['CVE_NEW'] += 1
if cve.status in [SRTool.NEW_RESERVED]:
summary[the_year]['CVE_NEW_RESERVED'] += 1
if cve.status in [SRTool.INVESTIGATE,SRTool.INVESTIGATE_INACTIVE]:
summary[the_year]['CVE_INVESTIGATE'] += 1
if cve.status in [SRTool.VULNERABLE,SRTool.VULNERABLE_INACTIVE]:
summary[the_year]['CVE_VULNERABLE'] += 1
if cve.status in [SRTool.NOT_VULNERABLE,SRTool.NOT_VULNERABLE_INACTIVE]:
summary[the_year]['CVE_NOT_VULNERABLE'] += 1
# Register the releated defects status
for cv in cve.cve_to_vulnerability.all():
for investigation in cv.vulnerability.vulnerability_investigation.all():
for id in investigation.investigation_to_defect.all():
# Only check defects for current and previously active products
if not id.product.get_product_tag('mode') in ['support','develop','eol']:
continue
# Register the defect status
summary[the_year]['DEFECT_TOTAL'] += 1
if id.defect.srt_status in [SRTool.HISTORICAL]:
summary[the_year]['DEFECT_HISTORICAL'] += 1
if id.defect.srt_status in [SRTool.NEW,SRTool.NEW_INACTIVE]:
summary[the_year]['DEFECT_NEW'] += 1
if id.defect.srt_status in [SRTool.NEW_RESERVED]:
summary[the_year]['DEFECT_NEW_RESERVED'] += 1
if id.defect.srt_status in [SRTool.INVESTIGATE,SRTool.INVESTIGATE_INACTIVE]:
summary[the_year]['DEFECT_INVESTIGATE'] += 1
if id.defect.srt_status in [SRTool.VULNERABLE,SRTool.VULNERABLE_INACTIVE]:
summary[the_year]['DEFECT_VULNERABLE'] += 1
if id.defect.srt_status in [SRTool.NOT_VULNERABLE,SRTool.NOT_VULNERABLE_INACTIVE]:
summary[the_year]['DEFECT_NOT_VULNERABLE'] += 1
# Print historgram
for the_year in range(YEAR_START,YEAR_STOP+1):
csvfile.write("%s%s" % (the_year,delimiter))
csvfile.write("%s%s" % (summary[the_year]['CVE_TOTAL'],delimiter))
csvfile.write("%s%s" % (summary[the_year]['CVE_HISTORICAL'],delimiter))
csvfile.write("%s%s" % (summary[the_year]['CVE_NEW'],delimiter))
csvfile.write("%s%s" % (summary[the_year]['CVE_NEW_RESERVED'],delimiter))
csvfile.write("%s%s" % (summary[the_year]['CVE_INVESTIGATE'],delimiter))
csvfile.write("%s%s" % (summary[the_year]['CVE_VULNERABLE'],delimiter))
csvfile.write("%s%s" % (summary[the_year]['CVE_NOT_VULNERABLE'],delimiter))
csvfile.write("%s%s" % (summary[the_year]['DEFECT_TOTAL'],delimiter))
csvfile.write("%s%s" % (summary[the_year]['DEFECT_HISTORICAL'],delimiter))
csvfile.write("%s%s" % (summary[the_year]['DEFECT_NEW'],delimiter))
csvfile.write("%s%s" % (summary[the_year]['DEFECT_NEW_RESERVED'],delimiter))
csvfile.write("%s%s" % (summary[the_year]['DEFECT_INVESTIGATE'],delimiter))
csvfile.write("%s%s" % (summary[the_year]['DEFECT_VULNERABLE'],delimiter))
csvfile.write("%s%s" % (summary[the_year]['DEFECT_NOT_VULNERABLE'],delimiter))
csvfile.write("%s%s" % (summary[the_year]['PUBLISH_DATE'],delimiter))
csvfile.write("\n")
return report_name,os.path.basename(report_name)
class SelectCvesReport(Report):
"""Report for the Select CVEs Page"""
def __init__(self, parent_page, *args, **kwargs):
_log_args("REPORT_SELECTCVES_INIT(%s)" % parent_page, *args, **kwargs)
super(SelectCvesReport, self).__init__(parent_page, *args, **kwargs)
def get_context_data(self, *args, **kwargs):
_log_args("REPORT_SELECTCVES_CONTEXT", *args, **kwargs)
context = super(SelectCvesReport, self).get_context_data(*args, **kwargs)
context['report_type_list'] = '\
\
'
context['report_get_title'] = ''
context['report_recordrange_list'] = '\
Selected
\
'
context['report_columnrange_list'] = ''
context['report_format_list'] = '\
Text
\
CSV
\
'
return context
def exec_report(self, *args, **kwargs):
_log_args("REPORT_SELECTCVES_EXEC", *args, **kwargs)
super(SelectCvesReport, self).exec_report(*args, **kwargs)
request_POST = self.request.POST
records = request_POST.get('records', '')
format = request_POST.get('format', '')
title = request_POST.get('title', '')
report_type = request_POST.get('report_type', '')
record_list = request_POST.get('record_list', '')
report_name = '%s/select_cves_%s_%s.%s' % (SRT_REPORT_DIR,report_type,datetime.today().strftime('%Y%m%d_%H%M'),format)
with open(report_name, 'w') as file:
if 'csv' == format:
tab = "\t"
else:
tab = ","
if ('summary' == report_type):
if 'csv' == format:
file.write("Name\tStatus\tType\tFormat\tVersion\tVulnerabilities\tDescription\n")
if 'txt' == format:
file.write("Report : CVEs Table\n")
file.write("\n")
file.write("Name,Status,Type,Format,Version,Vulnerabilities,Description\n")
for id in record_list.split(','):
if not id:
continue
cve = Cve.objects.get(id=id)
file.write("%s%s" % (cve.name,tab))
file.write("%s%s" % (cve.get_status_text,tab))
file.write("%s%s" % (cve.cve_data_type,tab))
file.write("%s%s" % (cve.cve_data_format,tab))
file.write("%s%s" % (cve.cve_data_version,tab))
for i,cv in enumerate(cve.cve_to_vulnerability.all()):
if i > 0:
file.write(" ")
file.write("%s" % cv.vulnerability.name)
file.write("%s" % tab)
file.write("%s%s" % (cve.description,tab))
file.write("\n")
return report_name,os.path.basename(report_name)
class VulnerabilitiesReport(Report):
"""Report for the Vulnerabilities Page"""
def __init__(self, parent_page, *args, **kwargs):
_log_args("REPORT_VULNERABILITIES_INIT(%s)" % parent_page, *args, **kwargs)
super(VulnerabilitiesReport, self).__init__(parent_page, *args, **kwargs)
def get_context_data(self, *args, **kwargs):
_log_args("REPORT_VULNERABILITIES_CONTEXT", *args, **kwargs)
context = super(VulnerabilitiesReport, self).get_context_data(*args, **kwargs)
context['report_type_list'] = '\
\
'
context['report_get_title'] = ''
context['report_recordrange_list'] = '\
Displayed
\
All
\
'
context['report_columnrange_list'] = '\
Default
\
All
\
'
context['report_format_list'] = '\
Text (comma delimited)
\
CSV (tab delimited)
\
'
return context
def print_row(self,writer,is_header,is_full,vulnerability):
if is_header:
if not is_full:
writer.writerow([
'Name',
'CVE',
'Status',
'Outcome',
'Priority',
'Comments',
'Comments Private',
'Investigations',
'Defects',
'Products',
])
else:
writer.writerow([
'Name',
'CVE',
'Status',
'Outcome',
'Priority',
'Comments',
'Comments Private',
'Investigations',
'Defects',
'Products',
])
else:
vulnerability_cves = ''
for i,vc in enumerate(vulnerability.vulnerability_to_cve.all()):
if i > 0:
vulnerability_cves += ' '
vulnerability_cves += vc.cve.name
vulnerability_investigations = ''
for i,investigation in enumerate(vulnerability.vulnerability_investigation.all()):
if i > 0:
vulnerability_investigations += ' '
vulnerability_investigations += investigation.name
vulnerability_defects = ''
i = 0
for investigation in vulnerability.vulnerability_investigation.all():
for id in investigation.investigation_to_defect.all():
if i > 0:
vulnerability_defects += ' '
i += 1
vulnerability_defects += id.defect.name
vulnerability_products = ''
for i,vi in enumerate(vulnerability.vulnerability2investigation.all()):
if i > 0:
vulnerability_products += ' '
vulnerability_products += vi.investigation.product.get_defect_tag('key')
if not is_full:
writer.writerow([
vulnerability.name,
vulnerability_cves,
vulnerability.get_status_text,
vulnerability.get_outcome_text,
vulnerability.get_priority_text,
vulnerability.comments,
vulnerability.comments_private,
vulnerability_investigations,
vulnerability_defects,
vulnerability_products,
])
else:
writer.writerow([
vulnerability.name,
vulnerability.cve_primary_name,
vulnerability.get_status_text,
vulnerability.get_outcome_text,
vulnerability.get_priority_text,
vulnerability.comments,
vulnerability.comments_private,
vulnerability_investigations,
vulnerability_defects,
vulnerability_products,
])
def exec_report(self, *args, **kwargs):
_log_args("REPORT_VULNERABILITIES_EXEC", *args, **kwargs)
super(VulnerabilitiesReport, self).exec_report(*args, **kwargs)
request_POST = self.request.POST
range = request_POST.get('range', '')
columns = request_POST.get('columns', '')
format = request_POST.get('format', '')
title = request_POST.get('title', '')
report_type = request_POST.get('report_type', '')
record_list = request_POST.get('record_list', '')
report_name = '%s/vulnerabilities_%s_%s.%s' % (SRT_REPORT_DIR,report_type,datetime.today().strftime('%Y%m%d_%H%M'),format)
if 'csv' == format:
delimiter = '\t'
else:
delimiter = ','
with open(report_name, 'w', newline='') as csvfile:
writer = csv.writer(csvfile, delimiter=delimiter,
quotechar='"', quoting=csv.QUOTE_MINIMAL)
if ('summary' == report_type):
self.print_row(writer,True,"all" == columns,None)
if 'displayed' == range:
for id in record_list.split(','):
if not id:
continue
vulnerability = Vulnerability.objects.get(id=id)
self.print_row(writer,False,"all" == columns,vulnerability)
elif 'all' == range:
query = Vulnerability.objects.all().order_by('name')
for vulnerability in query:
self.print_row(writer,False,"all" == columns,vulnerability)
return report_name,os.path.basename(report_name)
class InvestigationsReport(Report):
"""Report for the Investigations Page"""
def __init__(self, parent_page, *args, **kwargs):
_log_args("REPORT_INVESTIGATIONS_INIT(%s)" % parent_page, *args, **kwargs)
super(InvestigationsReport, self).__init__(parent_page, *args, **kwargs)
def get_context_data(self, *args, **kwargs):
_log_args("REPORT_INVESTIGATIONS_CONTEXT", *args, **kwargs)
context = super(InvestigationsReport, self).get_context_data(*args, **kwargs)
context['report_type_list'] = '\
\
'
context['report_get_title'] = ''
context['report_recordrange_list'] = '\
Displayed
\
All
\
'
context['report_columnrange_list'] = '\
Default
\
All
\
'
context['report_format_list'] = '\
Text
\
CSV \
(Separator: \
) \
\
'
context['report_custom_list'] = '\
Product defect prefix filter = (method to filter by product)
\
'
return context
def print_row(self,writer,is_header,is_full,investigation):
if is_header:
if not is_full:
writer.writerow([
'Name',
'Defects',
'Status',
'Outcome',
'Release Version',
'Priority',
'Comments',
'Comments Private',
'Vulnerability',
'Product',
'Updated',
])
else:
writer.writerow([
'Name',
'Defects',
'Status',
'Outcome',
'Release Version',
'Priority',
'Comments',
'Comments Private',
'Vulnerability',
'Product',
'Updated',
])
else:
investigation_defects = ''
for i,id in enumerate(investigation.investigation_to_defect.all()):
if i > 0:
investigation_defects += ' '
investigation_defects += id.defect.name
investigation_release_versions = ''
for i,id in enumerate(investigation.investigation_to_defect.all()):
if i > 0:
investigation_release_versions += ' '
investigation_release_versions += id.defect.release_version
if not is_full:
writer.writerow([
investigation.name,
investigation_defects,
investigation.get_status_text,
investigation.get_outcome_text,
investigation_release_versions,
investigation.get_priority_text,
investigation.comments,
investigation.comments_private,
investigation.vulnerability.get_long_name,
investigation.product.long_name,
investigation.srt_updated.strftime('%m-%d-%Y'),
])
else:
writer.writerow([
investigation.name,
investigation_defects,
investigation.get_status_text,
investigation.get_outcome_text,
investigation_release_versions,
investigation.get_priority_text,
investigation.comments,
investigation.comments_private,
investigation.vulnerability.get_long_name,
investigation.product.long_name,
investigation.srt_updated.strftime('%m-%d-%Y'),
])
def exec_report(self, *args, **kwargs):
_log_args("REPORT_INVESTIGATIONS_EXEC", *args, **kwargs)
super(InvestigationsReport, self).exec_report(*args, **kwargs)
request_POST = self.request.POST
range = request_POST.get('range', '')
columns = request_POST.get('columns', '')
format = request_POST.get('format', '')
title = request_POST.get('title', '')
report_type = request_POST.get('report_type', '')
record_list = request_POST.get('record_list', '')
name_filter = request_POST.get('name_filter', '').upper()
csv_separator = request_POST.get('csv_separator', 'semi')
report_name = '%s/investigations_%s_%s.%s' % (SRT_REPORT_DIR,report_type,datetime.today().strftime('%Y%m%d_%H%M'),format)
if 'csv' == format:
delimiter = ';'
if csv_separator == 'comma': delimiter = ','
if csv_separator == 'tab': delimiter = '\t'
else:
delimiter = ","
with open(report_name, 'w', newline='') as csvfile:
writer = csv.writer(csvfile, delimiter=delimiter,
quotechar='"', quoting=csv.QUOTE_MINIMAL)
if ('summary' == report_type):
self.print_row(writer,True,"all" == columns,None)
if 'displayed' == range:
for id in record_list.split(','):
if not id:
continue
investigation = Investigation.objects.get(id=id)
if not name_filter or (name_filter in investigation.product.get_defect_tag('key')):
self.print_row(writer,False,"all" == columns,investigation)
elif 'all' == range:
query = Investigation.objects.all().order_by('name')
for investigation in query:
if name_filter and (not name_filter in investigation.product.get_defect_tag('key')):
continue
self.print_row(writer,False,"all" == columns,investigation)
return report_name,os.path.basename(report_name)
class DefectsReport(Report):
"""Report for the Defects Page"""
def __init__(self, parent_page, *args, **kwargs):
_log_args("REPORT_DEFECTS_INIT(%s)" % parent_page, *args, **kwargs)
super(DefectsReport, self).__init__(parent_page, *args, **kwargs)
def get_context_data(self, *args, **kwargs):
_log_args("REPORT_DEFECTS_CONTEXT", *args, **kwargs)
context = super(DefectsReport, self).get_context_data(*args, **kwargs)
context['report_type_list'] = '\
\
'
context['report_get_title'] = ''
context['report_recordrange_list'] = '\
Displayed
\
All
\
'
context['report_columnrange_list'] = '\
Default
\
All
\
'
context['report_format_list'] = '\
Text (comma delimited)
\
CSV \
(Separator: \
) \
\
'
context['report_custom_list'] = '\
Defect name filter =
\
' % SrtSetting.get_setting('SRTOOL_DEFECT_SAMPLENAME',"DEFECT-XYZ")
return context
def print_row(self,writer,is_header,is_full,defect):
if is_header:
if not is_full:
writer.writerow([
'Name',
'Summary',
'Priority',
'Status',
'Resolution',
'SRT Priority',
'SRT Status',
'SRT Outcome',
'Release Version',
'Publish',
'Investigations',
'Product',
])
else:
writer.writerow([
'Name',
'Summary',
'Priority',
'Status',
'Resolution',
'SRT Priority',
'SRT Status',
'SRT Outcome',
'Release Version',
'Publish',
'URL',
'Investigations',
'Product',
])
else:
defect_investigations = ''
for i,di in enumerate(defect.defect_to_investigation.all()):
if i > 0:
defect_investigations += ' '
defect_investigations += di.investigation.name
if not is_full:
writer.writerow([
defect.name,
defect.summary,
defect.get_defect_priority_text,
defect.get_defect_status_text,
defect.get_defect_resolution_text,
defect.get_priority_text,
defect.get_status_text,
defect.get_outcome_text,
defect.release_version,
defect.publish,
defect_investigations,
defect.product.long_name if defect.product else '',
])
else:
writer.writerow([
defect.name,
defect.summary,
defect.get_defect_priority_text,
defect.get_defect_status_text,
defect.get_defect_resolution_text,
defect.get_priority_text,
defect.get_status_text,
defect.get_outcome_text,
defect.release_version,
defect.publish,
defect.url,
defect_investigations,
defect.product.long_name if defect.product else '',
])
def exec_report(self, *args, **kwargs):
_log_args("REPORT_DEFECTS_EXEC", *args, **kwargs)
super(DefectsReport, self).exec_report(*args, **kwargs)
request_POST = self.request.POST
range = request_POST.get('range', '')
columns = request_POST.get('columns', '')
format = request_POST.get('format', '')
title = request_POST.get('title', '')
report_type = request_POST.get('report_type', '')
record_list = request_POST.get('record_list', '')
name_filter = request_POST.get('name_filter', '').upper()
csv_separator = request_POST.get('csv_separator', 'semi')
report_name = '%s/defects_%s_%s.%s' % (SRT_REPORT_DIR,report_type,datetime.today().strftime('%Y%m%d_%H%M'),format)
if 'csv' == format:
delimiter = ';'
if csv_separator == 'comma': delimiter = ','
if csv_separator == 'tab': delimiter = '\t'
else:
delimiter = ','
with open(report_name, 'w', newline='') as csvfile:
writer = csv.writer(csvfile, delimiter=delimiter,
quotechar='"', quoting=csv.QUOTE_MINIMAL)
if ('summary' == report_type):
self.print_row(writer,True,"all" == columns,None)
if 'displayed' == range:
for id in record_list.split(','):
if not id:
continue
defect = Defect.objects.get(id=id)
if not name_filter or (name_filter in defect.name):
self.print_row(writer,False,"all" == columns,defect)
elif 'all' == range:
if name_filter:
query = Defect.objects.filter(name__contains=name_filter).order_by('name')
else:
query = Defect.objects.all().order_by('name')
for defect in query:
self.print_row(writer,False,"all" == columns,defect)
return report_name,os.path.basename(report_name)
#
# Products Reports
#
product_summary = {}
def scan_product_jira(product):
global product_summary
# Totals
critical_count = 0
high_count = 0
medium_count = 0
low_count = 0
p1_count = 0
p2_count = 0
p3_count = 0
p4_count = 0
px_count = 0
unresolved_count = 0
resolved_count = 0
fixed_count = 0
wontfix_count = 0
withdrawn_count = 0
rejected_count = 0
# Scan the registered defects
queryset = product.product_defect.all()
for defect in queryset:
if Defect.CRITICAL == defect.srt_priority: critical_count += 1
elif Defect.HIGH == defect.srt_priority: high_count += 1
elif Defect.MEDIUM == defect.srt_priority: medium_count += 1
elif Defect.LOW == defect.srt_priority: low_count += 1
if Defect.DEFECT_CRITICAL == defect.priority: p1_count += 1
elif Defect.DEFECT_HIGH == defect.priority: p2_count += 1
elif Defect.DEFECT_MEDIUM == defect.priority: p3_count += 1
elif Defect.DEFECT_LOW == defect.priority: p4_count += 1
if Defect.DEFECT_UNRESOLVED == defect.resolution: unresolved_count += 1
elif Defect.DEFECT_RESOLVED == defect.resolution: resolved_count += 1
elif Defect.DEFECT_FIXED == defect.resolution: fixed_count += 1
elif Defect.DEFECT_WILL_NOT_FIX == defect.resolution: wontfix_count += 1
elif Defect.DEFECT_WITHDRAWN == defect.resolution: withdrawn_count += 1
elif Defect.DEFECT_REJECTED == defect.resolution: rejected_count += 1
# Add this specific entry
product_summary[product.long_name] = [
critical_count,
high_count,
medium_count,
low_count,
p1_count,
p2_count,
p3_count,
p4_count,
px_count,
unresolved_count,
resolved_count,
fixed_count,
wontfix_count,
withdrawn_count,
rejected_count,
]
class ProductsReport(Report):
"""Report for the Products Page"""
global product_summary
def __init__(self, parent_page, *args, **kwargs):
_log_args("REPORT_PRODUCTS_INIT(%s)" % parent_page, *args, **kwargs)
super(ProductsReport, self).__init__(parent_page, *args, **kwargs)
def get_context_data(self, *args, **kwargs):
_log_args("REPORT_PRODUCTS_CONTEXT", *args, **kwargs)
context = super(ProductsReport, self).get_context_data(*args, **kwargs)
context['report_type_list'] = '\
\
\
'
context['report_get_title'] = '1'
context['report_recordrange_list'] = '\
All
\
'
context['report_columnrange_list'] = ''
context['report_format_list'] = '\
Text
\
CSV
\
Excel
\
'
return context
def exec_report(self, *args, **kwargs):
_log_args("REPORT_PRODUCTS_EXEC", *args, **kwargs)
super(ProductsReport, self).exec_report(*args, **kwargs)
request_POST = self.request.POST
records = request_POST.get('records', '')
format = request_POST.get('format', '')
title = request_POST.get('title', '')
report_type = request_POST.get('report_type', '')
record_list = request_POST.get('record_list', '')
if 'summary' == report_type:
report_name = '%s/products_%s_%s.%s' % (SRT_REPORT_DIR,report_type,datetime.today().strftime('%Y%m%d_%H%M'),format)
with open(report_name, 'w') as file:
if 'csv' == format:
tab = "\t"
else:
tab = ","
if ('summary' == report_type):
if 'csv' == format:
file.write("Name\tVersion\tProfile\tCPE\tSRT SPE\tInvestigations\tDefects\n")
if 'txt' == format:
file.write("Report : Products Table\n")
file.write("\n")
file.write("Name,Version,Profile,CPE,SRT SPE,Investigations,Defects\n")
for product in Product.objects.all():
file.write("%s%s" % (product.name,tab))
file.write("%s%s" % (product.version,tab))
file.write("%s%s" % (product.profile,tab))
file.write("%s%s" % (product.cpe,tab))
file.write("%s%s" % (product.defect_tags,tab))
file.write("%s%s" % (product.product_tags,tab))
if False:
for i,pi in enumerate(product.product_investigation.all()):
if i > 0:
file.write(" ")
file.write("%s" % (pi.name))
file.write("%s" % tab)
for i,pd in enumerate(product.product_defect.all()):
if i > 0:
file.write(" ")
file.write("%s" % (pd.name))
#file.write("%s" % tab)
file.write("\n")
elif 'status_jira' == report_type:
def resolution_color(i):
if 0 == i: fill = pyxl_backcolor_orn
elif 1 == i: fill = pyxl_backcolor_grn
elif 2 == i: fill = pyxl_backcolor_grn
elif 3 == i: fill = pyxl_backcolor_yel
elif 4 == i: fill = pyxl_backcolor_blu
elif 5 == i: fill = pyxl_backcolor_blu
else: fill = None
return(fill)
for product in Product.objects.all():
scan_product_jira(product)
format = "xlsx"
report_name = '%s/products_jira_%s_%s.%s' % (SRT_REPORT_DIR,report_type,datetime.today().strftime('%Y%m%d_%H%M'),format)
wb = Workbook()
ws = wb.active
ws.title = "Product Jira Summary"
ws.column_dimensions[get_column_letter(1)].width = 30
row = 1
first_row = 2
col = 1
for header in ('Product','Critical','High','Medium','Low','P1','P2','P3','P4','Unresolved','Resolved','Fixed',"Won't Fix",'Withdrawn','Rejected'):
border = pyxl_border_bottom_left if (col in (2,6,10)) else pyxl_border_bottom
pyxl_write_cell(ws,row,col,header,border=border)
col += 1
row += 1
for product in Product.objects.order_by("order"):
key = product.long_name
scan_product_jira(product)
pyxl_write_cell(ws,row,1,key)
# CVE Severity
col_excel = 2
col_summary = 1
for i in range(0,4):
border = pyxl_border_left if (i==0) else None
value = product_summary[key][col_summary+i]
pyxl_write_cell(ws,row,col_excel+i,value,border=border,fill=pyxl_cve_fills[i] if value else None)
# Jira Priority
col_excel = 6
col_summary = 5
for i in range(0,4):
border = pyxl_border_left if (i==0) else None
value = product_summary[key][col_summary+i]
pyxl_write_cell(ws,row,col_excel+i,value,border=border,fill=pyxl_cve_fills[i] if value else None)
# Jira Resolution
col_excel = 10
col_summary = 9
for i in range(0,6):
border = pyxl_border_left if (i==0) else None
value = product_summary[key][col_summary+i]
pyxl_write_cell(ws,row,col_excel+i,value,border=border,fill=resolution_color(i) if value else None)
row += 1
# Sums
row -= 1
for i in range(1,16):
border = pyxl_border_bottom_left if (i in (2,6,10)) else pyxl_border_bottom
ws.cell(row=row,column=i).border=border
row += 1
letters = (' ','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q')
for col_excel in range(2,16):
# CVE Severity
col_excel = 2
for i in range(0,4):
pyxl_write_cell(ws,row,col_excel+i,'=SUM(%s%d:%s%d)' % (letters[col_excel+i],first_row,letters[col_excel+i],row-1),fill=pyxl_cve_fills[i])
# Jira Priority
col_excel = 6
for i in range(0,4):
pyxl_write_cell(ws,row,col_excel+i,'=SUM(%s%d:%s%d)' % (letters[col_excel+i],first_row,letters[col_excel+i],row-1),fill=pyxl_cve_fills[i])
# Jira Resolution
col_excel = 10
for i in range(0,6):
pyxl_write_cell(ws,row,col_excel+i,'=SUM(%s%d:%s%d)' % (letters[col_excel+i],first_row,letters[col_excel+i],row-1),fill=resolution_color(i))
wb.save(report_name)
return report_name,os.path.basename(report_name)
#
# CVE Reports
#
class PublishCveReport(Report):
"""Report for the Publish Cve Page"""
def __init__(self, parent_page, *args, **kwargs):
_log_args("REPORT_PUBLISHCVE_INIT(%s)" % parent_page, *args, **kwargs)
super(PublishCveReport, self).__init__(parent_page, *args, **kwargs)
def get_context_data(self, *args, **kwargs):
_log_args("REPORT_PUBLISHCVE_CONTEXT", *args, **kwargs)
context = super(PublishCveReport, self).get_context_data(*args, **kwargs)
context['report_type_list'] = '\
\
'
context['report_get_title'] = '1'
context['report_recordrange_list'] = '\
Selected
\
'
context['report_columnrange_list'] = ''
context['report_format_list'] = '\
Text
\
CSV
\
'
return context
def exec_report(self, *args, **kwargs):
_log_args("REPORT_PUBLISHCVE_EXEC", *args, **kwargs)
super(PublishCveReport, self).exec_report(*args, **kwargs)
request_POST = self.request.POST
records = request_POST.get('records', '')
format = request_POST.get('format', '')
title = request_POST.get('title', '')
report_type = request_POST.get('report_type', '')
record_list = request_POST.get('record_list', '')
report_name = '%s/cve_publish_%s_%s.%s' % (SRT_REPORT_DIR,report_type,datetime.today().strftime('%Y%m%d_%H%M'),format)
with open(report_name, 'w') as file:
if 'csv' == format:
tab = "\t"
else:
tab = ","
if ('summary' == report_type):
if 'csv' == format:
file.write("Name\tStatus\tType\tFormat\tVersion\tVulnerabilities\tDescription\n")
if 'txt' == format:
file.write("Report : CVEs Table\n")
file.write("\n")
file.write("Name,Status,Type,Format,Version,Vulnerabilities,Description\n")
for id in record_list.split(','):
if not id:
continue
try:
cve = Cve.objects.get(id=id)
file.write("%s%s" % (cve.name,tab))
file.write("%s%s" % (cve.get_status_text,tab))
file.write("%s%s" % (cve.cve_data_type,tab))
file.write("%s%s" % (cve.cve_data_format,tab))
file.write("%s%s" % (cve.cve_data_version,tab))
for i,cv in enumerate(cve.cve_to_vulnerability.all()):
if i > 0:
file.write(" ")
file.write("%s" % cv.vulnerability.name)
file.write("%s" % tab)
file.write("%s" % (cve.description))
file.write("\n")
except Exception as e:
_log("EXCEPTION:%s" % e)
return report_name,os.path.basename(report_name)
class PublishPendingCveReport(Report):
"""Report for the Publish Cve Page"""
def __init__(self, parent_page, *args, **kwargs):
_log_args("REPORT_PUBLISHPENDINGCVE_INIT(%s)" % parent_page, *args, **kwargs)
super(PublishPendingCveReport, self).__init__(parent_page, *args, **kwargs)
def get_context_data(self, *args, **kwargs):
_log_args("REPORT_PUBLISHPENDINGCVE_CONTEXT", *args, **kwargs)
context = super(PublishPendingCveReport, self).get_context_data(*args, **kwargs)
context['report_type_list'] = '\
\
'
context['report_get_title'] = '1'
context['report_recordrange_list'] = '\
Selected
\
'
context['report_columnrange_list'] = ''
context['report_format_list'] = '\
Text
\
CSV
\
'
return context
def exec_report(self, *args, **kwargs):
_log_args("REPORT_PUBLISHPENDINGCVE_EXEC", *args, **kwargs)
super(PublishPendingCveReport, self).exec_report(*args, **kwargs)
request_POST = self.request.POST
records = request_POST.get('records', '')
format = request_POST.get('format', '')
title = request_POST.get('title', '')
report_type = request_POST.get('report_type', '')
record_list = request_POST.get('record_list', '')
report_name = '%s/cve_publish_%s_%s.%s' % (SRT_REPORT_DIR,report_type,datetime.today().strftime('%Y%m%d_%H%M'),format)
with open(report_name, 'w') as file:
if 'csv' == format:
tab = "\t"
else:
tab = ","
if ('summary' == report_type):
if 'csv' == format:
file.write("Name\tStatus\tType\tFormat\tVersion\tVulnerabilities\tDescription\n")
if 'txt' == format:
file.write("Report : CVEs Table\n")
file.write("\n")
file.write("Name,Status,Type,Format,Version,Vulnerabilities,Description\n")
for id in record_list.split(','):
if not id:
continue
try:
cve = Cve.objects.get(id=id)
file.write("%s%s" % (cve.name,tab))
file.write("%s%s" % (cve.get_status_text,tab))
file.write("%s%s" % (cve.cve_data_type,tab))
file.write("%s%s" % (cve.cve_data_format,tab))
file.write("%s%s" % (cve.cve_data_version,tab))
for i,cv in enumerate(cve.cve_to_vulnerability.all()):
if i > 0:
file.write(" ")
file.write("%s" % cv.vulnerability.name)
file.write("%s" % tab)
file.write("%s" % (cve.description))
file.write("\n")
except Exception as e:
_log("EXCEPTION:%s" % e)
return report_name,os.path.basename(report_name)
class PublishListReport(Report):
"""Report for the Publish Cve Page"""
def __init__(self, parent_page, *args, **kwargs):
_log_args("REPORT_PUBLISHLIST_INIT(%s)" % parent_page, *args, **kwargs)
super(PublishListReport, self).__init__(parent_page, *args, **kwargs)
def get_context_data(self, *args, **kwargs):
_log_args("REPORT_PUBLISHLIST_CONTEXT", *args, **kwargs)
context = super(PublishListReport, self).get_context_data(*args, **kwargs)
context['report_type_list'] = '\
\
\
'
context['report_columnrange_list'] = ''
context['report_format_list'] = '\
Text
\
CSV \
(Separator: \
) \
\
'
return context
def exec_report(self, *args, **kwargs):
_log_args("REPORT_PUBLISHLIST_EXEC", *args, **kwargs)
super(PublishListReport, self).exec_report(*args, **kwargs)
request_POST = self.request.POST
format = request_POST.get('format', '')
report_type = request_POST.get('report_type', '')
csv_separator = request_POST.get('csv_separator', 'semi')
report_name = '%s/publish_list_%s_%s.%s' % (SRT_REPORT_DIR,report_type,datetime.today().strftime('%Y%m%d_%H%M'),format)
with open(report_name, 'w') as file:
if 'csv' == format:
tab = ';'
if csv_separator == 'comma': tab = ','
if csv_separator == 'tab': tab = '\t'
else:
tab = ","
if ('preview' == report_type):
if 'csv' == format:
file.write("State\tCve_Name\tCve_Published\tCve_Modified\tCve_Status\tCve_Acknowledge\tReason\tCVE_Description\n".replace('\t',tab))
if 'txt' == format:
file.write("Report : CVEs Table\n")
file.write("\n")
file.write('%-7s %-18s %11s %11s %16s %11s %-35s %s\n' % ('State','Cve_Name','Published','Modified','Cve_Status','Acknowledge','CVE_Description','Reason'))
for publishset in PublishSet.objects.all():
if 'csv' == format:
file.write("%s%s" % (publishset.state_text,tab))
file.write("%s%s" % (publishset.cve.name,tab))
file.write("%s%s" % (publishset.cve.publishedDate,tab))
file.write("%s%s" % (publishset.cve.lastModifiedDate,tab))
file.write("%s%s" % (publishset.cve.get_status_text,tab))
file.write("%s%s" % (publishset.cve.acknowledge_date,tab))
file.write("%s%s" % (publishset.reason,tab))
file.write("%s%s" % (publishset.cve.description,tab))
file.write("\n")
if 'txt' == format:
try:
acknowledge_date = publishset.cve.acknowledge_date.strftime('%m/%d/%Y')
except:
acknowledge_date = ''
if publishset.cve.description:
description = publishset.cve.description[:30] + '...'
else:
description = ''
file.write("%-7s," % publishset.state_text)
file.write("%-18s," % publishset.cve.name)
file.write("%11s," % publishset.cve.publishedDate)
file.write("%11s," % publishset.cve.lastModifiedDate)
file.write("%16s," % publishset.cve.get_status_text)
file.write("%11s," % acknowledge_date)
file.write("%-35s," % description)
file.write("%s," % publishset.reason)
file.write("\n")
if ('report' == report_type):
product_list = Product.objects.all()
def get_product_status_matrix(product_list,cve):
# Preset the default product status labels
status_table = {}
product_top_order = 99
product_top_defect = []
for product in product_list:
status_table[product.key] = publishset.cve.get_status_text
# Set the specific status for the child investigations
for cv in cve.cve_to_vulnerability.all():
#status_text = cv.vulnerability.get_status_text
for investigation in cv.vulnerability.vulnerability_investigation.all():
product_key = investigation.product.key
release_version_list = []
for id in investigation.investigation_to_defect.all():
# Find defect(s) for higest ordered product
if product_top_order > investigation.product.order:
product_top_order = investigation.product.order
product_top_defect = []
if product_top_order == investigation.product.order:
product_top_defect.append(id.defect.name)
# Gather the status or release version
if id.defect.release_version:
release_version_list.append(id.defect.release_version)
release_version = '/'.join(release_version_list)
if release_version:
status_table[product_key] = release_version
elif investigation.status in (SRTool.NOT_VULNERABLE,SRTool.VULNERABLE):
status_table[product_key] = investigation.get_status_text
else:
status_table[product_key] = ''
return status_table
if 'csv' == format:
file.write("State\tCve_Name\tCve_Published\tCve_Modified\tCve_Status\tCve_Acknowledge\tCVE_Description")
for product in product_list:
file.write("\t%s" % product.long_name)
file.write("\n")
if 'txt' == format:
file.write("Report : CVEs Table\n")
file.write("\n")
file.write('%-7s,%-18s,%11s,%11s,%16s,%11s,%-35s,' % ('State','Cve_Name','Published','Modified','Cve_Status','Acknowledge','CVE_Description'))
for product in product_list:
min_len = max(16,len(product.long_name)+1)
str_format = "%s%ds," % ('%',min_len)
file.write(str_format % product.long_name)
file.write("\n")
for publishset in PublishSet.objects.all():
if 'csv' == format:
# Print common status
file.write("%s%s" % (publishset.state_text,tab))
file.write("%s%s" % (publishset.cve.name,tab))
file.write("%s%s" % (publishset.cve.publishedDate,tab))
file.write("%s%s" % (publishset.cve.lastModifiedDate,tab))
file.write("%s%s" % (publishset.cve.get_status_text,tab))
file.write("%s%s" % (publishset.cve.acknowledge_date,tab))
file.write("%s%s" % (publishset.reason,tab))
file.write("%s%s" % (publishset.cve.description,tab))
# Compute the product columns
status_table = get_product_status_matrix(product_list,publishset.cve)
# Print the product columns
for product in Product.objects.all():
file.write("%s%s" % (status_table[product.key],tab))
file.write("\n")
if 'txt' == format:
try:
acknowledge_date = publishset.cve.acknowledge_date.strftime('%m/%d/%Y')
except:
acknowledge_date = ''
if publishset.cve.description:
description = publishset.cve.description[:30] + '...'
else:
description = ''
# Print common status
file.write("%-7s," % publishset.state_text)
file.write("%-18s," % publishset.cve.name)
file.write("%11s," % publishset.cve.publishedDate)
file.write("%11s," % publishset.cve.lastModifiedDate)
file.write("%16s," % publishset.cve.get_status_text)
file.write("%11s," % acknowledge_date)
file.write("%-35s," % description)
# Compute the product columns
status_table = get_product_status_matrix(product_list,publishset.cve)
# Print the product columns
for product in Product.objects.all():
min_len = max(16,len(product.long_name)+1)
str_format = "%s%ds," % ('%',min_len)
file.write(str_format % status_table[product.key])
file.write("\n")
return report_name,os.path.basename(report_name)
class PackageFiltersReport(Report):
"""Report for the Publish Cve Page"""
def __init__(self, parent_page, *args, **kwargs):
_log_args("REPORT_PACKAGEFILTERSREPORT_INIT(%s)" % parent_page, *args, **kwargs)
super(PackageFiltersReport, self).__init__(parent_page, *args, **kwargs)
def get_context_data(self, *args, **kwargs):
_log_args("REPORT_PACKAGEFILTERSREPORT_CONTEXT", *args, **kwargs)
context = super(PackageFiltersReport, self).get_context_data(*args, **kwargs)
context['report_type_list'] = '\
\
'
context['report_get_title'] = ''
context['report_recordrange_list'] = '\
All
\
'
context['report_columnrange_list'] = ''
context['report_format_list'] = '\
r
\
'
return context
def exec_report(self, *args, **kwargs):
_log_args("REPORT_PUBLISHPENDINGCVE_EXEC", *args, **kwargs)
super(PackageFiltersReport, self).exec_report(*args, **kwargs)
request_POST = self.request.POST
records = request_POST.get('records', '')
format = request_POST.get('format', '')
title = request_POST.get('title', '')
report_type = request_POST.get('report_type', '')
record_list = request_POST.get('record_list', '')
report_name = '%s/package_keywords.%s' % (SRT_REPORT_DIR,format)
with open(report_name, 'w') as file:
if 'csv' == format:
tab = "\t"
else:
tab = ","
if ('summary' == report_type):
with open(report_name, 'w', newline='') as csvfile:
writer = csv.writer(csvfile, delimiter=',',
quotechar='"', quoting=csv.QUOTE_MINIMAL)
writer.writerow(['Mode','Name','RealName','InvalidName','Weight'])
query = Package.objects.all().order_by('name')
for package in query:
if 0 == package.weight:
package.weight = 1
writer.writerow(['FOR' if (Package.FOR == package.mode) else 'AGAINST',package.name,package.realname,package.invalidname,package.weight])
return report_name,os.path.basename(report_name)
###############################################################################
#
# PublishSummaryReport: Publish CVE status summary across products
#
class PublishSummaryReport(PublishListReport):
"""Report for the Publish Cve Page"""
def __init__(self, parent_page, *args, **kwargs):
_log_args("REPORT_PUBLISHSUMMARY_INIT(%s)" % parent_page, *args, **kwargs)
super(PublishSummaryReport, self).__init__(parent_page, *args, **kwargs)
def get_context_data(self, *args, **kwargs):
_log_args("REPORT_PUBLISHSUMMARY_CONTEXT", *args, **kwargs)
context = super(PublishSummaryReport, self).get_context_data(*args, **kwargs)
# Add a custom extension report type
context['report_type_list'] = '\
\
'
context['report_custom_list'] = ''
# Add scope
context['report_custom_list'] += '\
New CVEs
\
Investigate CVEs
\
Vulnerable CVEs
\
Not Vulnerable CVEs
\
New-Reserved CVEs
\
Historical CVEs
\
'
# Add extra
context['report_custom_list'] += '
'
context['report_custom_list'] += '\
Truncate fields (for simple text reports)
\
'
return context
def get_product_status_matrix(self,product_list,cve):
# Preset the default product status labels
status_table = {}
product_top_order = 99
product_top_defect = []
# Default all product status to the CVE's status
for product in product_list:
status_table[product.key] = ''
# Set the specific status for the child investigations
for cv in cve.cve_to_vulnerability.all():
#status_text = cv.vulnerability.get_status_text
for investigation in cv.vulnerability.vulnerability_investigation.all():
# product_key = investigation.product.key
release_version_list = []
# Gather release versions, find the highest product's respective defect
for id in investigation.investigation_to_defect.all():
# Find defect(s) for higest ordered product
if product_top_order > investigation.product.order:
product_top_order = investigation.product.order
product_top_defect = []
if product_top_order == investigation.product.order:
product_top_defect.append(id.defect.name)
# Gather the status or release version
if id.defect.release_version:
release_version_list.append(id.defect.release_version)
release_version = '/'.join(release_version_list)
# Set investigation status, unless there are release versions
status_table[investigation.product.key] = investigation.get_status_text
if release_version:
status_table[investigation.product.key] = release_version
return status_table,product_top_defect
def exec_report(self, *args, **kwargs):
_log_args("REPORT_PUBLISHSUMMARY_EXEC", *args, **kwargs)
super(PublishSummaryReport, self).exec_report(*args, **kwargs)
request_POST = self.request.POST
format = request_POST.get('format', '')
report_type = request_POST.get('report_type', '')
csv_separator = request_POST.get('csv_separator', 'semi')
truncate = ('on' == request_POST.get('truncate', 'off'))
status_list = []
if ('on' == request_POST.get('new', 'off')): status_list.append(Cve.NEW)
if ('on' == request_POST.get('investigate', 'off')): status_list.append(Cve.INVESTIGATE)
if ('on' == request_POST.get('vulnerable', 'off')): status_list.append(Cve.VULNERABLE)
if ('on' == request_POST.get('not-vulnerable', 'off')): status_list.append(Cve.NOT_VULNERABLE)
if ('on' == request_POST.get('new-reserved', 'off')): status_list.append(Cve.NEW_RESERVED)
if ('on' == request_POST.get('historical', 'off')): status_list.append(Cve.HISTORICAL)
# Default to the regular report output if not our custom extension
if not report_type in ('publish_summary'):
return(super(PublishSummaryReport, self).exec_report(*args, **kwargs))
if 'csv' == format:
separator = ';'
if csv_separator == 'comma': separator = ','
if csv_separator == 'tab': separator = '\t'
report_name = '%s/cve-svns-srtool-%s.csv' % (SRT_REPORT_DIR,datetime.today().strftime('%Y_%m_%d'))
else:
separator = ","
report_name = '%s/cve-svns-srtool-%s.txt' % (SRT_REPORT_DIR,datetime.today().strftime('%Y_%m_%d'))
# Get the desired product list
product_list = Product.objects.order_by('-order')
if 'publish_summary' == report_type:
with open(report_name, 'w', newline='') as csvfile:
writer = None
# Assemble the header
text_format = '%-18s,%16s,%-11s,%-8s,%-11s,%-8s,%-30s,%-25s,%15s,%15s,%11s,'
header = [
'CVE Number',
'Status',
'V2_Severity',
'V2_Score',
'V3_Severity',
'V3_Score',
'CVE Description',
'YP Comments',
'Created Date',
'Modified Date',
'YP Ack Date',
]
# Assemble the product column namess
for product in product_list:
product_title = product.key
header.append(product_title)
min_len = max(16,len(product_title)+1)
str_format = "%s%ds," % ('%',min_len)
text_format += str_format
# # Add Top Defect
# header.append('Top Defect')
# text_format += '%s'
# Print the header
if 'csv' == format:
writer = csv.writer(csvfile, delimiter=separator, quotechar='"', quoting=csv.QUOTE_MINIMAL)
writer.writerow(header)
else:
writer = csvfile
print(text_format % tuple(header), file=csvfile)
for i,cve in enumerate(Cve.objects.filter(status__in=status_list).order_by('name_sort')):
# Compute the product columns
status_table,product_top_defect = self.get_product_status_matrix(product_list,cve)
# Assemble the row data
if cve.description:
if truncate:
description = cve.description[:26] + '...'
else:
description = cve.description
else:
description = ''
# Use publish date if acknowledge date not available
try:
acknowledge_date = cve.acknowledge_date
if not acknowledge_date:
acknowledge_date = datetime.strptime(cve.publishedDate, '%Y-%m-%d')
acknowledge_date = acknowledge_date.strftime('%m/%d/%Y')
except:
acknowledge_date = ''
_log("NO ACK:%s,%s" % (cve.acknowledge_date,cve.publishedDate))
row = [
cve.name,
cve.get_status_text,
cve.cvssV2_severity,
cve.cvssV2_baseScore,
cve.cvssV3_baseSeverity,
cve.cvssV3_baseScore,
description,
cve.get_public_comments[:20] if truncate else cve.get_public_comments,
cve.srt_created.strftime('%Y/%m/%d') if cve.srt_created else '',
cve.srt_updated.strftime('%Y/%m/%d') if cve.srt_updated else '',
acknowledge_date,
]
# Append the product columns
for product in product_list:
# Show inactive status as normal status
row.append(status_table[product.key].replace('(','').replace(')',''))
# row.append('/'.join(product_top_defect))
# Print the row
if 'csv' == format:
writer.writerow(row)
else:
print(text_format % tuple(row), file=writer)
return report_name,os.path.basename(report_name)
class CpesSrtoolReport(Report):
"""Report for the Publish Cve Page"""
def __init__(self, parent_page, *args, **kwargs):
_log_args("REPORT_CPESSRTOOLREPORT_INIT(%s)" % parent_page, *args, **kwargs)
super(CpesSrtoolReport, self).__init__(parent_page, *args, **kwargs)
def get_context_data(self, *args, **kwargs):
_log_args("REPORT_CPESSRTOOLREPORT_CONTEXT", *args, **kwargs)
context = super(CpesSrtoolReport, self).get_context_data(*args, **kwargs)
context['report_type_list'] = '\
\
'
context['report_get_title'] = ''
context['report_recordrange_list'] = '\
All
\
Only packages against CVEs
\
'
context['report_columnrange_list'] = ''
context['report_format_list'] = '\
text
\
CSV
\
'
return context
def exec_report(self, *args, **kwargs):
_log_args("REPORT_CPESSRTOOLREPORT_EXEC", *args, **kwargs)
super(CpesSrtoolReport, self).exec_report(*args, **kwargs)
request_POST = self.request.POST
records = request_POST.get('records', '')
format = request_POST.get('format', '')
title = request_POST.get('title', '')
report_type = request_POST.get('report_type', '')
record_list = request_POST.get('record_list', '')
report_name = '%s/cpes_srtool_%s_%s.%s' % (SRT_REPORT_DIR,report_type,datetime.today().strftime('%Y%m%d_%H%M'),format)
reportfile = open(report_name, 'w', newline='')
if 'csv' == format:
writer = csv.writer(reportfile, delimiter=',',
quotechar='"', quoting=csv.QUOTE_MINIMAL)
writer.writerow(['Package','CVE','Vulnerability','Affected','Related'])
else:
reportfile.write("Package,CVE,Vulnerability,Affected,Related")
if ('summary' == report_type):
query = Package.objects.all().order_by('name')
for package in query:
name = package.name
cves = ''
for pc in package.package2cve.all():
cves += '%s ' % pc.cve.name
vulnerabilities = ''
for pc in package.package2cve.all():
for cv in pc.cve.cve_to_vulnerability.all():
vulnerabilities += '%s ' % cv.vulnerability.name
affected = ''
for pc in package.package2cve.all():
for cv in pc.cve.cve_to_vulnerability.all():
for vp in cv.vulnerability.affected_products.all():
if 0 == vp.relation:
affected += '%s ' % vp.investigation.name
related = ''
for pc in package.package2cve.all():
for cv in pc.cve.cve_to_vulnerability.all():
for vp in cv.vulnerability.affected_products.all():
if 1 == vp.relation:
related += '%s ' % vp.investigation.name
if ("cves" == records) and not cves:
continue
if 'csv' == format:
writer.writerow([name,cves.strip(),vulnerabilities.strip(),affected.strip(),related.strip()])
else:
reportfile.write("%s,%s,%s,%s,%s\n" % (name,cves.strip(),vulnerabilities.strip(),affected.strip(),related.strip()))
reportfile.close()
return report_name,os.path.basename(report_name)
###############################################################################
#
# History reports
#
class HistoryDefectReport(Report):
"""Report for the History Defect Page"""
def __init__(self, parent_page, *args, **kwargs):
_log_args("WR_HISTORY_DEFECT_INIT(%s)" % parent_page, *args, **kwargs)
super(HistoryDefectReport, self).__init__(parent_page, *args, **kwargs)
def get_context_data(self, *args, **kwargs):
_log_args("WR_HISTORY_DEFECT_CONTEXT", *args, **kwargs)
context = super(HistoryDefectReport, self).get_context_data(*args, **kwargs)
context['report_type_list'] = '\
\
'
context['report_columnrange_list'] = ''
context['report_format_list'] = '\
Text
\
CSV \
(Separator: \
) \
\
'
context['report_recordrange_list'] = '\
Selected
\
All
\
'
# Add a date range
date_start = datetime.strptime('2019-2-15', '%Y-%m-%d')
date_stop = datetime.strptime('2019-3-15', '%Y-%m-%d')
context['report_date_list'] = '\
Start:
\
Stop: \
' % (date_start.strftime('%m/%d/%Y'),date_stop.strftime('%m/%d/%Y'))
# Done!
return context
def exec_report(self, *args, **kwargs):
_log_args("WR_HISTORY_DEFECT_EXEC", *args, **kwargs)
request_POST = self.request.POST
records = request_POST.get('records', '')
format = request_POST.get('format', '')
# title = request_POST.get('title', '')
report_type = request_POST.get('report_type', '')
record_list = request_POST.get('record_list', '')
csv_separator = request_POST.get('csv_separator', 'semi')
# Dates (make as no timezone)
msg = ''
try:
msg = 'Start:%s' % request_POST.get('date_start', '')
date_start = datetime.strptime(request_POST.get('date_start', ''), '%m/%d/%Y')
msg = 'Stop:%s' % request_POST.get('date_stop', '')
date_stop = datetime.strptime(request_POST.get('date_stop', ''), '%m/%d/%Y')
if date_stop < date_start:
return 'Error:stop date is before start date',''
except Exception as e:
return 'Error:bad format for dates (must be mm/dd/yyyy) (%s)(%s)' % (msg,e),''
report_name = '%s/defect_history_%s_%s.%s' % (SRT_REPORT_DIR,report_type,datetime.today().strftime('%Y%m%d_%H%M'),format)
with open(report_name, 'w') as file:
if 'csv' == format:
separator = ";"
if csv_separator == 'comma': separator = ","
if csv_separator == 'tab': separator = "\t"
writer = csv.writer(report_name, delimiter=separator,
quotechar='"', quoting=csv.QUOTE_MINIMAL)
else:
separator = ","
if ('history' == report_type):
if 'csv' == format:
writer.writerow(['Index','Defect','Date','Author','Comment'])
if 'txt' == format:
file.write("Report : Defect History\n")
file.write("\n")
text_format='%02d) %-14s %-10s %-10s %s\n'
file.write(text_format % (0,'Defect','Date','Author','Comment'))
for i,dh in enumerate(DefectHistory.objects.filter(date__gte=date_start,date__lte=date_stop).order_by('defect__name')):
if 'csv' == format:
writer.writerow([i+1,dh.defect.name,dh.date.strftime('%Y-%m-%d'),dh.author,dh.comment])
if 'txt' == format:
file.write(text_format % (i+1,dh.defect.name,dh.date.strftime('%Y-%m-%d'),dh.author,dh.comment))
return report_name,os.path.basename(report_name)
###############################################################################
#
# Notifications reports
#
class NotificationsReport(Report):
"""Report for the Notifications Page"""
def __init__(self, parent_page, *args, **kwargs):
_log_args("WR_NOTIFICATION_INIT(%s)" % parent_page, *args, **kwargs)
super(NotificationsReport, self).__init__(parent_page, *args, **kwargs)
def get_context_data(self, *args, **kwargs):
_log_args("WR_NOTIFICATION_CONTEXT", *args, **kwargs)
context = super(NotificationsReport, self).get_context_data(*args, **kwargs)
context['report_type_list'] = '\
\
'
context['report_columnrange_list'] = ''
context['report_format_list'] = '\
Text
\
CSV \
(Separator: \
) \
\
'
context['report_recordrange_list'] = '\
All
\
'
# Add a date range
date_start = datetime.today() - timedelta(days=30)
date_stop = datetime.today()
context['report_date_list'] = '\
Start:
\
Stop: \
' % (date_start.strftime('%m/%d/%Y'),date_stop.strftime('%m/%d/%Y'))
# Done!
return context
def exec_report(self, *args, **kwargs):
_log_args("WR_NOTIFICATION_EXEC", *args, **kwargs)
request_POST = self.request.POST
records = request_POST.get('records', '')
format = request_POST.get('format', '')
# title = request_POST.get('title', '')
report_type = request_POST.get('report_type', '')
record_list = request_POST.get('record_list', '')
csv_separator = request_POST.get('csv_separator', 'semi')
# Dates (make as no timezone)
msg = ''
try:
msg = 'Start:%s' % request_POST.get('date_start', '')
date_start = datetime.strptime(request_POST.get('date_start', ''), '%m/%d/%Y')
msg = 'Stop:%s' % request_POST.get('date_stop', '')
date_stop = datetime.strptime(request_POST.get('date_stop', ''), '%m/%d/%Y')
if date_stop < date_start:
return 'Error:stop date is before start date',''
except Exception as e:
return 'Error:bad format for dates (must be mm/dd/yyyy) (%s)(%s)' % (msg,e),''
date_start = date_start.strftime('%Y-%m-%d')
date_stop = date_stop.strftime('%Y-%m-%d')
report_name = '%s/notifications_%s_%s.%s' % (SRT_REPORT_DIR,report_type,datetime.today().strftime('%Y%m%d_%H%M'),format)
with open(report_name, 'w') as file:
if 'csv' == format:
separator = ";"
if csv_separator == 'comma': separator = ","
if csv_separator == 'tab': separator = "\t"
writer = csv.writer(file, delimiter=separator,
quotechar='"', quoting=csv.QUOTE_MINIMAL)
else:
separator = ","
if ('summary' == report_type):
if 'csv' == format:
writer.writerow(['Date','Category','Priority','Decription','URL','Author'])
if 'txt' == format:
file.write("Report : Notifications\n")
file.write("\n")
text_format='%02d) %-10s %-25s %-10s "%s",%s,%s\n'
file.write(text_format % (0,'Date','Category','Priority','Decription','URL','Author'))
# for i,notify in enumerate(Notify.objects.filter(srt_updated__gte=date_start,srt_updated__lte=date_stop).order_by('-srt_updated')):
for i,notify in enumerate(Notify.objects.all().order_by('-srt_updated')):
srt_updated = notify.srt_updated.strftime('%Y-%m-%d')
if (date_start > srt_updated) or (date_stop < srt_updated):
continue
if 'csv' == format:
writer.writerow([i+1,srt_updated,notify.category,notify.get_priority_text,notify.description,notify.url,notify.author])
if 'txt' == format:
file.write(text_format % (i+1,srt_updated,notify.category,notify.get_priority_text,notify.description,notify.url,notify.author))
return report_name,os.path.basename(report_name)
###############################################################################
#
# ErrorLogs reports
#
class ErrorLogsReport(Report):
"""Report for the Error Logs Page"""
def __init__(self, parent_page, *args, **kwargs):
_log_args("WR_ERRORLOGS_INIT(%s)" % parent_page, *args, **kwargs)
super(ErrorLogsReport, self).__init__(parent_page, *args, **kwargs)
def get_context_data(self, *args, **kwargs):
_log_args("WR_ERRORLOGS_CONTEXT", *args, **kwargs)
context = super(ErrorLogsReport, self).get_context_data(*args, **kwargs)
context['report_type_list'] = '\
\
'
context['report_columnrange_list'] = ''
context['report_format_list'] = '\
Text
\
CSV \
(Separator: \
) \
\
'
context['report_recordrange_list'] = '\
All
\
'
# Add a date range
date_start = datetime.today() - timedelta(days=30)
date_stop = datetime.today()
context['report_date_list'] = '\
Start:
\
Stop: \
' % (date_start.strftime('%m/%d/%Y'),date_stop.strftime('%m/%d/%Y'))
# Done!
return context
def exec_report(self, *args, **kwargs):
_log_args("WR_ERRORLOGS_EXEC", *args, **kwargs)
request_POST = self.request.POST
records = request_POST.get('records', '')
format = request_POST.get('format', '')
# title = request_POST.get('title', '')
report_type = request_POST.get('report_type', '')
record_list = request_POST.get('record_list', '')
csv_separator = request_POST.get('csv_separator', 'semi')
# Dates (make as no timezone)
msg = ''
try:
msg = 'Start:%s' % request_POST.get('date_start', '')
date_start = datetime.strptime(request_POST.get('date_start', ''), '%m/%d/%Y')
msg = 'Stop:%s' % request_POST.get('date_stop', '')
date_stop = datetime.strptime(request_POST.get('date_stop', ''), '%m/%d/%Y')
if date_stop < date_start:
return 'Error:stop date is before start date',''
except Exception as e:
return 'Error:bad format for dates (must be mm/dd/yyyy) (%s)(%s)' % (msg,e),''
date_start = date_start.strftime('%Y-%m-%d')
date_stop = date_stop.strftime('%Y-%m-%d')
report_name = '%s/errorlogs_%s_%s.%s' % (SRT_REPORT_DIR,report_type,datetime.today().strftime('%Y%m%d_%H%M'),format)
with open(report_name, 'w') as file:
if 'csv' == format:
separator = ";"
if csv_separator == 'comma': separator = ","
if csv_separator == 'tab': separator = "\t"
writer = csv.writer(file, delimiter=separator,
quotechar='"', quoting=csv.QUOTE_MINIMAL)
else:
separator = ","
if ('summary' == report_type):
if 'csv' == format:
writer.writerow(['Date','Severity','Decription'])
if 'txt' == format:
file.write("Report : Error Logs\n")
file.write("Start=%s,Stop=%s\n" % (date_start,date_stop))
text_format='%02d) %-10s %-10s "%s"\n'
file.write(text_format % (0,'Date','Severity','Decription'))
# for i,notify in enumerate(ErrorLog.objects.filter(srt_created__gte=date_start,srt_created__lte=date_stop).order_by('-srt_created')):
for i,notify in enumerate(ErrorLog.objects.all().order_by('-srt_created')):
srt_created = notify.srt_created.strftime('%Y-%m-%d')
if (date_start > srt_created) or (date_stop < srt_created):
continue
if 'csv' == format:
writer.writerow([i+1,srt_created,notify.severity,notify.description])
if 'txt' == format:
file.write(text_format % (i+1,srt_created,notify.get_severity_text,notify.description))
return report_name,os.path.basename(report_name)
###############################################################################
#
class DefaultReport(Report):
"""Report for the Default Page"""
def __init__(self, parent_page, *args, **kwargs):
_log_args("REPORT_GENERIC_INIT(%s)" % parent_page, *args, **kwargs)
super(DefaultReport, self).__init__(parent_page, *args, **kwargs)
self.default_orderby = "name"
def get_context_data(self, *args, **kwargs):
_log_args("REPORT_GENERIC_CONTEXT", *args, **kwargs)
context = super(DefaultReport, self).get_context_data(*args, **kwargs)
context['report_enable_submit'] = ''
#context['report_recordrange_list'] = '\
# Selected
\
# all
\
#context['report_columnrange_list'] = ''
# Selected
# All
#context['report_format_list'] = '\
# Text
\
# CSV
\
# RTF
# XML
# CVE NIST JSON
return context
def exec_report(self, *args, **kwargs):
_log_args("REPORT_GENERIC_EXEC", *args, **kwargs)
super(DefaultReport, self).exec_report(*args, **kwargs)
return None
class ReportManager():
@staticmethod
def get_report_class(parent_page, *args, **kwargs):
if ('management' == parent_page) or ('manage' == parent_page):
return ManagementReport(parent_page, *args, **kwargs)
elif 'cve' == parent_page:
return CveReport(parent_page, *args, **kwargs)
elif 'vulnerability' == parent_page:
return VulnerabilityReport(parent_page, *args, **kwargs)
elif 'investigation' == parent_page:
return InvestigationReport(parent_page, *args, **kwargs)
elif 'defect' == parent_page:
return DefectReport(parent_page, *args, **kwargs)
elif 'cves' == parent_page:
return CvesReport(parent_page, *args, **kwargs)
elif 'select-cves' == parent_page:
return SelectCvesReport(parent_page, *args, **kwargs)
elif 'vulnerabilities' == parent_page:
return VulnerabilitiesReport(parent_page, *args, **kwargs)
elif 'investigations' == parent_page:
return InvestigationsReport(parent_page, *args, **kwargs)
elif 'defects' == parent_page:
return DefectsReport(parent_page, *args, **kwargs)
elif 'products' == parent_page:
return ProductsReport(parent_page, *args, **kwargs)
elif 'select-publish' == parent_page:
return PublishCveReport(parent_page, *args, **kwargs)
elif 'update-published' == parent_page:
return PublishPendingCveReport(parent_page, *args, **kwargs)
elif 'publish' == parent_page:
return PublishListReport(parent_page, *args, **kwargs)
elif 'publish-list' == parent_page:
return PublishListReport(parent_page, *args, **kwargs)
elif 'publish-summary' == parent_page:
return PublishSummaryReport(parent_page, *args, **kwargs)
elif 'package-filters' == parent_page:
return PackageFiltersReport(parent_page, *args, **kwargs)
elif 'cpes_srtool' == parent_page:
return CpesSrtoolReport(parent_page, *args, **kwargs)
elif 'manage_notifications' == parent_page:
return NotificationsReport(parent_page, *args, **kwargs)
elif 'error_logs' == parent_page:
return ErrorLogsReport(parent_page, *args, **kwargs)
elif 'history_defect' == parent_page:
return HistoryDefectReport(parent_page, *args, **kwargs)
else:
return DefaultReport(parent_page, *args, **kwargs)
@staticmethod
def get_context_data(parent_page, *args, **kwargs):
reporter = ReportManager.get_report_class(parent_page, *args, **kwargs)
return reporter.get_context_data(*args, **kwargs)
@staticmethod
def exec_report(parent_page, *args, **kwargs):
reporter = ReportManager.get_report_class(parent_page, *args, **kwargs)
return reporter.exec_report(*args, **kwargs)